branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>JonyNL/autocartas<file_sep>/client/app/src/main/java/com/jonyn/autocartas/ActivityCreateObj.java
package com.jonyn.autocartas;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;
import com.jonyn.autocartas.remote.APIService;
import com.jonyn.autocartas.remote.APIUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ActivityCreateObj extends AppCompatActivity {
private APIService mApiService;
private MainActivity.crudSelection selection;
private LinearLayout llNewUser;
private ScrollView svNewCoche;
private EditText etUser;
private EditText etName;
private EditText etPasswd;
private EditText etIdCoche;
private EditText etModelo;
private EditText etPais;
private EditText etMotor;
private EditText etCilindros;
private EditText etPotencia;
private EditText etRevXmin;
private EditText etVelocidad;
private EditText etConsumo;
private Button btnSaveObject;
public final String TAG = this.getClass().getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_obj);
mApiService = APIUtils.getAPIService();
Intent i = getIntent();
selection = (MainActivity.crudSelection) i.getSerializableExtra(ActivityCrud.CRUDSELECTION);
Toolbar toolbar = findViewById(R.id.toolbar);
btnSaveObject = findViewById(R.id.btnSaveObject);
svNewCoche = findViewById(R.id.svNewCoche);
llNewUser = findViewById(R.id.llNewUser);
if (selection == MainActivity.crudSelection.USERS) {
toolbar.setTitle(getString(R.string.create_user).toUpperCase());
etUser = findViewById(R.id.etUser);
etName = findViewById(R.id.etName);
etPasswd = findViewById(R.id.etPasswd);
llNewUser.setVisibility(View.VISIBLE);
btnSaveObject.setText(getString(R.string.save, getString(R.string.user)));
} else {
toolbar.setTitle(getString(R.string.create_coche).toUpperCase());
etIdCoche = findViewById(R.id.etIdCoche);
etModelo = findViewById(R.id.etModelo);
etPais = findViewById(R.id.etPais);
etMotor = findViewById(R.id.etMotor);
etCilindros = findViewById(R.id.etCilindros);
etPotencia = findViewById(R.id.etPotencia);
etRevXmin = findViewById(R.id.etRevXmin);
etVelocidad = findViewById(R.id.etVelocidad);
etConsumo = findViewById(R.id.etConsumo);
svNewCoche.setVisibility(View.VISIBLE);
btnSaveObject.setText(getString(R.string.save, getString(R.string.coche)));
}
setSupportActionBar(toolbar);
btnSaveObject.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (selection == MainActivity.crudSelection.USERS) {
createUser(etUser.getText().toString(), etName.getText().toString(),
etPasswd.getText().toString());
} else {
createCoche(etIdCoche.getText().toString(),
etModelo.getText().toString(), etPais.getText().toString(),
Integer.parseInt(etMotor.getText().toString()),
Integer.parseInt(etCilindros.getText().toString()),
Integer.parseInt(etPotencia.getText().toString()),
Integer.parseInt(etRevXmin.getText().toString()),
Integer.parseInt(etVelocidad.getText().toString()),
Integer.parseInt(etConsumo.getText().toString()));
}
}
});
}
/**
* Metodo que crea un coche en la base de datos desde el API
*
* @param id: id del coche a crear
* @param modelo: modelo del coche a crear
* @param pais: pais del coche a crear
* @param motor: motor del coche a crear
* @param cilindros: cilindros del coche a crear
* @param potencia: potencia del coche a crear
* @param revxmin: revxmin del coche a crear
* @param velocidad: velocidad del coche a crear
* @param consAt100km: consAt100km del coche a crear
* */
private void createCoche(String id, String modelo, String pais, int motor, int cilindros,
int potencia, int revxmin, int velocidad, int consAt100km) {
mApiService.createCoche(id, modelo, pais, motor, cilindros, potencia, revxmin, velocidad,
consAt100km).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
Toast.makeText(ActivityCreateObj.this,
"Coche creado correctamente", Toast.LENGTH_SHORT).show();
finish();
} else if (response.code() == 406) {
Toast.makeText(ActivityCreateObj.this,
"ID ya registrado en Base de Datos", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.i(TAG, "Error al crear coche en el API. " + t.getMessage());
}
});
}
/**
* Metodo que crea un usuario en la base de datos desde el API
*
* @param user: user del usuario a crear
* @param nombre: nombre del usuario a crear
* @param passwd: <PASSWORD> del usuario a crear
* */
private void createUser(String user, String nombre, String passwd) {
mApiService.createUser(user, nombre, passwd).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
Toast.makeText(ActivityCreateObj.this,
"Usuario creado correctamente", Toast.LENGTH_SHORT).show();
finish();
} else if (response.code() == 406) {
Toast.makeText(ActivityCreateObj.this,
"Usuario ya registrado en Base de Datos", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.i(TAG, "Error al crear usuario en el API. " + t.getMessage());
}
});
}
}
<file_sep>/client/app/src/main/java/com/jonyn/autocartas/ActivityGetObjects.java
package com.jonyn.autocartas;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.jonyn.autocartas.adapters.CochesCrudAdapter;
import com.jonyn.autocartas.adapters.UsersCrudAdapter;
import com.jonyn.autocartas.modelos.Coche;
import com.jonyn.autocartas.modelos.User;
import com.jonyn.autocartas.remote.APIService;
import com.jonyn.autocartas.remote.APIUtils;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ActivityGetObjects extends AppCompatActivity {
private RecyclerView rvListObjects;
private CochesCrudAdapter adapterCoches;
private UsersCrudAdapter adapterUsers;
private APIService mApiService;
private MainActivity.crudSelection selection;
private List objects;
public final String TAG = this.getClass().getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_objects);
mApiService = APIUtils.getAPIService();
// Accedes a la tabla sobre la que se hace la consulta desde los Extras del Intent
// y la asignas a una variable local
Intent i = getIntent();
selection = (MainActivity.crudSelection) i.getSerializableExtra(ActivityCrud.CRUDSELECTION);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(selection.toString());
rvListObjects = findViewById(R.id.rvListObjects);
rvListObjects.setLayoutManager(new LinearLayoutManager(
this, LinearLayoutManager.VERTICAL, false));
// Comprueba si la llamada va a ser sobre la tabla Users o sobre la tabla Coches
if (selection == MainActivity.crudSelection.USERS){
objects = new ArrayList<User>();
adapterUsers = new UsersCrudAdapter(objects);
rvListObjects.setAdapter(adapterUsers);
readUsers();
} else {
objects = new ArrayList<Coche>();
adapterCoches = new CochesCrudAdapter((ArrayList<Coche>) objects, this);
rvListObjects.setAdapter(adapterCoches);
readCoches();
}
}
/**
* Metodo que recibe listado de usuarios del API y los asigna a una lista
*
* */
private void readUsers() {
Log.i(TAG, "readUsers:called");
mApiService.readUsers().enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
if (response.isSuccessful()) {
objects.clear();
objects.addAll(response.body());
Toast.makeText(ActivityGetObjects.this, "Todo OK", Toast.LENGTH_SHORT).show();
Log.i(TAG, response.body().toString());
adapterUsers.notifyDataSetChanged();
} else Toast.makeText(ActivityGetObjects.this, "NOT OK", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<List<User>> call, Throwable t) {
Log.i(TAG, "Error al leer usuarios del API. " + t.getMessage());
}
});
}
/**
* Metodo que recibe listado de coches del API y los asigna a una lista
*
* */
private void readCoches() {
Log.i(TAG, "readUsers:called");
mApiService.readCoches().enqueue(new Callback<List<Coche>>() {
@Override
public void onResponse(Call<List<Coche>> call, Response<List<Coche>> response) {
if (response.isSuccessful()) {
objects.clear();
objects.addAll(response.body());
Toast.makeText(ActivityGetObjects.this, "Todo OK", Toast.LENGTH_SHORT).show();
Log.i(TAG, response.body().toString());
adapterCoches.notifyDataSetChanged();
} else Toast.makeText(ActivityGetObjects.this, "NOT OK", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<List<Coche>> call, Throwable t) {
Log.i(TAG, "Error al leer usuarios del API. " + t.getMessage());
}
});
}
}
<file_sep>/client/app/src/main/java/com/jonyn/autocartas/ActivityNewUrl.java
package com.jonyn.autocartas;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jonyn.autocartas.remote.APIUtils;
/**
* Asigna una nueva URL al Servicio del API (Activity Actualmente no funcional)
*
*
* */
public class ActivityNewUrl extends AppCompatActivity {
private EditText etIp;
private EditText etPort;
private FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_url);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("NEW URL");
setSupportActionBar(toolbar);
etIp = findViewById(R.id.etIp);
etPort = findViewById(R.id.etPort);
fab = findViewById(R.id.fabChangeUrl);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
APIUtils.setIp(etIp.getText().toString());
APIUtils.setPort(etPort.getText().toString());
if (APIUtils.removeInstance()) {
Toast.makeText(ActivityNewUrl.this, "URL modificada", Toast.LENGTH_SHORT).show();
finish();
}
}
});
}
}
<file_sep>/Server/WebContent/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Index</title>
</head>
<body>
<h1 align="center">AUTOCARTAS APIREST</h1>
<table class="egt" border="1" height="300" align="center">
<caption>Listado de Endpoints y descripción corta</caption>
<tr >
<th width="150">Endpoint</th>
<th>Descripción</th>
</tr>
<tr>
<td>/login</td>
<td>Busca el usuario en la base de datos y lo asigna a una variable local.</td>
</tr>
<tr>
<td colspan="2">- POST = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/login">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/login</a></td>
</tr>
<tr>
<td>/logout</td>
<td>Busca la sesión y en caso de encontrarla la borra y asigna el usuario del API a null.</td>
</tr>
<tr>
<td colspan="2">- POST = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/logout">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/logout</a></td>
</tr>
<tr>
<td>/newgame</td>
<td>Comprueba que la sesion no tenga una partida y la crea, en caso de haber una la devuelve.</td>
</tr>
<tr>
<td colspan="2">- POST = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/newgame">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/newgame</a></td>
</tr>
<tr>
<td>/resetgame</td>
<td>Busca y elimina la partida de ese usuario y le crea una nueva.</td>
</tr>
<tr>
<td colspan="2">- POST = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/resetgame">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/resetgame</a></td>
</tr>
<tr>
<td>/raffle</td>
<td>Elige un usuario de forma aleatoria indicando cual va a ser el primero en jugar.</td>
</tr>
<tr>
<td colspan="2">- POST = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/raffle">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/raffle</a></td>
</tr>
<tr>
<td>/playcard</td>
<td>recibe las elecciones del usuario y ejecuta la partida.</td>
</tr>
<tr>
<td colspan="2">- POST = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/playcard">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/playcard</a></td>
</tr>
<tr>
<td>/ready</td>
<td>Asigna las variables necesarias para el CPU y avisa al usuario para que haga su jugada.</td>
</tr>
<tr>
<td colspan="2">- POST = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/ready">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/ready</a></td>
</tr>
<tr>
<td>/stats</td>
<td>Devuelve un listado de usuarios ordenados en base a sus estadísticas.</td>
</tr>
<tr>
<td colspan="2">- POST = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/stats">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/stats</a></td>
</tr>
<tr>
<th colspan="2">CRUD</th>
</tr>
<tr>
<td>/users</td>
<td>Devuelve un listado de los usuarios registrados en la base de datos.</td>
</tr>
<tr>
<td colspan="2">- GET = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/users">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/raffle</a></td>
</tr>
<tr>
<td>/users/{user}</td>
<td>Busca el usuario indicado y en caso de encontrarlo lo devuelve.</td>
</tr>
<tr>
<td colspan="2">- GET = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/users/{user}">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/users/{user}</a></td>
</tr>
<tr>
<td>/users</td>
<td>Crea un nuevo usuario en la base de datos y avisa del resultado de la operación.</td>
</tr>
<tr>
<td colspan="2">- POST = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/users">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/users</a></td>
</tr>
<tr>
<td>/users/{user}/{attr}/{newvalue}</td>
<td>Edita el campo del usuario indicado por el valor nuevo también indicado.</td>
</tr>
<tr>
<td colspan="2">- PUT = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/users/{user}/{attr}/{newvalue}">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/users/{user}/{attr}/{newvalue}</a></td>
</tr>
<tr>
<td>/users/{user}</td>
<td>Intenta eliminar el usuario indicado y avisa del resultado.</td>
</tr>
<tr>
<td colspan="2">- DELETE = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/users/{user}">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/users/{user}</a></td>
</tr>
<tr>
<td>/coches</td>
<td>Devuelve un listado de los coches registrados en la base de datos.</td>
</tr>
<tr>
<td colspan="2">- GET = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/coches">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/coches</a></td>
</tr>
<tr>
<td>/coches/{id}</td>
<td>Busca el coche con el id indicado y en caso de encontrarlo lo devuelve.</td>
</tr>
<tr>
<td colspan="2">- GET = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/coches/{id}">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/coches/{id}</a></td>
</tr>
<tr>
<td>/coches</td>
<td>Crea un nuevo coche en la base de datos y avisa del resultado de la operación.</td>
</tr>
<tr>
<td colspan="2">- POST = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/coches">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/coches</a></td>
</tr>
<tr>
<td>/coches/{idCoche}/{attr}/{newvalue}</td>
<td>Edita el campo del coche indicado por el valor nuevo también indicado.</td>
</tr>
<tr>
<td colspan="2">- PUT = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/coches/{idCoche}/{attr}/{newvalue}">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/coches/{idCoche}/{attr}/{newvalue}</a></td>
</tr>
<tr>
<td>/coches/{idCoche}</td>
<td>Intenta eliminar el coche con el id indicado y avisa del resultado.</td>
</tr>
<tr>
<td colspan="2">- DELETE = <a href="http://localhost:8081/AUTOCARTASREST/rest/restcoches/coches/{idCoche}">
http://localhost:8081/AUTOCARTASREST/rest/restcoches/coches/{idCoche}</a></td>
</tr>
</table>
</body>
</html><file_sep>/client/app/src/main/java/com/jonyn/autocartas/Iiterfaces/ICocheSeleccionado.java
package com.jonyn.autocartas.Iiterfaces;
import com.jonyn.autocartas.modelos.Coche;
public interface ICocheSeleccionado {
void onCocheSeleccionado(Coche c);
}
<file_sep>/client/app/src/main/java/com/jonyn/autocartas/SesionActivity.java
package com.jonyn.autocartas;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.jonyn.autocartas.modelos.ResPartida;
import com.jonyn.autocartas.remote.APIService;
import com.jonyn.autocartas.remote.APIUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class SesionActivity extends AppCompatActivity {
APIService mApiService;
public static final String ID_SESION = "com.jonyn.autocartas.ID_SESION";
public static final String USER = "com.jonyn.autocartas.USER";
private String user;
private String idSesion;
private Button btnNewGame;
private Button btnResetGame;
private Button btnLogOut;
public final String TAG = this.getClass().getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sesion);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Sesion");
setSupportActionBar(toolbar);
mApiService = APIUtils.getAPIService();
Intent i = getIntent();
user = i.getStringExtra(USER);
idSesion = i.getStringExtra(ID_SESION);
btnNewGame = findViewById(R.id.btnNewGame);
btnResetGame = findViewById(R.id.btnReset);
btnLogOut = findViewById(R.id.btnLogOut);
btnNewGame.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getNewGame(idSesion);
}
});
btnResetGame.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getResetGame(idSesion);
}
});
btnLogOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
logout(user, idSesion);
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
// Si volvemos a la activity anterior pulsando el boton atras, cerramos la sesion
logout(user, idSesion);
}
/**
* Metodo que cierra la sesion en la API
*
* @param user: usuario de la sesion
* @param idSesion: id de la sesion a cerrar
* */
private void logout(String user, String idSesion) {
mApiService.logout(user, idSesion).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
Log.i(TAG, "Response logout OK: " + response.body());
Toast.makeText(SesionActivity.this, response.body(), Toast.LENGTH_SHORT).show();
SesionActivity.this.finish();
} else {
Log.i(TAG, "Response logout NOT OK: " + response.message());
Toast.makeText(SesionActivity.this, "API: Error en la sesion", Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.i(TAG, "Error al intentar cerrar sesion en la API: "+t.getMessage());
Toast.makeText(SesionActivity.this, "API: Error al cerrar sesión", Toast.LENGTH_SHORT).show();
}
});
}
/**
* Metodo para reasignar una partida en la API
*
* @param idSesion: id de la sesion que resetea la sesion
* */
private void getResetGame(String idSesion) {
mApiService.getResetGame(idSesion).enqueue(new Callback<ResPartida>() {
@Override
public void onResponse(Call<ResPartida> call, Response<ResPartida> response) {
if (response.isSuccessful()) {
Log.i(TAG, "Response resetGame OK: " + response.body().getIdSesion());
Toast.makeText(SesionActivity.this, "Partida restablecida correctamente", Toast.LENGTH_SHORT).show();
Intent i = new Intent(SesionActivity.this, GamescreenActivity.class);
i.putExtra(GamescreenActivity.RESPARTIDA, response.body());
startActivity(i);
} else {
Log.i(TAG, "Response resetGame NOT OK: " + response.message());
Toast.makeText(SesionActivity.this, "Error al restablecer partida", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<ResPartida> call, Throwable t) {
Log.i(TAG, "API: Error al restablecer la partida: " + t.getMessage());
}
});
}
/**
* Metodo para recibir una partida de la API
*
* @param idSesion: id de la sesion que recibe la partida
* */
private void getNewGame(String idSesion) {
mApiService.getNewGame(idSesion).enqueue(new Callback<ResPartida>() {
@Override
public void onResponse(Call<ResPartida> call, Response<ResPartida> response) {
if (response.isSuccessful()) {
Log.i(TAG, "Response newGame OK: " + response.body().getIdSesion());
Intent i = new Intent(SesionActivity.this, GamescreenActivity.class);
i.putExtra(GamescreenActivity.RESPARTIDA, response.body());
startActivity(i);
} else {
Log.i(TAG, "Response newGame NOT OK: " + response.message());
Toast.makeText(SesionActivity.this, "Error al crear nueva partida", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<ResPartida> call, Throwable t) {
Log.i(TAG, "Error al recibir partida: " + t.getMessage());
Toast.makeText(SesionActivity.this, "Error al recibir partida en la API", Toast.LENGTH_SHORT).show();
}
});
}
}
<file_sep>/Server/src/modelos/ResPartida.java
package modelos;
import java.io.Serializable;
import java.util.ArrayList;
public class ResPartida implements Serializable{
private String idSesion;
private String playP1id;
private String playP2id;
private String caracteristica;
private boolean playerFirst;
private boolean deletedGame;
private int ronda;
private int vPlayer;
private int empates;
private int vCpu;
private ArrayList<Coche> manoP1;
public ResPartida() {
}
public ResPartida(String idSesion, String playP1id, String playP2id, String caracteristica, int ronda, int vPlayer, int empates,
int vCpu, ArrayList<Coche> manoP1) {
this.idSesion = idSesion;
this.playP1id = playP1id;
this.playP2id = playP2id;
this.caracteristica = caracteristica;
this.playerFirst = true;
this.deletedGame = false;
this.ronda = ronda;
this.vPlayer = vPlayer;
this.empates = empates;
this.vCpu = vCpu;
this.manoP1 = manoP1;
}
/* GET & SET idSesion */
public String getIdSesion() {
return idSesion;
}
public void setIdSesion(String idSesion) {
this.idSesion = idSesion;
}
/* GET & SET Caracteristica */
public String getCaracteristica() {
return caracteristica;
}
public void setCaracteristica(String caracteristica) {
this.caracteristica = caracteristica;
}
/* GET & SET deletedGame */
public boolean isDeletedGame() {
return deletedGame;
}
public void setDeletedGame(boolean deletedGame) {
this.deletedGame = deletedGame;
}
/* GET & SET playerFirst */
public boolean isPlayerFirst() {
return playerFirst;
}
public void setPlayerFirst(boolean playerFirst) {
this.playerFirst = playerFirst;
}
/* GET & SET ronda */
public int getRonda() {
return ronda;
}
public void setRonda(int ronda) {
this.ronda = ronda;
}
/* GET & SET vPlayer */
public int getvPlayer() {
return vPlayer;
}
public void setvPlayer(int vPlayer) {
this.vPlayer = vPlayer;
}
/* GET & SET vCpu */
public int getvCpu() {
return vCpu;
}
public void setvCpu(int vCpu) {
this.vCpu = vCpu;
}
/* GET & SET empates */
public int getEmpates() {
return empates;
}
public void setEmpates(int empates) {
this.empates = empates;
}
/* GET & SET manoP1 */
public ArrayList<Coche> getManoP1() {
return manoP1;
}
public void setManoP1(ArrayList<Coche> manoP1) {
this.manoP1 = manoP1;
}
/* GET & SET lastPlayP1id */
public String getPlayP1id() {
return playP1id;
}
public void setLaslPlayP1id(String playP1id) {
this.playP1id = playP1id;
}
/* GET & SET lastPlayP2id */
public String getPlayP2id() {
return playP2id;
}
public void setLastPlayP2id(String playP2id) {
this.playP2id = playP2id;
}
}
<file_sep>/client/app/src/main/java/com/jonyn/autocartas/MainActivity.java
package com.jonyn.autocartas;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.jonyn.autocartas.adapters.UsersAdapter;
import com.jonyn.autocartas.modelos.User;
import com.jonyn.autocartas.remote.APIService;
import com.jonyn.autocartas.remote.APIUtils;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
/**
* Enumerado para la gestion de los menus para los metodos CRUD de la base de datos
* */
public enum crudSelection {
USERS, CARS;
}
private crudSelection selection;
private APIService mApiService;
private Button btnLogin;
private Button btnStats;
private EditText etUser;
private EditText etPasswd;
public final String TAG = this.getClass().getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Autocartas");
mApiService = APIUtils.getAPIService();
etUser = findViewById(R.id.etUser);
etPasswd = findViewById(R.id.etPasswd);
btnLogin = findViewById(R.id.btnLogin);
btnStats = findViewById(R.id.btnStats);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String user = etUser.getText().toString();
String passwd = etPasswd.getText().toString();
if (user.length() == 0) {
Toast.makeText(MainActivity.this, "Campo user no puede estar vacio", Toast.LENGTH_SHORT).show();
} else if (passwd.length() == 0) {
Toast.makeText(MainActivity.this, "Campo password no puede estar vacio", Toast.LENGTH_SHORT).show();
} else
login(user, passwd);
}
});
btnStats.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, RankingActivity.class);
startActivity(i);
}
});
}
/**
* Metodo que nos loguea en la API
*
* @param user: usuario que va a hacer login
* @param passwd: <PASSWORD>
* */
private void login(final String user, final String passwd) {
final String usr = user;
mApiService.login(user, passwd).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
Intent i = new Intent(MainActivity.this, SesionActivity.class);
i.putExtra(SesionActivity.USER, usr);
i.putExtra(SesionActivity.ID_SESION, response.body());
Toast.makeText(MainActivity.this, "Sesión abierta como: " + user, Toast.LENGTH_SHORT).show();
startActivity(i);
} else if (response.code() == 412) {
Toast.makeText(MainActivity.this, "Reabriendo sesión", Toast.LENGTH_SHORT).show();
login(user, passwd);
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.i(TAG, "login: Error al recibir login del API" + t.getMessage());
Toast.makeText(MainActivity.this, "API: Error en login", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_crud, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i;
switch (item.getItemId()) {
case R.id.iCrudCoches:
selection = crudSelection.CARS;
i = new Intent(MainActivity.this, ActivityCrud.class);
i.putExtra(ActivityCrud.CRUDSELECTION, selection);
startActivity(i);
return true;
case R.id.iCrudUsers:
selection = crudSelection.USERS;
i = new Intent(MainActivity.this, ActivityCrud.class);
i.putExtra(ActivityCrud.CRUDSELECTION, selection);
startActivity(i);
return true;
case R.id.iUrl:
i = new Intent(MainActivity.this, ActivityNewUrl.class);
startActivity(i);
return true;
default:
return false;
}
}
@Override
protected void onResume() {
super.onResume();
this.mApiService = APIUtils.getAPIService();
}
}
<file_sep>/client/settings.gradle
include ':app'
rootProject.name='Autocartas'
| 4c447d2d68f7c0dd5a80f82959bd9556f2961979 | [
"Java",
"HTML",
"Gradle"
] | 9 | Java | JonyNL/autocartas | e615f606364dba49ccbca72416332df8cb4def8f | 5a76cf46f489be522661685eb8b348e2b793720f |
refs/heads/master | <file_sep>#pragma once
#include "Utils.hpp"
#include "Structs.hpp"
namespace ppr {
class RadixSort {
GLuint sortProgram = -1;
GLuint permuteProgram = -1;
GLuint histogramProgram = -1;
GLuint pfxWorkProgram = -1;
struct Consts { GLuint NumKeys, Shift, Descending, IsSigned; };
const uint32_t WG_COUNT = 8; // planned multiply radix sort support (aka. Async Compute)
GLuint TmpKeys = -1;
GLuint TmpValues = -1;
GLuint VarBuffer = -1;
GLuint Histograms = -1;
GLuint PrefixSums = -1;
public:
RadixSort() {
// for adopt for AMD
initShaderComputeSPIRV("./shaders-spv/radix/single.comp.spv", sortProgram);
initShaderComputeSPIRV("./shaders-spv/radix/permute.comp.spv", permuteProgram);
initShaderComputeSPIRV("./shaders-spv/radix/histogram.comp.spv", histogramProgram);
initShaderComputeSPIRV("./shaders-spv/radix/pfx-work.comp.spv", pfxWorkProgram);
TmpKeys = allocateBuffer<uint64_t>(1024 * 1024 * 4);
TmpValues = allocateBuffer<uint32_t>(1024 * 1024 * 4);
Histograms = allocateBuffer<uint32_t>(WG_COUNT * 256);
PrefixSums = allocateBuffer<uint32_t>(WG_COUNT * 256);
VarBuffer = allocateBuffer<Consts>(1);
}
~RadixSort() {
glDeleteBuffers(1, &TmpKeys);
glDeleteBuffers(1, &TmpValues);
glDeleteBuffers(1, &VarBuffer);
}
void sort(GLuint &InKeys, GLuint &InVals, uint32_t size = 1, uint32_t descending = 0) {
bool swapness = true;
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 20, InKeys);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 21, InVals);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 24, VarBuffer);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 25, TmpKeys);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 26, TmpValues);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 27, Histograms);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 28, PrefixSums);
for (GLuint i = 0; i < 8; i++) { // 64-bit uint
Consts consts = { size, i, descending, 0 };
glNamedBufferSubData(VarBuffer, 0, strided<Consts>(1), &consts);
dispatch(histogramProgram, WG_COUNT);
dispatch(pfxWorkProgram, 1);
dispatch(permuteProgram, WG_COUNT);
swapness = !swapness;
}
}
};
}<file_sep>#pragma once
#include "Utils.hpp"
#include "Structs.hpp"
namespace ppr {
class VertexInstance;
class AccessorSet : public BaseClass {
public:
AccessorSet() {
glCreateBuffers(1, &meshAccessorsBuffer);
}
friend SceneObject;
friend VertexInstance;
int32_t addVirtualAccessor(VirtualAccessor accessorDesc) {
int32_t accessorPtr = meshAccessors.size();
meshAccessors.push_back(accessorDesc);
glNamedBufferData(meshAccessorsBuffer, meshAccessors.size() * sizeof(VirtualAccessor), meshAccessors.data(), GL_STATIC_DRAW);
return accessorPtr;
}
void bind() {
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 7, meshAccessorsBuffer != -1 ? meshAccessorsBuffer : 0);
}
private:
std::vector<VirtualAccessor> meshAccessors;
GLuint meshAccessorsBuffer = -1;
};
class BufferViewSet : public BaseClass {
public:
BufferViewSet() {
glCreateBuffers(1, &bViewBuffer);
}
friend SceneObject;
friend VertexInstance;
int32_t addBufferView(VirtualBufferView accessorDesc) {
int32_t accessorPtr = bufferViews.size();
bufferViews.push_back(accessorDesc);
glNamedBufferData(bViewBuffer, bufferViews.size() * sizeof(VirtualBufferView), bufferViews.data(), GL_STATIC_DRAW);
return accessorPtr;
}
void bind() {
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 8, bViewBuffer != -1 ? bViewBuffer : 0);
}
private:
std::vector<VirtualBufferView> bufferViews;
GLuint bViewBuffer = -1;
};
class VertexInstance : public BaseClass {
public:
VertexInstance() {
GLuint dispatchData[3] = { 1, 1, 1 };
glCreateBuffers(1, &indirect_dispatch_buffer);
glNamedBufferData(indirect_dispatch_buffer, sizeof(dispatchData), dispatchData, GL_DYNAMIC_DRAW);
glCreateBuffers(1, &meshUniformBuffer);
glNamedBufferData(meshUniformBuffer, sizeof(MeshUniformStruct), &meshUniformData, GL_STATIC_DRAW);
}
friend SceneObject;
size_t getNodeCount();
void setNodeCount(size_t tcount);
void setMaterialOffset(int32_t id);
void useIndex16bit(bool b16);
void setTransform(glm::mat4 t);
void setTransform(glm::dmat4 t) {
this->setTransform(glm::mat4(t));
}
void setIndexed(const int32_t b);
void setVertices(const GLuint &buf);
void setIndices(const GLuint &buf, const bool &all = true);
void setLoadingOffset(const int32_t &off);
void bind();
// setting of accessors
void setVertexAccessor(int32_t accessorID) {
meshUniformData.vertexAccessor = accessorID;
syncUniform();
}
void setNormalAccessor(int32_t accessorID) {
meshUniformData.normalAccessor = accessorID;
syncUniform();
}
void setTexcoordAccessor(int32_t accessorID) {
meshUniformData.texcoordAccessor = accessorID;
syncUniform();
}
void setModifierAccessor(int32_t accessorID) {
meshUniformData.modifierAccessor = accessorID;
syncUniform();
}
void setAccessorSet(AccessorSet * accessorSet) {
this->accessorSet = accessorSet;
}
void setBufferViewSet(BufferViewSet * bufferViewSet) {
this->bufferViewSet = bufferViewSet;
}
private:
bool index16bit = false;
GLuint vbo_triangle_ssbo = -1;
GLuint mat_triangle_ssbo = -1;
GLuint vebo_triangle_ssbo = -1;
GLuint indirect_dispatch_buffer = -1;
BufferViewSet * bufferViewSet;
AccessorSet * accessorSet;
MeshUniformStruct meshUniformData;
GLuint meshUniformBuffer = -1;
void syncUniform() {
glNamedBufferData(meshUniformBuffer, sizeof(MeshUniformStruct), &meshUniformData, GL_STATIC_DRAW);
}
};
}
#include "./VertexInstance.inl"
<file_sep>#pragma once
#include "Utils.hpp"
#include "Structs.hpp"
#include "TextureSet.hpp"
namespace ppr {
class MaterialSet : public BaseClass {
private:
TextureSet * texset = nullptr;
GLuint mats = -1;
std::vector<VirtualMaterial> submats;
void init();
public:
MaterialSet() {
submats = std::vector<VirtualMaterial>(0); // init
init();
}
void setTextureSet(TextureSet *txs) { texset = txs; }
void setTextureSet(TextureSet &txs) { texset = &txs; }
void clearSubmats() { submats.resize(0); }
size_t addSubmat(const VirtualMaterial * submat) {
size_t idx = submats.size();
submats.push_back(*submat);
return idx;
}
size_t addSubmat(const VirtualMaterial &submat) {
return this->addSubmat(&submat);
}
void setSumbat(const size_t& i, const VirtualMaterial &submat) {
if (submats.size() <= i) submats.resize(i+1);
submats[i] = submat;
}
void loadToVGA();
void bindWithContext(GLuint & prog);
};
}
#include "MaterialSet.inl"<file_sep>#pragma once
#include "Utils.hpp"
#include "Structs.hpp"
namespace ppr {
class TextureSet : public BaseClass {
private:
GLuint firstBind = 6;
GLuint texturesBuffer = -1;
//std::vector<uint64_t> vctr;
std::vector<GLint> vctr;
void init();
public:
std::vector<uint32_t> textures;
std::vector<uint32_t> freedomTextures;
std::map<std::string, uint32_t> texnames;
TextureSet() {
textures = std::vector<uint32_t>(0);
textures.push_back(-1);
freedomTextures = std::vector<uint32_t>(0);
texnames = std::map<std::string, uint32_t>();
init();
}
void loadToVGA();
void bindWithContext(GLuint & prog);
void freeTextureByGL(const GLuint& idx);
void freeTexture(const uint32_t& idx);
void clearGlTextures();
uint32_t loadTexture(std::string tex, bool force_write = false);
uint32_t loadTexture(const GLuint & gltexture);
GLuint getGLTexture(const uint32_t & idx);
uint32_t getTexture(const GLuint & idx);
};
}
#include "TextureSet.inl"<file_sep>#include "TextureSet.hpp"
namespace ppr {
inline void TextureSet::init(){
glCreateBuffers(1, &texturesBuffer);
}
inline void TextureSet::loadToVGA() {
/*
uint32_t pcount = std::min((uint32_t)textures.size(), 64u);
vctr.resize(pcount);
for (int i = 0; i < pcount; i++) {
uint64_t texHandle = glGetTextureHandleARB(textures[i]);
glMakeTextureHandleResidentARB(texHandle);
vctr[i] = texHandle;
}
glNamedBufferData(texturesBuffer, vctr.size() * sizeof(GLuint64), vctr.data(), GL_STATIC_DRAW);
*/
uint32_t pcount = std::min((uint32_t)textures.size(), 64u);
vctr.resize(pcount);
for (int i = 0; i < pcount; i++) vctr[i] = firstBind+i-1; // use bindings, except first (move indice)
}
inline void TextureSet::bindWithContext(GLuint & prog) {
//glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 16, texturesBuffer); // bindless texture buffer
//glProgramUniformHandleui64vARB(prog, 1, vctr.size(), vctr.data()); // bindless texture (uniform)
glBindTextures(firstBind, vctr.size()-1, textures.data()+1); // bind textures, except first
glProgramUniform1iv(prog, 1, vctr.size(), vctr.data());
}
inline void TextureSet::clearGlTextures() {
for (int i = 1; i < textures.size(); i++) {
this->freeTexture(i);
}
}
inline void TextureSet::freeTexture(const uint32_t& idx) {
freedomTextures.push_back(idx);
textures[idx] = -1;
}
inline void TextureSet::freeTextureByGL(const GLuint & gltexture) {
for (int i = 1; i < textures.size(); i++) {
if (textures[i] == gltexture) {
this->freeTexture(i);
}
}
}
// get texture by GL
inline uint32_t TextureSet::getTexture(const GLuint & gltexture) {
for (int i = 1; i < textures.size(); i++) {
if (textures[i] == gltexture && textures[i] != -1) return i;
}
return 0;
}
inline GLuint TextureSet::getGLTexture(const uint32_t & idx) {
return textures[idx];
}
inline uint32_t TextureSet::loadTexture(const GLuint & gltexture) {
int32_t idx = getTexture(gltexture);
if (idx && idx >= 0 && idx != -1) return idx;
if (freedomTextures.size() > 0) {
idx = freedomTextures[freedomTextures.size() - 1];
freedomTextures.pop_back();
textures[idx] = gltexture;
}
else {
idx = textures.size();
textures.push_back(gltexture);
}
return idx;
};
#ifdef USE_FREEIMAGE
inline uint32_t TextureSet::loadTexture(std::string tex, bool force_write) {
if (tex == "") return 0;
if (!force_write && texnames.find(tex) != texnames.end()) {
return getTexture(texnames[tex]); // if already in dictionary
}
FREE_IMAGE_FORMAT formato = FreeImage_GetFileType(tex.c_str(), 0);
if (formato == FIF_UNKNOWN) {
return 0;
}
FIBITMAP* imagen = FreeImage_Load(formato, tex.c_str());
if (!imagen) {
return 0;
}
FIBITMAP* temp = FreeImage_ConvertTo32Bits(imagen);
FreeImage_Unload(imagen);
imagen = temp;
uint32_t width = FreeImage_GetWidth(imagen);
uint32_t height = FreeImage_GetHeight(imagen);
uint8_t * pixelsPtr = FreeImage_GetBits(imagen);
GLuint texture = 0;
glCreateTextures(GL_TEXTURE_2D, 1, &texture);
glTextureStorage2D(texture, 1, GL_RGBA8, width, height);
glTextureParameteri(texture, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTextureParameteri(texture, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTextureParameteri(texture, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTextureParameteri(texture, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTextureSubImage2D(texture, 0, 0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, pixelsPtr);
texnames[tex] = texture;
return this->loadTexture(texture);
}
#endif
}
<file_sep>#define OS_WIN
#include <iomanip>
#ifdef OS_WIN
#define GLFW_EXPOSE_NATIVE_WIN32
#define GLFW_EXPOSE_NATIVE_WGL
#endif
#ifdef OS_LNX
#define GLFW_EXPOSE_NATIVE_X11
#define GLFW_EXPOSE_NATIVE_GLX
#endif
#include <GLFW/glfw3.h>
#include <GLFW/glfw3native.h>
#include <tiny_gltf.h>
#include <tiny_obj_loader.h>
#define TINYOBJLOADER_IMPLEMENTATION
#include <tiny_obj_loader.h>
#include "Prismarine/Utils.hpp"
#include "Prismarine/Dispatcher.hpp"
#include "Prismarine/SceneObject.hpp"
#include "Prismarine/VertexInstance.hpp"
#include "Prismarine/MaterialSet.hpp"
#include "Prismarine/Radix.hpp"
#include <functional>
#include "bullet/btBulletCollisionCommon.h"
#include "bullet/btBulletDynamicsCommon.h"
namespace PaperExample {
using namespace ppr;
const int32_t kW = 0;
const int32_t kA = 1;
const int32_t kS = 2;
const int32_t kD = 3;
const int32_t kQ = 4;
const int32_t kE = 5;
const int32_t kSpc = 6;
const int32_t kSft = 7;
const int32_t kC = 8;
const int32_t kK = 9;
const int32_t kM = 10;
class Controller {
bool monteCarlo = true;
public:
glm::dvec3 eye = glm::dvec3(0.0f, 6.0f, 6.0f);
glm::dvec3 view = glm::dvec3(0.0f, 2.0f, 0.0f);
glm::dvec2 mposition;
ppr::Dispatcher * raysp;
glm::dmat4 project() {
#ifdef USE_CAD_SYSTEM
return glm::lookAt(eye, view, glm::dvec3(0.0f, 0.0f, 1.0f));
#elif USE_180_SYSTEM
return glm::lookAt(eye, view, glm::dvec3(0.0f, -1.0f, 0.0f));
#else
return glm::lookAt(eye, view, glm::dvec3(0.0f, 1.0f, 0.0f));
#endif
}
void setRays(ppr::Dispatcher * r) {
raysp = r;
}
void work(const glm::dvec2 &position, const double &diff, const bool &mouseleft, const bool keys[10]) {
glm::dmat4 viewm = project();
glm::dmat4 unviewm = glm::inverse(viewm);
glm::dvec3 ca = (viewm * glm::dvec4(eye, 1.0f)).xyz();
glm::dvec3 vi = (viewm * glm::dvec4(view, 1.0f)).xyz();
bool isFocus = true;
if (mouseleft && isFocus)
{
glm::dvec2 mpos = glm::dvec2(position) - mposition;
double diffX = mpos.x;
double diffY = mpos.y;
if (glm::abs(diffX) > 0.0) this->rotateX(vi, diffX);
if (glm::abs(diffY) > 0.0) this->rotateY(vi, diffY);
if (monteCarlo) raysp->clearSampler();
}
mposition = glm::dvec2(position);
if (keys[kW] && isFocus)
{
this->forwardBackward(ca, vi, diff);
if (monteCarlo) raysp->clearSampler();
}
if (keys[kS] && isFocus)
{
this->forwardBackward(ca, vi, -diff);
if (monteCarlo) raysp->clearSampler();
}
if (keys[kA] && isFocus)
{
this->leftRight(ca, vi, diff);
if (monteCarlo) raysp->clearSampler();
}
if (keys[kD] && isFocus)
{
this->leftRight(ca, vi, -diff);
if (monteCarlo) raysp->clearSampler();
}
if ((keys[kE] || keys[kSpc]) && isFocus)
{
this->topBottom(ca, vi, diff);
if (monteCarlo) raysp->clearSampler();
}
if ((keys[kQ] || keys[kSft] || keys[kC]) && isFocus)
{
this->topBottom(ca, vi, -diff);
if (monteCarlo) raysp->clearSampler();
}
eye = (unviewm * glm::vec4(ca, 1.0f)).xyz();
view = (unviewm * glm::vec4(vi, 1.0f)).xyz();
}
void leftRight(glm::dvec3 &ca, glm::dvec3 &vi, const double &diff) {
ca.x -= diff / 100.0f;
vi.x -= diff / 100.0f;
}
void topBottom(glm::dvec3 &ca, glm::dvec3 &vi, const double &diff) {
ca.y += diff / 100.0f;
vi.y += diff / 100.0f;
}
void forwardBackward(glm::dvec3 &ca, glm::dvec3 &vi, const double &diff) {
ca.z -= diff / 100.0f;
vi.z -= diff / 100.0f;
}
void rotateY(glm::dvec3 &vi, const double &diff) {
glm::dmat4 rot = glm::rotate(-diff / float(raysp->displayHeight) / 0.5f, glm::dvec3(1.0f, 0.0f, 0.0f));
vi = (rot * glm::dvec4(vi, 1.0f)).xyz();
}
void rotateX(glm::dvec3 &vi, const double &diff) {
glm::dmat4 rot = glm::rotate(-diff / float(raysp->displayHeight) / 0.5f, glm::dvec3(0.0f, 1.0f, 0.0f));
vi = (rot * glm::dvec4(vi, 1.0f)).xyz();
}
};
const std::string bgTexName = "background2.jpg";
GLuint loadCubemap() {
FREE_IMAGE_FORMAT formato = FreeImage_GetFileType(bgTexName.c_str(), 0);
if (formato == FIF_UNKNOWN) {
return 0;
}
FIBITMAP* imagen = FreeImage_Load(formato, bgTexName.c_str());
if (!imagen) {
return 0;
}
FIBITMAP* temp = FreeImage_ConvertTo32Bits(imagen);
FreeImage_Unload(imagen);
imagen = temp;
uint32_t width = FreeImage_GetWidth(imagen);
uint32_t height = FreeImage_GetHeight(imagen);
GLuint texture = 0;
glCreateTextures(GL_TEXTURE_2D, 1, &texture);
glTextureStorage2D(texture, 1, GL_RGBA8, width, height);
glTextureParameteri(texture, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteri(texture, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTextureParameteri(texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureParameteri(texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
uint8_t * pixelsPtr = FreeImage_GetBits(imagen);
glTextureSubImage2D(texture, 0, 0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, pixelsPtr);
return texture;
}
bool loadMeshFile(std::string inputfile, std::vector<tinyobj::material_t> &materials, std::vector<tinyobj::shape_t> &shapes, tinyobj::attrib_t &attrib) {
std::string err = "";
bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, inputfile.c_str());
if (!err.empty()) { // `err` may contain warning message.
std::cerr << err << std::endl;
}
return ret;
}
void loadMesh(std::vector<tinyobj::shape_t> &shapes, tinyobj::attrib_t &attrib, std::vector<float> &rawmeshdata) {
// Loop over shapes
for (size_t s = 0; s < shapes.size(); s++) {
// Loop over faces(polygon)
size_t index_offset = 0;
for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) {
int fv = shapes[s].mesh.num_face_vertices[f];
// Loop over vertices in the face.
for (size_t v = 0; v < fv; v++) {
// access to vertex
tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v];
rawmeshdata.push_back(attrib.vertices[3 * idx.vertex_index + 0]);
rawmeshdata.push_back(attrib.vertices[3 * idx.vertex_index + 1]);
rawmeshdata.push_back(attrib.vertices[3 * idx.vertex_index + 2]);
if (attrib.normals.size() > 0) {
rawmeshdata.push_back(attrib.normals[3 * idx.normal_index + 0]);
rawmeshdata.push_back(attrib.normals[3 * idx.normal_index + 1]);
rawmeshdata.push_back(attrib.normals[3 * idx.normal_index + 2]);
}
else {
rawmeshdata.push_back(0);
rawmeshdata.push_back(0);
rawmeshdata.push_back(0);
}
if (attrib.texcoords.size() > 0) {
rawmeshdata.push_back(attrib.texcoords[2 * idx.texcoord_index + 0]);
rawmeshdata.push_back(attrib.texcoords[2 * idx.texcoord_index + 1]);
}
else {
rawmeshdata.push_back(0);
rawmeshdata.push_back(0);
}
}
index_offset += fv;
// per-face material
shapes[s].mesh.material_ids[f];
}
}
}
class MeshTemplate {
public:
ppr::VertexInstance * deviceHandle = nullptr;
std::vector<float> rawMeshData;
std::vector<tinyobj::material_t> materials;
std::vector<tinyobj::shape_t> shapes;
tinyobj::attrib_t attrib;
glm::dmat4 transform = glm::dmat4(1.0);
MeshTemplate * load(std::string inputfile) {
if (loadMeshFile(inputfile, materials, shapes, attrib)) {
loadMesh(shapes, attrib, rawMeshData);
GLuint glBuf = -1;
glCreateBuffers(1, &glBuf);
glNamedBufferData(glBuf, rawMeshData.size() * sizeof(float), rawMeshData.data(), GL_STATIC_DRAW);
// virtual accessor template
ppr::VirtualAccessor vattr;
vattr.offset4 = 0;
ppr::VirtualBufferView bfv;
bfv.stride4 = 8;
bfv.offset4 = 0;
uint32_t stride = 8;
deviceHandle = new ppr::VertexInstance();
AccessorSet * acs = new AccessorSet();
BufferViewSet * bfvi = new BufferViewSet();
vattr.bufferView = bfvi->addBufferView(bfv);
deviceHandle->setBufferViewSet(bfvi);
deviceHandle->setAccessorSet(acs);
vattr.offset4 = 0;
vattr.components = 3 - 1;
deviceHandle->setVertexAccessor(acs->addVirtualAccessor(vattr));
vattr.offset4 = 3;
vattr.components = 3 - 1;
deviceHandle->setNormalAccessor(acs->addVirtualAccessor(vattr));
vattr.offset4 = 6;
vattr.components = 2 - 1;
deviceHandle->setTexcoordAccessor(acs->addVirtualAccessor(vattr));
deviceHandle->setIndexed(false);
deviceHandle->setVertices(glBuf);
deviceHandle->setNodeCount(rawMeshData.size() / stride / 3);
return this;
}
}
};
class PhysicsObject {
public:
uint32_t materialID = 0;
btRigidBody* rigidBody = nullptr;
MeshTemplate* meshTemplate = nullptr;
double disappearTime = 0.0;
double creationTime = 0.0;
};
// possible rigid bodies
std::string rigidMeshTypeList[2] = { "toys/sphere.obj", "toys/box.obj" };
uint32_t activeShapes[1] = { 0 };
std::vector<MeshTemplate *> meshTemplates;
std::vector<PhysicsObject *> objects;
class PathTracerApplication {
public:
PathTracerApplication(const int32_t& argc, const char ** argv, GLFWwindow * wind);
void passKeyDown(const int32_t& key);
void passKeyRelease(const int32_t& key);
void mousePress(const int32_t& button);
void mouseRelease(const int32_t& button);
void mouseMove(const double& x, const double& y);
void process();
void resize(const int32_t& width, const int32_t& height);
void resizeBuffers(const int32_t& width, const int32_t& height);
void pushPhysicsObject(bool withImpulse = true);
void addStaticObject(glm::vec3 position, glm::quat rotation, uint32_t materialID);
void addRigidObject(glm::dvec3 position = glm::dvec3(0.0), int materialID = 0);
private:
btBroadphaseInterface* broadphase;
btDefaultCollisionConfiguration* collisionConfiguration;
btCollisionDispatcher* dispatcher;
btSequentialImpulseConstraintSolver* solver;
btDiscreteDynamicsWorld* dynamicsWorld;
GLFWwindow * window;
ppr::Dispatcher * rays;
ppr::SceneObject * intersector;
Controller * cam;
ppr::MaterialSet * materialManager;
double time = 0;
double diff = 0;
glm::dvec2 mousepos;
double mscale = 1.0f;
int32_t depth = 16;
int32_t switch360key = false;
bool lbutton = false;
bool keys[11] = { false , false , false , false , false , false , false, false, false };
#ifdef EXPERIMENTAL_GLTF
tinygltf::Model gltfModel;
std::vector<PhysicsObject> meshVec = std::vector<PhysicsObject>();
std::vector<GLuint> glBuffers = std::vector<GLuint>();
std::vector<uint32_t> rtTextures = std::vector<uint32_t>();
#endif
struct {
bool show_test_window = false;
bool show_another_window = false;
float f = 0.0f;
} goptions;
};
uint32_t _byType(int &type) {
switch (type) {
case TINYGLTF_TYPE_VEC4:
return 4;
break;
case TINYGLTF_TYPE_VEC3:
return 3;
break;
case TINYGLTF_TYPE_VEC2:
return 2;
break;
case TINYGLTF_TYPE_SCALAR:
return 1;
break;
}
return 1;
}
int32_t getTextureIndex(std::map<std::string, double> &mapped) {
return mapped.count("index") > 0 ? mapped["index"] : -1;
}
void PathTracerApplication::pushPhysicsObject(bool withImpulse) {
glm::dvec3 genDir = glm::normalize(cam->view - cam->eye);
glm::dvec3 genPos = cam->eye + genDir * 2.0 + glm::dvec3(0, 1, 0);
genDir *= 200.0;
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
uint32_t shapeType = 0;
btScalar mass = 2; btVector3 fallInertia(0, 0, 0);
btCollisionShape* fallShape = new btMultiSphereShape(
new btVector3[6]{
btVector3(-0.5f, 0.0f, 0.0f),
btVector3(0.5f, 0.0f, 0.0f),
btVector3(0.0f, 0.0f, 0.5f),
btVector3(0.0f, 0.0f, -0.5f),
btVector3(0.0f, 0.125, 0.0f),
btVector3(0.0f, -0.125, 0.0f)
},
new float[6]{ 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f },
6
);
fallShape->calculateLocalInertia(mass, fallInertia);
auto rotation = btQuaternion(0, 0, 0, 1);
rotation.setEuler(
std::uniform_real_distribution<float>(0, glm::two_pi<float>())(rng),
std::uniform_real_distribution<float>(0, glm::two_pi<float>())(rng),
std::uniform_real_distribution<float>(0, glm::two_pi<float>())(rng)
);
btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(rotation, btVector3(genPos.x, genPos.y, genPos.z)));
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia);
btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI);
fallRigidBody->applyCentralForce(btVector3(genDir.x, genDir.y, genDir.z));
dynamicsWorld->addRigidBody(fallRigidBody);
// init timing state
double time = glfwGetTime() * 1000.f;
PhysicsObject * psb = new PhysicsObject();
psb->meshTemplate = meshTemplates[shapeType];
psb->rigidBody = fallRigidBody;
psb->materialID = std::uniform_int_distribution<int>(0, 1)(rng);
psb->creationTime = time;
psb->disappearTime = 100000.f;
objects.push_back(psb);
}
void PathTracerApplication::addStaticObject(glm::vec3 position, glm::quat rotation, uint32_t materialID) {
btCollisionShape* groundShape = new btBoxShape(btVector3(32.0, 0.1, 32.0));//new btStaticPlaneShape(btVector3(0, 1, 0), 1);
btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(rotation.x, rotation.y, rotation.z, rotation.w), btVector3(position.x, position.y, position.z)));
btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0));
btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);
dynamicsWorld->addRigidBody(groundRigidBody);
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
// init timing state
double time = glfwGetTime() * 1000.f;
PhysicsObject * psb = new PhysicsObject();
psb->meshTemplate = meshTemplates[1];
psb->rigidBody = groundRigidBody;
psb->materialID = materialID;
psb->creationTime = time;
psb->disappearTime = 0.f;
objects.push_back(psb);
}
void PathTracerApplication::addRigidObject(glm::dvec3 position, int materialID) {
uint32_t shapeType = 0;
btScalar mass = 2; btVector3 fallInertia(0, 0, 0);
btCollisionShape* fallShape = new btMultiSphereShape(
new btVector3[6]{
btVector3(-0.5f, 0.0f, 0.0f),
btVector3(0.5f, 0.0f, 0.0f),
btVector3(0.0f, 0.0f, 0.5f),
btVector3(0.0f, 0.0f, -0.5f),
btVector3(0.0f, 0.125, 0.0f),
btVector3(0.0f, -0.125, 0.0f)
},
new float[6]{ 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f },
6
);
fallShape->calculateLocalInertia(mass, fallInertia);
auto rotation = btQuaternion(0, 0, 0, 1);
btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(rotation, btVector3(position.x, position.y, position.z)));
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia);
btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI);
dynamicsWorld->addRigidBody(fallRigidBody);
// init timing state
double time = glfwGetTime() * 1000.f;
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd());
PhysicsObject * psb = new PhysicsObject();
psb->meshTemplate = meshTemplates[shapeType];
psb->rigidBody = fallRigidBody;
psb->materialID = materialID;
psb->creationTime = time;
psb->disappearTime = 0.f;
objects.push_back(psb);
}
glm::vec2 whitePositions[] = { { 7, 3 }, { 14, 17 }, { 14, 4 }, { 18, 4 }, { 0, 7 }, { 5, 8 }, { 11, 5 }, { 10, 7 }, { 7, 6 }, { 6, 10 }, { 12, 6 }, { 3, 2 }, { 5, 11 }, { 7, 5 }, { 14, 15 }, { 12, 11 }, { 8, 12 }, { 4, 15 }, { 2, 11 }, { 9, 9 }, { 10, 3 }, { 6, 17 }, { 7, 2 }, { 14, 5 }, { 13, 3 }, { 13, 16 }, { 3, 6 }, { 1, 10 }, { 4, 1 }, { 10, 9 }, { 5, 17 }, { 12, 7 }, { 3, 5 }, { 2, 7 }, { 5, 10 }, { 10, 10 }, { 5, 7 }, { 7, 4 }, { 12, 4 }, { 8, 13 }, { 9, 8 }, { 15, 17 }, { 3, 10 }, { 4, 13 }, { 2, 13 }, { 8, 16 }, { 12, 3 }, { 17, 5 }, { 13, 2 }, { 15, 3 }, { 2, 3 }, { 6, 5 }, { 11, 7 }, { 16, 5 }, { 11, 8 }, { 14, 7 }, { 15, 6 }, { 1, 7 }, { 5, 9 }, { 10, 11 }, { 6, 6 }, { 4, 18 }, { 7, 14 }, { 17, 3 }, { 4, 9 }, { 10, 12 }, { 6, 3 }, { 16, 7 }, { 14, 14 }, { 16, 18 }, { 3, 13 }, { 1, 13 }, { 2, 10 }, { 7, 9 }, { 13, 1 }, { 12, 15 }, { 4, 3 }, { 5, 2 }, { 10, 2 } };
glm::vec2 blackPosition[] = { { 16, 6 }, { 16, 9 }, { 13, 4 }, { 1, 6 }, { 0, 10 }, { 3, 7 }, { 1, 11 }, { 8, 5 }, { 6, 7 }, { 5, 5 }, { 15, 11 }, { 13, 7 }, { 18, 9 }, { 2, 6 }, { 7, 10 }, { 15, 14 }, { 13, 10 }, { 17, 18 }, { 7, 15 }, { 5, 14 }, { 3, 18 }, { 15, 16 }, { 14, 8 }, { 12, 8 }, { 7, 13 }, { 1, 15 }, { 8, 9 }, { 6, 14 }, { 12, 2 }, { 17, 6 }, { 18, 5 }, { 17, 11 }, { 9, 7 }, { 6, 4 }, { 5, 4 }, { 6, 11 }, { 11, 9 }, { 13, 6 }, { 18, 6 }, { 0, 8 }, { 8, 3 }, { 4, 6 }, { 9, 2 }, { 4, 17 }, { 14, 12 }, { 13, 9 }, { 18, 11 }, { 3, 15 }, { 4, 8 }, { 2, 8 }, { 12, 9 }, { 16, 17 }, { 8, 10 }, { 9, 11 }, { 17, 7 }, { 16, 11 }, { 14, 10 }, { 3, 9 }, { 1, 9 }, { 8, 7 }, { 2, 14 }, { 9, 6 }, { 5, 3 }, { 14, 16 }, { 5, 16 }, { 16, 8 }, { 13, 5 }, { 8, 4 }, { 4, 7 }, { 5, 6 }, { 11, 2 }, { 12, 5 }, { 15, 8 }, { 2, 9 }, { 9, 15 }, { 8, 1 }, { 4, 4 }, { 16, 15 }, { 12, 10 }, { 13, 11 }, { 2, 16 }, { 4, 14 }, { 5, 15 }, { 10, 1 }, { 6, 8 }, { 6, 12 }, { 17, 9 }, { 8, 8 } };
PathTracerApplication::PathTracerApplication(const int32_t& argc, const char ** argv, GLFWwindow * wind) {
window = wind;
if (argc < 1) std::cerr << "-m (--model) for load obj model, -s (--scale) for resize model" << std::endl;
std::string model_input = "";
std::string directory = ".";
// read arguments
for (int i = 1; i < argc; ++i) {
std::string arg = std::string(argv[i]);
if ((arg == "-m") || (arg == "--model")) {
if (i + 1 < argc) {
model_input = std::string(argv[++i]);
}
else {
std::cerr << "Model filename required" << std::endl;
}
}
else
if ((arg == "-s") || (arg == "--scale")) {
if (i + 1 < argc) {
mscale = std::stof(argv[++i]);
}
}
else
if ((arg == "-di") || (arg == "--dir")) {
if (i + 1 < argc) {
directory = std::string(argv[++i]);
}
}
else
if ((arg == "-d") || (arg == "--depth")) {
if (i + 1 < argc) {
depth = std::stoi(argv[++i]);
}
}
}
if (model_input == "") {
std::cerr << "Physics mode enabled..." << std::endl;
}
for (int i = 0; i < 2;i++) {
meshTemplates.push_back((new MeshTemplate())->load(rigidMeshTypeList[i]));
}
// initial transform
glm::dmat4 matrix(1.0);
matrix = glm::dmat4(1.0);
matrix = glm::scale(matrix, glm::dvec3(1.f, 0.6f, 1.f));
meshTemplates[0]->transform = matrix;
matrix = glm::dmat4(1.0);
matrix = glm::scale(matrix, glm::dvec3(32.0, 0.01f, 32.0));
meshTemplates[1]->transform = matrix;
// init material system
auto textureSet = new ppr::TextureSet();
int texturePart = textureSet->loadTexture("wood.jpg");
materialManager = new ppr::MaterialSet();
materialManager->setTextureSet(textureSet);
// init ray tracer
rays = new ppr::Dispatcher();
rays->setSkybox(loadCubemap());
// camera contoller
cam = new Controller();
cam->setRays(rays);
// create geometry intersector
intersector = new ppr::SceneObject();
intersector->allocate(1024 * 1024);
// here is 5 basic materials
// black plastic
{
ppr::VirtualMaterial submat;
submat.diffuse = glm::vec4(0.1f, 0.1f, 0.1f, 1.f);
submat.specular = glm::vec4(0.0f, 0.4f, 0.00f, 1.0f);
submat.emissive = glm::vec4(0.0f);
materialManager->addSubmat(&submat);
}
// white plastic
{
ppr::VirtualMaterial submat;
submat.diffuse = glm::vec4(0.9f, 0.9f, 0.9f, 1.f);
submat.specular = glm::vec4(0.0f, 0.4f, 0.00f, 1.0f);
submat.emissive = glm::vec4(0.0f);
materialManager->addSubmat(&submat);
}
// go dock floor
{
ppr::VirtualMaterial submat;
submat.diffusePart = texturePart;
submat.diffuse = glm::vec4(0.9f, 0.9f, 0.9f, 1.f);
submat.specular = glm::vec4(0.0f, 0.1f, 0.00f, 1.0f);
submat.emissive = glm::vec4(0.0f);
materialManager->addSubmat(&submat);
}
// init physics
broadphase = new btDbvtBroadphase();
collisionConfiguration = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collisionConfiguration);
solver = new btSequentialImpulseConstraintSolver;
dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
dynamicsWorld->setGravity(btVector3(0, -10, 0));
// invisible physics plane (planned ray trace)
btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), 1);
btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0)));
btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0));
btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);
dynamicsWorld->addRigidBody(groundRigidBody);
// add dock
addStaticObject(glm::vec3(0.0, 0.0, 0.0), glm::quat(glm::vec3(0.0, 0.0, 0.0)), 2);
// add rigid bodies
for (int i = 0; i < sizeof(whitePositions) / sizeof(glm::vec2); i++) {
addRigidObject(glm::vec3(whitePositions[i].x - 9.f, 0.5f, whitePositions[i].y - 9.f) * glm::vec3(3.0f), 0);
}
// add rigid bodies
for (int i = 0; i < sizeof(blackPosition) / sizeof(glm::vec2); i++) {
addRigidObject(glm::vec3(blackPosition[i].x - 9.f, 0.5f, blackPosition[i].y - 9.f) * glm::vec3(3.0f), 1);
}
// init timing state
time = glfwGetTime() * 1000.f;
diff = 0;
}
// key downs
void PathTracerApplication::passKeyDown(const int32_t& key) {
if (key == GLFW_KEY_W) keys[kW] = true;
if (key == GLFW_KEY_A) keys[kA] = true;
if (key == GLFW_KEY_S) keys[kS] = true;
if (key == GLFW_KEY_D) keys[kD] = true;
if (key == GLFW_KEY_Q) keys[kQ] = true;
if (key == GLFW_KEY_E) keys[kE] = true;
if (key == GLFW_KEY_C) keys[kC] = true;
if (key == GLFW_KEY_SPACE) keys[kSpc] = true;
if (key == GLFW_KEY_LEFT_SHIFT) keys[kSft] = true;
if (key == GLFW_KEY_K) keys[kK] = true;
if (key == GLFW_KEY_M) keys[kM] = true;
}
// key release
void PathTracerApplication::passKeyRelease(const int32_t& key) {
if (key == GLFW_KEY_W) keys[kW] = false;
if (key == GLFW_KEY_A) keys[kA] = false;
if (key == GLFW_KEY_S) keys[kS] = false;
if (key == GLFW_KEY_D) keys[kD] = false;
if (key == GLFW_KEY_Q) keys[kQ] = false;
if (key == GLFW_KEY_E) keys[kE] = false;
if (key == GLFW_KEY_C) keys[kC] = false;
if (key == GLFW_KEY_SPACE) keys[kSpc] = false;
if (key == GLFW_KEY_LEFT_SHIFT) keys[kSft] = false;
if (key == GLFW_KEY_K) {
if (keys[kK]) switch360key = true;
keys[kK] = false;
}
if (key == GLFW_KEY_M) {
pushPhysicsObject();
keys[kM] = false;
}
}
// mouse moving and pressing
void PathTracerApplication::mousePress(const int32_t& button) { if (button == GLFW_MOUSE_BUTTON_LEFT) lbutton = true; }
void PathTracerApplication::mouseRelease(const int32_t& button) { if (button == GLFW_MOUSE_BUTTON_LEFT) lbutton = false; }
void PathTracerApplication::mouseMove(const double& x, const double& y) { mousepos.x = x, mousepos.y = y; }
// resize buffers and canvas functions
void PathTracerApplication::resizeBuffers(const int32_t& width, const int32_t& height) { rays->resizeBuffers(width, height); }
void PathTracerApplication::resize(const int32_t& width, const int32_t& height) { rays->resize(width, height); }
// processing
void PathTracerApplication::process() {
double t = glfwGetTime() * 1000.f;
diff = t - time;
time = t;
// switch to 360 degree view
cam->work(mousepos, diff, lbutton, keys);
if (switch360key) {
rays->switchMode();
switch360key = false;
}
// clear BVH and load materials
dynamicsWorld->stepSimulation(diff / 1000.f, 10);
intersector->clearTribuffer();
materialManager->loadToVGA();
// initial transform
glm::dmat4 matrix(1.0);
matrix = glm::scale(matrix, glm::dvec3(mscale));
// reload meshes with parameters
for (int i = 0; i < objects.size();i++) {
PhysicsObject * obj = objects[i];
btTransform trans = obj->rigidBody->getWorldTransform();
btScalar matr[16];
trans.getOpenGLMatrix(matr);
obj->meshTemplate->deviceHandle->setTransform(glm::dmat4(glm::make_mat4(matr)) *obj->meshTemplate->transform * matrix);
obj->meshTemplate->deviceHandle->setMaterialOffset(obj->materialID);
intersector->loadMesh(obj->meshTemplate->deviceHandle);
if ((time - obj->creationTime) >= obj->disappearTime && obj->disappearTime > 0.0) {
objects.erase(objects.begin() + i); i--;
dynamicsWorld->removeRigidBody(obj->rigidBody);
}
}
// build BVH in device
intersector->build(matrix);
// process ray tracing
rays->camera(cam->eye, cam->view);
for (int32_t j = 0;j < depth;j++) {
if (rays->getRayCount() <= 0) break;
rays->intersection(intersector);
rays->applyMaterials(materialManager);
rays->shade();
rays->reclaim();
}
rays->sample();
rays->render();
}
}
PaperExample::PathTracerApplication * app;
static void error_callback(int32_t error, const char* description){
std::cerr << ("Error: \n" + std::string(description)) << std::endl;
}
static void key_callback(GLFWwindow* window, int32_t key, int32_t scancode, int32_t action, int32_t mods){
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GLFW_TRUE);
if (action == GLFW_PRESS) app->passKeyDown(key);
if (action == GLFW_RELEASE) app->passKeyRelease(key);
}
static void mouse_callback(GLFWwindow* window, int32_t button, int32_t action, int32_t mods){
if (action == GLFW_PRESS) app->mousePress(button);
if (action == GLFW_RELEASE) app->mouseRelease(button);
}
static void mouse_move_callback(GLFWwindow* window, double x, double y){
app->mouseMove(x, y);
}
int main(const int argc, const char ** argv)
{
glfwSetErrorCallback(error_callback);
if (!glfwInit()) exit(EXIT_FAILURE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_CONTEXT_NO_ERROR, GLFW_TRUE);
const double measureSeconds = 2.0;
const unsigned superSampling = 2;
int32_t baseWidth = 640;
int32_t baseHeight = 360;
//int32_t baseWidth = 800;
//int32_t baseHeight = 450;
GLFWwindow* window = glfwCreateWindow(baseWidth, baseHeight, "Simple example", NULL, NULL);
if (!window) { glfwTerminate(); exit(EXIT_FAILURE); }
#ifdef _WIN32 //Windows DPI scaling
HWND win = glfwGetWin32Window(window);
int32_t baseDPI = 96;
int32_t dpi = baseDPI;
#else //Other not supported
int32_t baseDPI = 96;
int32_t dpi = 96;
#endif
// DPI scaling for Windows
#if (defined MSVC && defined _WIN32)
dpi = GetDpiForWindow(win);
int32_t canvasWidth = baseWidth * ((double)dpi / (double)baseDPI);
int32_t canvasHeight = baseHeight * ((double)dpi / (double)baseDPI);
#else
int32_t canvasWidth = baseWidth;
int32_t canvasHeight = baseHeight;
glfwGetFramebufferSize(window, &canvasWidth, &canvasHeight);
dpi = double(baseDPI) * (double(canvasWidth) / double(baseWidth));
#endif
glfwMakeContextCurrent(window);
glfwSwapInterval(0);
if (glewInit() != GLEW_OK) glfwTerminate();
app = new PaperExample::PathTracerApplication(argc, argv, window);
app->resizeBuffers(baseWidth * superSampling, baseHeight * superSampling);
app->resize(canvasWidth, canvasHeight);
glfwSetKeyCallback(window, key_callback);
glfwSetMouseButtonCallback(window, mouse_callback);
glfwSetCursorPosCallback(window, mouse_move_callback);
glfwSetWindowSize(window, canvasWidth, canvasHeight);
double lastTime = glfwGetTime();
double prevFrameTime = lastTime;
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
int32_t oldWidth = canvasWidth, oldHeight = canvasHeight, oldDPI = dpi;
glfwGetFramebufferSize(window, &canvasWidth, &canvasHeight);
// DPI scaling for Windows
#if (defined MSVC && defined _WIN32)
dpi = GetDpiForWindow(win);
#else
{
glfwGetWindowSize(window, &baseWidth, &baseHeight);
dpi = double(baseDPI) * (double(canvasWidth) / double(baseWidth));
}
#endif
// scale window by DPI
double ratio = double(dpi) / double(baseDPI);
if (oldDPI != dpi) {
canvasWidth = baseWidth * ratio;
canvasHeight = baseHeight * ratio;
glfwSetWindowSize(window, canvasWidth, canvasHeight);
}
// scale canvas
if (oldWidth != canvasWidth || oldHeight != canvasHeight) {
// set new base size
baseWidth = canvasWidth / ratio;
baseHeight = canvasHeight / ratio;
// resize canvas
app->resize(canvasWidth, canvasHeight);
}
// do ray tracing
app->process();
// Measure speed
double currentTime = glfwGetTime();
if (currentTime - lastTime >= measureSeconds) {
std::cout << "FPS: " << 1.f / (currentTime - prevFrameTime) << std::endl;
lastTime += measureSeconds;
}
prevFrameTime = currentTime;
glfwSwapBuffers(window);
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
<file_sep>#include "VertexInstance.hpp"
namespace ppr {
inline void VertexInstance::setNodeCount(size_t tcount) {
uint32_t tiledWork = tiled(tcount, 128);
glNamedBufferSubData(indirect_dispatch_buffer, 0, sizeof(uint32_t), &tiledWork);
meshUniformData.nodeCount = tcount;
syncUniform();
}
inline size_t VertexInstance::getNodeCount() {
return meshUniformData.nodeCount;
}
inline void VertexInstance::useIndex16bit(bool b16) {
index16bit = b16;
}
inline void VertexInstance::setMaterialOffset(int32_t id) {
meshUniformData.materialID = id;
syncUniform();
}
inline void VertexInstance::setTransform(glm::mat4 t) {
meshUniformData.transform = glm::transpose(t);
meshUniformData.transformInv = glm::inverse(t);
syncUniform();
}
inline void VertexInstance::setIndexed(const int32_t b) {
meshUniformData.isIndexed = b;
syncUniform();
}
inline void VertexInstance::setLoadingOffset(const int32_t &off) {
meshUniformData.loadingOffset = off;
syncUniform();
}
inline void VertexInstance::setVertices(const GLuint &buf) {
vbo_triangle_ssbo = buf;
}
inline void VertexInstance::setIndices(const GLuint &buf, const bool &all) {
vebo_triangle_ssbo = buf;
}
inline void VertexInstance::bind() {
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, vbo_triangle_ssbo != -1 ? vbo_triangle_ssbo : 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, vebo_triangle_ssbo != -1 ? vebo_triangle_ssbo : 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, mat_triangle_ssbo != -1 ? mat_triangle_ssbo : 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 6, meshUniformBuffer != -1 ? meshUniformBuffer : 0);
}
}
<file_sep>#pragma once
#include "Utils.hpp"
#include "VertexInstance.hpp"
#include "Radix.hpp"
namespace ppr {
class SceneObject : public BaseClass {
private:
RadixSort * sorter = nullptr;
bool dirty = false;
uint32_t maxt = 1024 * 1024 * 1;
uint32_t worksize = 128;
GLuint geometryLoaderProgramI16 = -1;
GLuint geometryLoaderProgram2 = -1;
GLuint buildProgramH = -1;
GLuint aabbMakerProgramH = -1;
GLuint refitProgramH = -1;
GLuint resortProgramH = -1;
GLuint minmaxProgram2 = -1;
GLuint mat_triangle_ssbo_upload = -1;
GLuint mat_triangle_ssbo = -1;
GLuint vbo_vertex_textrue = -1;
GLuint vbo_normal_textrue = -1;
GLuint vbo_texcoords_textrue = -1;
GLuint vbo_modifiers_textrue = -1;
GLuint vbo_vertex_textrue_upload = -1;
GLuint vbo_normal_textrue_upload = -1;
GLuint vbo_texcoords_textrue_upload = -1;
GLuint vbo_modifiers_textrue_upload = -1;
GLuint vbo_sampler = -1;
// uniform buffer
GLuint geometryBlockUniform = -1;
GeometryBlockUniform geometryBlockData;
// uniforms
GeometryUniformStruct geometryUniformData;
GLuint aabbCounter = -1;
GLuint leafBuffer = -1;
GLuint bvhnodesBuffer = -1;
GLuint mortonBuffer = -1;
GLuint mortonBufferIndex = -1;
GLuint bvhflagsBuffer = -1;
GLuint activeBuffer = -1;
GLuint childBuffer = -1;
GLuint lscounterTemp = -1; // zero store
GLuint minmaxBufRef = -1; // default bound
GLuint tcounter = -1; // triangle counter
GLuint minmaxBuf = -1; // minmax buffer
void initShaders();
void init();
glm::vec3 offset = glm::vec3(-1.0001f);
glm::vec3 scale = glm::vec3( 2.0002f);
public:
SceneObject() { init(); }
~SceneObject() {
glDeleteProgram(geometryLoaderProgramI16);
glDeleteProgram(geometryLoaderProgram2);
glDeleteProgram(buildProgramH);
glDeleteProgram(aabbMakerProgramH);
glDeleteProgram(refitProgramH);
glDeleteProgram(resortProgramH);
glDeleteProgram(minmaxProgram2);
glDeleteBuffers(1, &mat_triangle_ssbo);
glDeleteTextures(1, &vbo_vertex_textrue);
glDeleteTextures(1, &vbo_normal_textrue);
glDeleteTextures(1, &vbo_texcoords_textrue);
glDeleteTextures(1, &vbo_modifiers_textrue);
glDeleteSamplers(1, &vbo_sampler);
glDeleteBuffers(1, &geometryBlockUniform);
glDeleteBuffers(1, &aabbCounter);
glDeleteBuffers(1, &leafBuffer);
glDeleteBuffers(1, &bvhnodesBuffer);
glDeleteBuffers(1, &mortonBuffer);
glDeleteBuffers(1, &mortonBufferIndex);
glDeleteBuffers(1, &bvhflagsBuffer);
glDeleteBuffers(1, &lscounterTemp);
glDeleteBuffers(1, &minmaxBufRef);
glDeleteBuffers(1, &tcounter);
glDeleteBuffers(1, &minmaxBuf);
}
int32_t materialID = 0;
size_t triangleCount = 0;
void syncUniforms();
void allocate(const size_t &count);
void setMaterialID(int32_t id);
void bindUniforms();
void bind();
void bindBVH();
void bindLeafs();
void clearTribuffer();
void loadMesh(VertexInstance * gobject);
bool isDirty() const;
void markDirty();
void resolve();
void build(const glm::dmat4 &optimization = glm::dmat4(1.0));
void configureIntersection(bool clearDepth);
};
}
#include "./SceneObject.inl"
<file_sep>#define OS_WIN
#include <iomanip>
#ifdef OS_WIN
#define GLFW_EXPOSE_NATIVE_WIN32
#define GLFW_EXPOSE_NATIVE_WGL
#endif
#ifdef OS_LNX
#define GLFW_EXPOSE_NATIVE_X11
#define GLFW_EXPOSE_NATIVE_GLX
#endif
#include <GLFW/glfw3.h>
#include <GLFW/glfw3native.h>
#include <tiny_gltf.h>
#include "Prismarine/Utils.hpp"
#include "Prismarine/Dispatcher.hpp"
#include "Prismarine/SceneObject.hpp"
#include "Prismarine/VertexInstance.hpp"
#include "Prismarine/MaterialSet.hpp"
#include "Prismarine/Radix.hpp"
#include <functional>
namespace PaperExample {
using namespace ppr;
const int32_t kW = 0;
const int32_t kA = 1;
const int32_t kS = 2;
const int32_t kD = 3;
const int32_t kQ = 4;
const int32_t kE = 5;
const int32_t kSpc = 6;
const int32_t kSft = 7;
const int32_t kC = 8;
const int32_t kK = 9;
const int32_t kM = 10;
const int32_t kL = 11;
class Controller {
bool monteCarlo = true;
public:
glm::dvec3 eye = glm::dvec3(0.0f, 6.0f, 6.0f);
glm::dvec3 view = glm::dvec3(0.0f, 2.0f, 0.0f);
glm::dvec2 mposition;
ppr::Dispatcher * raysp;
glm::dmat4 project() {
#ifdef USE_CAD_SYSTEM
return glm::lookAt(eye, view, glm::dvec3(0.0f, 0.0f, 1.0f));
#elif USE_180_SYSTEM
return glm::lookAt(eye, view, glm::dvec3(0.0f, -1.0f, 0.0f));
#else
return glm::lookAt(eye, view, glm::dvec3(0.0f, 1.0f, 0.0f));
#endif
}
void setRays(ppr::Dispatcher * r) {
raysp = r;
}
void work(const glm::dvec2 &position, const double &diff, const bool &mouseleft, const bool keys[10]) {
glm::dmat4 viewm = project();
glm::dmat4 unviewm = glm::inverse(viewm);
glm::dvec3 ca = (viewm * glm::dvec4(eye, 1.0f)).xyz();
glm::dvec3 vi = (viewm * glm::dvec4(view, 1.0f)).xyz();
bool isFocus = true;
if (mouseleft && isFocus)
{
glm::dvec2 mpos = glm::dvec2(position) - mposition;
double diffX = mpos.x;
double diffY = mpos.y;
if (glm::abs(diffX) > 0.0) this->rotateX(vi, diffX);
if (glm::abs(diffY) > 0.0) this->rotateY(vi, diffY);
if (monteCarlo) raysp->clearSampler();
}
mposition = glm::dvec2(position);
if (keys[kW] && isFocus)
{
this->forwardBackward(ca, vi, diff);
if (monteCarlo) raysp->clearSampler();
}
if (keys[kS] && isFocus)
{
this->forwardBackward(ca, vi, -diff);
if (monteCarlo) raysp->clearSampler();
}
if (keys[kA] && isFocus)
{
this->leftRight(ca, vi, diff);
if (monteCarlo) raysp->clearSampler();
}
if (keys[kD] && isFocus)
{
this->leftRight(ca, vi, -diff);
if (monteCarlo) raysp->clearSampler();
}
if ((keys[kE] || keys[kSpc]) && isFocus)
{
this->topBottom(ca, vi, diff);
if (monteCarlo) raysp->clearSampler();
}
if ((keys[kQ] || keys[kSft] || keys[kC]) && isFocus)
{
this->topBottom(ca, vi, -diff);
if (monteCarlo) raysp->clearSampler();
}
eye = (unviewm * glm::vec4(ca, 1.0f)).xyz();
view = (unviewm * glm::vec4(vi, 1.0f)).xyz();
}
void leftRight(glm::dvec3 &ca, glm::dvec3 &vi, const double &diff) {
ca.x -= diff / 100.0f;
vi.x -= diff / 100.0f;
}
void topBottom(glm::dvec3 &ca, glm::dvec3 &vi, const double &diff) {
ca.y += diff / 100.0f;
vi.y += diff / 100.0f;
}
void forwardBackward(glm::dvec3 &ca, glm::dvec3 &vi, const double &diff) {
ca.z -= diff / 100.0f;
vi.z -= diff / 100.0f;
}
void rotateY(glm::dvec3 &vi, const double &diff) {
glm::dmat4 rot = glm::rotate(-diff / float(raysp->displayHeight) / 0.5f, glm::dvec3(1.0f, 0.0f, 0.0f));
vi = (rot * glm::dvec4(vi, 1.0f)).xyz();
}
void rotateX(glm::dvec3 &vi, const double &diff) {
glm::dmat4 rot = glm::rotate(-diff / float(raysp->displayHeight) / 0.5f, glm::dvec3(0.0f, 1.0f, 0.0f));
vi = (rot * glm::dvec4(vi, 1.0f)).xyz();
}
};
const std::string bgTexName = "background.jpg";
GLuint loadCubemap() {
FREE_IMAGE_FORMAT formato = FreeImage_GetFileType(bgTexName.c_str(), 0);
if (formato == FIF_UNKNOWN) {
return 0;
}
FIBITMAP* imagen = FreeImage_Load(formato, bgTexName.c_str());
if (!imagen) {
return 0;
}
FIBITMAP* temp = FreeImage_ConvertTo32Bits(imagen);
FreeImage_Unload(imagen);
imagen = temp;
uint32_t width = FreeImage_GetWidth(imagen);
uint32_t height = FreeImage_GetHeight(imagen);
GLuint texture = 0;
glCreateTextures(GL_TEXTURE_2D, 1, &texture);
glTextureStorage2D(texture, 1, GL_RGBA8, width, height);
glTextureParameteri(texture, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteri(texture, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTextureParameteri(texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureParameteri(texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
uint8_t * pixelsPtr = FreeImage_GetBits(imagen);
glTextureSubImage2D(texture, 0, 0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, pixelsPtr);
return texture;
}
class PathTracerApplication {
public:
PathTracerApplication(const int32_t& argc, const char ** argv, GLFWwindow * wind);
void passKeyDown(const int32_t& key);
void passKeyRelease(const int32_t& key);
void mousePress(const int32_t& button);
void mouseRelease(const int32_t& button);
void mouseMove(const double& x, const double& y);
void process();
void resize(const int32_t& width, const int32_t& height);
void resizeBuffers(const int32_t& width, const int32_t& height);
void saveHdr(std::string name = "") {
ppr::Dispatcher::HdrImage image = rays->snapHdr();
// allocate RGBAF
FIBITMAP * btm = FreeImage_AllocateT(FIT_RGBAF, image.width, image.height);
// copy HDR data
int ti = 0;
for (int r = 0; r < image.height; r++) {
auto row = FreeImage_GetScanLine(btm, r);
memcpy(row, image.image + r * 4 * image.width, image.width * sizeof(float) * 4);
}
// convert as 48 bits
//btm = FreeImage_ConvertToRGBF(btm);
// save HDR
FreeImage_Save(FIF_EXR, btm, name.c_str(), EXR_FLOAT | EXR_PIZ);
FreeImage_Unload(btm);
}
private:
GLFWwindow * window;
ppr::Dispatcher * rays;
ppr::SceneObject * intersector;
Controller * cam;
ppr::MaterialSet * materialManager;
double time = 0;
double diff = 0;
glm::dvec2 mousepos;
double mscale = 1.0f;
int32_t depth = 16;
int32_t switch360key = false;
int32_t img_counter = 0;
bool lbutton = false;
bool keys[12] = { false , false , false , false , false , false , false, false, false, false, false };
#ifdef EXPERIMENTAL_GLTF
tinygltf::Model gltfModel;
std::vector<std::vector<ppr::VertexInstance *>> meshVec = std::vector<std::vector<ppr::VertexInstance *>>();
std::vector<GLuint> glBuffers = std::vector<GLuint>();
std::vector<uint32_t> rtTextures = std::vector<uint32_t>();
#endif
struct {
bool show_test_window = false;
bool show_another_window = false;
float f = 0.0f;
} goptions;
};
uint32_t _byType(int &type) {
switch (type) {
case TINYGLTF_TYPE_VEC4:
return 4;
break;
case TINYGLTF_TYPE_VEC3:
return 3;
break;
case TINYGLTF_TYPE_VEC2:
return 2;
break;
case TINYGLTF_TYPE_SCALAR:
return 1;
break;
}
return 1;
}
int32_t getTextureIndex(std::map<std::string, double> &mapped) {
return mapped.count("index") > 0 ? mapped["index"] : -1;
}
PathTracerApplication::PathTracerApplication(const int32_t& argc, const char ** argv, GLFWwindow * wind) {
window = wind;
if (argc < 1) std::cerr << "-m (--model) for load obj model, -s (--scale) for resize model" << std::endl;
std::string model_input = "";
std::string directory = ".";
// read arguments
for (int i = 1; i < argc; ++i) {
std::string arg = std::string(argv[i]);
if ((arg == "-m") || (arg == "--model")) {
if (i + 1 < argc) {
model_input = std::string(argv[++i]);
}
else {
std::cerr << "Model filename required" << std::endl;
}
}
else
if ((arg == "-s") || (arg == "--scale")) {
if (i + 1 < argc) {
mscale = std::stof(argv[++i]);
}
}
else
if ((arg == "-di") || (arg == "--dir")) {
if (i + 1 < argc) {
directory = std::string(argv[++i]);
}
}
else
if ((arg == "-d") || (arg == "--depth")) {
if (i + 1 < argc) {
depth = std::stoi(argv[++i]);
}
}
}
if (model_input == "") {
std::cerr << "No model found :(" << std::endl;
}
// init material system
materialManager = new MaterialSet();
// init ray tracer
rays = new ppr::Dispatcher();
rays->setSkybox(loadCubemap());
// camera contoller
cam = new Controller();
cam->setRays(rays);
#ifdef EXPERIMENTAL_GLTF
tinygltf::TinyGLTF loader;
std::string err = "";
loader.LoadASCIIFromFile(&gltfModel, &err, directory + "/" + model_input);
// load textures (TODO - native samplers support in ray tracers)
ppr::TextureSet * txset = new ppr::TextureSet();
materialManager->setTextureSet(txset);
for (int i = 0; i < gltfModel.textures.size(); i++) {
tinygltf::Texture& gltfTexture = gltfModel.textures[i];
std::string uri = directory + "/" + gltfModel.images[gltfTexture.source].uri;
uint32_t rtTexture = txset->loadTexture(uri);
// todo with rtTexture processing
rtTextures.push_back(rtTexture);
}
// load materials (include PBR)
materialManager->clearSubmats();
for (int i = 0; i < gltfModel.materials.size(); i++) {
tinygltf::Material & material = gltfModel.materials[i];
ppr::VirtualMaterial submat;
// diffuse?
int32_t texId = getTextureIndex(material.values["baseColorTexture"].json_double_value);
submat.diffusePart = texId >= 0 ? rtTextures[texId] : 0;
if (material.values["baseColorFactor"].number_array.size() >= 3) {
submat.diffuse = glm::vec4(glm::make_vec3(&material.values["baseColorFactor"].number_array[0]), 1.0f);
}
else {
submat.diffuse = glm::vec4(1.0f);
}
// metallic roughness
texId = getTextureIndex(material.values["metallicRoughnessTexture"].json_double_value);
submat.specularPart = texId >= 0 ? rtTextures[texId] : 0;
submat.specular = glm::vec4(1.0f);
if (material.values["metallicFactor"].number_array.size() >= 1) {
submat.specular.z = material.values["metallicFactor"].number_array[0];
}
if (material.values["roughnessFactor"].number_array.size() >= 1) {
submat.specular.y = material.values["roughnessFactor"].number_array[0];
}
// emission
if (material.additionalValues["emissiveFactor"].number_array.size() >= 3) {
submat.emissive = glm::vec4(glm::make_vec3(&material.additionalValues["emissiveFactor"].number_array[0]), 1.0f);
}
else {
submat.emissive = glm::vec4(0.0f);
}
// emissive texture
texId = getTextureIndex(material.additionalValues["emissiveTexture"].json_double_value);
submat.emissivePart = texId >= 0 ? rtTextures[texId] : 0;
// normal map
texId = getTextureIndex(material.additionalValues["normalTexture"].json_double_value);
submat.bumpPart = texId >= 0 ? rtTextures[texId] : 0;
// load material
materialManager->addSubmat(submat);
}
// make raw mesh buffers
for (int i = 0; i < gltfModel.buffers.size();i++) {
GLuint glBuf = -1;
glCreateBuffers(1, &glBuf);
glNamedBufferData(glBuf, gltfModel.buffers[i].data.size(), &gltfModel.buffers[i].data.at(0), GL_STATIC_DRAW);
glBuffers.push_back(glBuf);
}
BufferViewSet * bfvi = new BufferViewSet();
for (auto const &bv : gltfModel.bufferViews) {
VirtualBufferView bfv;
bfv.offset4 = bv.byteOffset / 4;
bfv.stride4 = bv.byteStride / 4;
bfvi->addBufferView(bfv);
}
// load mesh templates (better view objectivity)
for (int m = 0; m < gltfModel.meshes.size();m++) {
std::vector<ppr::VertexInstance *> primitiveVec = std::vector<ppr::VertexInstance *>();
tinygltf::Mesh &glMesh = gltfModel.meshes[m];
for (int i = 0; i < glMesh.primitives.size();i++) {
tinygltf::Primitive & prim = glMesh.primitives[i];
ppr::VertexInstance * geom = new ppr::VertexInstance();
AccessorSet * acs = new AccessorSet();
geom->setAccessorSet(acs);
geom->setBufferViewSet(bfvi);
// make attributes
std::map<std::string, int>::const_iterator it(prim.attributes.begin());
std::map<std::string, int>::const_iterator itEnd(prim.attributes.end());
// load modern mode
for(auto const &it : prim.attributes) {
tinygltf::Accessor &accessor = gltfModel.accessors[it.second];
auto& bufferView = gltfModel.bufferViews[accessor.bufferView];
// virtual accessor template
ppr::VirtualAccessor vattr;
vattr.offset4 = accessor.byteOffset / 4;
vattr.bufferView = accessor.bufferView;
// vertex
if (it.first.compare("POSITION") == 0) { // vertices
vattr.components = 3 - 1;
geom->setVertices(glBuffers[bufferView.buffer]);
geom->setVertexAccessor(acs->addVirtualAccessor(vattr));
} else
// normal
if (it.first.compare("NORMAL") == 0) {
vattr.components = 3 - 1;
geom->setNormalAccessor(acs->addVirtualAccessor(vattr));
} else
// texcoord
if (it.first.compare("TEXCOORD_0") == 0) {
vattr.components = 2 - 1;
geom->setTexcoordAccessor(acs->addVirtualAccessor(vattr));
}
}
// indices
// planned of support accessors there
if (prim.indices >= 0) {
tinygltf::Accessor &idcAccessor = gltfModel.accessors[prim.indices];
auto& bufferView = gltfModel.bufferViews[idcAccessor.bufferView];
geom->setNodeCount(idcAccessor.count / 3);
geom->setIndices(glBuffers[bufferView.buffer]);
bool isInt16 = idcAccessor.componentType == TINYGLTF_COMPONENT_TYPE_SHORT || idcAccessor.componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT;
int32_t loadingOffset = (bufferView.byteOffset + idcAccessor.byteOffset) / (isInt16 ? 2 : 4);
geom->setLoadingOffset(loadingOffset);
geom->setIndexed(true);
// is 16-bit indices?
geom->useIndex16bit(isInt16);
}
// use material
geom->setMaterialOffset(prim.material);
// if triangles, then load mesh
if (prim.mode == TINYGLTF_MODE_TRIANGLES) {
primitiveVec.push_back(geom);
}
}
meshVec.push_back(primitiveVec);
}
#endif
// create geometry intersector
intersector = new ppr::SceneObject();
intersector->allocate(1024 * 2048);
// init timing state
time = glfwGetTime() * 1000.f;
diff = 0;
}
// key downs
void PathTracerApplication::passKeyDown(const int32_t& key) {
if (key == GLFW_KEY_W) keys[kW] = true;
if (key == GLFW_KEY_A) keys[kA] = true;
if (key == GLFW_KEY_S) keys[kS] = true;
if (key == GLFW_KEY_D) keys[kD] = true;
if (key == GLFW_KEY_Q) keys[kQ] = true;
if (key == GLFW_KEY_E) keys[kE] = true;
if (key == GLFW_KEY_C) keys[kC] = true;
if (key == GLFW_KEY_SPACE) keys[kSpc] = true;
if (key == GLFW_KEY_LEFT_SHIFT) keys[kSft] = true;
if (key == GLFW_KEY_K) keys[kK] = true;
if (key == GLFW_KEY_L) keys[kL] = true;
}
// key release
void PathTracerApplication::passKeyRelease(const int32_t& key) {
if (key == GLFW_KEY_W) keys[kW] = false;
if (key == GLFW_KEY_A) keys[kA] = false;
if (key == GLFW_KEY_S) keys[kS] = false;
if (key == GLFW_KEY_D) keys[kD] = false;
if (key == GLFW_KEY_Q) keys[kQ] = false;
if (key == GLFW_KEY_E) keys[kE] = false;
if (key == GLFW_KEY_C) keys[kC] = false;
if (key == GLFW_KEY_SPACE) keys[kSpc] = false;
if (key == GLFW_KEY_LEFT_SHIFT) keys[kSft] = false;
if (key == GLFW_KEY_K) {
if (keys[kK]) switch360key = true;
keys[kK] = false;
}
if (key == GLFW_KEY_L) {
saveHdr("snapshots/hdr_snapshot_" + std::to_string(img_counter++) + ".exr");
keys[kL] = false;
}
}
// mouse moving and pressing
void PathTracerApplication::mousePress(const int32_t& button) { if (button == GLFW_MOUSE_BUTTON_LEFT) lbutton = true; }
void PathTracerApplication::mouseRelease(const int32_t& button) { if (button == GLFW_MOUSE_BUTTON_LEFT) lbutton = false; }
void PathTracerApplication::mouseMove(const double& x, const double& y) { mousepos.x = x, mousepos.y = y; }
// resize buffers and canvas functions
void PathTracerApplication::resizeBuffers(const int32_t& width, const int32_t& height) { rays->resizeBuffers(width, height); }
void PathTracerApplication::resize(const int32_t& width, const int32_t& height) { rays->resize(width, height); }
// processing
void PathTracerApplication::process() {
double t = glfwGetTime() * 1000.f;
diff = t - time;
time = t;
// switch to 360 degree view
cam->work(mousepos, diff, lbutton, keys);
if (switch360key) {
rays->switchMode();
switch360key = false;
}
// initial transform
glm::dmat4 matrix(1.0);
matrix *= glm::scale(glm::dvec3(mscale));
// clear BVH and load materials
intersector->clearTribuffer();
materialManager->loadToVGA();
#ifdef EXPERIMENTAL_GLTF
// load meshes
std::function<void(tinygltf::Node &, glm::dmat4, int)> traverse = [&](tinygltf::Node & node, glm::dmat4 inTransform, int recursive)->void {
glm::dmat4 localTransform(1.0);
localTransform *= (node.matrix.size() >= 16 ? glm::make_mat4(node.matrix.data()) : glm::dmat4(1.0));
localTransform *= (node.translation.size() >= 3 ? glm::translate(glm::make_vec3(node.translation.data())) : glm::dmat4(1.0));
localTransform *= (node.scale.size() >= 3 ? glm::scale(glm::make_vec3(node.scale.data())) : glm::dmat4(1.0));
localTransform *= (node.rotation.size() >= 4 ? glm::mat4_cast(glm::make_quat(node.rotation.data())) : glm::dmat4(1.0));
glm::dmat4 transform = inTransform * localTransform;
if (node.mesh >= 0) {
std::vector<ppr::VertexInstance *>& mesh = meshVec[node.mesh]; // load mesh object (it just vector of primitives)
for (int p = 0; p < mesh.size(); p++) { // load every primitive
ppr::VertexInstance * geom = mesh[p];
geom->setTransform(transform);
intersector->loadMesh(geom);
}
}
else
if (node.children.size() > 0) {
for (int n = 0; n < node.children.size(); n++) {
if (recursive >= 0) traverse(gltfModel.nodes[node.children[n]], transform, recursive-1);
}
}
};
// load scene
uint32_t sceneID = 0;
if (gltfModel.scenes.size() > 0) {
for (int n = 0; n < gltfModel.scenes[sceneID].nodes.size(); n++) {
tinygltf::Node & node = gltfModel.nodes[gltfModel.scenes[sceneID].nodes[n]];
traverse(node, glm::dmat4(matrix), 2);
}
}
#endif
// build BVH in device
intersector->build(matrix);
// process ray tracing
rays->camera(cam->eye, cam->view);
for (int32_t j = 0;j < depth;j++) {
if (rays->getRayCount() <= 0) break;
rays->intersection(intersector);
rays->applyMaterials(materialManager); // low level function for getting surface materials (may have few materials)
rays->shade(); // low level function for change rays
rays->reclaim();
}
rays->sample();
rays->render();
}
}
PaperExample::PathTracerApplication * app;
static void error_callback(int32_t error, const char* description){
std::cerr << ("Error: \n" + std::string(description)) << std::endl;
}
static void key_callback(GLFWwindow* window, int32_t key, int32_t scancode, int32_t action, int32_t mods){
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GLFW_TRUE);
if (action == GLFW_PRESS) app->passKeyDown(key);
if (action == GLFW_RELEASE) app->passKeyRelease(key);
}
static void mouse_callback(GLFWwindow* window, int32_t button, int32_t action, int32_t mods){
if (action == GLFW_PRESS) app->mousePress(button);
if (action == GLFW_RELEASE) app->mouseRelease(button);
}
static void mouse_move_callback(GLFWwindow* window, double x, double y){
app->mouseMove(x, y);
}
int main(const int argc, const char ** argv)
{
glfwSetErrorCallback(error_callback);
if (!glfwInit()) exit(EXIT_FAILURE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
#ifdef USE_OPENGL_45_COMPATIBLE
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
#else
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
#endif
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_CONTEXT_NO_ERROR, GLFW_TRUE);
// planks
// great around 30 (or higher) FPS
// fine around 15 FPS
// "may works" around 5-10 FPS
// GPU rating (by increment)
// GTX 1060
// GTX 1070
// VEGA 56
// VEGA 64 (nearly same line GTX 1080)
// GTX 1080 Ti
// Titan Xp
const double measureSeconds = 2.0;
const double superSampling = 2.0; // IT SHOULD! Should be double resolution!
// VEGA 64 should work fine without interlacing, for VEGA 56 will harder, GTX 1080 Ti should work great, GTX 1070 should also work great with interlacing
int32_t baseWidth = 640;
int32_t baseHeight = 360;
// GTX 1070 should work fine without interlacing, VEGA 64 should work great, GTX 1060 with interlacing also should work great
//int32_t baseWidth = 400;
//int32_t baseHeight = 300;
// VEGA 64 (with interlacing) should work fine, GTX 1080 Ti may works without interlacing
//int32_t baseWidth = 960;
//int32_t baseHeight = 540;
// VEGA 56 test with or without interlacing (or GTX 1070 with interlacing), from VEGA 56 with interlacing should work fine, GTX 1080 Ti should work fine without interlacing in some cases
//int32_t baseWidth = 800;
//int32_t baseHeight = 450;
// GTX 1080 Ti should work fine with interlacing (1440p)
//int32_t baseWidth = 1280;
//int32_t baseHeight = 640;
GLFWwindow* window = glfwCreateWindow(baseWidth, baseHeight, "Simple example", NULL, NULL);
if (!window) { glfwTerminate(); exit(EXIT_FAILURE); }
#ifdef _WIN32 //Windows DPI scaling
HWND win = glfwGetWin32Window(window);
int32_t baseDPI = 96;
int32_t dpi = baseDPI;
#else //Other not supported
int32_t baseDPI = 96;
int32_t dpi = 96;
#endif
// DPI scaling for Windows
#if (defined MSVC && defined _WIN32)
dpi = GetDpiForWindow(win);
int32_t canvasWidth = baseWidth * ((double)dpi / (double)baseDPI);
int32_t canvasHeight = baseHeight * ((double)dpi / (double)baseDPI);
#else
int32_t canvasWidth = baseWidth;
int32_t canvasHeight = baseHeight;
glfwGetFramebufferSize(window, &canvasWidth, &canvasHeight);
dpi = double(baseDPI) * (double(canvasWidth) / double(baseWidth));
#endif
glfwMakeContextCurrent(window);
glfwSwapInterval(0);
if (glewInit() != GLEW_OK) glfwTerminate();
app = new PaperExample::PathTracerApplication(argc, argv, window);
app->resizeBuffers(int(double(baseWidth) * double(superSampling)), int(double(baseHeight) * double(superSampling)));
app->resize(canvasWidth, canvasHeight);
glfwSetKeyCallback(window, key_callback);
glfwSetMouseButtonCallback(window, mouse_callback);
glfwSetCursorPosCallback(window, mouse_move_callback);
glfwSetWindowSize(window, canvasWidth, canvasHeight);
double lastTime = glfwGetTime();
double prevFrameTime = lastTime;
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
int32_t oldWidth = canvasWidth, oldHeight = canvasHeight, oldDPI = dpi;
glfwGetFramebufferSize(window, &canvasWidth, &canvasHeight);
// DPI scaling for Windows
#if (defined MSVC && defined _WIN32)
dpi = GetDpiForWindow(win);
#else
{
glfwGetWindowSize(window, &baseWidth, &baseHeight);
dpi = double(baseDPI) * (double(canvasWidth) / double(baseWidth));
}
#endif
// scale window by DPI
double ratio = double(dpi) / double(baseDPI);
if (oldDPI != dpi) {
canvasWidth = baseWidth * ratio;
canvasHeight = baseHeight * ratio;
glfwSetWindowSize(window, canvasWidth, canvasHeight);
}
// scale canvas
if (oldWidth != canvasWidth || oldHeight != canvasHeight) {
// set new base size
baseWidth = canvasWidth / ratio;
baseHeight = canvasHeight / ratio;
// resize canvas
app->resize(canvasWidth, canvasHeight);
}
// do ray tracing
app->process();
// Measure speed
double currentTime = glfwGetTime();
if (currentTime - lastTime >= measureSeconds) {
std::cout << "FPS: " << 1.f / (currentTime - prevFrameTime) << std::endl;
lastTime += measureSeconds;
}
prevFrameTime = currentTime;
glfwSwapBuffers(window);
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
<file_sep>#include "MaterialSet.hpp"
namespace ppr {
inline void MaterialSet::init(){
glCreateBuffers(1, &mats);
}
inline void MaterialSet::loadToVGA() {
glNamedBufferData(mats, strided<VirtualMaterial>(submats.size()), submats.data(), GL_STATIC_DRAW);
if (texset) texset->loadToVGA(); // load texture descriptors to VGA
}
inline void MaterialSet::bindWithContext(GLuint & prog) {
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 15, mats);
if (texset) texset->bindWithContext(prog); // use texture set
}
}
<file_sep>#include "SceneObject.hpp"
namespace ppr {
inline void SceneObject::initShaders() {
initShaderComputeSPIRV("./shaders-spv/hlbvh/refit.comp.spv", refitProgramH);
//initShaderComputeSPIRV("./shaders-spv/hlbvh/refit-new.comp.spv", refitProgramH);
initShaderComputeSPIRV("./shaders-spv/hlbvh/build.comp.spv", buildProgramH);
initShaderComputeSPIRV("./shaders-spv/hlbvh/aabbmaker.comp.spv", aabbMakerProgramH);
initShaderComputeSPIRV("./shaders-spv/hlbvh/minmax.comp.spv", minmaxProgram2);
initShaderComputeSPIRV("./shaders-spv/vertex/loader.comp.spv", geometryLoaderProgram2);
initShaderComputeSPIRV("./shaders-spv/vertex/loader-int16.comp.spv", geometryLoaderProgramI16);
}
inline void SceneObject::init() {
initShaders();
sorter = new RadixSort();
minmaxBufRef = allocateBuffer<bbox>(1);
minmaxBuf = allocateBuffer<bbox>(1);
lscounterTemp = allocateBuffer<uint32_t>(1);
tcounter = allocateBuffer<uint32_t>(1);
geometryBlockUniform = allocateBuffer<GeometryBlockUniform>(1);
bbox bound;
bound.mn.x = 100000.f;
bound.mn.y = 100000.f;
bound.mn.z = 100000.f;
bound.mn.w = 100000.f;
bound.mx.x = -100000.f;
bound.mx.y = -100000.f;
bound.mx.z = -100000.f;
bound.mx.w = -100000.f;
glNamedBufferSubData(lscounterTemp, 0, strided<int32_t>(1), zero);
glNamedBufferSubData(minmaxBuf, 0, strided<bbox>(1), &bound);
glNamedBufferSubData(minmaxBufRef, 0, strided<bbox>(1), &bound);
}
inline void SceneObject::allocate(const size_t &count) {
maxt = count * 2;
size_t height = std::min(maxt > 0 ? (maxt - 1) / 2047 + 1 : 0, 2047u) + 1;
vbo_vertex_textrue = allocateTexture2D<GL_RGBA32F>(6144, height);
vbo_normal_textrue = allocateTexture2D<GL_RGBA32F>(6144, height);
vbo_texcoords_textrue = allocateTexture2D<GL_RGBA32F>(6144, height);
vbo_modifiers_textrue = allocateTexture2D<GL_RGBA32F>(6144, height);
vbo_vertex_textrue_upload = allocateTexture2D<GL_RGBA32F>(6144, height);
vbo_normal_textrue_upload = allocateTexture2D<GL_RGBA32F>(6144, height);
vbo_texcoords_textrue_upload = allocateTexture2D<GL_RGBA32F>(6144, height);
vbo_modifiers_textrue_upload = allocateTexture2D<GL_RGBA32F>(6144, height);
glCreateSamplers(1, &vbo_sampler);
glSamplerParameteri(vbo_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glSamplerParameteri(vbo_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glSamplerParameteri(vbo_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glSamplerParameteri(vbo_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
mat_triangle_ssbo = allocateBuffer<int32_t>(maxt);
mat_triangle_ssbo_upload = allocateBuffer<int32_t>(maxt);
aabbCounter = allocateBuffer<int32_t>(1);
bvhnodesBuffer = allocateBuffer<HlbvhNode>(maxt * 2);
bvhflagsBuffer = allocateBuffer<uint32_t>(maxt * 2);
activeBuffer = allocateBuffer<uint32_t>(maxt * 2);
mortonBuffer = allocateBuffer<uint64_t>(maxt * 1);
mortonBufferIndex = allocateBuffer<uint32_t>(maxt * 1);
leafBuffer = allocateBuffer<HlbvhNode>(maxt * 1);
childBuffer = allocateBuffer<HlbvhNode>(maxt * 1);
clearTribuffer();
}
inline void SceneObject::syncUniforms() {
geometryBlockData.geometryUniform = geometryUniformData;
glNamedBufferSubData(geometryBlockUniform, 0, strided<GeometryBlockUniform>(1), &geometryBlockData);
this->bindUniforms();
}
inline void SceneObject::setMaterialID(int32_t id) {
materialID = id;
}
inline void SceneObject::bindUniforms() {
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 14, geometryBlockUniform);
}
inline void SceneObject::bind() {
// mosaic buffers for write
glBindImageTexture(0, vbo_vertex_textrue_upload, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);
glBindImageTexture(1, vbo_normal_textrue_upload, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);
glBindImageTexture(2, vbo_texcoords_textrue_upload, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);
glBindImageTexture(3, vbo_modifiers_textrue_upload, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);
// use mosaic sampler
glBindSampler(0, vbo_sampler);
glBindSampler(1, vbo_sampler);
glBindSampler(2, vbo_sampler);
glBindSampler(3, vbo_sampler);
// mosaic buffer
glBindTextureUnit(0, vbo_vertex_textrue);
glBindTextureUnit(1, vbo_normal_textrue);
glBindTextureUnit(2, vbo_texcoords_textrue);
glBindTextureUnit(3, vbo_modifiers_textrue);
// material SSBO
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 10, mat_triangle_ssbo);
}
inline void SceneObject::bindLeafs() {
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 17, leafBuffer);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 18, mortonBufferIndex);
}
inline void SceneObject::bindBVH() {
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 9, bvhnodesBuffer);
}
inline void SceneObject::clearTribuffer() {
markDirty();
glCopyNamedBufferSubData(minmaxBufRef, minmaxBuf, 0, 0, strided<bbox>(1));
glCopyNamedBufferSubData(lscounterTemp, tcounter, 0, 0, strided<uint32_t>(1));
geometryUniformData.triangleOffset = 0;
}
inline void SceneObject::configureIntersection(bool clearDepth) {
this->geometryUniformData.clearDepth = clearDepth;
this->syncUniforms();
}
inline void SceneObject::loadMesh(VertexInstance * gobject) {
if (!gobject || gobject->meshUniformData.nodeCount <= 0) return;
glCopyNamedBufferSubData(tcounter, gobject->meshUniformBuffer, 0, offsetof(MeshUniformStruct, storingOffset), sizeof(uint32_t));
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, tcounter);
this->bind();
gobject->bind();
if (gobject->accessorSet) gobject->accessorSet->bind();
if (gobject->bufferViewSet) gobject->bufferViewSet->bind();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 10, mat_triangle_ssbo_upload);
dispatchIndirect(gobject->index16bit ? geometryLoaderProgramI16 : geometryLoaderProgram2, gobject->indirect_dispatch_buffer);
markDirty();
glUseProgram(0);
}
inline bool SceneObject::isDirty() const {
return dirty;
}
inline void SceneObject::markDirty() {
dirty = true;
}
inline void SceneObject::resolve() {
dirty = false;
}
inline void SceneObject::build(const glm::dmat4 &optimization) {
// get triangle count that uploaded
glGetNamedBufferSubData(tcounter, 0, strided<uint32_t>(1), &this->triangleCount);
size_t triangleCount = std::min(uint32_t(this->triangleCount), uint32_t(maxt));
geometryUniformData.triangleCount = triangleCount;
// validate
if (this->triangleCount <= 0 || !dirty) return;
// copy uploading buffers to BVH
size_t maxHeight = std::min(maxt > 0 ? (maxt - 1) / 2047 + 1 : 0, 2047u) + 1;
size_t height = std::min(triangleCount > 0 ? (triangleCount - 1) / 2047 + 1 : 0, maxHeight) + 1;
glCopyImageSubData(vbo_vertex_textrue_upload, GL_TEXTURE_2D, 0, 0, 0, 0, vbo_vertex_textrue, GL_TEXTURE_2D, 0, 0, 0, 0, 6144, height, 1);
glCopyImageSubData(vbo_normal_textrue_upload, GL_TEXTURE_2D, 0, 0, 0, 0, vbo_normal_textrue, GL_TEXTURE_2D, 0, 0, 0, 0, 6144, height, 1);
glCopyImageSubData(vbo_texcoords_textrue_upload, GL_TEXTURE_2D, 0, 0, 0, 0, vbo_texcoords_textrue, GL_TEXTURE_2D, 0, 0, 0, 0, 6144, height, 1);
glCopyImageSubData(vbo_modifiers_textrue_upload, GL_TEXTURE_2D, 0, 0, 0, 0, vbo_modifiers_textrue, GL_TEXTURE_2D, 0, 0, 0, 0, 6144, height, 1);
glCopyNamedBufferSubData(mat_triangle_ssbo_upload, mat_triangle_ssbo, 0, 0, std::min(uint32_t(this->triangleCount), uint32_t(maxt)) * sizeof(uint32_t));
// use optimization matrix
glCopyNamedBufferSubData(minmaxBufRef, minmaxBuf, 0, 0, strided<bbox>(1));
{
glm::dmat4 mat(1.0);
mat *= glm::inverse(optimization);
geometryUniformData.transform = *(Vc4x4 *)glm::value_ptr(glm::transpose(glm::mat4(mat)));
geometryUniformData.transformInv = *(Vc4x4 *)glm::value_ptr(glm::transpose(glm::inverse(glm::mat4(mat))));
}
// get bounding box of scene
this->syncUniforms();
this->bind();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, minmaxBuf);
dispatch(minmaxProgram2, 1);
// getting boundings
bbox bound;
glGetNamedBufferSubData(minmaxBuf, 0, strided<bbox>(1), &bound);
scale = (glm::make_vec4((float *)&bound.mx) - glm::make_vec4((float *)&bound.mn)).xyz();
offset = glm::make_vec4((float *)&bound.mn).xyz();
// fit BVH to boundings
{
glm::dmat4 mat(1.0);
mat *= glm::inverse(glm::translate(glm::dvec3(offset)) * glm::scale(glm::dvec3(scale)));
mat *= glm::inverse(glm::dmat4(optimization));
geometryUniformData.transform = *(Vc4x4 *)glm::value_ptr(glm::transpose(glm::mat4(mat)));
geometryUniformData.transformInv = *(Vc4x4 *)glm::value_ptr(glm::transpose(glm::inverse(glm::mat4(mat))));
}
// bind buffers
glCopyNamedBufferSubData(lscounterTemp, aabbCounter, 0, 0, strided<uint32_t>(1));
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, mortonBuffer);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, mortonBufferIndex);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, aabbCounter);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, leafBuffer);
// get nodes morton codes and boundings
this->bind();
this->syncUniforms();
dispatch(aabbMakerProgramH, tiled(triangleCount, worksize));
glGetNamedBufferSubData(aabbCounter, 0, strided<uint32_t>(1), &triangleCount);
if (triangleCount <= 0) return;
// radix sort of morton-codes
sorter->sort(mortonBuffer, mortonBufferIndex, triangleCount); // early serial tests
geometryUniformData.triangleCount = triangleCount;
// debug
//std::vector<GLuint64> mortons(triangleCount);
//glGetNamedBufferSubData(mortonBuffer, 0, strided<GLuint64>(mortons.size()), mortons.data());
// bind BVH buffers
this->syncUniforms();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, bvhnodesBuffer);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 5, bvhflagsBuffer);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 6, activeBuffer);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 7, childBuffer);
// build BVH itself
dispatch(buildProgramH, 1);
dispatch(refitProgramH, 1);
//dispatch(refitProgramH, tiled(triangleCount, 1024));
// set back triangle count
this->geometryUniformData.triangleCount = this->triangleCount;
this->syncUniforms();
this->resolve();
}
}
<file_sep>#pragma once
#include "Utils.hpp"
namespace ppr {
typedef float Vc1;
typedef int32_t iVc1;
struct Vc2 {
float x;
float y;
};
struct Vc3 {
float x;
float y;
float z;
};
struct Vc4 {
float x;
float y;
float z;
float w;
};
struct Vc4x4 {
Vc4 m0;
Vc4 m1;
Vc4 m2;
Vc4 m3;
};
struct iVc2 {
int32_t x;
int32_t y;
};
struct iVc3 {
int32_t x;
int32_t y;
int32_t z;
};
struct iVc4 {
int32_t x;
int32_t y;
int32_t z;
int32_t w;
};
const Vc4x4 mat4r = {
{ 1.0f, 0.0f, 0.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 0.0f, 1.0f },
};
const Vc4 vec4r = { 0.0f, 0.0f, 0.0f, 0.0f };
const iVc4 ivec4r = { 0, 0, 0, 0 };
struct Minmax {
Vc4 mn;
Vc4 mx;
};
struct Minmaxi {
iVc4 mn;
iVc4 mx;
};
//typedef Minmax bbox;
struct bbox {
glm::vec4 mn;
glm::vec4 mx;
};
struct Ray {
glm::vec4 origin;
glm::vec4 direct;
glm::vec4 color;
glm::vec4 final;
int bitfield; // up to 32-bits
int idx; // ray index itself
int texel; // texel index
int hit; // index of hit chain
};
struct Hit {
glm::vec4 uvt; // UV, distance, triangle
glm::vec4 normalHeight; // normal with height mapping, will already interpolated with geometry
glm::vec4 tangent; // also have 4th extra slot
glm::vec4 texcoord;
// low four 16 bit - texcoords
glm::uvec4 metallicRoughness; // four 16-bit float
// color parameters
glm::uvec4 emission_albedo;
//glm::vec4 emission;
//glm::vec4 albedo;
// integer metadata
int bitfield;
int ray; // ray index
int materialID;
int next;
};
struct Texel {
Vc4 coord;
Vc4 last3d;
iVc4 EXT;
};
struct HlbvhNode {
bbox box;
iVc4 pdata;
};
struct VboDataStride {
Vc4 vertex;
Vc4 normal;
Vc4 texcoord;
Vc4 color;
Vc4 modifiers;
};
struct ColorChain {
Vc4 color = {0.0f, 0.0f, 0.0f, 0.0f};
iVc4 cdata = {0, 0, 0, 0};
};
struct MaterialUniformStruct {
iVc1 materialID;
iVc1 _reserved;
iVc1 time;
iVc1 lightcount;
Vc4 backgroundColor = vec4r; // for skybox configure
iVc4 iModifiers0 = ivec4r;
iVc4 iModifiers1 = ivec4r;
Vc4 fModifiers0 = vec4r;
Vc4 fModifiers1 = vec4r;
Vc4x4 transformModifier = mat4r;
};
struct SamplerUniformStruct {
Vc2 sceneRes;
iVc1 samplecount;
iVc1 rayCount;
iVc1 iteration;
iVc1 phase;
iVc1 hitCount;
iVc1 reserved0;
iVc1 reserved1;
iVc1 currentRayLimit;
iVc2 padding;
};
struct LightUniformStruct {
Vc4 lightVector;
Vc4 lightColor;
Vc4 lightOffset;
Vc4 lightAmbient;
};
struct GeometryUniformStruct {
Vc4x4 transform = mat4r;
Vc4x4 transformInv = mat4r;
iVc1 materialID = 0;
iVc1 triangleCount = 1;
iVc1 triangleOffset = 0;
iVc1 clearDepth = 0;
};
struct CameraUniformStruct {
Vc4x4 projInv = mat4r;
Vc4x4 camInv = mat4r;
Vc4x4 prevCamInv = mat4r;
Vc1 prob;
iVc1 enable360;
iVc1 interlace;
iVc1 interlaceStage;
};
struct GeometryBlockUniform {
GeometryUniformStruct geometryUniform = GeometryUniformStruct();
};
struct RayBlockUniform {
SamplerUniformStruct samplerUniform = SamplerUniformStruct();
CameraUniformStruct cameraUniform = CameraUniformStruct();
MaterialUniformStruct materialUniform = MaterialUniformStruct();
};
struct MeshUniformStruct {
GLint vertexAccessor = -1;
GLint normalAccessor = -1;
GLint texcoordAccessor = -1;
GLint modifierAccessor = -1;
glm::mat4 transform;
glm::mat4 transformInv;
GLint materialID = 0;
GLint isIndexed = 0;
GLint nodeCount = 1;
GLint primitiveType = 0;
GLint loadingOffset = 0;
GLint storingOffset = 0;
GLint _reserved0 = 1;
GLint _reserved1 = 2;
};
struct VirtualBufferView {
GLint offset4 = 0;
GLint stride4 = 1;
};
struct VirtualAccessor {
GLint offset4 = 0;
GLint components : 2, type : 4, normalized : 1;
GLint bufferView = -1;
};
struct VirtualMaterial {
glm::vec4 diffuse = glm::vec4(0.0f);
glm::vec4 specular = glm::vec4(0.0f);
glm::vec4 transmission = glm::vec4(0.0f);
glm::vec4 emissive = glm::vec4(0.0f);
float ior = 1.0f;
float roughness = 0.0001f;
float alpharef = 0.0f;
float unk0f = 0.0f;
uint32_t diffusePart = 0;
uint32_t specularPart = 0;
uint32_t bumpPart = 0;
uint32_t emissivePart = 0;
int32_t flags = 0;
int32_t alphafunc = 0;
int32_t binding = 0;
int32_t unk0i = 0;
glm::ivec4 iModifiers0 = glm::ivec4(0);
};
struct GroupFoundResult {
int nextResult = -1;
float boxDistance = 100000.f;
glm::ivec2 range;
};
}<file_sep># OpenGL Ray Tracer (aka. "Prismarine")
## Updates
See `Projects`.
## Screenshots
<details>
<summary>9/3/2017 (1280x720)</summary>
<img src="Screenshots/dms1.png" width="640"/>
</details>
## Details
- Here is headers-only (at this moment) ray tracer. May used for other projects. Main framework in shaders.
## Features:
- CMake support (Windows)
- Fixed most bugs
- GPU optimized BVH (HLBVH)
- Direct light for sun
- Modern OpenGL based
- Support NVidia GTX 1070 and newer
- Optimized for performance
- Open source (at now)
## Requirement
- OpenGL 4.6 with extensions :)
- Latest CMake
## Building
- Run CMAKE and configure project (probably, available only for Windows)
- Also, you need [shaderc](https://github.com/google/shaderc) for preprocess shaders (also can be found with Vulkan SDK)
## Running and testing
Basic render application:
```
${ApplicationName}.exe -m sponza.obj -s 1.0
-m model_name.obj - loading 3D model to view (planned multiply models and animation support)
-s 1.0 - scaling of 3D model
```
## Contributors
- ???
## Leaders
- <NAME> (<EMAIL>)
## Inspired by
- [RadeonRays SDK](https://github.com/GPUOpen-LibrariesAndSDKs/RadeonRays_SDK)
- [WebGL Path Tracing by evanw (and forks)](https://github.com/evanw/webgl-path-tracing)
- [GPU Path Tracer by peterkutz](https://github.com/peterkutz/GPUPathTracer)
- [Something from Shadertoy](https://www.shadertoy.com/)
- [Radix Sort by CiNoNim](https://github.com/cNoNim/radix-sort)
- Other functions and modifications from few resources
<file_sep>#pragma once
#include "Utils.hpp"
#include "Structs.hpp"
#include "SceneObject.hpp"
#include "MaterialSet.hpp"
namespace ppr {
class Dispatcher : public BaseClass {
private:
RadixSort * sorter = nullptr;
GLuint skybox = -1;
GLuint renderProgram = -1;
GLuint surfProgram = -1;
GLuint matProgram = -1;
GLuint reclaimProgram = -1;
GLuint cameraProgram = -1;
GLuint clearProgram = -1;
GLuint samplerProgram = -1;
GLuint traverseProgram = -1;
GLuint resolverProgram = -1;
GLuint traverseDirectProgram = -1;
GLuint filterProgram = -1;
GLuint deinterlaceProgram = -1;
GLuint colorchains = -1;
GLuint quantized = -1;
GLuint rays = -1;
GLuint hits = -1;
GLuint texels = -1;
GLuint activenl = -1;
GLuint activel = -1;
GLuint freedoms = -1;
GLuint availables = -1;
GLuint arcounter = -1;
GLuint arcounterTemp = -1;
GLuint hitChains = -1;
GLuint deferredStack = -1;
GLuint lightUniform = -1;
GLuint rayBlockUniform = -1;
RayBlockUniform rayBlockData;
size_t framenum = 0;
int32_t currentSample = 0;
int32_t maxSamples = 4;
int32_t maxFilters = 1;
int32_t currentRayLimit = 0;
int32_t worksize = 128;
// position texture
GLuint positionimg = -1;
GLuint prevsampled = -1;
GLuint presampled = -1;
GLuint reprojected = -1;
GLuint sampleflags = -1;
GLuint filtered = -1;
GLuint vao = -1;
GLuint posBuf = -1;
GLuint idcBuf = -1;
void initShaders();
void initVAO();
void init();
MaterialUniformStruct materialUniformData;
SamplerUniformStruct samplerUniformData;
CameraUniformStruct cameraUniformData;
GLuint resultCounters = -1;
GLuint resultFounds = -1;
GLuint givenRays = -1;
public:
Dispatcher() { init(); }
~Dispatcher() {
glDeleteProgram(renderProgram);
glDeleteProgram(matProgram);
glDeleteProgram(reclaimProgram);
glDeleteProgram(cameraProgram);
glDeleteProgram(clearProgram);
glDeleteProgram(samplerProgram);
glDeleteProgram(traverseProgram);
glDeleteProgram(resolverProgram);
glDeleteProgram(surfProgram);
glDeleteProgram(filterProgram);
glDeleteBuffers(1, &colorchains);
glDeleteBuffers(1, &quantized);
glDeleteBuffers(1, &rays);
glDeleteBuffers(1, &hits);
glDeleteBuffers(1, &texels);
glDeleteBuffers(1, &activenl);
glDeleteBuffers(1, &activel);
glDeleteBuffers(1, &freedoms);
glDeleteBuffers(1, &availables);
glDeleteBuffers(1, &arcounter);
glDeleteBuffers(1, &arcounterTemp);
glDeleteBuffers(1, &lightUniform);
glDeleteBuffers(1, &rayBlockUniform);
glDeleteTextures(1, &presampled);
glDeleteTextures(1, &sampleflags);
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &posBuf);
glDeleteBuffers(1, &idcBuf);
}
uint32_t width = 256;
uint32_t height = 256;
uint32_t displayWidth = 256;
uint32_t displayHeight = 256;
void setSkybox(GLuint skb) {
skybox = skb;
}
void switchMode();
void resize(const uint32_t & w, const uint32_t & h);
void resizeBuffers(const uint32_t & w, const uint32_t & h);
void syncUniforms();
void reloadQueuedRays(bool doSort = false, bool sortMortons = false);
LightUniformStruct * lightUniformData;
int32_t raycountCache = 0;
int32_t qraycountCache = 0;
glm::vec4 lightColor[6];
glm::vec4 lightAmbient[6];
glm::vec4 lightVector[6];
glm::vec4 lightOffset[6];
struct HdrImage {
GLfloat * image = nullptr;
int width = 1;
int height = 1;
};
HdrImage snapHdr();
HdrImage snapRawHdr();
void setLightCount(size_t lightcount);
void bindUniforms();
void bind();
void clearRays();
void sample();
void camera(const glm::mat4 &persp, const glm::mat4 &frontSide);
void camera(const glm::vec3 &eye, const glm::vec3 &view, const glm::mat4 &persp);
void camera(const glm::vec3 &eye, const glm::vec3 &view);
void clearSampler();
void reclaim();
void render();
int intersection(SceneObject * obj, const int clearDepth = 0);
void shade();
void applyMaterials(MaterialSet * mat);
int32_t getRayCount();
};
}
#include "./Dispatcher.inl"<file_sep>cmake_minimum_required (VERSION 3.0)
set (PROJECT_NAME prismarine-examples)
set (APPLICATION_NAME prismarine-gltf)
option(USE_OPENGL_45_COMPATIBLE "Enabling OpenGL 4.5 Compatibility (early AMD OpenGL 4.5)" OFF)
project (${PROJECT_NAME})
if (COMPILER_ID MATCHES "MSVC")
set(MSVC_${lang}_ARCHITECTURE_ID "${ARCHITECTURE_ID}")
endif()
set(SOURCES_LIST
#include
"./External/include/*/*.hpp"
"./External/include/*/*.hh"
"./External/include/*/*.h"
"./External/include/*.hpp"
"./External/include/*.hh"
"./External/include/*.h"
#ray-tracer
"./Include/Prismarine/*.hpp"
"./Include/Prismarine/*.inl"
#shaders
"./ShadersSDK/include/*.*"
"./ShadersSDK/render/*.*"
"./ShadersSDK/hlbvh/*.*"
"./ShadersSDK/tools/*.*"
)
set (DEFINES
-DNOMINMAX
-DGLM_FORCE_SWIZZLE
-DGLM_ENABLE_EXPERIMENTAL
-DGLFW_INCLUDE_NONE
-DUSE_FREEIMAGE
-DEXPERIMENTAL_GLTF
-DTINYGLTF_IMPLEMENTATION
-DSTB_IMAGE_IMPLEMENTATION
)
if(USE_OPENGL_45_COMPATIBLE)
set (DEFINES ${DEFINES} -DUSE_OPENGL_45_COMPATIBLE)
endif()
set (DEP_DIR "${PROJECT_SOURCE_DIR}")
set (LIB_DIR "${DEP_DIR}/External/lib" "${DEP_DIR}/lib" "${CMAKE_MODULE_PATH}/lib" "${DEP_DIR}/External/lib/bullet")
set (INC_DIR "${DEP_DIR}/External/include" "${DEP_DIR}/include" "${CMAKE_MODULE_PATH}/include" "${DEP_DIR}/External/include/bullet" "${PROJECT_SOURCE_DIR}")
set (CMAKE_MODULE_PATH
"${DEP_DIR}/modules"
"${CMAKE_MODULE_PATH}/modules"
"${PROJECT_SOURCE_DIR}/modules/" )
find_package(OpenGL REQUIRED)
set (LIBS
${OPENGL_LIBRARIES}
glfw3
glew32
FreeImage
)
set (CMAKE_CXX_STANDARD_REQUIRED ON)
set (CMAKE_CXX_STANDARD 17)
set (CMAKE_CXX_EXTENSIONS ON)
if(MSVC)
set (CMAKE_CXX_FLAGS "/EHsc /MD /std:c++17 -DMSVC")
set (CMAKE_C_FLAGS "/EHsc")
else()
set (CMAKE_CXX_FLAGS "-std=c++17")
set (CMAKE_C_FLAGS "")
endif()
set (INCLUDE_LIST
${INC_DIR}
${OPENGL_INCLUDE_DIR}
)
add_definitions(${DEFINES})
link_directories(${LIB_DIR})
include_directories(${INCLUDE_LIST})
file (GLOB RSOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${SOURCES_LIST})
add_executable(${APPLICATION_NAME} Source/Examples/Viewer.cpp ${RSOURCES})
target_link_libraries(${APPLICATION_NAME} ${LIBS})
foreach(source IN LISTS RSOURCES)
get_filename_component(source_path "${source}" PATH)
string(REPLACE "/" "\\" source_path_msvc "${source_path}")
source_group("${source_path_msvc}" FILES "${source}")
endforeach()
set (LIBS
${OPENGL_LIBRARIES}
glfw3
glew32
FreeImage
LinearMath_RelWithDebugInfo
Bullet3Common_RelWithDebugInfo
Bullet3Dynamics_RelWithDebugInfo
Bullet3Collision_RelWithDebugInfo
BulletCollision_RelWithDebugInfo
BulletDynamics_RelWithDebugInfo
BulletInverseDynamics_RelWithDebugInfo
BulletSoftBody_RelWithDebugInfo
)
set (APPLICATION_NAME prismarine-physics)
add_executable(${APPLICATION_NAME} Source/Examples/Physics.cpp ${RSOURCES})
target_link_libraries(${APPLICATION_NAME} ${LIBS})
foreach(source IN LISTS RSOURCES)
get_filename_component(source_path "${source}" PATH)
string(REPLACE "/" "\\" source_path_msvc "${source_path}")
source_group("${source_path_msvc}" FILES "${source}")
endforeach()
set (APPLICATION_NAME prismarine-go)
add_executable(${APPLICATION_NAME} Source/Examples/Go.cpp ${RSOURCES})
target_link_libraries(${APPLICATION_NAME} ${LIBS})
foreach(source IN LISTS RSOURCES)
get_filename_component(source_path "${source}" PATH)
string(REPLACE "/" "\\" source_path_msvc "${source_path}")
source_group("${source_path_msvc}" FILES "${source}")
endforeach()
<file_sep>#include "Dispatcher.hpp"
namespace ppr {
inline void Dispatcher::initShaders() {
initShaderComputeSPIRV("./shaders-spv/raytracing/surface.comp.spv", surfProgram);
initShaderComputeSPIRV("./shaders-spv/raytracing/testmat.comp.spv", matProgram);
initShaderComputeSPIRV("./shaders-spv/raytracing/reclaim.comp.spv", reclaimProgram);
initShaderComputeSPIRV("./shaders-spv/raytracing/camera.comp.spv", cameraProgram);
initShaderComputeSPIRV("./shaders-spv/raytracing/clear.comp.spv", clearProgram);
initShaderComputeSPIRV("./shaders-spv/raytracing/sampler.comp.spv", samplerProgram);
initShaderComputeSPIRV("./shaders-spv/raytracing/filter.comp.spv", filterProgram);
initShaderComputeSPIRV("./shaders-spv/raytracing/directTraverse.comp.spv", traverseDirectProgram);
initShaderComputeSPIRV("./shaders-spv/raytracing/deinterlace.comp.spv", deinterlaceProgram);
{
renderProgram = glCreateProgram();
glAttachShader(renderProgram, loadShaderSPIRV("./shaders-spv/raytracing/render.vert.spv", GL_VERTEX_SHADER));
glAttachShader(renderProgram, loadShaderSPIRV("./shaders-spv/raytracing/render.frag.spv", GL_FRAGMENT_SHADER));
glLinkProgram(renderProgram);
validateProgram(renderProgram);
}
}
inline void Dispatcher::initVAO() {
Vc2 arr[4] = { { -1.0f, -1.0f },{ 1.0f, -1.0f },{ -1.0f, 1.0f },{ 1.0f, 1.0f } };
glCreateBuffers(1, &posBuf);
glNamedBufferData(posBuf, strided<Vc2>(4), arr, GL_STATIC_DRAW);
uint32_t idc[6] = { 0, 1, 2, 3, 2, 1 };
glCreateBuffers(1, &idcBuf);
glNamedBufferData(idcBuf, strided<uint32_t>(6), idc, GL_STATIC_DRAW);
glCreateVertexArrays(1, &vao);
glVertexArrayElementBuffer(vao, idcBuf);
glEnableVertexArrayAttrib(vao, 0);
glVertexArrayAttribFormat(vao, 0, 2, GL_FLOAT, GL_FALSE, 0);
glVertexArrayVertexBuffer(vao, 0, posBuf, 0, strided<Vc2>(1));
}
inline void Dispatcher::init() {
initShaders();
initVAO();
lightUniformData = new LightUniformStruct[6];
for (int i = 0; i < 6;i++) {
lightColor[i] = glm::vec4((glm::vec3(255.f, 250.f, 244.f) / 255.f) * 50.f, 40.0f);
lightAmbient[i] = glm::vec4(0.0f);
lightVector[i] = glm::vec4(0.2f, 1.0f, 0.4f, 400.0f);
lightOffset[i] = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f);
}
bbox bound;
bound.mn.x = 100000.f;
bound.mn.y = 100000.f;
bound.mn.z = 100000.f;
bound.mn.w = 100000.f;
bound.mx.x = -100000.f;
bound.mx.y = -100000.f;
bound.mx.z = -100000.f;
bound.mx.w = -100000.f;
framenum = 0;
resultCounters = allocateBuffer<uint32_t>(2);
arcounter = allocateBuffer<int32_t>(8);
arcounterTemp = allocateBuffer<int32_t>(1);
rayBlockUniform = allocateBuffer<RayBlockUniform>(1);
lightUniform = allocateBuffer<LightUniformStruct>(6);
glNamedBufferSubData(arcounterTemp, 0, strided<int32_t>(1), zero);
materialUniformData.lightcount = 1;
cameraUniformData.enable360 = 0;
syncUniforms();
}
inline void Dispatcher::setLightCount(size_t lightcount) {
materialUniformData.lightcount = lightcount;
}
inline void Dispatcher::switchMode() {
clearRays();
clearSampler();
cameraUniformData.enable360 = cameraUniformData.enable360 == 1 ? 0 : 1;
}
inline void Dispatcher::resize(const uint32_t & w, const uint32_t & h) {
displayWidth = w;
displayHeight = h;
if (sampleflags != -1) glDeleteTextures(1, &sampleflags);
if (presampled != -1) glDeleteTextures(1, &presampled);
if (filtered != -1) glDeleteTextures(1, &filtered);
if (prevsampled != -1) glDeleteTextures(1, &prevsampled);
if (positionimg != -1) glDeleteTextures(1, &positionimg);
//reprojected = allocateTexture2D<GL_RGBA32F>(displayWidth, displayHeight);
//positionimg = allocateTexture2D<GL_RGBA32F>(displayWidth, displayHeight);
sampleflags = allocateTexture2D<GL_R32UI>(displayWidth, displayHeight);
presampled = allocateTexture2D<GL_RGBA32F>(displayWidth, displayHeight);
prevsampled = allocateTexture2D<GL_RGBA32F>(displayWidth, displayHeight);
filtered = allocateTexture2D<GL_RGBA32F>(displayWidth, displayHeight);
// set sampler of
glTextureParameteri(presampled, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteri(presampled, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// previous frame for temporal AA
glTextureParameteri(prevsampled, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteri(prevsampled, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// set sampler of
glTextureParameteri(filtered, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteri(filtered, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
samplerUniformData.samplecount = displayWidth * displayHeight;
clearSampler();
}
inline void Dispatcher::resizeBuffers(const uint32_t & w, const uint32_t & h) {
width = w, height = h;
bool enableInterlacing = false;
if (colorchains != -1) glDeleteBuffers(1, &colorchains);
if (rays != -1) glDeleteBuffers(1, &rays);
if (hits != -1) glDeleteBuffers(1, &hits);
if (activel != -1) glDeleteBuffers(1, &activel);
if (activenl != -1) glDeleteBuffers(1, &activenl);
if (texels != -1) glDeleteBuffers(1, &texels);
if (freedoms != -1) glDeleteBuffers(1, &freedoms);
if (availables != -1) glDeleteBuffers(1, &availables);
if (quantized != -1) glDeleteBuffers(1, &quantized);
if (deferredStack != -1) glDeleteBuffers(1, &deferredStack);
const int32_t cmultiplier = 4;
const int32_t wrsize = width * height;
currentRayLimit = std::min(wrsize * cmultiplier / (enableInterlacing ? 2 : 1), 4096 * 4096);
colorchains = allocateBuffer<ColorChain>(currentRayLimit * 4);
rays = allocateBuffer<Ray>(currentRayLimit);
hits = allocateBuffer<Hit>(currentRayLimit);
activel = allocateBuffer<int32_t>(currentRayLimit);
activenl = allocateBuffer<int32_t>(currentRayLimit);
texels = allocateBuffer<Texel>(wrsize);
freedoms = allocateBuffer<int32_t>(currentRayLimit);
availables = allocateBuffer<int32_t>(currentRayLimit);
deferredStack = allocateBuffer<int32_t>(currentRayLimit * 16);
samplerUniformData.sceneRes = { float(width), float(height) };
samplerUniformData.currentRayLimit = currentRayLimit;
cameraUniformData.interlace = enableInterlacing ? 1 : 0;
clearRays();
syncUniforms();
}
inline void Dispatcher::syncUniforms() {
for (int i = 0; i < materialUniformData.lightcount; i++) {
lightUniformData[i].lightColor = *(Vc4 *)glm::value_ptr(lightColor[i]);
lightUniformData[i].lightVector = *(Vc4 *)glm::value_ptr(lightVector[i]);
lightUniformData[i].lightOffset = *(Vc4 *)glm::value_ptr(lightOffset[i]);
lightUniformData[i].lightAmbient = *(Vc4 *)glm::value_ptr(lightAmbient[i]);
}
rayBlockData.cameraUniform = cameraUniformData;
rayBlockData.samplerUniform = samplerUniformData;
rayBlockData.materialUniform = materialUniformData;
glNamedBufferSubData(rayBlockUniform, 0, strided<RayBlockUniform>(1), &rayBlockData);
glNamedBufferSubData(lightUniform, 0, strided<LightUniformStruct>(6), lightUniformData);
glMemoryBarrier(GL_ALL_BARRIER_BITS);
}
inline void Dispatcher::bindUniforms() {
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 12, lightUniform);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 13, rayBlockUniform);
}
inline void Dispatcher::bind() {
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, rays);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, hits);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, texels);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, colorchains);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, activel);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 5, availables);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 6, activenl);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 7, freedoms);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 8, arcounter);
syncUniforms();
bindUniforms();
}
inline void Dispatcher::clearRays() {
for (int i = 0; i < 8;i++) {
glCopyNamedBufferSubData(arcounterTemp, arcounter, 0, sizeof(uint32_t) * i, sizeof(uint32_t));
}
}
inline void Dispatcher::sample() {
// collect samples
glBindImageTexture(0, presampled, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);
glBindImageTexture(1, sampleflags, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R32UI);
this->bind();
dispatch(samplerProgram, tiled(displayWidth * displayHeight, worksize));
currentSample = (currentSample + 1) % maxSamples;
// filter by deinterlacing, etc.
glBindImageTexture(0, presampled, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);
glBindImageTexture(1, filtered, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);
glBindImageTexture(2, prevsampled, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);
// deinterlace if need
dispatch(deinterlaceProgram, tiled(displayWidth * displayHeight, worksize));
// use temporal AA
dispatch(filterProgram, tiled(displayWidth * displayHeight, worksize));
// save previous frame
glCopyImageSubData(filtered, GL_TEXTURE_2D, 0, 0, 0, 0, prevsampled, GL_TEXTURE_2D, 0, 0, 0, 0, displayWidth, displayHeight, 1);
}
inline void Dispatcher::camera(const glm::mat4 &persp, const glm::mat4 &frontSide) {
clearRays();
materialUniformData.time = rand();
cameraUniformData.camInv = *(Vc4x4 *)glm::value_ptr(glm::inverse(frontSide));
cameraUniformData.projInv = *(Vc4x4 *)glm::value_ptr(glm::inverse(persp));
cameraUniformData.interlaceStage = (framenum++) % 2;
this->bind();
dispatch(cameraProgram, tiled(width * height, worksize));
reloadQueuedRays(true);
}
inline void Dispatcher::camera(const glm::vec3 &eye, const glm::vec3 &view, const glm::mat4 &persp) {
#ifdef USE_CAD_SYSTEM
glm::mat4 sidemat = glm::lookAt(eye, view, glm::vec3(0.0f, 0.0f, 1.0f));
#elif USE_180_SYSTEM
glm::mat4 sidemat = glm::lookAt(eye, view, glm::vec3(0.0f, -1.0f, 0.0f));
#else
glm::mat4 sidemat = glm::lookAt(eye, view, glm::vec3(0.0f, 1.0f, 0.0f));
#endif
this->camera(persp, sidemat);
}
inline void Dispatcher::camera(const glm::vec3 &eye, const glm::vec3 &view) {
this->camera(eye, view, glm::perspective(glm::pi<float>() / 3.0f, float(displayWidth) / float(displayHeight), 0.001f, 1000.0f));
}
inline void Dispatcher::clearSampler() {
this->bind();
glBindImageTexture(0, sampleflags, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R32UI);
dispatch(clearProgram, tiled(displayWidth * displayHeight, worksize));
}
inline void Dispatcher::reloadQueuedRays(bool doSort, bool sortMortons) {
glGetNamedBufferSubData(arcounter, 0 * sizeof(uint32_t), sizeof(uint32_t), &raycountCache);
samplerUniformData.rayCount = raycountCache;
syncUniforms();
uint32_t availableCount = 0;
glGetNamedBufferSubData(arcounter, 2 * sizeof(int32_t), sizeof(int32_t), &availableCount);
glCopyNamedBufferSubData(arcounter, arcounter, 2 * sizeof(int32_t), 3 * sizeof(int32_t), sizeof(int32_t));
// set to zeros
glCopyNamedBufferSubData(arcounterTemp, arcounter, 0, sizeof(uint32_t) * 7, sizeof(uint32_t));
glCopyNamedBufferSubData(arcounterTemp, arcounter, 0, sizeof(uint32_t) * 2, sizeof(uint32_t));
glCopyNamedBufferSubData(arcounterTemp, arcounter, 0, sizeof(uint32_t) * 0, sizeof(uint32_t));
// copy active collection
if (raycountCache > 0) {
glCopyNamedBufferSubData(activenl, activel, 0, 0, strided<uint32_t>(raycountCache));
}
// copy collection of available ray memory
if (availableCount > 0) {
glCopyNamedBufferSubData(freedoms, availables, 0, 0, strided<uint32_t>(availableCount));
}
glMemoryBarrier(GL_ALL_BARRIER_BITS);
}
inline void Dispatcher::reclaim() {
int32_t rsize = getRayCount();
if (rsize <= 0) return;
this->bind();
dispatch(reclaimProgram, tiled(rsize, worksize));
reloadQueuedRays(true);
}
inline void Dispatcher::render() {
this->bind();
glEnable(GL_TEXTURE_2D);
glBindTextureUnit(5, filtered);
glBindTextureUnit(6, prevsampled);
glScissor(0, 0, displayWidth, displayHeight);
glViewport(0, 0, displayWidth, displayHeight);
glUseProgram(renderProgram);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glMemoryBarrier(GL_ALL_BARRIER_BITS);
glBindVertexArray(0);
}
inline int Dispatcher::intersection(SceneObject * obj, const int clearDepth) {
if (!obj || obj->triangleCount <= 0) return 0;
int32_t rsize = getRayCount();
if (rsize <= 0) return 0;
this->bind();
obj->bindBVH();
obj->bindLeafs();
obj->bind();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 19, deferredStack);
dispatch(traverseDirectProgram, tiled(rsize, worksize));
return 1;
}
inline void Dispatcher::applyMaterials(MaterialSet * mat) {
mat->bindWithContext(surfProgram);
glCopyNamedBufferSubData(arcounter, rayBlockUniform, 7 * sizeof(int32_t), offsetof(RayBlockUniform, samplerUniform) + offsetof(SamplerUniformStruct, hitCount), sizeof(int32_t));
GLuint tcount = 0; glGetNamedBufferSubData(arcounter, 7 * sizeof(int32_t), sizeof(int32_t), &tcount);
if (tcount <= 0) return;
dispatch(surfProgram, tiled(tcount, worksize));
}
inline void Dispatcher::shade() {
int32_t rsize = getRayCount();
if (rsize <= 0) return;
materialUniformData.time = rand(); this->bind();
glBindTextureUnit(5, skybox);
dispatch(matProgram, tiled(rsize, worksize));
}
inline Dispatcher::HdrImage Dispatcher::snapRawHdr() {
HdrImage img;
img.width = displayWidth;
img.height = displayHeight;
img.image = new GLfloat[displayWidth * displayHeight * 4];
glGetTextureSubImage(presampled, 0, 0, 0, 0, displayWidth, displayHeight, 1, GL_RGBA, GL_FLOAT, displayWidth * displayHeight * 4 * sizeof(GLfloat), img.image);
return img;
}
inline Dispatcher::HdrImage Dispatcher::snapHdr() {
HdrImage img;
img.width = displayWidth;
img.height = displayHeight;
img.image = new GLfloat[displayWidth * displayHeight * 4];
glGetTextureSubImage(filtered, 0, 0, 0, 0, displayWidth, displayHeight, 1, GL_RGBA, GL_FLOAT, displayWidth * displayHeight * 4 * sizeof(GLfloat), img.image);
return img;
}
inline int32_t Dispatcher::getRayCount() {
return raycountCache >= 32 ? raycountCache : 0;
}
}
<file_sep>#pragma once
#define RAY_TRACING_ENGINE
#include <vector>
#include <iostream>
#include <chrono>
#include <array>
#include <random>
#include <map>
#include "GL/glew.h"
#include "glm/glm.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtx/component_wise.hpp"
#include "glm/gtx/rotate_vector.hpp"
#include "glm/gtc/quaternion.hpp"
#include "glm/gtx/transform.hpp"
#ifdef USE_FREEIMAGE
#include "external/include/FreeImage.h"
#endif
namespace ppr {
//using namespace gl;
class BaseClass {};
class Dispatcher;
class SceneObject;
static int32_t tiled(int32_t sz, int32_t gmaxtile) {
return (int32_t)ceil((double)sz / (double)gmaxtile);
}
static double milliseconds() {
auto duration = std::chrono::high_resolution_clock::now();
double millis = std::chrono::duration_cast<std::chrono::nanoseconds>(duration.time_since_epoch()).count() / 1000000.0;
return millis;
}
template<class T>
size_t strided(size_t sizeo) {
return sizeof(T) * sizeo;
}
static std::string readSource(const std::string &filePath, const bool& lineDirective = false) {
std::string content;
std::ifstream fileStream(filePath, std::ios::in);
if (!fileStream.is_open()) {
std::cerr << "Could not read file " << filePath << ". File does not exist." << std::endl;
return "";
}
std::string line = "";
while (!fileStream.eof()) {
std::getline(fileStream, line);
if (lineDirective || line.find("#line") == std::string::npos) content.append(line + "\n");
}
fileStream.close();
return content;
}
static std::vector<char> readBinary(const std::string &filePath) {
std::ifstream file(filePath, std::ios::in | std::ios::binary | std::ios::ate);
std::vector<char> data;
if (file.is_open()) {
std::streampos size = file.tellg();
data.resize(size);
file.seekg(0, std::ios::beg);
file.read(&data[0], size);
file.close();
}
else {
std::cerr << "Failure to open " + filePath << std::endl;
}
return data;
};
inline GLuint loadShaderSPIRV(std::string path, GLenum shaderType = GL_COMPUTE_SHADER, std::string entryName = "main") {
std::vector<GLchar> str = readBinary(path);
GLuint comp = glCreateShader(shaderType);
{
const GLchar * strc = str.data();
int32_t size = str.size();
#ifdef USE_OPENGL_45_COMPATIBLE
glShaderBinary(1, &comp, GL_SHADER_BINARY_FORMAT_SPIR_V_ARB, strc, size);
glSpecializeShaderARB(comp, entryName.c_str(), 0, nullptr, nullptr);
#else
glShaderBinary(1, &comp, GL_SHADER_BINARY_FORMAT_SPIR_V, strc, size);
glSpecializeShader(comp, entryName.c_str(), 0, nullptr, nullptr);
#endif
GLint status = false;
glGetShaderiv(comp, GL_COMPILE_STATUS, &status);
if (!status) {
char * log = new char[32768];
GLsizei len = 0;
glGetShaderInfoLog(comp, 32768, &len, log);
std::string logStr = std::string(log, len);
std::cerr << logStr << std::endl;
}
}
return comp;
}
inline void validateProgram(GLuint prog) {
GLint status = false;
glGetProgramiv(prog, GL_LINK_STATUS, &status);
if (!status) {
char * log = new char[32768];
GLsizei len = 0;
glGetProgramInfoLog(prog, 32768, &len, log);
std::string logStr = std::string(log, len);
std::cerr << logStr << std::endl;
}
}
inline void initShaderComputeSPIRV(std::string path, GLuint & prog, std::string entryName = "main") {
prog = glCreateProgram();
glAttachShader(prog, loadShaderSPIRV(path, GL_COMPUTE_SHADER, entryName));
glLinkProgram(prog);
validateProgram(prog);
}
template<class T>
GLuint allocateBuffer(size_t size = 1) {
GLuint buf = 0;
glCreateBuffers(1, &buf);
glNamedBufferStorage(buf, sizeof(T) * size, nullptr, GL_DYNAMIC_STORAGE_BIT);
return buf;
}
template<GLenum format = GL_RGBA8>
GLuint allocateTexture2D(size_t width, size_t height) {
GLuint tex = 0;
glCreateTextures(GL_TEXTURE_2D, 1, &tex);
glTextureStorage2D(tex, 1, format, width, height);
return tex;
}
void dispatch(const GLuint &program, const GLuint gridSize) {
glUseProgram(program);
glDispatchCompute(gridSize, 1, 1);
glMemoryBarrier(GL_ALL_BARRIER_BITS);
}
void dispatchIndirect(const GLuint &program, const GLuint& buffer) {
glUseProgram(program);
glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, buffer);
glDispatchComputeIndirect(0);
glMemoryBarrier(GL_ALL_BARRIER_BITS);
}
const int32_t zero[1] = { 0 };
}
| 125425860a88a200de6da96d0260ce2faaad6445 | [
"Markdown",
"CMake",
"C++"
] | 17 | C++ | gitter-badger/prismarine-1 | 1028e7ed4d83525f3521cde611cad3810db0e3ed | 912892c49d85ceb0f6752cf3f43db3404ef78b73 |
refs/heads/master | <file_sep>// Libgmk
// ©2015 <NAME>, All Rights Reserved.
// Test_MidDispatch.cpp
//
// Testing the MidiDispatcher class
//
#include <iostream>
#include "libgmkConfig.h"
#include "MidiDispatcher.h"
// declare test predicate functions and test handlers
//
//
//
//
//
//
#if 0 /* Lame, I know */
int main(int argc, char** argv)
{
std::cout<<"*****************************************"<<std::endl;
std::cout<<"Testing MidiDispatcher"<<std::endl;
std::cout<<"libgmk Version: "<<libgmk_VERSION_MAJOR<<"."<<libgmk_VERSION_MINOR<<std::endl;
std::cout<<"*****************************************"<<std::endl;
MidiDispatcher* midiDispatch = new MidiDispatcher;
midiDispatch->selfTest();
}
#endif /* 0 */
<file_sep>#ifndef _MIDICALLBACKOSX_H_
#define _MIDICALLBACKOSX_H_
// libgmk
// ©2015 <NAME>
// ALL RIGHTS RESERVED
//
// MidiCallbackOSX.h
// Callbacks for CoreMidi
//
#include <iostream>
#include <CoreMIDI/CoreMIDI.h>
#include <CoreServices/CoreServices.h>
#include "MidiNode.h"
// the reading callback
static void midiInputCallback(const MIDIPacketList *list, void *readProcRef, void *srcConnRefCon);
static void midiParsePacket(MIDIPacket *packet, MidiNodeID *devID, MidiDispatcher *dispatcher);
// for any changes in overall state
void midiNotifyCallback(const MIDINotification *msg, void *refCon);
// related to sysex
void sysexCallback(MIDISysexSendRequest *theRequest);
#endif // _MIDICALLBACKOSX_H_
<file_sep>#ifndef _LOGGER_H_
#define _LOGGER_H_
// libgmk
// ©2015 <NAME>
// ALL RIGHTS RESERVED
//
// Logger.h
// Thread-safe logging
//
#endif /* _LOGGER_H_ */
<file_sep>#ifndef _MIDINODE_H_
#define _MIDINODE_H_
// libgmk
// ©2015 <NAME>
// ALL RIGHTS RESERVED
//
// MidiInterfaceOSX.h
// OSX concrete class for MIDI interface magic
//
#include <limits>
// I'd like to make this fixed width but rumor has it that this might not be cross-platform
// should this become a private typedef?
using MidiNodeID = unsigned int;
using MidiNodeType = unsigned int;
const MidiNodeType MidiSourceNode = 1;
const MidiNodeType MidiVirtualSourceNode = 2;
const MidiNodeType MidiDestinationNode = 3;
const MidiNodeType MidiVirtualDestinationNode = 4;
const MidiNodeType MidiDeviceNode = 5;
const MidiNodeType MidiVirtualDeviceNode = 6;
static MidiNodeID currentMidiNodeID = 0;
static MidiNodeID generateNodeID(void)
{
if(currentMidiNodeID>=UINT_MAX)
{
// wrap it around
currentMidiNodeID=0;
}
return ++currentMidiNodeID;
}
#endif /* _MIDINODE_H */
<file_sep>#ifndef _MIDICMD_H_
#define _MIDICMD_H_
// libgmk
// ©2015 <NAME>
// ALL RIGHTS RESERVED
//
// MidiCmd.h
// MIDI message abstraction
//
#include <cstdint>
#include "MidiNode.h"
const uint8_t kMidiNoteOff = 0x80;
const uint8_t kMidiNoteOn = 0x90;
const uint8_t kMidiPolyTouch = 0xA0;
const uint8_t kMidiCtlChg = 0xB0;
const uint8_t kMidiProgChg = 0xC0;
const uint8_t kMidiChTouch = 0xD0;
const uint8_t kMidiPitchBend = 0xE0;
const uint8_t kMidiSysMsg = 0xF0;
class MidiChanCmd
{
public:
MidiChanCmd(uint8_t inStatus, uint8_t inChannel, uint8_t inArg1, uint8_t inArg2, uint64_t inTimeStamp, MidiNodeID inDevID) :
status(inStatus),
channel(inChannel),
arg1(inArg1),
arg2(inArg2),
timeStamp(inTimeStamp),
midiDevID(inDevID)
{};
~MidiChanCmd();
// we need move and copy constructors so we can use it in
// a ThreadQueue
// should this become a free function taking 2 args?
bool matches(const MidiChanCmd& prototype) const;
// just the message data
uint8_t status;
uint8_t channel;
uint8_t arg1;
uint8_t arg2;
// if available
uint64_t timeStamp;
MidiNodeID midiDevID;
};
// function for comparison of two cmds
//namespace{
bool midiCmdsMatch(const MidiChanCmd& cmdA, const MidiChanCmd& cmdB);
//}
/*
// if I decide to support this, we need to think about the ctor/dtor
class MidiSysCmd : public MidiChanCmd
{
public:
MidiSysCmd();
~MidiSysCmd();
// if it is sysex, ignore arg1 and arg2, it is all here
uint8_t data[256];
};
*/
#endif /* _MIDICMD_H_ */
<file_sep>#ifndef _MIDIINTERFACEOSX_H_
#define _MIDIINTERFACEOSX_H_
// libgmk
// ©2015 <NAME>
// ALL RIGHTS RESERVED
//
// MidiInterfaceOSX.h
// OSX concrete class for MIDI interface magic
//
#include <vector>
#include <map>
#include <string>
#include <CoreMIDI/CoreMIDI.h>
#include <CoreServices/CoreServices.h>
#include "libgmkConfig.h"
#include "AbstractMidiInterface.h"
#include "MidiCallbackOSX.h"
#include "CoreMidi/CoreMidiUtils.h"
#include "MidiDispatcher.h"
class MidiInterfaceOSX : public AbstractMidiInterface
{
public:
MidiInterfaceOSX();
~MidiInterfaceOSX();
// virtual bool startInterface(void);
virtual bool checkStatus(void);
virtual bool reset(void);
// virtual void stopInterface(void);
// virtual void pauseInterface(void);
// virtual void closeInterface(void);
// Device tasks - minimal for now
virtual MidiNodeID getBaseNode(void);
virtual unsigned int getNumNodes(void);
virtual bool isNodeValid(MidiNodeID devID);
virtual bool getNodeSysName(MidiNodeID devID, std::string &devSysName);
virtual bool getNodeMfgName(MidiNodeID devID, std::string &devMfgName);
virtual bool isNodeInput(MidiNodeID devID);
virtual bool isNodeOutput(MidiNodeID devID);
// sources & destinations
virtual unsigned int getNumDevices(void);
virtual unsigned int getNumSources(void);
virtual unsigned int getNumDestinations(void);
virtual bool addSource(MidiNodeID devID);
virtual bool removeSource(MidiNodeID devID);
virtual bool addDestination(MidiNodeID devID);
virtual bool removeDestination(MidiNodeID devID);
// self testing
bool selfTest(void);
private:
// inits
bool midiInit(void);
bool openInputPort(void);
bool openOutputPort(void);
// dtor
bool closeInputPort(void);
bool closeOutputPort(void);
bool closeMidi(void);
// device info
void updateNodeInfo(void);
//void addSourceToList(MidiNodeID devID, MIDIEndpointRef devRef);
//void addDestinationToList(MidiNodeID devID, MIDIEndpointRef devRef);
//void addDeviceToList(MidiNodeID devID, MIDIEndpointRef devRef);
//void removeSourceFromList(MidiNodeID devID);
//void removeDestinationFromList(MidiNodeID devID);
//void removeDeviceFromList(MidiNodeID devID);
void clearLists(void);
MIDIDeviceRef getNodeRef(MidiNodeID devID);
MIDIEndpointRef getNodeEndpoint(MidiNodeID devID);
bool getDeviceProperty(MidiNodeID devID, const CFStringRef propKey, std::string &stringProp);
bool getDeviceProperty(MidiNodeID devID, const CFStringRef propKey, int &intProp);
// OSX data
MIDIClientRef clientRef;
MIDIPortRef inPort, outPort;
// support for virtual endpoint or points?
MIDIEndpointRef virtDest=0;
// entities and devices
MidiNodeID baseID;
MidiDispatcher *defaultDispatcher;
std::map<MidiNodeID, MidiNodeType> midiNodeList;
std::map<MidiNodeID, MIDIEndpointRef> sources;
std::map<MidiNodeID, MIDIEndpointRef> destinations;
std::map<MidiNodeID, MIDIDeviceRef> devices;
// should these string consts go somewhere else globally?
CFStringRef clientName = CFSTR("libgmk_Client");
// const char* clientNameCStr = "libgmk_Client";
CFStringRef inPortName = CFSTR("libgmk_inPort");
// const char* inPortNameCStr = "libgmk_inPort";
CFStringRef outPortName = CFSTR("libgmk_outPort");
// const char* outPortNameCStr = "libgmk_outPort";
};
#endif // _MIDIINTERFACEOSX_H_
<file_sep>// Libgmk
// ©2015 <NAME>, All Rights Reserved.
// Test_MidiOSX.cpp
//
// Testing the OSX (CoreMidi) functionality as it is built
//
#include <iostream>
#include "libgmkConfig.h"
#include "MidiInterfaceOSX.h"
int main(int argc, char** argv)
{
std::cout<<"*****************************************"<<std::endl;
std::cout<<"Testing MidiInterfaceOSX"<<std::endl;
std::cout<<"libgmk Version: "<<libgmk_VERSION_MAJOR<<"."<<libgmk_VERSION_MINOR<<std::endl;
std::cout<<"*****************************************"<<std::endl;
MidiInterfaceOSX* midiInterface = new MidiInterfaceOSX;
midiInterface->selfTest();
// Test connecting ports to devices and destinations
// Send some garbage to each output device
// Test input from a device, press enter to continue
// Meanwhile, print out MIDI packets recvd
// Test the creation of a virtual destination,
// prompt user to send MIDI via another program
// TODO: Spawn process to do that?
// test disconnecting input and output
// Kill interface
// say goodbye
}
<file_sep>cmake_minimum_required(VERSION 2.6)
project(libgmk)
set(UTIL_TARGET gmk_util)
# utilities for the library
# these should be largely cross-platform
# this is just the beginning
set(util_sources
Logger.cpp
ThreadQueue.h
)
add_library(${UTIL_TARGET} SHARED
${util_sources}
)
target_include_directories(${UTIL_TARGET} PUBLIC
${CMAKE_SOURCE_DIR}/util/
${CMAKE_SOURCE_DIR}/build/
)
<file_sep>#ifndef _MIDIDISPATCHER_H_
#define _MIDIDISPATCHER_H_
// libgmk
// ©2015 <NAME>
// ALL RIGHTS RESERVED
//
// MidiDispatcher.h
// The fellow who doles out all the MIDI packets
//
#include "libgmkConfig.h"
#include "AbstractMidiInterface.h"
#include "MidiNode.h"
#include "ThreadQueue.h"
#include "MidiCmd.h"
using MidiListenerID = unsigned int;
using MidiInputID = unsigned int;
using MidiCmdHandler = void(MidiChanCmd&);
// MidiListener cannot be edited on the fly.
class MidiListener
{
public:
MidiListener(MidiChanCmd inProto, MidiCmdHandler inMsgHndlr, MidiListenerID inListenerID) :
prototype(inProto),
msgHandler(inMsgHndlr),
listenerID(inListenerID)
{};
virtual ~MidiListener(){};
MidiChanCmd prototype;
MidiCmdHandler msgHandler;
MidiListenerID listenerID;
}
class MidiDispatcher
{
public:
MidiDispatcher();
~MidiDispatcher();
MidiListenerID createListenerID(void);
MidiListenerID addListener(MidiChanCmd prototype, void* protoHndlr);
void removeListener(MidiListenerID listenerID);
// queue is managed internally
// clients may only push and trigger processing
void pushMidiCmd(MidiChanCmd* inputCmd);
void processQueue(void); // called by audio callback I think
// maybe this again?
bool selfTest(void);
private:
// no copy/assign allowed
MidiDispatcher(const MidiDispatcher&)=delete;
MidiDispatcher& operator=(const MidiDispatcher&)=delete;
// storage of bindings and cmds
std::vector<MidiListener> bindings;
ThreadQueue<MidiChanCmd*> midiCmdQueue;
static MidiListenerID curListenerID=0;
};
#endif /* _MIDIDISPATCHER_H_ */
<file_sep># libgmk
A library for music and audio applications written in C++ (in progress).
<file_sep>bool midiCmdsMatch(const MidiChanCmd& cmdA, const MidiChanCmd& cmdB)
{
// local vars to track matching fields
bool statusMatch=false;
bool arg1Match=false;
bool arg2Match=false;
bool devIDMatch=false;
// if all defined fields match, return true
// don't worry about NULL, they mean user doesn't care
if(cmdA->status==NULL)
{
statusMatch=true;
} else if(cmdA->status==cmdB->status)
{
statusMatch=true;
}
if(cmdA->arg1==NULL)
{
arg1Match==true;
} else if (cmdA->arg1==cmdB->arg1)
{
arg1Match=true;
}
if(cmdA->arg2==NULL)
{
arg2Match=true;
} else if (cmdA->arg2==cmdB->arg2)
{
arg2Match=true;
}
if(cmdA->midiDevID==NULL)
{
devIDMatch=true;
} else if (cmdA->midiDevID==cmdB->midiDevID)
{
devIDMatch=true;
}
// if anything is false, return false.
return (statusMatch||arg1Match||arg2Match||devIDMatch);
}
<file_sep>#ifndef COREMIDIUTILS_H
#define COREMIDIUTILS_H
// libgmk
// ©2015 <NAME>, All Rights Reserved.
// CoreMidiUtils.cpp
//
// Utilities for dealing with CoreMIDI
#include <string>
#include <iostream>
#include <CoreMIDI/CoreMIDI.h>
#include <CoreServices/CoreServices.h>
bool getCoreMidiErrorString(OSStatus errCode, std::string &errString);
void printCoreMIDIError(OSStatus errIn);
#endif // COREMIDIUTILS_H
<file_sep>// libgmk
// ©2015 <NAME>
// ALL RIGHTS RESERVED
//
// MidiCallbackOSX.cpp
// Callbacks for CoreMidi
//
#include "MidiCallbackOSX.h"
// the reading callback
void midiInputCallback(const MIDIPacketList *list, void *readProcRef, void *srcConnRefCon)
{
MIDIPacket *pkt = (MIDIPacket*)list->packet;
MidiNodeID *devID = (MidiNodeID*)srcConnRefCon;
for (unsigned int i=0; i<list->numPackets; ++i)
{
midiParsePacket(pkt, devID, (MidiDispatcher&)readProcRef);
pkt = MIDIPacketNext(pkt);
}
std::cout<<"CoreMIDI input: "<<list->numPackets<<"packet(s) received."<<std::endl;
}
// system change notifications
void midiNotifyCallback(const MIDINotification *msg, void *refCon)
{
// testing - refCon will prob be a void ptr to the interface object
std::cout<<"CoreMIDI system notification, messageId: "<<msg->messageID<<std::endl;
}
// sysex notifications
void sysexCallback(MIDISysexSendRequest *theRequest)
{
// will use this callback if I support sysex messaging
std::cout<<"MIDI sysex message. Complete: "<<theRequest->complete<<std::endl;
}
// std::string from CFString: CFStringGetCString and perhaps append to caller supplied std::string &
// to use when getting object properties
// Factory function for MidiCmds - need to also pash the dispatch queue into the callback
static void midiParsePacket(MIDIPacket *packet, MidiNodeID *devID, MidiDispatcher *dispatcher)
{
unsigned int i=0;
while(i<packet->length)
{
// grab the status and channel bytes
uint8_t status = packet->data[i] & 0xF0;
uint8_t channel = packet->data[i] & 0x0F;
// switch on the status to decipher the packet and construct the command
// push it into the supplied dispatcher
// i is updated according to the size of each packet type
switch(status)
{
case kMidiNoteOff:
MidiChanCmd mCmd(kMidiNoteOff, channel, packet->data[i+1], packet->data[i+2], packet->timeStamp, devID);
dispatcher.pushMidiCmd(mCmd);
i+=3;
break;
case kMidiNoteOn:
MidiChanCmd mCmd(kMidiNoteOn, channel, packet->data[i+1], packet->data[i+2], packet->timeStamp, devID);
dispatcher.pushMidiCmd(mCmd);
i+=3;
break;
case kMidiPolyTouch:
MidiChanCmd mCmd(kMidiPolyTouch, channel, packet->data[i+1], packet->data[i+2], packet->timeStamp, devID);
dispatcher.pushMidiCmd(mCmd);
i+=3;
break;
case kMidiCtlChg:
MidiChanCmd mCmd(kMidiCtlChg, channel, packet->data[i+1], packet->data[i+2], packet->timeStamp, devID);
dispatcher.pushMidiCmd(mCmd);
i+=3;
break;
case kMidiProgChg:
MidiChanCmd mCmd(kMidiProgChg, channel, packet->data[i+1], 0, packet->timeStamp, devID);
dispatcher.pushMidiCmd(mCmd);
i+=2;
break;
case kMidiChTouch:
MidiChanCmd mCmd(kMidiChTouch, channel, packet->data[i+1], 0, packet->timeStamp, devID);
dispatcher.pushMidiCmd(mCmd);
i+=2;
break;
case kMidiPitchBend:
MidiChanCmd mCmd(kMidiPitchBend, channel, (packet->data[i+2]<<7 | packet->data[i+1]), 0, packet->timeStamp, devID);
dispatcher.pushMidiCmd(mCmd);
i+=3;
break;
case kMidiSysMsg:
// have to think on how to process this, another function
break;
// if we support running status or sysex, our default case can figure that out
default:
// running or sysex
}
}
}
<file_sep>// Libgmk
// ©2015 <NAME>, All Rights Reserved.
// CoreMidiUtils.cpp
//
// Utilities for dealing with CoreMIDI
#include "CoreMidiUtils.h"
// pass in the OSStatus and a std::string, errString is descriptive upon true return value
// return of false means the OSStatus is not a CoreMidi error
bool getCoreMidiErrorString(OSStatus errCode, std::string &errString)
{
if(errCode==kMIDIInvalidClient)
{
errString+="CoreMIDI: invalid Client Error";
return true;
}
if(errCode==kMIDIInvalidPort)
{
errString+="CoreMIDI: invalid port error";
return true;
}
if(errCode==kMIDIWrongEndpointType)
{
errString+="CoreMIDI: wrong endpoint type error";
return true;
}
if(errCode==kMIDINoConnection)
{
errString+="CoreMIDI: no connection error";
return true;
}
if(errCode==kMIDIUnknownEndpoint)
{
errString+="CoreMIDI: unknown endpoint error";
return true;
}
if(errCode==kMIDIUnknownProperty)
{
errString+="CoreMIDI: unknown property error";
return true;
}
if(errCode==kMIDIWrongPropertyType)
{
errString+="CoreMIDI: wrong property error";
return true;
}
if(errCode==kMIDINoCurrentSetup)
{
errString+="CoreMIDI: no current setup error";
return true;
}
if(errCode==kMIDIServerStartErr)
{
errString+="CoreMIDI: server start error";
return true;
}
if(errCode==kMIDISetupFormatErr)
{
errString+="CoreMIDI: setup format error";
return true;
}
if(errCode==kMIDIWrongThread)
{
errString+="CoreMIDI: wrong thread error";
return true;
}
if(errCode==kMIDIObjectNotFound)
{
errString+="CoreMIDI: object not found error";
return true;
}
if(errCode==kMIDIIDNotUnique)
{
errString+="CoreMIDI: MIDIID not unique error";
return true;
}
errString+="No CoreMIDI error found";
return false;
}
void printCoreMIDIError(OSStatus errIn)
{
std::string errorString;
// strictly speaking this function doesn't need to worry if the error is not found, so can ignore ret value
getCoreMidiErrorString(errIn, errorString);
if(errorString.size()>0) // don't put a null on there
{
std::cout<<errorString<<std::endl;
return;
}
std::cout<<"No error string found for value: "<<errIn<<std::endl;
}
<file_sep>// libgmk
// ©2015 <NAME>
// ALL RIGHTS RESERVED
//
// MidiInterfaceOSX.cpp
// OSX concrete class for MIDI interface magic
//
#include "MidiInterfaceOSX.h"
MidiInterfaceOSX::MidiInterfaceOSX()
{
bool midiResult;
midiResult = midiInit();
if(midiResult==true)
{
std::cout<<"CoreMIDI initialized."<<std::endl;
return;
}
else {
std::cout<<"libgmk: Error intializing CoreMIDI."<<std::endl;
}
}
MidiInterfaceOSX::~MidiInterfaceOSX()
{
if(virtDest) { MIDIEndpointDispose(virtDest);}
clearLists();
closeInputPort();
closeOutputPort();
closeMidi();
CFRelease(clientName);
CFRelease(inPortName);
CFRelease(outPortName);
}
bool MidiInterfaceOSX::midiInit(void)
{
// this function does all private setup of OSX on construction of the instance
// when complete it will be ready to start by clients
OSStatus initErr;
std::string errorString = "";
initErr = MIDIClientCreate(clientName, NULL, NULL, &clientRef);
if (initErr != noErr)
{
std::cout<<"Error encountered during client init: "<<initErr<<std::endl;
printCoreMIDIError(initErr);
return false;
}
// create the input port
if(!openInputPort())
{
std::cout<<"Error opening input port (midiInitFunc)"<<std::endl;
return false;
}
// create the output port
if(!openOutputPort())
{
std::cout<<"Error opening output port (midiInitFunc)"<<std::endl;
return false;
}
// get intel on available devices (src and dest)
// should this return a bool?
updateNodeInfo();
return true;
}
bool MidiInterfaceOSX::openInputPort(void)
{
OSStatus portErr;
// TODO: we will need to pass *this or the dispatch object instead of NULL
portErr = MIDIInputPortCreate(clientRef, inPortName, midiInputCallback, &defaultDispatcher, &inPort);
// check for errors
if(portErr != noErr)
{
std::cout<<"Error opening input port: "<<portErr<<std::endl;
printCoreMIDIError(portErr);
return false;
}
return true;
}
bool MidiInterfaceOSX::openOutputPort(void)
{
OSStatus portErr;
// TODO: we will need to pass *this or the dispatch object instead of NULL
portErr = MIDIOutputPortCreate(clientRef, outPortName, &outPort);
// check for errors
if(portErr != noErr)
{
std::cout<<"Error opening output port: "<<portErr<<std::endl;
printCoreMIDIError(portErr);
return false;
}
return true;
}
bool MidiInterfaceOSX::closeInputPort(void)
{
MIDIPortDispose(inPort);
inPort=0;
}
bool MidiInterfaceOSX::closeOutputPort(void)
{
MIDIPortDispose(outPort);
outPort=0;
}
bool MidiInterfaceOSX::closeMidi(void)
{
// according to CoreMIDI we are allowed to close the client without much worry
MIDIClientDispose(clientRef);
clientRef=0;
}
void MidiInterfaceOSX::clearLists()
{
if(!sources.empty() || !destinations.empty() || !devices.empty() || !midiNodeList.empty())
{
sources.clear();
destinations.clear();
devices.clear();
midiNodeList.clear();
}
}
void MidiInterfaceOSX::updateNodeInfo(void)
{
// if we want an update, we want fresh info. All active midiDevIDs are now invalid?
clearLists();
baseID = currentMidiNodeID + 1; // any new nodes get the ++
// baseID = currentMidiNodeID;
// get source info
unsigned int srcCnt = getNumSources();
MidiNodeID nodeID = 0;
if (srcCnt>0)
{
for (int i = 0 ; i < srcCnt ; ++i)
{
// generate a new MidiNodeID
MIDIEndpointRef source = MIDIGetSource(i);
if (source != NULL)
{
nodeID = generateNodeID();
sources[nodeID] = source;
midiNodeList[nodeID] = MidiSourceNode;
}
}
} else { std::cout<<"libgmk: Warning - no MIDI sources found"<<std::endl; }
// retrieve destination info
unsigned int destCnt = getNumDestinations();
if (destCnt>0)
{
for (int i = 0 ; i < destCnt ; ++i)
{
MIDIEndpointRef dest = MIDIGetDestination(i);
if (dest != NULL)
{
nodeID = generateNodeID();
destinations[nodeID] = dest;
midiNodeList[nodeID] = MidiDestinationNode;
}
}
} else { std::cout<<"libgmk: Warning - no MIDI destinations found"<<std::endl; }
unsigned int deviceCnt = getNumDevices();
if (deviceCnt>0)
{
for (int i=0; i<deviceCnt; i++)
{
MIDIDeviceRef dev = MIDIGetDevice(i);
if(dev != NULL)
{
nodeID = generateNodeID();
devices[nodeID] = dev;
midiNodeList[nodeID] = MidiDeviceNode;
}
}
} else { std::cout<<"libgmk: Warning - no MIDI devices found"<<std::endl; }
}
//bool MidiInterfaceOSX::startInterface()
//{
// // same as constructor
//}
//void MidiInterfaceOSX::stopInterface(void)
//{
// // same as destructor or pause ... ambiguous
//}
//void MidiInterfaceOSX::pauseInterface(void)
//{
// // should be implemented in MidiDispatcher
//}
//void MidiInterfaceOSX::closeInterface(void)
//{
// // same as destructor
//}
bool MidiInterfaceOSX::checkStatus()
{
// see if we have clients and ports set up
// do we need to log something for clients in each case?
if(!clientRef)
{
std::cout<<"libgmk: client is invalid"<<std::endl;
return false;
}
if(!inPort)
{
std::cout<<"libgmk: input port is invalid"<<std::endl;
return false;
}
if(!outPort)
{
std::cout<<"libgmk: output port is invalid"<<std::endl;
return false;
}
return true;
}
bool MidiInterfaceOSX::reset()
{
OSStatus resetErr;
resetErr = MIDIRestart();
if(resetErr != noErr)
{
std::cout<<"libgmk: error reseting MIDI:"<<std::endl;
printCoreMIDIError(resetErr);
return false;
}
// do we need to call midiInit?
updateNodeInfo();
return true;
}
unsigned int MidiInterfaceOSX::getNumDevices()
{
return MIDIGetNumberOfDevices();
}
MidiNodeID MidiInterfaceOSX::getBaseNode()
{
return baseID;
}
unsigned int MidiInterfaceOSX::getNumNodes(void)
{
// what to do if this is not initialized? just return the size I guess
return midiNodeList.size();
}
bool MidiInterfaceOSX::isNodeValid(MidiNodeID devID)
{
if(sources.count(devID)) return true;
if(destinations.count(devID)) return true;
if(devices.count(devID)) return true;
// if the ID is not in any of the lists, it doesn't mean anything
return false;
}
bool MidiInterfaceOSX::getDeviceProperty(MidiNodeID devID, const CFStringRef propKey, std::string &stringProp)
{
OSStatus getPropErr;
MIDIDeviceRef devRef;
CFStringRef strRef = NULL;
devRef = getNodeRef(devID);
if(!devRef)
{
std::cout<<"libgmk: problem getting device property, devID and ref are invalid: "<<devID<<" and "<<devRef<<std::endl;
return false;
}
getPropErr = MIDIObjectGetStringProperty(devRef, propKey, &strRef);
// in the case that the object does not have this property, just return false and return an empty string
if (getPropErr==kMIDIUnknownProperty)
{
// not sure what special handling this will need
std::cout<<"No name available for node: "<<devID<<std::endl;
return false;
}
if (getPropErr != noErr)
{
// should add the prop key to this logline
std::cout<<"libgmk: error getting device property for devID: "<<devID<<std::endl;
printCoreMIDIError(getPropErr);
return false;
}
// stuff data into string
stringProp.append(CFStringGetCStringPtr(strRef,kCFStringEncodingUTF8));
CFRelease(strRef);
return true;
}
bool MidiInterfaceOSX::getNodeSysName(MidiNodeID devID, std::string &devSysName)
{
OSStatus sysNameErr;
CFStringRef devTempStr;
if(!isNodeValid(devID))
{
std::cout<<"libgmk: problem getting system name, device is invalid"<<std::endl;
return false;
}
if(!getDeviceProperty(devID, kMIDIPropertyDisplayName, devSysName))
{
std::cout<<"libgmk: error getting system name, getDeviceProperty failed."<<std::endl;
return false;
}
return true;
}
bool MidiInterfaceOSX::getNodeMfgName(MidiNodeID devID, std::string &devMfgName)
{
OSStatus sysNameErr;
CFStringRef devTempStr;
if(!isNodeValid(devID))
{
std::cout<<"libgmk: problem getting device mfg name, device is invalid"<<std::endl;
return false;
}
// if(!getDeviceProperty(devID, kMIDIPropertyName, devMfgName)) // this returns some device type info (bluetooth, IAC, etc.)
if(!getDeviceProperty(devID, kMIDIPropertyManufacturer, devMfgName))
{
std::cout<<"libgmk: error getting Mfg name, getDeviceProperty failed."<<std::endl;
return false;
}
return true;
}
bool MidiInterfaceOSX::isNodeInput(MidiNodeID devID)
{
if(!isNodeValid(devID)) return false;
if(sources.count(devID)>0) return true;
return false;
}
bool MidiInterfaceOSX::isNodeOutput(MidiNodeID devID)
{
if(!isNodeValid(devID)) return false;
if(destinations.count(devID)>0) return true;
return false;
}
MIDIDeviceRef MidiInterfaceOSX::getNodeRef(MidiNodeID devID)
{
if(!isNodeValid(devID))
{
std::cout<<"libgmk: problem getting deviceRef, devID is invalid"<<std::endl;
return NULL;
}
if(midiNodeList.at(devID)==MidiSourceNode)
{
return sources.at(devID);
} else if (midiNodeList.at(devID)==MidiDestinationNode)
{
return destinations.at(devID);
} else if (midiNodeList.at(devID)==MidiDeviceNode)
{
return devices.at(devID);
}
// otherwise, I don't support the type yet
return 0;
}
// this might be handled by getNodeRef() just fine
//MIDIEndpointRef MidiInterfaceOSX::getNodeEndpoint(MidiNodeID devID)
//{
//
//}
unsigned int MidiInterfaceOSX::getNumSources(void)
{
return MIDIGetNumberOfSources();
}
unsigned int MidiInterfaceOSX::getNumDestinations(void)
{
return MIDIGetNumberOfDestinations();
}
bool MidiInterfaceOSX::addSource(MidiNodeID devID)
{
OSStatus srcConErr = noErr;
MIDIEndpointRef nodeRef;
if (!checkStatus()) // check if MIDI is good
{
std::cout<<"libgmk: Error adding Source to callback. Midi interface status is not ready."<<std::endl;
return false;
}
// check if node is already connected!!!
//
//
if(!isNodeValid(devID))
{
std::cout<<"libgmk: Error adding source to port. Node is not valid: "<<devID<<std::endl;
return false;
}
if(!isNodeInput(devID))
{
std::cout<<"libgmk: Error adding source to port. Node is not an input: "<<devID<<std::endl;
return false;
}
// get the endpoint
nodeRef = getNodeRef(devID);
// make connection in CoreMIDI
srcConErr = MIDIPortConnectSource(inPort, nodeRef, &devID);
if(srcConErr!=noErr)
{
// may need to cover the case where port is already connected!
std::cout<<"libgmk: Error connecting source to port. nodeID: "<<devID<<std::endl;
printCoreMIDIError(srcConErr);
return false;
}
// do what we need to to the callback
// something something
return true;
}
bool MidiInterfaceOSX::removeSource(MidiNodeID devID)
{
OSStatus disConErr = noErr;
MIDIEndpointRef nodeRef;
if (!checkStatus()) // check if MIDI is good
{
std::cout<<"libgmk: Error removing source from port. Midi interface status is not ready."<<std::endl;
return false;
}
if(!isNodeValid(devID))
{
std::cout<<"libgmk: Error removing source from port. Node is not valid: "<<devID<<std::endl;
return false;
}
// get the endpoint for the nodeID
nodeRef = getNodeRef(devID);
if(nodeRef)
{
// disconnect within CoreMIDI
disConErr = MIDIPortDisconnectSource(inPort, nodeRef);
} else {
std::cout<<"libgmk: Error removing source from port. Could not get the endpointRef for ID: "<<devID<<std::endl;
return false;
}
if(disConErr!=noErr)
{
// may need to cover the case where port is already DISconnected!
std::cout<<"libgmk: Error disconnecting source from port. nodeID: "<<devID<<std::endl;
printCoreMIDIError(disConErr);
return false;
}
// do what we need to to the callback
return true;
}
bool MidiInterfaceOSX::addDestination(MidiNodeID devID)
{
OSStatus destConErr = noErr;
MIDIEndpointRef nodeRef; // would this be better as an objectRef?
if (!checkStatus()) // check if MIDI is good
{
std::cout<<"libgmk: Error adding destination to port. Midi interface status is not ready."<<std::endl;
return false;
}
// check if node is already connected!!!
//
//
if(!isNodeValid(devID))
{
std::cout<<"libgmk: Error destination to port. Node is not valid: "<<devID<<std::endl;
return false;
}
if(!isNodeOutput(devID))
{
std::cout<<"libgmk: Error adding source to port. Node is not an input: "<<devID<<std::endl;
return false;
}
// get the endpoint
nodeRef = getNodeRef(devID);
// make connection in CoreMIDI
// destConErr = MIDIPortConnectDest(inPort, nodeRef, &devID);
destConErr = -1; // generic fail
// this is where we use the dispatcher to track connected destinations
// if(destConErr!=noErr)
// {
// // may need to cover the case where port is already connected!
// std::cout<<"libgmk: Error connecting destination to port. nodeID: "<<devID<<std::endl;
// printCoreMIDIError(destConErr);
// }
// do what we need to to the callback
// something something
return true;
}
bool MidiInterfaceOSX::removeDestination(MidiNodeID devID)
{
OSStatus disConErr = noErr;
MIDIEndpointRef nodeRef;
if (!checkStatus()) // check if MIDI is good
{
std::cout<<"libgmk: Error removing source from port. Midi interface status is not ready."<<std::endl;
return false;
}
if(!isNodeValid(devID))
{
std::cout<<"libgmk: Error removing source from port. Node is not valid: "<<devID<<std::endl;
return false;
}
// get the endpoint for the nodeID
nodeRef = getNodeRef(devID);
if(nodeRef)
{
// disconnect within CoreMIDI
// disConErr = MIDIPortDisconnectSource(inPort, nodeRef);
disConErr = -1;
// TODO: use the dispatcher to do this
} else {
std::cout<<"libgmk: Error removing source from port. Could not get the endpointRef for ID: "<<devID<<std::endl;
return false;
}
if(disConErr!=noErr)
{
// may need to cover the case where port is already DISconnected!
std::cout<<"libgmk: Error disconnecting destination from port. nodeID: "<<devID<<std::endl;
printCoreMIDIError(disConErr);
return false;
}
// do what we need to to the callback
return true;
}
bool MidiInterfaceOSX::selfTest(void)
{
// object should be successfully constructed before this call
std::cout<<"*****************************************"<<std::endl;
std::cout<<"Begin MidiInterfaceOSX self-test"<<std::endl;
std::cout<<"libgmk Version: "<<libgmk_VERSION_MAJOR<<"."<<libgmk_VERSION_MINOR<<std::endl;
std::cout<<"*****************************************"<<std::endl;
// open the interface, scan devices
unsigned int numDevs = getNumDevices();
unsigned int numSrcs = getNumSources();
unsigned int numDests = getNumDestinations();
unsigned int numNodes = getNumNodes();
unsigned int totalNodes = numDevs+numSrcs+numDests;
std::cout<<"*****************************************"<<std::endl;
std::cout<<"Testing count getters."<<std::endl;
std::cout<<"*****************************************"<<std::endl;
std::cout<<"Number of devices connected: "<<numDevs<<std::endl;
std::cout<<"Number of sources connected: "<<numSrcs<<std::endl;
std::cout<<"Number of destinations connected: "<<numDests<<std::endl;
std::cout<<"Total nodes: "<<totalNodes<<std::endl;
std::cout<<"Nodes reported: "<<numNodes<<std::endl;
std::cout<<"*****************************************"<<std::endl;
if (totalNodes==numNodes)
{
std::cout<<"TEST PASSED: node counts from OS match those calculated."<<std::endl;
} else {
std::cout<<"TEST FAILED: node counts from OS do not match those calculated."<<std::endl;
}
std::cout<<"*****************************************"<<std::endl;
std::cout<<"Testing reset and base node tracking."<<std::endl;
std::cout<<"*****************************************"<<std::endl;
MidiNodeID startNode = getBaseNode();
MidiNodeID testNode;
std::cout<<"Base node before reset: "<<startNode<<std::endl;
std::cout<<"Resetting CoreMidi, please wait."<<std::endl;
reset();
testNode = startNode;
startNode = getBaseNode();
if(checkStatus())
{
std::cout<<"TEST PASSED: CoreMIDI has been reset."<<std::endl;
} else {
std::cout<<"TEST FAILED: error reseting CoreMIDI."<<std::endl;
}
std::cout<<"Base node after reset: "<<startNode<<std::endl;
if(startNode==testNode)
{
std::cout<<"TEST FAILED: base node number should change after reset."<<std::endl;
}
std::cout<<"*****************************************"<<std::endl;
std::cout<<"Device info tests."<<std::endl;
std::cout<<"*****************************************"<<std::endl;
std::cout<<"Testing MidiInterfaceOSX::isNodeValid()."<<std::endl;
for(unsigned int i = 0; i<numNodes; i++)
{
testNode=startNode+i;
// these should all say true
if(isNodeValid(testNode))
{
std::cout<<"TEST PASSED: MidiInterfaceOSX::isNodeValid() true for nodeID: "<<testNode<<std::endl;
} else {
std::cout<<"TEST FAILED: MidiInterfaceOSX::isNodeValid() false for nodeID: "<<testNode<<std::endl;
}
}
// this should fail
testNode++;
if(isNodeValid(testNode))
{
std::cout<<"TEST FAILED: MidiInterfaceOSX::isNodeValid() true for nodeID: "<<testNode<<std::endl;
} else {
std::cout<<"TEST PASSED: MidiInterfaceOSX::isNodeValid() false for nodeID: "<<testNode<<std::endl;
}
testNode = startNode;
std::string devName("");
MIDIDeviceRef testRef = 0;
std::cout<<"Testing getters for Midi node info."<<std::endl;
std::cout<<"getDeviceRef:"<<std::endl;
for(unsigned int i = 0; i<numNodes; i++)
{
testRef = getNodeRef(testNode);
if(testRef!=0)
{
std::cout<<"TEST PASSED: Retrieved DeviceRef for nodeID: "<<testNode<<std::endl;
} else {
std::cout<<"TEST FAILED: No DeviceRef found for nodeID: "<<testNode<<std::endl;
}
testNode++;
}
std::cout<<"getDeviceProperty: MfgName, SysName, is input, is output."<<std::endl;
testNode = startNode;
std::cout<<"Testing public interfaces to getDeviceProperty()"<<std::endl;
std::cout<<"This is not a strict test since we cannot predict studio state."<<std::endl;
std::vector<MidiNodeID> inNodes, outNodes;
for(unsigned int i = 0; i<numNodes; i++)
{
devName.clear();
if(!isNodeValid(testNode))
{
std::cout<<"Invalid node: "<<testNode<<std::endl;
break;
} else {
//std::cout<<"nodeID: "<<testNode<<std::endl;
}
// Mfg name
//if(!devName.empty()) { devName.clear();}
if(getNodeMfgName(testNode, devName))
{
std::cout<<"NodeID: "<<testNode<<"| Mfg Name: "<<devName<<std::endl;
} else {
std::cout<<"NodeID: "<<testNode<<"| Mfg Name: "<<"not found"<<std::endl;
}
// System name
devName.clear();
if(getNodeSysName(testNode, devName))
{
std::cout<<"NodeID: "<<testNode<<"| System Name: "<<devName<<std::endl;
} else {
std::cout<<"NodeID: "<<testNode<<"| System Name: "<<"not found"<<std::endl;
}
if(isNodeInput(testNode))
{
std::cout<<"NodeID: "<<testNode<<" is an input."<<std::endl;
inNodes.push_back(testNode);
} else {
std::cout<<"NodeID: "<<testNode<<" is NOT an input."<<std::endl;
}
if(isNodeOutput(testNode))
{
std::cout<<"NodeID: "<<testNode<<" is an output."<<std::endl;
outNodes.push_back(testNode);
} else {
std::cout<<"NodeID: "<<testNode<<" is NOT an output."<<std::endl;
}
testNode++;
}
// test input and output (simple)
std::cout<<"*****************************************"<<std::endl;
std::cout<<"MIDI I/O tests."<<std::endl;
std::cout<<"*****************************************"<<std::endl;
// test adding sources and destinations
std::cout<<"Test adding source..."<<std::endl<<std::endl;
bool addSucceed;
MidiNodeID inputTestID = inNodes.at(0);
if(isNodeValid(inputTestID)&&isNodeInput(inputTestID))
{
addSucceed = addSource(inputTestID);
} else {
std::cout<<"TEST FAILED: First input found is no longer valid for addSource() test."<<std::endl;
}
if(!addSucceed)
{
std::cout<<"TEST FAILED: CoreMIDI error connecting input to port. nodeID: "<<inputTestID<<std::endl;
printCoreMIDIError(addSucceed);
std::cout<<addSucceed<<std::endl;
} else {
std::cout<<"TEST PASSED: nodeID: "<<inputTestID<<" succesfully added to port: "<<inPort<<std::endl;
}
std::cout<<std::endl;
std::cout<<"Test adding destination... this will FAIL"<<std::endl<<std::endl;
MidiNodeID outputTestID = outNodes.at(0);
if(isNodeValid(outputTestID)&&isNodeOutput(outputTestID))
{
addSucceed = addDestination(outputTestID);
} else {
std::cout<<"TEST FAILED: First output found is no longer valid for addDestination() test."<<std::endl;
}
if(!addSucceed)
{
std::cout<<"TEST FAILED: CoreMIDI error connecting output to port. nodeID: "<<inputTestID<<std::endl;
printCoreMIDIError(addSucceed);
std::cout<<addSucceed<<std::endl;
} else {
std::cout<<"TEST PASSED: nodeID: "<<outputTestID<<" succesfully added to port: "<<outPort<<std::endl;
}
std::cout<<"Test getting some input..."<<std::endl<<std::endl;
sleep(1);
std::cout<<"LOL/jk... Can't even fake it yet... FAIL"<<std::endl<<std::endl;
std::cout<<"Test removing source..."<<std::endl<<std::endl;
bool removeSucceed;
// we kept track of the input we added, like a good client
// we'll assume the checks above cover our ass
removeSucceed = removeSource(inputTestID);
if(!removeSucceed)
{
std::cout<<"TEST FAILED: failed to remove source from port. nodeID: "<<inputTestID<<std::endl;
} else {
std::cout<<"TEST PASSED: nodeID: "<<outputTestID<<" succesfully removed from port: "<<outPort<<std::endl;
}
std::cout<<std::endl;
std::cout<<"Test remove destination... this will FAIL"<<std::endl<<std::endl;
removeSucceed = removeDestination(outputTestID);
if(!removeSucceed)
{
std::cout<<"TEST FAILED: failed to remove destination from port. nodeID: "<<outputTestID<<std::endl;
} else {
std::cout<<"TEST PASSED: nodeID: "<<outputTestID<<" succesfully removed from port: "<<outPort<<std::endl;
}
}
<file_sep>#ifndef _ABSTRACTMIDIINTERFACE_H_
#define _ABSTRACTMIDIINTERFACE_H_
// libgmk
// © 2015 <NAME>
// AbstractMidiInterface.h
//
// Interface for using the OS provided MIDI libraries.
// Clients will use a handle to this.
//
#include "MidiNode.h"
class AbstractMidiInterface
{
public:
AbstractMidiInterface(){};
virtual ~AbstractMidiInterface(){};
// virtual bool startInterface(void)=0; // same as constructor?
// virtual bool stopInterface(void)=0; // ambiguous.
virtual bool checkStatus(void)=0;
virtual bool reset(void)=0;
// virtual void pauseInterface(void)=0; // MidiDistpatch responsibility
// virtual void closeInterface(void)=0; // same as destructor?
// Node tasks - just enough to figure out which device to use.
virtual MidiNodeID getBaseNode(void)=0;
virtual unsigned int getNumNodes(void)=0;
virtual bool isNodeValid(MidiNodeID devID)=0;
virtual bool getNodeSysName(MidiNodeID devID, std::string &devSysName)=0;
virtual bool getNodeMfgName(MidiNodeID devID, std::string &devMfgName)=0;
virtual bool isNodeInput(MidiNodeID devID)=0;
virtual bool isNodeOutput(MidiNodeID devID)=0;
// sources & destinations
virtual unsigned int getNumDevices(void)=0;
virtual unsigned int getNumSources(void)=0;
virtual unsigned int getNumDestinations(void)=0;
virtual bool addSource(MidiNodeID devID)=0;
virtual bool removeSource(MidiNodeID devID)=0;
virtual bool addDestination(MidiNodeID devID)=0;
virtual bool removeDestination(MidiNodeID devID)=0;
private:
// disallow copy constructor and assignment
// AbstractMidiInterface(const AbstractMidiInterface&);
// AbstractMidiInterface& operator=(const AbstractMidiInterface&);
};
#endif // _ABSTRACTMIDIINTERFACE_H_
<file_sep>// libgmk
// ©2015 <NAME>
// ALL RIGHTS RESERVED
//
// Logger.cpp
// Thread-safe logging
//
<file_sep>// I'm not sure this exists
//
<file_sep>cmake_minimum_required(VERSION 2.6)
# making some tests
set(test_midi_osx_files
Test_MidiOSX.cpp
)
set(test_midi_dispatch_files
Test_MidiDispatch.cpp
)
add_executable(test_midi_osx ${test_midi_osx_files})
add_executable(test_midi_dispatch ${test_midi_dispatch_files})
# just testing this module - private includes are not passed through to the main library, nor should they be.
target_link_libraries(test_midi_osx libgmk)
target_link_libraries(test_midi_dispatch libgmk)
<file_sep>cmake_minimum_required(VERSION 2.6)
project(libgmk)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# versioning
set (libgmk_VERSION_MAJOR 0)
set (libgmk_VERSION_MINOR 1)
# config header for passing build info into compile code
configure_file(
"${PROJECT_SOURCE_DIR}/libgmk.config"
"${PROJECT_BINARY_DIR}/libgmkConfig.h"
)
# modules
add_subdirectory(midi)
add_subdirectory(tests)
add_subdirectory(util)
# list the subprojects for libgmk
set(libgmk_SUBLIBRARIES
gmk_midi
gmk_util
)
# some global compile flags
# this is where we can suppress some debugging to std::cout
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -std=c++11")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g -std=c++11")
if(UNIX)
# this may belong somewhere else
set(STATIC_LINKER_FLAGS "-Wl,--export-all-symbols")
if(APPLE)
# enable the handy CFSTR() macro for initializers
add_definitions("-fconstant-cfstrings")
endif()
endif()
# get all of our sub-libaries together
# create the library - we are not ready for primetime yet
add_library(libgmk INTERFACE )
target_include_directories(libgmk INTERFACE ${PROJECT_BINARY_DIR})
target_link_libraries(libgmk INTERFACE gmk_midi)
| a6132e57f74bd24d0d7f98923adc521b86f8608f | [
"Markdown",
"C",
"CMake",
"C++"
] | 20 | C++ | gmkling/libgmk | 3ebc8ce1d8f37e8b71f7c68464cd5d981861fc5d | 916ae8513ca7f577dbade724d7f18f3053207fb9 |
refs/heads/master | <file_sep>//
// UtilsMacros.h
//
//
// Created by <NAME> on 2015/12/22.
// Copyright © 2015年 <NAME>. All rights reserved.
//
#ifndef UtilsMacros_h
#define UtilsMacros_h
#define NUM @"0123456789"
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
// 标记过期方法
#define EWDeprecated(instead) NS_DEPRECATED(2_0, 2_0, 2_0, 2_0, instead)
// 国际化
#define EWLanguageStr(key) [NSBundle.mainBundle localizedStringForKey:key value:nil table:nil]
//获取系统对象
#define kApplication [UIApplication sharedApplication]
#define kAppWindow [UIApplication sharedApplication].delegate.window
#define kAppDelegate [AppDelegate shareAppDelegate]
#define kRootViewController [UIApplication sharedApplication].delegate.window.rootViewController
#define kUserDefaults [NSUserDefaults standardUserDefaults]
#define kDevice [UIDevice currentDevice]
#define kMachineModel [UIDevice currentDevice].machineModel
#define kMachineModelName [UIDevice currentDevice].machineModelName
#define kNotificationCenter [NSNotificationCenter defaultCenter]
#define kAppVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]
#define kAppBuildVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]
#define kAppDisplayName [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]
//-------------------根据尺寸判断手机型号-------------------------
#define UI_IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define UI_IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define UI_IS_RETINA ([[UIScreen mainScreen] scale] >= 2.0)
#define iphone5 ((kScreenWidth==320)?1:0)
#define iphone6 ((kScreenWidth==375)?1:0)
#define iphone6plus ((kScreenWidth==414)?1:0)
#define SCREENSIZE_IS_XR ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(828, 1792), [[UIScreen mainScreen] currentMode].size) && !UI_IS_IPAD : NO)
#define SCREENSIZE_IS_X ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) && !UI_IS_IPAD : NO)
#define SCREENSIZE_IS_XS_MAX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size) && !UI_IS_IPAD : NO)
#define IS_IPhoneX_All ([UIScreen mainScreen].bounds.size.height == 812 || [UIScreen mainScreen].bounds.size.height == 896)
#define kStatusBarHeight [[UIApplication sharedApplication] statusBarFrame].size.height
#define kNavBarHeight 44.0
#define kTabBarHeight ([[UIApplication sharedApplication] statusBarFrame].size.height>20?83:49)
#define kTopHeight (kStatusBarHeight + kNavBarHeight)
#define kScreen_Bounds [UIScreen mainScreen].bounds
#define kHOME_INDICATOR_HEIGHT (IS_IPhoneX_All ? 34.0f : 0.0f)
#define kMARGIN 10//默认间距
#define FitNavigateHeightToX ((kScreenHeight==812)?88:64)
//获取屏幕宽高比咧
#define Iphone6ScaleWidth kScreenWidth/375.0
#define Iphone6ScaleHeight kScreenHeight/667.0
//根据ip6的屏幕来拉伸
#define KScaleWidth(width) ((width)*(kScreenWidth/375.0f))
//强弱引用
#define kWeakSelf(type) __weak typeof(type) weak##type = type;
#define kStrongSelf(type) __strong typeof(type) type = weak##type;
//View 圆角和加边框
#define ViewBorderRadius(View, Radius, Width, Color)\
\
[View.layer setCornerRadius:(Radius)];\
[View.layer setMasksToBounds:YES];\
[View.layer setBorderWidth:(Width)];\
[View.layer setBorderColor:[Color CGColor]]
// View 圆角
#define ViewRadius(View, Radius)\
\
[View.layer setCornerRadius:(Radius)];\
[View.layer setMasksToBounds:YES]
// 十六进制颜色
#define hexColor(colorV) [UIColor colorWithHexString:colorV]
///IOS 版本判断
#define IOSAVAILABLEVERSION(version) ([[UIDevice currentDevice] availableVersion:version] < 0)
// 当前系统版本--谨慎使用
#define CurrentSystemVersion [[UIDevice currentDevice].systemVersion doubleValue]
//当前语言
#define CurrentLanguage ([NSLocale preferredLanguages] objectAtIndex:0])
//-------------------打印日志-------------------------
//DEBUG 模式下打印日志,当前行
#ifdef DEBUG
#define EWLog(...) printf("[%s] %s [第%d行]: %s\n", __TIME__ ,__PRETTY_FUNCTION__ ,__LINE__, [[NSString stringWithFormat:__VA_ARGS__] UTF8String]);
#else
#define EWLog(...)
#endif
//拼接字符串
#define NSStringFormat(format,...) [NSString stringWithFormat:format,##__VA_ARGS__]
//定义UIImage对象
#define ImageWithFile(_pointer) [UIImage imageWithContentsOfFile:([[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@@%dx", _pointer, (int)[UIScreen mainScreen].nativeScale] ofType:@"png"])]
#define IMAGE_NAMED(name) [UIImage imageNamed:name]
//数据验证
#define StrValid(f) (f!=nil && [f isKindOfClass:[NSString class]] && ![f isEqualToString:@""])
#define SafeStr(f) (StrValid(f) ? f:@"")
#define HasString(str,key) ([str rangeOfString:key].location!=NSNotFound)
#define ValidStr(f) StrValid(f)
#define ValidDict(f) (f!=nil && [f isKindOfClass:[NSDictionary class]])
#define ValidArray(f) (f!=nil && [f isKindOfClass:[NSArray class]] && [f count]>0)
#define ValidNum(f) (f!=nil && [f isKindOfClass:[NSNumber class]])
#define ValidClass(f,cls) (f!=nil && [f isKindOfClass:[cls class]])
#define ValidData(f) (f!=nil && [f isKindOfClass:[NSData class]])
//获取一段时间间隔
#define kStartTime CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
#define kEndTime EWLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)
//打印当前方法名
#define ITTDPRINTMETHODNAME() ITTDPRINT(@"%s", __PRETTY_FUNCTION__)
//发送通知
#define KPostNotification(name,obj) [[NSNotificationCenter defaultCenter] postNotificationName:name object:obj];
// 防止多次调用
#define kPreventRepeatClickTime(_seconds_) \
static BOOL shouldPrevent; \
if (shouldPrevent) return; \
shouldPrevent = YES; \
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((_seconds_) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ \
shouldPrevent = NO; \
}); \
//单例化一个类
#define SINGLETON_FOR_HEADER(className) \
\
+ (className *)shared##className;
#define SINGLETON_FOR_CLASS(className) \
\
+ (className *)shared##className { \
static className *shared##className = nil; \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
shared##className = [[self alloc] init]; \
}); \
return shared##className; \
}
// 回到主线程
#define within_main_thread(block,...)\
do {\
if ([[NSThread currentThread] isMainThread]) {\
if (block) {\
block(__VA_ARGS__);\
}\
} else {\
if (block) {\
dispatch_async(dispatch_get_main_queue(), ^{\
block(__VA_ARGS__);\
});\
}\
}\
} while (0);\
//-------------------线程安全-------------------------
// 同步
#define dispatch_main_sync_safe(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_sync(dispatch_get_main_queue(), block);\
}
// 异步
#define dispatch_main_async_safe(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}
#endif /* UtilsMacros_h */
<file_sep>use_frameworks!
platform :ios, '8.0'
target 'EWObjcTools_Example' do
pod 'EWObjcTools', :path => '../'
target 'EWObjcTools_Tests' do
inherit! :search_paths
end
end
<file_sep># EWObjcTools
[](https://travis-ci.org/ericwangtju/EWObjcTools)
[](https://cocoapods.org/pods/EWObjcTools)
[](https://cocoapods.org/pods/EWObjcTools)
[](https://cocoapods.org/pods/EWObjcTools)
## Example
To run the example project, clone the repo, and run `pod install` from the Example directory first.
## Requirements
## Installation
EWObjcTools is available through [CocoaPods](https://cocoapods.org). To install
it, simply add the following line to your Podfile:
```ruby
pod 'EWObjcTools'
```
## Author
ericwangtju, <EMAIL>
## License
EWObjcTools is available under the MIT license. See the LICENSE file for more info.
| 8dcba73636cca25e6991743adbcba7a70a066042 | [
"Markdown",
"C",
"Ruby"
] | 3 | C | ericwangtju/EWObjcTools | ec402cfb9465b0f3c29f91c0b03ef283ae56a614 | f4142ea87f86f353e5b74b8dc1ef16e0170a4b4c |
refs/heads/master | <repo_name>flowermasters/flowercodeTest<file_sep>/apps/Test/TestController.php
<?php
namespace apps\Test;
class TestController extends \framework\core\system\System_controller
{
function loginAction()
{
$this->views = new TestViews;
$this->views->content();
}
}<file_sep>/apps/Test/TestModels.php
<?php
namespace apps\Test;
class TestModels extends \framework\core\system\System_Models
{
public function TestModel()
{
R::setup($db['name'],$db['user_name'],$db['password'] );
}
}<file_sep>/framework/core/system/System_controller.php
<?php
namespace framework\core\system;
/*
Это главный контролер
*/
class System_Controller
{
// function __construct()
// {
// echo "<br>string";
// }
}
<file_sep>/framework/core/system/System_views.php
<?php
namespace framework\core\system;
/*
Это главная вюшка
*/
class System_views
{
}<file_sep>/apps/Admin/AdminController.php
<?php
namespace apps\Admin;
/*
если выводится ошибка то зайдите в файл xcrud_config находяшимся в /framework/core/moduls/xcrud/
и поменяй те там в переменной $db_xcrud праметры на свои
*/
class AdminController extends \framework\core\system\System_controller
{
function Articles()
{
// $this->views = new AdminViews;
// $this->views->ArticlesViews();
// $xcrud = Xcrud::get_instance();
// $xcrud->table('materials');
// echo $xcrud->render();
}
}<file_sep>/apps/Admin/AdminUrl.php
<?php
/*
url('/admin/', 'apps\Admin\AdminController' ,'Articles'),
В первом '/admin/' это путь по которому будет выводится инфа
в втором 'apps\Admin\AdminController' это путь контролеру в котором есть нужная нам функция
в третих это функчия которая нам нужна
*/
return array(
url('/admin/', 'apps\Admin\AdminController' ,'Articles'),
);
?><file_sep>/apps/Test/TestUrl.php
<?php
/*
url('/', 'apps\Test\TestController' ,'loginAction'),
В первом '/', это путь по которому будет выводится инфа
в втором 'apps\Test\TestController' это путь контролеру в котором есть нужная нам функция
в третих 'loginAction' это функчия которая нам нужна
*/
return array(
url('/', 'apps\Test\TestController' ,'loginAction'),
);
?><file_sep>/framework/core/moduls/urls.php
<?php
/*
URLS.php это файл ЧПУ
на самом верху пишется путь к файлу которому мы хотим работать урлами
И это всегда должны быть файлы приложений с концом Url.php
*/
require BASE_DIR . '/apps/Admin/AdminUrl.php';
require BASE_DIR . '/apps/Test/TestUrl.php';
function url($ur = '',$className,$name ){
$url = $_SERVER['REQUEST_URI'];
if($ur === $url){
$con = new $className;
$con->$name();
};
}<file_sep>/framework/core/db.php
<?php
namespace framework\core;
class Db
{
public function __construct()
{
$this->db = new PDO('mysql:host=localhost;dbname=itninja', 'root', '');
}
public function query($sql)
{
$query = $this->db->query($sql);
$result = $query->fetchColumn();
return $query;
}
public function row($sql)
{
$result = $this->query($sql);
return $result->fetchAll();
}
public function column($spl)
{
$result = $this->query($sql);
return $result->fetchColumn();
}
}
<file_sep>/apps/Test/TestViews.php
<?php
namespace apps\Test;
class TestViews extends \framework\core\system\System_views
{
public function header()
{
require BASE_DIR.'/templates/test/part/header.html';
}
public function content()
{
require BASE_DIR.'/templates/test/index.html';
}
public function saidbar()
{
require BASE_DIR.'/templates/test/part/saibar.html';
}
public function footer()
{
require BASE_DIR.'/templates/test/part/footer.html';
}
}<file_sep>/apps/Admin/AdminViews.php
<?php
namespace apps\Admin;
class AdminViews extends \framework\core\system\System_views
{
public function ArticlesViews()
{
require BASE_DIR.'/templates/admin/content.html';
}
}<file_sep>/framework/core/system/System_models.php
<?php
namespace framework\core\system;
/*
Это главная модель
*/
class System_Models
{
} | f6942e32af1f922ea7312bdb2711e2cfd567d84c | [
"PHP"
] | 12 | PHP | flowermasters/flowercodeTest | 51c2e6d8ac6297d939bc3ec4d1456a1e1c749541 | f225ca5a13f77e85d043264e9da8c6ab4bec6055 |
refs/heads/master | <file_sep># Drones
Este es un proyecto del equipo Paperclip Task Force para el concurso HackaDron:
Un software que permite utilizar drones autónomos para recoger basura en espacios abiertos, utilizando machine learning y computer vision para identificar la basura a partir las imágenes de la cámara del dron.
# Funcionamiento
Usamos un algoritmo de detección de esquinas para identificar puntos en los que puede haber objetos:
[](http://gonthalo.github.io/Drones "Original")
[](http://gonthalo.github.io/Drones "Puntos identificados")
(habrá continuación)
<file_sep>import csv
import sys
from PIL import Image
from time import time
import pylab as pl
import numpy as np
from random import random
import cv2
import sklearn
from sklearn import metrics, cluster
from matplotlib import pyplot as plt
matriz = []
desviacion = [(0, 0), (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, 1), (-1 , -1), (2, 1), (2, 2), (-2, 2), (-1, 2), (-2, -1), (0, -2)]
# esta es la forma del "punto" que la function generate() pone en la imagen
def generate(n): #genera una imagen de prueba con "n" puntos de color aleatorio y fondo verde
img = Image.new("RGB", (400, 400), "black")
for ii in range(400):
for jj in range(400):
img.putpixel((ii, jj), (15 + int(random()*10), 220 + int(random()*10), 40 + int(random()*10)))
for ii in range(n):
px = 5 + int(random()*390)
py = 5 + int(random()*390)
color = tuple([int(random()*255) for kk in range(3)])
for xx, yy in desviacion:
img.putpixel((px + xx, py + yy), color)
return img
def get_shades(imag): #toma una imagen PIL en color y devuelve tres imagenes en blanco y negro que coinciden con las capas de cada color
lista = []
for index in range(3):
imag2 = Image.new("L", imag.size, 0)
for ii in range(imag.size[0]):
for jj in range(imag.size[1]):
imag2.putpixel((ii, jj), imag.getpixel((ii, jj))[index])
lista.append(imag2)
return tuple(lista)
def parseimg(imag): #convierte una imagen PIL en una matriz
return [[imag.getpixel((ii, jj)) for jj in range(imag.size[0])] for ii in range(imag.size[1])]
def get_points(archivo): #identifica posibles puntos de interes en una imagen y los devuelve, mostrando su posicion en la imagen
total = []
imag = Image.open(archivo, "r")
for index in range(3):
img = get_shades(imag)[index]
img.save("auxiliar.png")
img = cv2.imread("auxiliar.png")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
corners = cv2.goodFeaturesToTrack(gray,25,0.01,10)
corners = np.int0(corners).tolist()
total += corners
imag = cv2.imread(archivo)
for i in np.array(total):
x,y = i.ravel()
cv2.circle(imag,(x,y),7,(245, 10, 10),1)
plt.imshow(imag),plt.show()
cv2.imwrite("resultado.png", imag)
return total
def get_clusters(points):
distance_matrix = metrics.pairwise.euclidean_distances(map(lambda x: x[0], points))
afin = cluster.AffinityPropagation(preference = -50).fit(distance_matrix)
centros = afin.cluster_centers_indices_
print len(centros)
return centros
imagen1 = generate(4)
imagen1.save("imagen_dron.png")
puntitos = get_points("imagen_dron.png")
print puntitos
print get_clusters(puntitos)
print get_points("prado.jpg")
| 4a20ed37740425f568d9f71f76323f9fa948aa2c | [
"Markdown",
"Python"
] | 2 | Markdown | gonthalo/Drones | 6efd7b670d7baad8ee39dca6955ed9b55058ff0d | 5eb043705bd84086d6dd880f7dd7aaef5f91d748 |
refs/heads/master | <repo_name>AdamDrueKing/ListsPractice<file_sep>/ListsPractice/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ListsPractice
{
class Program
{
static void Main(string[] args)
{
//List<int> favNumbers = new List<int>();
//favNumbers.Add(7);
//favNumbers.Add(25);
//favNumbers.Add(30);
//foreach(int number in favNumbers)
//{
// Console.WriteLine(number);
//}
//Console.WriteLine(favNumbers.Count);
//List<string> books = new List<string> { "Cat in the hat", "Todad and frog", "Green eggs and ham" };
//Console.WriteLine(books[0]);
//books.Insert(0, "Horton hears a who");
//Console.WriteLine(books[0]);
////Create a list and add 5 animals using the .Add()
////Print each animal in the list
//List<string> animals = new List<string>();
//animals.Add("Lion");
//animals.Add("Dolphin");
//animals.Add("Hippo");
//animals.Add("Platypus");
//animals.Add("Hare");
//foreach(string animal in animals)
//{
// Console.WriteLine(animal);
//}
////Create the following list:
////A bool list {true, false, false, true, false}
////Loop through each value
////If the value is true, print "Better bring an umbrella"
////If the value is false print "No rain today enjoy the sun"
//List<bool> trueFalse = new List<bool> {true, false, false, true, false };
//foreach (bool answer in trueFalse)
//{
// if (answer == true)
// {
// Console.WriteLine("Better bring an umbrella");
// }
// else
// {
// Console.WriteLine("No rain today, enjoy the sun");
// }
//}
//List<string> favFoods = new List<string>() { "Steak", "fish", "katsudon", "Ice cream", "nachos" };
//if (favFoods.Contains("fish"))
// {
// Console.WriteLine("I like fish too!!!");
//}
////Create a list with the following numbers: 1 23 9 77 922 6 32 63 14 5
////Use the contains mehtod with the following values: 23 77 15
////Remove these elements: 23 77 32 and 6
////Use .Contains() again on these values: 23 77 15
//List<int> numbers = new List<int> { 1, 23, 9, 77, 922, 6, 32, 63, 14, 5 };
//if (numbers.Contains(23))
//{
// Console.WriteLine("Busted!");
// numbers.Remove(23);
//}
//if (numbers.Contains(77))
//{
// Console.WriteLine("Busted, again!");
// numbers.Remove(77);
//}
//if (numbers.Contains(15))
//{
// Console.WriteLine("Busted, once more!");
//}
//if (numbers.Contains(32))
//{
// numbers.Remove(32);
//}
//if (numbers.Contains(6))
//{
// numbers.Remove(6);
//}
//if(numbers.Contains(23))
//{
// Console.WriteLine("Busted!");
//}
//if (numbers.Contains(77))
//{
// Console.WriteLine("Busted, again!");
//}
//if (numbers.Contains(15))
//{
// Console.WriteLine("Busted, once more!");
//}
////OR
//List<int> numbersTwo = new List<int> { 1, 23, 9, 77, 922, 6, 32, 63, 14, 5 };
//Console.WriteLine(numbersTwo.Contains(23));
//Console.WriteLine(numbersTwo.Contains(77));
//Console.WriteLine(numbersTwo.Contains(15));
//numbersTwo.Remove(23);
//numbersTwo.Remove(77);
//numbersTwo.Remove(32);
//numbersTwo.Remove(6);
//Console.WriteLine(numbersTwo.Contains(23));
//Console.WriteLine(numbersTwo.Contains(77));
//Console.WriteLine(numbersTwo.Contains(15));
//Ask the user for a movie***
//if the movie is not in the list, add it***
//inform the user that the movie has been added***
//if the movie IS in the list, inform the user that the movie is on the way
//if the user enters quit, the program should exit
//the user should be able to add as many movies as they want
//When the user quits, show them all of the movies that are one the list
Console.WriteLine("Welcome to the movie database!!! Please select a movie of your choice.");
List<string> movieDatabase = new List<string>();
movieDatabase.Add("Rocky");
movieDatabase.Add("Nightmare on Elm Street");
movieDatabase.Add("Hocus Pocus");
movieDatabase.Add("3 Ninjas");
movieDatabase.Add("Howard the Duck");
movieDatabase.Add("The Last Dragon");
string userAnswer = Console.ReadLine();
//Do While
if (userAnswer == "quit")
{
Console.WriteLine("Thank you for your time. Here is a list of our movies: " + movieDatabase);
}
else
{
}
do
{
if (movieDatabase.Contains(userAnswer))
{
Console.WriteLine("Your movie is on the way!!!");
}
else
{
movieDatabase.Add(userAnswer);
Console.WriteLine("The movie title isn't available, but has been added. Please be patient");
}
Console.WriteLine("Would you like to select another movie?");
if (movieDatabase.Contains(userAnswer))
{
Console.WriteLine("Your movie is on the way!!!");
}
else
{
movieDatabase.Add(userAnswer);
Console.WriteLine("The movie title isn't available, but has been added. Please be patient");
}
}
while (userAnswer != "quit");
string movieSearch;
Console.WriteLine("Welcome to ...");
List<string> movies = new List<string> { "" };
}
}
}
| 21aecbbb8e5069af611d831a88b1b5d503d38a32 | [
"C#"
] | 1 | C# | AdamDrueKing/ListsPractice | 28fdc27996d08257e499ac562c47a17bc0537d51 | 60cb07b7f34cd059434e72fa36cc74a0997796f9 |
refs/heads/master | <file_sep>require "carve_range/version"
require "date"
module CarveRange
def self.carve(old_date_range, new_date_range, space=0)
old_start = old_date_range.first
old_end = old_date_range.last
new_start = new_date_range.first
new_end = new_date_range.last
if new_start <= old_start && new_end < old_end # +__|==+--|
modified_date_range = old_date_range.select { |d| d > (new_end + space)? d : false }
return modified_date_range.first..modified_date_range.last, new_date_range
elsif new_start > old_start && new_end >= old_end # |--+==|__+
modified_date_range = old_date_range.select { |d| d < (new_start - space)? d : false }
return modified_date_range.first..modified_date_range.last, new_date_range
elsif new_start > old_start && new_end < old_end # |-+=+-|
pre_date_range = old_date_range.select { |d| d < (new_start - space)? d : false }
post_date_range = old_date_range.select { |d| d > (new_end + space)? d : false }
return pre_date_range.first..pre_date_range.last, post_date_range.first..post_date_range.last, new_date_range
elsif new_start <= old_start && new_end >= old_end # +=|=====|=+
return nil, new_date_range
end
return old_date_range, new_date_range
end
end
<file_sep>source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/possibly/carve_range" }
# Specify your gem's dependencies in carve_range.gemspec
gemspec
<file_sep># CarveRange
Takes two date ranges (A,B) and returns an array of date ranges in A that do not overlap with date range B, and includes B.
## Example 1
Date Range A: #########
Date Range B: #####
Carve(A,B): [##, ##, ####]
## Example 1 Why?
Date Range A: #########
Date Range B: #####
Date Range A': ##
Date Range A'': ##
A' + A'' + B: [##, ##, ####]
## Example 2
Date Range A: #####
Date Range B: #####
Carve(A,B): [##,#####]
## Example 3
Date Range A: #####
Date Range B: ###
Carve(A,B): [##,###]
## Example 4
Date Range A: #####
Date Range B: #######
Carve(A,B): [#######]
## Use Case
Your tracking your activity in a calendar for a month. For days 1-30, you Went Jogging, so you create an Event that Starts At Day 1 and Ends At day 30. Oops! You double-check your journal and realize that Day 15-18 you said you went Jogging, but actually you Stayed Home.
You can "carve" the 1 Event (that contains a Start Date and and End Date) with this gem such that you could get 3 Events. The first event is Days 1-14 (you Went Jogging those days). The second event is Days 15-18 (you Stayed Home those days). The third event is Days 19-30 (you Went Jogging those days).
This gem could take the first Event's date range (Date Range A) and another Date Range (Event you want to add to the calendar, Days 15-18, Date Range B) and return [Date Range A' (1-14), Date Range A'' (19-30), Date Range B (15-18)].
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'carve_range'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install carve_range
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/possibly/carve_range.
## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
<file_sep>require "test_helper"
class CarveRangeTest < Minitest::Test
def setup
@old_date_range = Date.today..Date.today+7
end
def test_that_it_has_a_version_number
refute_nil ::CarveRange::VERSION
end
def test_new_date_overlaps_only_start_of_old_date
# Scenario: +__|==+---|
new_date_range = Date.today-7..Date.today+3
expected_old_date_range = Date.today+4..Date.today+7
expected_new_date_range = new_date_range
result = ::CarveRange.carve(@old_date_range, new_date_range)
assert expected_old_date_range == result.first
assert new_date_range == result[1]
end
def test_new_date_overlaps_only_end_of_old_date
# Scenario: |--+==|__+
new_date_range = Date.today+3..Date.today+10
expected_old_date_range = Date.today..Date.today+2
result = ::CarveRange.carve(@old_date_range, new_date_range)
assert expected_old_date_range == result.first
assert new_date_range == result[1]
end
def test_new_date_overlaps_only_middle_of_old_date
# Scenario: |-+=+-|
new_date_range = Date.today+1..Date.today+4
expected_pre_date_range = Date.today..Date.today
expected_post_date_range = Date.today+5..@old_date_range.last
result = ::CarveRange.carve(@old_date_range, new_date_range)
assert_equal expected_pre_date_range, result.first
assert_equal expected_post_date_range, result[1]
assert_equal new_date_range, result[2]
end
def test_new_date_overlaps_entirety_of_old_date
# Scenario: +=|=====|=+
new_date_range = Date.today-1..Date.today+8
expected_old_date_range = nil
result = ::CarveRange.carve(@old_date_range, new_date_range)
assert expected_old_date_range == result.first
assert new_date_range == result[1]
end
def test_new_date_and_old_date_dont_overlap
# Scenario: +==+ |--|
new_date_range = Date.today-5..Date.today-3
result = ::CarveRange.carve(@old_date_range, new_date_range)
assert @old_date_range == result.first
assert new_date_range == result[1]
end
end
| 3d0cbd17a98bfac1a33eabccfc07a0d9f7458a67 | [
"Markdown",
"Ruby"
] | 4 | Ruby | possibly/carve_range | cf65afd343ae42439b3bbd34a9f777b3f3353896 | fe424389546f6af7da61cd477d867ff2e527105b |
refs/heads/master | <file_sep>import { AngularEditorConfig } from '@kolkov/angular-editor';
export const editorConfigImport : AngularEditorConfig= {
editable: true,
spellcheck: true,
height: 'auto',
minHeight: '0',
maxHeight: 'auto',
width: 'auto',
minWidth: '0',
translate: 'yes',
enableToolbar: true,
showToolbar: true,
placeholder: 'Enter text here...',
defaultParagraphSeparator: '',
defaultFontName: '',
defaultFontSize: '',
fonts: [
{ class: 'arial', name: 'Arial' },
{ class: 'times-new-roman', name: 'Times New Roman' },
{ class: 'calibri', name: 'Calibri' },
{ class: 'comic-sans-ms', name: 'Comic Sans MS' }
],
customClasses: [
{
name: 'quote',
class: 'quote',
},
{
name: 'redText',
class: 'redText'
},
{
name: 'titleText',
class: 'titleText',
tag: 'h1',
},
],
uploadUrl: 'v1/image',
// upload: (file: File) => { ... }
uploadWithCredentials: false,
sanitize: false,
toolbarPosition: 'top',
toolbarHiddenButtons: [
['bold', 'italic'],
['fontSize']
]
};<file_sep>enum RubriqueEnum {
ALLER_FRANCE = "Je soushaite aller en France",
ECOLE_FRANCE = "Les écoles en France",
VYG = "Voyage",
LGMT = "Logement",
AVI = "AVI",
VISA = "Visas",
CAMPUS = "Campus France",
EN_FRANCE = "Je suis en France"
}
export class Rubrique {
id: string;
pays: string;
data: any;
name: string;
sRubrique: string;
constructor(rubriqueEnum: string, data: any, sRubrique: string, pays: string) {
this.data = data;
this.name = rubriqueEnum;
this.sRubrique = sRubrique;
this.pays = pays;
}
}
<file_sep>const config = require('config.json');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = require('_helpers/db');
const Temoignage = db.Temoignage;
module.exports = {
getAll,
getById,
create,
update,
delete: _delete
};
async function getAll() {
return await Temoignage.find();
}
async function getById(id) {
return await Temoignage.findById(id);
}
async function create(temoignageParam) {
const temoignage = new Temoignage({ data: temoignageParam.dataTemoignage });
// save temoignage
await temoignage.save();
}
async function _delete(id) {
await Temoignage.findByIdAndRemove(id);
}
async function update(id, param) {
const temoignage = await Temoignage.findById(id);
// validate
if (!temoignage) throw 'Témoignage non trouvé';
Object.assign(temoignage, param);
await temoignage.save();
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CreateActeurComponent } from './create-acteur/create-acteur.component';
import { FlexLayoutModule } from '@angular/flex-layout';
import { FlexModule } from '@angular/flex-layout/flex';
import { AngularEditorModule } from '@kolkov/angular-editor';
import { ActeurRoutingModule } from './acteur-routing.module'
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule, MatLabel } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { RouterModule } from '@angular/router';
import { DisplayActeurComponent } from './display-acteur/display-acteur.component';
import { SafeHtmlPipe } from '@app/acteur/safe-html.pipe';
import { EditActeurComponent } from './edit-acteur/edit-acteur.component';
@NgModule({
declarations: [CreateActeurComponent, DisplayActeurComponent, SafeHtmlPipe, EditActeurComponent],
imports: [
CommonModule,
ActeurRoutingModule,
RouterModule,
AngularEditorModule,
FlexModule,
FlexLayoutModule,
FormsModule,
ReactiveFormsModule,
MatButtonModule,
MatFormFieldModule,
MatSelectModule,
MatInputModule
],
exports: [
MatSelectModule,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule
]
})
export class ActeurModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AlertService, ClientHttpService } from '@app/_services';
import { first } from 'rxjs/operators';
@Component({
selector: 'app-display-acteur',
templateUrl: './display-acteur.component.html',
styleUrls: ['./display-acteur.component.less']
})
export class DisplayActeurComponent implements OnInit {
acteurs: any[] = [];
acteur = null;
isDeleting: boolean = true;
constructor(private clientHttpService: ClientHttpService,
private alertService: AlertService,
private router: Router) { }
ngOnInit(): void {
this.clientHttpService.getAllActeur().subscribe((values) => {
this.acteurs = values;
})
}
deleteTemoignage(id: string) {
this.isDeleting = true;
this.clientHttpService.deleteActeur(id)
.pipe(first())
.subscribe(() => {
this.acteur = this.acteurs.filter(x => x.id !== id);
this.isDeleting = false;
this.alertService.success("Suppression réussi");
this.ngOnInit();
},
(error) => {
this.alertService.error(error);
});
}
}
<file_sep>export * from './client-http.service';
export * from './alert.service';
<file_sep>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CreateActeurComponent } from './create-acteur/create-acteur.component';
import { DisplayActeurComponent } from './display-acteur/display-acteur.component';
import { EditActeurComponent } from './edit-acteur/edit-acteur.component';
const routes: Routes = [
{ path: '', component: DisplayActeurComponent },
{ path: 'create', component: CreateActeurComponent },
{ path: 'edit/:id', component: EditActeurComponent },
{ path: '**', component: DisplayActeurComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ActeurRoutingModule { }
<file_sep>const config = require('config.json');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = require('_helpers/db');
const User = db.User;
module.exports = {
authenticate,
getAll,
getById,
create,
update,
delete: _delete
};
async function authenticate({ user_login, user_pass }) {
const user = await User.findOne({ user_login });
if (user && bcrypt.compareSync(user_pass, user.user_pass)) {
const token = jwt.sign({ sub: user._id }, config.secret, { expiresIn: '7d' });
return {
...user.toJSON(),
token
};
}
}
async function getAll() {
return await User.find();
}
async function getById(id) {
return await User.findById(id);
}
async function create(userParam) {
// validate
console.log("when creation a user ", userParam);
if (await User.findOne({ user_login: userParam.user_login })) {
throw `Nom d'utilisateur ` + userParam.user_login + ` existant`;
}
const user = new User(userParam);
// hash user_pass
if (userParam.user_pass) {
user.user_pass = <PASSWORD>.hashSync(userParam.user_pass, 10);
}
// save user
await user.save();
}
async function update(id, userParam) {
const user = await User.findById(id);
// validate
if (!user) throw 'Utilisateur non trouvé';
if (user.user_login !== userParam.user_login && await User.findOne({ user_login: userParam.user_login })) {
throw `Nom d'utilisateur ` + userParam.user_login + ` existant`;
}
// hash user_pass if it was entered
if (userParam.user_pass) {
userParam.user_pass = <PASSWORD>.hashSync(userParam.user_pass, 10);
}
// copy userParam properties to user
Object.assign(user, userParam);
await user.save();
}
async function _delete(id) {
await User.findByIdAndRemove(id);
}<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CreateTemoignageComponent } from './create-temoignage/create-temoignage.component';
import { DisplayTemoignageComponent } from './display-temoignage/display-temoignage.component';
import { EditTemoignageComponent } from './edit-temoignage/edit-temoignage.component';
const routes: Routes = [
{ path: '', component: DisplayTemoignageComponent },
{ path: 'create', component: CreateTemoignageComponent },
{ path: 'edit/:id', component: EditTemoignageComponent },
{ path: '**', component: DisplayTemoignageComponent }
//{ path: 'create-sous-rubrique', component: SousRubriqueComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class TemoignageRoutingModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Rubrique } from '@app/_models/rubrique';
import { AlertService, ClientHttpService } from '@app/_services';
import { first } from 'rxjs/operators';
@Component({
selector: 'app-display-rubrique',
templateUrl: './display-rubrique.component.html',
styleUrls: ['./display-rubrique.component.less']
})
export class DisplayRubriqueComponent implements OnInit {
rubriques: any[] = [];
rubrique = null;
isDeleting: boolean = true;
constructor(private clientHttpService: ClientHttpService,
private alertService: AlertService,
private route: ActivatedRoute,
private router: Router) { }
ngOnInit(): void {
this.clientHttpService.getAllRubrique().subscribe((values) => {
this.rubriques = values;
})
}
deleteTemoignage(id: string) {
this.isDeleting = true;
this.clientHttpService.deleteRubrique(id)
.subscribe(() => {
this.rubrique = this.rubriques.filter(x => x.id !== id);
this.isDeleting = false;
this.ngOnInit();
this.alertService.success("Suppression réussi");
},
(error) => {
this.alertService.error(error);
});
}
}
<file_sep>const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
user_login: { type: String, unique: true, required: true },
user_firstname: { type: String, required: true },
user_lastname: { type: String, required: true },
user_pass: { type: String, required: true },
user_nikname: { type: String, required: false },
user_email: { type: String, required: false },
user_url: { type: String, required: false },
user_registered: { type: Date, default: Date.now },
user_activation_key: { type: String, required: false },
user_status: { type: String, required: false },
display_name: { type: String, required: false }
});
// schema.set('toJSON', {
// virtuals: true,
// versionKey: false,
// transform: function (doc, ret) {
// delete ret._id;
// delete ret.hash;
// }
// });
module.exports = mongoose.model('User', schema);<file_sep>import { Component, OnInit, SecurityContext } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { countries } from '@app/_helpers/countries.const';
import { editorConfigImport } from '@app/_helpers/editor-config.const';
import { ClientHttpService, AlertService } from '@app/_services';
import { Observable } from 'rxjs';
@Component({
selector: 'app-edit-temoignage',
templateUrl: './edit-temoignage.component.html',
styleUrls: ['./edit-temoignage.component.less']
})
export class EditTemoignageComponent implements OnInit {
htmlContent: any = "";
editorConfig = editorConfigImport;
countryList = countries.map(val => { return val.name });
sRubrique$: Observable<any>;
chosenCountry: string = "";
constructor(private clientHttpService: ClientHttpService,
private alertService: AlertService,
private route: ActivatedRoute,
private router: Router,
private sanitizer: DomSanitizer,
private formBuilder: FormBuilder) { }
ngOnInit(): void {
const id = this.route.snapshot.params['id'];
this.clientHttpService.getTemoignageById(id).subscribe((value) => {
this.htmlContent = value.data
})
}
onFormSubmit() {
const id = this.route.snapshot.params['id'];
if (this.htmlContent) {
this.clientHttpService.updateTemoignage(id, {
data: this.htmlContent
}).subscribe(() => {
this.router.navigate(['/temoignage'], { relativeTo: this.route });
this.alertService.success("Mise a jour réussi");
},
(error) => {
this.alertService.error(error);
});
}
}
}<file_sep>import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { AngularEditorModule } from '@kolkov/angular-editor';
import { CreateRubriqueComponent } from './create-rubrique/create-rubrique.component';
import { RubriqueRoutingModule } from './rubrique-routing.module';
import { DisplayRubriqueComponent } from './display-rubrique/display-rubrique.component';
import { SafeHtmlPipe } from '@app/rubrique/safe-html.pipe';
// Flexbox and CSS Grid (both)
import { FlexLayoutModule } from '@angular/flex-layout';
// Flexbox mode (only)
import { FlexModule } from '@angular/flex-layout/flex';
import { SousRubriqueComponent } from './sous-rubrique/sous-rubrique.component';
import {RouterModule} from '@angular/router';
import { EditRubriqueComponent } from './edit-rubrique/edit-rubrique.component';
@NgModule({
declarations: [CreateRubriqueComponent, DisplayRubriqueComponent, SafeHtmlPipe, SousRubriqueComponent, EditRubriqueComponent],
imports: [
CommonModule,
RubriqueRoutingModule,
RouterModule,
AngularEditorModule,
FormsModule,
ReactiveFormsModule,
MatSelectModule,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
FlexLayoutModule,
FlexModule
],
exports: [
MatSelectModule,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule
],
})
export class RubriqueModule { }
<file_sep>import { Component, OnInit, SecurityContext } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { countries } from '@app/_helpers/countries.const';
import { editorConfigImport } from '@app/_helpers/editor-config.const';
import { Rubrique } from '@app/_models/rubrique';
import { ClientHttpService, AlertService } from '@app/_services';
import { Observable } from 'rxjs';
enum RubriqueEnum {
ALLER_FRANCE = "Je souhaite aller en France",
ECOLE_FRANCE = "Les écoles en France",
VYG = "Voyage",
LGMT = "Logement",
AVI = "AVI",
VISA = "Visas",
CAMPUS = "Campus France",
EN_FRANCE = "Je suis en France"
}
@Component({
selector: 'app-edit-rubrique',
templateUrl: './edit-rubrique.component.html',
styleUrls: ['./edit-rubrique.component.less']
})
export class EditRubriqueComponent implements OnInit {
htmlContent: any = "";
rubriqueEnum = RubriqueEnum;
editorConfig = editorConfigImport;
readonly rubriqueList: string[] = [
RubriqueEnum.ALLER_FRANCE,
RubriqueEnum.AVI,
RubriqueEnum.CAMPUS,
RubriqueEnum.ECOLE_FRANCE,
RubriqueEnum.EN_FRANCE,
RubriqueEnum.LGMT,
RubriqueEnum.VISA,
RubriqueEnum.VYG
]
countryList = countries.map(val => { return val.name });
sRubrique$: Observable<any>;
chosenCountry: string = "";
constructor(private clientHttpService: ClientHttpService,
private alertService: AlertService,
private route: ActivatedRoute,
private router: Router,
private sanitizer: DomSanitizer,
private formBuilder: FormBuilder) { }
rubriqueForm: FormGroup = this.formBuilder.group({
rubrique: ['', Validators.required],
sRubrique: [''],
pays: ['', Validators.required]
})
ngOnInit(): void {
this.sRubrique$ = this.clientHttpService.getAllSousRubrique();
const id = this.route.snapshot.params['id'];
this.clientHttpService.getRubriqueById(id).subscribe((value) => {
this.rubriqueForm.get("rubrique").setValue(value.name);
this.rubriqueForm.get("sRubrique").setValue(value.sRubrique);
this.rubriqueForm.get("pays").setValue(value.pays);
this.htmlContent = value.data
})
}
get rubrique() {
return this.rubriqueForm.get("rubrique");
}
get dataRubrique() {
return this.rubriqueForm.get("dataRubrique");
}
onFormSubmit() {
const id = this.route.snapshot.params['id'];
let rubriqueToSend: Rubrique;
rubriqueToSend = new Rubrique(this.rubriqueForm.get("rubrique").value, this.htmlContent,
this.rubriqueForm.get("sRubrique").value, this.rubriqueForm.get("pays").value);
if (this.rubriqueForm.valid) {
this.clientHttpService.updateRubrique(id, rubriqueToSend).subscribe(() => {
this.router.navigate(['/rubrique'], { relativeTo: this.route });
this.alertService.success("Mise a jour réussi");
},
(error) => {
this.alertService.error(error);
});
}
}
}
<file_sep>export class Article {
id: string;
data: any;
}<file_sep>import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
// Flexbox and CSS Grid (both)
import { FlexLayoutModule } from '@angular/flex-layout';
// Flexbox mode (only)
import { FlexModule } from '@angular/flex-layout/flex';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { RouterModule } from '@angular/router';
import { SafeHtmlPipe } from '@app/temoignage/safe-html.pipe';
import { AngularEditorModule } from '@kolkov/angular-editor';
import { CreateTemoignageComponent } from './create-temoignage/create-temoignage.component';
import { DisplayTemoignageComponent } from './display-temoignage/display-temoignage.component';
import { TemoignageRoutingModule } from './temoignage-routing.module';
import { EditTemoignageComponent } from './edit-temoignage/edit-temoignage.component';
@NgModule({
declarations: [CreateTemoignageComponent, DisplayTemoignageComponent, SafeHtmlPipe, EditTemoignageComponent],
imports: [
CommonModule,
TemoignageRoutingModule,
RouterModule,
AngularEditorModule,
FormsModule,
ReactiveFormsModule,
MatSelectModule,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
FlexLayoutModule,
FlexModule
],
exports: [
MatSelectModule,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
],
})
export class TemoignageModule { }
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CreateRubriqueComponent } from './create-rubrique/create-rubrique.component';
import { DisplayRubriqueComponent } from './display-rubrique/display-rubrique.component';
import { EditRubriqueComponent } from './edit-rubrique/edit-rubrique.component';
import { SousRubriqueComponent } from './sous-rubrique/sous-rubrique.component';
const routes: Routes = [
{ path: '', component: DisplayRubriqueComponent },
{ path: 'create', component: CreateRubriqueComponent },
{ path: 'edit/:id', component: EditRubriqueComponent },
{ path: 'create-sous-rubrique', component: SousRubriqueComponent },
{ path: '**', component: DisplayRubriqueComponent },
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class RubriqueRoutingModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { AlertService, ClientHttpService } from '@app/_services';
enum RubriqueEnum {
ALLER_FRANCE = "Je soushaite aller en France",
ECOLE_FRANCE = "Les écoles en France",
VYG = "Voyage",
LGMT = "Logement",
AVI = "AVI",
VISA = "Visas",
CAMPUS = "Campus France",
EN_FRANCE = "Je suis en France"
}
@Component({
selector: 'app-sous-rubrique',
templateUrl: './sous-rubrique.component.html',
styleUrls: ['./sous-rubrique.component.less']
})
export class SousRubriqueComponent implements OnInit {
readonly rubriqueList: string[] = [
RubriqueEnum.ALLER_FRANCE,
RubriqueEnum.AVI,
RubriqueEnum.CAMPUS,
RubriqueEnum.ECOLE_FRANCE,
RubriqueEnum.EN_FRANCE,
RubriqueEnum.LGMT,
RubriqueEnum.VISA,
RubriqueEnum.VYG
]
constructor(private clientHttpService: ClientHttpService,
private alertService: AlertService,
private route: ActivatedRoute,
private router: Router,
private formBuilder: FormBuilder) { }
sousRubriqueForm: FormGroup = this.formBuilder.group({
sRubrique: ['', Validators.required]
})
ngOnInit(): void {
}
onFormSubmit() {
this.clientHttpService.createSousRubrique(this.sousRubriqueForm.get("sRubrique").value).subscribe(() => {
const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
this.router.navigate(['/rubrique'], { relativeTo: this.route });
},
(error) => {
this.alertService.error(error);
});
}
}
<file_sep>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { User } from '@app/_models';
import { environment } from '@environments/environment';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Article } from '../_models/article';
import { Rubrique } from '../_models/rubrique';
@Injectable({ providedIn: 'root' })
export class ClientHttpService {
private userSubject: BehaviorSubject<User>;
public user: Observable<User>;
baseUri: string = 'http://localhost:4000/api';
constructor(private router: Router,
private http: HttpClient) {
this.userSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('user')));
this.user = this.userSubject.asObservable();
}
public get userValue(): User {
return this.userSubject.value;
}
login(user_login, user_pass) {
return this.http.post<User>(`${this.baseUri}/users/authenticate`, { user_login, user_pass })
.pipe(map(user => {
// store user details and jwt token in local storage to keep user
// logged in between page refreshes
localStorage.setItem('user', JSON.stringify(user));
this.userSubject.next(user);
return user;
}));
}
logout() {
// remove user from local storage and set current user to null
localStorage.removeItem('user');
this.userSubject.next(null);
this.router.navigate(['/account/login']);
}
register(user: User) {
return this.http.post(`${this.baseUri}/users/register`, user);
}
getAll() {
return this.http.get<User[]>(`${this.baseUri}/users`);
}
getById(id: string) {
return this.http.get<User>(`${this.baseUri}/users/${id}`);
}
update(id, params) {
return this.http.put(`${this.baseUri}/users/${id}`, params)
.pipe(map(x => {
// update stored user if the logged in user updated their own record
if (id == this.userValue._id) {
// update local storage
const user = { ...this.userValue, ...params };
localStorage.setItem('user', JSON.stringify(user));
// publish updated user to subscribers
this.userSubject.next(user);
}
return x;
}));
}
delete(id: string) {
return this.http.delete(`${this.baseUri}/users/${id}`)
.pipe(map(x => {
// auto logout if the logged in user deleted their own record
if (id == this.userValue._id) {
this.logout();
}
return x;
}));
}
// ################################### Article services ################################### //
createArticle(dataArticle) {
return this.http.post<Article>(`${this.baseUri}/article/create`, { dataArticle });
}
getAllArticle() {
return this.http.get<Article[]>(`${this.baseUri}/article`).pipe(
map(val => {
return val.map(v => v.data)
})
)
}
// ################################### Rubriques services ################################### //
createRubrique(dataRubrique) {
return this.http.post<Rubrique>(`${this.baseUri}/rubrique/create`, dataRubrique);
}
getAllRubrique() {
return this.http.get<Rubrique[]>(`${this.baseUri}/rubrique`);
}
getRubriqueById(id) {
return this.http.get<Rubrique>(`${this.baseUri}/rubrique/${id}`);
}
updateRubrique(id, params) {
return this.http.put<any[]>(`${this.baseUri}/rubrique/${id}`, params);
}
deleteRubrique(id: string) {
return this.http.delete(`${this.baseUri}/rubrique/${id}`);
}
createSousRubrique(dataSRubrique) {
return this.http.post<any>(`${this.baseUri}/sous-rubrique/create`, { dataSRubrique });
}
getAllSousRubrique() {
return this.http.get<any[]>(`${this.baseUri}/sous-rubrique`);
}
deleteSRubrique(id: string) {
return this.http.delete(`${this.baseUri}/sous-rubrique/${id}`);
}
// ################################### Témoignages services ################################### //
createTemoignage(dataTemoignage) {
return this.http.post<any>(`${this.baseUri}/temoignage/create`, dataTemoignage);
}
getTemoignageById(id) {
return this.http.get<any>(`${this.baseUri}/temoignage/${id}`);
}
updateTemoignage(id, params) {
return this.http.put<any[]>(`${this.baseUri}/temoignage/${id}`, params);
}
getAllTemoignage() {
return this.http.get<any[]>(`${this.baseUri}/temoignage`);
}
deleteTemoignage(id: string) {
return this.http.delete(`${this.baseUri}/temoignage/${id}`);
}
// ################################### Acteurs services ################################### //
createActeur(dataActeur) {
return this.http.post<any>(`${this.baseUri}/acteur/create`, dataActeur);
}
getActeurById(id) {
return this.http.get<any>(`${this.baseUri}/acteur/${id}`);
}
getAllActeur() {
return this.http.get<any[]>(`${this.baseUri}/acteur`);
}
updateActeur(id, params) {
return this.http.put<any[]>(`${this.baseUri}/acteur/${id}`, params);
}
deleteActeur(id: string) {
return this.http.delete(`${this.baseUri}/acteur/${id}`);
}
}<file_sep># Stuwell
Comment fonctionne l'application
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AlertService, ClientHttpService } from '@app/_services';
import { Observable } from 'rxjs';
import { first } from 'rxjs/operators';
@Component({
selector: 'app-display-temoignage',
templateUrl: './display-temoignage.component.html',
styleUrls: ['./display-temoignage.component.less']
})
export class DisplayTemoignageComponent implements OnInit {
temoignage$: Observable<any>;
temoignages: any[] = [];
temoignage = null;
isDeleting: boolean = true;
constructor(private clientHttpService: ClientHttpService,
private alertService: AlertService,
private route: ActivatedRoute,
private router: Router) { }
ngOnInit(): void {
this.temoignage$ = this.clientHttpService.getAllTemoignage();
this.clientHttpService.getAllTemoignage().subscribe((values) => {
this.temoignages = values;
})
}
deleteTemoignage(id: string) {
this.isDeleting = true;
this.clientHttpService.deleteTemoignage(id)
.pipe(first())
.subscribe(() => {
this.temoignage = this.temoignages.filter(x => x.id !== id);
this.isDeleting = false;
this.ngOnInit();
this.alertService.success("Suppression réussi");
},
(error) => {
this.alertService.error(error);
});
}
}
<file_sep>export class User {
_id: string;
user_login: string;
user_pass: string;
user_nikname: string;
user_email: string;
user_url: string;
user_registered: Date;
user_activation_key: string;
user_status: string;
display_name: string;
token: string;
}<file_sep>
export const countries: any[] = [
{ id: 4, name: "Afghanistan", alpha2: "af", alpha3: "afg" },
{ id: 710, name: "<NAME>", alpha2: "za", alpha3: "zaf" },
{ id: 248, name: "<NAME>", alpha2: "ax", alpha3: "ala" },
{ id: 8, name: "Albanie", alpha2: "al", alpha3: "alb" },
{ id: 12, name: "Algérie", alpha2: "dz", alpha3: "dza" },
{ id: 276, name: "Allemagne", alpha2: "de", alpha3: "deu" },
{ id: 20, name: "Andorre", alpha2: "ad", alpha3: "and" },
{ id: 24, name: "Angola", alpha2: "ao", alpha3: "ago" },
{ id: 660, name: "Anguilla", alpha2: "ai", alpha3: "aia" },
{ id: 10, name: "Antarctique", alpha2: "aq", alpha3: "ata" },
{ id: 28, name: "Antigua-et-Barbuda", alpha2: "ag", alpha3: "atg" },
{ id: 682, name: "<NAME>", alpha2: "sa", alpha3: "sau" },
{ id: 32, name: "Argentine", alpha2: "ar", alpha3: "arg" },
{ id: 51, name: "Arménie", alpha2: "am", alpha3: "arm" },
{ id: 533, name: "Aruba", alpha2: "aw", alpha3: "abw" },
{ id: 36, name: "Australie", alpha2: "au", alpha3: "aus" },
{ id: 40, name: "Autriche", alpha2: "at", alpha3: "aut" },
{ id: 31, name: "Azerbaïdjan", alpha2: "az", alpha3: "aze" },
{ id: 44, name: "Bahamas", alpha2: "bs", alpha3: "bhs" },
{ id: 48, name: "Bahreïn", alpha2: "bh", alpha3: "bhr" },
{ id: 50, name: "Bangladesh", alpha2: "bd", alpha3: "bgd" },
{ id: 52, name: "Barbade", alpha2: "bb", alpha3: "brb" },
{ id: 112, name: "Biélorussie", alpha2: "by", alpha3: "blr" },
{ id: 56, name: "Belgique", alpha2: "be", alpha3: "bel" },
{ id: 84, name: "Belize", alpha2: "bz", alpha3: "blz" },
{ id: 204, name: "Bénin", alpha2: "bj", alpha3: "ben" },
{ id: 60, name: "Bermudes", alpha2: "bm", alpha3: "bmu" },
{ id: 64, name: "Bhoutan", alpha2: "bt", alpha3: "btn" },
{ id: 68, name: "Bolivie", alpha2: "bo", alpha3: "bol" },
{ id: 535, name: "<NAME>", alpha2: "bq", alpha3: "bes" },
{ id: 70, name: "Bosnie-Herzégovine", alpha2: "ba", alpha3: "bih" },
{ id: 72, name: "Botswana", alpha2: "bw", alpha3: "bwa" },
{ id: 74, name: "<NAME>", alpha2: "bv", alpha3: "bvt" },
{ id: 76, name: "Brésil", alpha2: "br", alpha3: "bra" },
{ id: 96, name: "Brunei", alpha2: "bn", alpha3: "brn" },
{ id: 100, name: "Bulgarie", alpha2: "bg", alpha3: "bgr" },
{ id: 854, name: "<NAME>", alpha2: "bf", alpha3: "bfa" },
{ id: 108, name: "Burundi", alpha2: "bi", alpha3: "bdi" },
{ id: 136, name: "<NAME>", alpha2: "ky", alpha3: "cym" },
{ id: 116, name: "Cambodge", alpha2: "kh", alpha3: "khm" },
{ id: 120, name: "Cameroun", alpha2: "cm", alpha3: "cmr" },
{ id: 124, name: "Canada", alpha2: "ca", alpha3: "can" },
{ id: 132, name: "Cap-Vert", alpha2: "cv", alpha3: "cpv" },
{ id: 140, name: "<NAME>", alpha2: "cf", alpha3: "caf" },
{ id: 152, name: "Chili", alpha2: "cl", alpha3: "chl" },
{ id: 156, name: "Chine", alpha2: "cn", alpha3: "chn" },
{ id: 162, name: "<NAME>", alpha2: "cx", alpha3: "cxr" },
{ id: 196, name: "Chypre (pays)", alpha2: "cy", alpha3: "cyp" },
{ id: 166, name: "<NAME>", alpha2: "cc", alpha3: "cck" },
{ id: 170, name: "Colombie", alpha2: "co", alpha3: "col" },
{ id: 174, name: "Comores (pays)", alpha2: "km", alpha3: "com" },
{ id: 178, name: "République du Congo", alpha2: "cg", alpha3: "cog" },
{ id: 180, name: "République démocratique du Congo", alpha2: "cd", alpha3: "cod" },
{ id: 184, name: "<NAME>", alpha2: "ck", alpha3: "cok" },
{ id: 410, name: "<NAME>", alpha2: "kr", alpha3: "kor" },
{ id: 408, name: "<NAME>", alpha2: "kp", alpha3: "prk" },
{ id: 188, name: "<NAME>", alpha2: "cr", alpha3: "cri" },
{ id: 384, name: "<NAME>", alpha2: "ci", alpha3: "civ" },
{ id: 191, name: "Croatie", alpha2: "hr", alpha3: "hrv" },
{ id: 192, name: "Cuba", alpha2: "cu", alpha3: "cub" },
{ id: 531, name: "Curaçao", alpha2: "cw", alpha3: "cuw" },
{ id: 208, name: "Danemark", alpha2: "dk", alpha3: "dnk" },
{ id: 262, name: "Djibouti", alpha2: "dj", alpha3: "dji" },
{ id: 214, name: "République dominicaine", alpha2: "do", alpha3: "dom" },
{ id: 212, name: "Dominique", alpha2: "dm", alpha3: "dma" },
{ id: 818, name: "Égypte", alpha2: "eg", alpha3: "egy" },
{ id: 222, name: "Salvador", alpha2: "sv", alpha3: "slv" },
{ id: 784, name: "<NAME>", alpha2: "ae", alpha3: "are" },
{ id: 218, name: "Équateur (pays)", alpha2: "ec", alpha3: "ecu" },
{ id: 232, name: "Érythrée", alpha2: "er", alpha3: "eri" },
{ id: 724, name: "Espagne", alpha2: "es", alpha3: "esp" },
{ id: 233, name: "Estonie", alpha2: "ee", alpha3: "est" },
{ id: 840, name: "États-Unis", alpha2: "us", alpha3: "usa" },
{ id: 231, name: "Éthiopie", alpha2: "et", alpha3: "eth" },
{ id: 238, name: "Malouines", alpha2: "fk", alpha3: "flk" },
{ id: 234, name: "<NAME>", alpha2: "fo", alpha3: "fro" },
{ id: 242, name: "Fidji", alpha2: "fj", alpha3: "fji" },
{ id: 246, name: "Finlande", alpha2: "fi", alpha3: "fin" },
{ id: 250, name: "France", alpha2: "fr", alpha3: "fra" },
{ id: 266, name: "Gabon", alpha2: "ga", alpha3: "gab" },
{ id: 270, name: "Gambie", alpha2: "gm", alpha3: "gmb" },
{ id: 268, name: "Géorgie (pays)", alpha2: "ge", alpha3: "geo" },
{ id: 239, name: "<NAME>ud-et-les îles Sandwich du Sud", alpha2: "gs", alpha3: "sgs" },
{ id: 288, name: "Ghana", alpha2: "gh", alpha3: "gha" },
{ id: 292, name: "Gibraltar", alpha2: "gi", alpha3: "gib" },
{ id: 300, name: "Grèce", alpha2: "gr", alpha3: "grc" },
{ id: 308, name: "Grenade (pays)", alpha2: "gd", alpha3: "grd" },
{ id: 304, name: "Groenland", alpha2: "gl", alpha3: "grl" },
{ id: 312, name: "Guadeloupe", alpha2: "gp", alpha3: "glp" },
{ id: 316, name: "Guam", alpha2: "gu", alpha3: "gum" },
{ id: 320, name: "Guatemala", alpha2: "gt", alpha3: "gtm" },
{ id: 831, name: "Guernesey", alpha2: "gg", alpha3: "ggy" },
{ id: 324, name: "Guinée", alpha2: "gn", alpha3: "gin" },
{ id: 624, name: "Guinée-Bissau", alpha2: "gw", alpha3: "gnb" },
{ id: 226, name: "<NAME>", alpha2: "gq", alpha3: "gnq" },
{ id: 328, name: "Guyana", alpha2: "gy", alpha3: "guy" },
{ id: 254, name: "Guyane", alpha2: "gf", alpha3: "guf" },
{ id: 332, name: "Haïti", alpha2: "ht", alpha3: "hti" },
{ id: 334, name: "<NAME>", alpha2: "hm", alpha3: "hmd" },
{ id: 340, name: "Honduras", alpha2: "hn", alpha3: "hnd" },
{ id: 344, name: "<NAME>", alpha2: "hk", alpha3: "hkg" },
{ id: 348, name: "Hongrie", alpha2: "hu", alpha3: "hun" },
{ id: 833, name: "<NAME>", alpha2: "im", alpha3: "imn" },
{ id: 581, name: "Îles mineures éloignées des États-Unis", alpha2: "um", alpha3: "umi" },
{ id: 92, name: "<NAME>", alpha2: "vg", alpha3: "vgb" },
{ id: 850, name: "Îles Vierges des États-Unis", alpha2: "vi", alpha3: "vir" },
{ id: 356, name: "Inde", alpha2: "in", alpha3: "ind" },
{ id: 360, name: "Indonésie", alpha2: "id", alpha3: "idn" },
{ id: 364, name: "Iran", alpha2: "ir", alpha3: "irn" },
{ id: 368, name: "Irak", alpha2: "iq", alpha3: "irq" },
{ id: 372, name: "Irlande (pays)", alpha2: "ie", alpha3: "irl" },
{ id: 352, name: "Islande", alpha2: "is", alpha3: "isl" },
{ id: 376, name: "Israël", alpha2: "il", alpha3: "isr" },
{ id: 380, name: "Italie", alpha2: "it", alpha3: "ita" },
{ id: 388, name: "Jamaïque", alpha2: "jm", alpha3: "jam" },
{ id: 392, name: "Japon", alpha2: "jp", alpha3: "jpn" },
{ id: 832, name: "Jersey", alpha2: "je", alpha3: "jey" },
{ id: 400, name: "Jordanie", alpha2: "jo", alpha3: "jor" },
{ id: 398, name: "Kazakhstan", alpha2: "kz", alpha3: "kaz" },
{ id: 404, name: "Kenya", alpha2: "ke", alpha3: "ken" },
{ id: 417, name: "Kirghizistan", alpha2: "kg", alpha3: "kgz" },
{ id: 296, name: "Kiribati", alpha2: "ki", alpha3: "kir" },
{ id: 414, name: "Koweït", alpha2: "kw", alpha3: "kwt" },
{ id: 418, name: "Laos", alpha2: "la", alpha3: "lao" },
{ id: 426, name: "Lesotho", alpha2: "ls", alpha3: "lso" },
{ id: 428, name: "Lettonie", alpha2: "lv", alpha3: "lva" },
{ id: 422, name: "Liban", alpha2: "lb", alpha3: "lbn" },
{ id: 430, name: "Liberia", alpha2: "lr", alpha3: "lbr" },
{ id: 434, name: "Libye", alpha2: "ly", alpha3: "lby" },
{ id: 438, name: "Liechtenstein", alpha2: "li", alpha3: "lie" },
{ id: 440, name: "Lituanie", alpha2: "lt", alpha3: "ltu" },
{ id: 442, name: "Luxembourg (pays)", alpha2: "lu", alpha3: "lux" },
{ id: 446, name: "Macao", alpha2: "mo", alpha3: "mac" },
{ id: 807, name: "<NAME>", alpha2: "mk", alpha3: "mkd" },
{ id: 450, name: "Madagascar", alpha2: "mg", alpha3: "mdg" },
{ id: 458, name: "Malaisie", alpha2: "my", alpha3: "mys" },
{ id: 454, name: "Malawi", alpha2: "mw", alpha3: "mwi" },
{ id: 462, name: "Maldives", alpha2: "mv", alpha3: "mdv" },
{ id: 466, name: "Mali", alpha2: "ml", alpha3: "mli" },
{ id: 470, name: "Malte", alpha2: "mt", alpha3: "mlt" },
{ id: 580, name: "<NAME>", alpha2: "mp", alpha3: "mnp" },
{ id: 504, name: "Maroc", alpha2: "ma", alpha3: "mar" },
{ id: 584, name: "<NAME> (pays)", alpha2: "mh", alpha3: "mhl" },
{ id: 474, name: "Martinique", alpha2: "mq", alpha3: "mtq" },
{ id: 480, name: "Maurice (pays)", alpha2: "mu", alpha3: "mus" },
{ id: 478, name: "Mauritanie", alpha2: "mr", alpha3: "mrt" },
{ id: 175, name: "Mayotte", alpha2: "yt", alpha3: "myt" },
{ id: 484, name: "Mexique", alpha2: "mx", alpha3: "mex" },
{ id: 583, name: "<NAME> (pays)", alpha2: "fm", alpha3: "fsm" },
{ id: 498, name: "Moldavie", alpha2: "md", alpha3: "mda" },
{ id: 492, name: "Monaco", alpha2: "mc", alpha3: "mco" },
{ id: 496, name: "Mongolie", alpha2: "mn", alpha3: "mng" },
{ id: 499, name: "Monténégro", alpha2: "me", alpha3: "mne" },
{ id: 500, name: "Montserrat", alpha2: "ms", alpha3: "msr" },
{ id: 508, name: "Mozambique", alpha2: "mz", alpha3: "moz" },
{ id: 104, name: "Birmanie", alpha2: "mm", alpha3: "mmr" },
{ id: 516, name: "Namibie", alpha2: "na", alpha3: "nam" },
{ id: 520, name: "Nauru", alpha2: "nr", alpha3: "nru" },
{ id: 524, name: "Népal", alpha2: "np", alpha3: "npl" },
{ id: 558, name: "Nicaragua", alpha2: "ni", alpha3: "nic" },
{ id: 562, name: "Niger", alpha2: "ne", alpha3: "ner" },
{ id: 566, name: "Nigeria", alpha2: "ng", alpha3: "nga" },
{ id: 570, name: "Niue", alpha2: "nu", alpha3: "niu" },
{ id: 574, name: "<NAME>", alpha2: "nf", alpha3: "nfk" },
{ id: 578, name: "Norvège", alpha2: "no", alpha3: "nor" },
{ id: 540, name: "Nouvelle-Calédonie", alpha2: "nc", alpha3: "ncl" },
{ id: 554, name: "Nouvelle-Zélande", alpha2: "nz", alpha3: "nzl" },
{ id: 86, name: "<NAME>'<NAME>", alpha2: "io", alpha3: "iot" },
{ id: 512, name: "Oman", alpha2: "om", alpha3: "omn" },
{ id: 800, name: "Ouganda", alpha2: "ug", alpha3: "uga" },
{ id: 860, name: "Ouzbékistan", alpha2: "uz", alpha3: "uzb" },
{ id: 586, name: "Pakistan", alpha2: "pk", alpha3: "pak" },
{ id: 585, name: "Palaos", alpha2: "pw", alpha3: "plw" },
{ id: 275, name: "Palestine", alpha2: "ps", alpha3: "pse" },
{ id: 591, name: "Panama", alpha2: "pa", alpha3: "pan" },
{ id: 598, name: "Papouasie-Nouvelle-Guinée", alpha2: "pg", alpha3: "png" },
{ id: 600, name: "Paraguay", alpha2: "py", alpha3: "pry" },
{ id: 528, name: "Pays-Bas", alpha2: "nl", alpha3: "nld" },
{ id: 604, name: "Pérou", alpha2: "pe", alpha3: "per" },
{ id: 608, name: "Philippines", alpha2: "ph", alpha3: "phl" },
{ id: 612, name: "<NAME>", alpha2: "pn", alpha3: "pcn" },
{ id: 616, name: "Pologne", alpha2: "pl", alpha3: "pol" },
{ id: 258, name: "<NAME>", alpha2: "pf", alpha3: "pyf" },
{ id: 630, name: "<NAME>", alpha2: "pr", alpha3: "pri" },
{ id: 620, name: "Portugal", alpha2: "pt", alpha3: "prt" },
{ id: 634, name: "Qatar", alpha2: "qa", alpha3: "qat" },
{ id: 638, name: "<NAME>", alpha2: "re", alpha3: "reu" },
{ id: 642, name: "Roumanie", alpha2: "ro", alpha3: "rou" },
{ id: 826, name: "Royaume-Uni", alpha2: "gb", alpha3: "gbr" },
{ id: 643, name: "Russie", alpha2: "ru", alpha3: "rus" },
{ id: 646, name: "Rwanda", alpha2: "rw", alpha3: "rwa" },
{ id: 732, name: "<NAME>", alpha2: "eh", alpha3: "esh" },
{ id: 652, name: "Saint-Barthélemy", alpha2: "bl", alpha3: "blm" },
{ id: 659, name: "Saint-Christophe-et-Niévès", alpha2: "kn", alpha3: "kna" },
{ id: 674, name: "Saint-Marin", alpha2: "sm", alpha3: "smr" },
{ id: 663, name: "Saint-Martin", alpha2: "mf", alpha3: "maf" },
{ id: 534, name: "Saint-Martin", alpha2: "sx", alpha3: "sxm" },
{ id: 666, name: "Saint-Pierre-et-Miquelon", alpha2: "pm", alpha3: "spm" },
{ id: 336, name: "Saint-Siège (État de la Cité du Vatican)", alpha2: "va", alpha3: "vat" },
{ id: 670, name: "Saint-Vincent-et-les-Grenadines", alpha2: "vc", alpha3: "vct" },
{ id: 654, name: "<NAME> et <NAME>", alpha2: "sh", alpha3: "shn" },
{ id: 662, name: "Sainte-Lucie", alpha2: "lc", alpha3: "lca" },
{ id: 90, name: "<NAME>", alpha2: "sb", alpha3: "slb" },
{ id: 882, name: "Samoa", alpha2: "ws", alpha3: "wsm" },
{ id: 16, name: "<NAME>", alpha2: "as", alpha3: "asm" },
{ id: 678, name: "<NAME>", alpha2: "st", alpha3: "stp" },
{ id: 686, name: "Sénégal", alpha2: "sn", alpha3: "sen" },
{ id: 688, name: "Serbie", alpha2: "rs", alpha3: "srb" },
{ id: 690, name: "Seychelles", alpha2: "sc", alpha3: "syc" },
{ id: 694, name: "<NAME>", alpha2: "sl", alpha3: "sle" },
{ id: 702, name: "Singapour", alpha2: "sg", alpha3: "sgp" },
{ id: 703, name: "Slovaquie", alpha2: "sk", alpha3: "svk" },
{ id: 705, name: "Slovénie", alpha2: "si", alpha3: "svn" },
{ id: 706, name: "Somalie", alpha2: "so", alpha3: "som" },
{ id: 729, name: "Soudan", alpha2: "sd", alpha3: "sdn" },
{ id: 728, name: "<NAME>", alpha2: "ss", alpha3: "ssd" },
{ id: 144, name: "<NAME>", alpha2: "lk", alpha3: "lka" },
{ id: 752, name: "Suède", alpha2: "se", alpha3: "swe" },
{ id: 756, name: "Suisse", alpha2: "ch", alpha3: "che" },
{ id: 740, name: "Suriname", alpha2: "sr", alpha3: "sur" },
{ id: 744, name: "<NAME> <NAME>", alpha2: "sj", alpha3: "sjm" },
{ id: 748, name: "Eswatini", alpha2: "sz", alpha3: "swz" },
{ id: 760, name: "Syrie", alpha2: "sy", alpha3: "syr" },
{ id: 762, name: "Tadjikistan", alpha2: "tj", alpha3: "tjk" },
{ id: 158, name: "Taïwan \/ (République de Chine (Taïwan))", alpha2: "tw", alpha3: "twn" },
{ id: 834, name: "Tanzanie", alpha2: "tz", alpha3: "tza" },
{ id: 148, name: "Tchad", alpha2: "td", alpha3: "tcd" },
{ id: 203, name: "Tchéquie", alpha2: "cz", alpha3: "cze" },
{ id: 260, name: "Terres australes et antarctiques françaises", alpha2: "tf", alpha3: "atf" },
{ id: 764, name: "Thaïlande", alpha2: "th", alpha3: "tha" },
{ id: 626, name: "<NAME>", alpha2: "tl", alpha3: "tls" },
{ id: 768, name: "Togo", alpha2: "tg", alpha3: "tgo" },
{ id: 772, name: "Tokelau", alpha2: "tk", alpha3: "tkl" },
{ id: 776, name: "Tonga", alpha2: "to", alpha3: "ton" },
{ id: 780, name: "Trinité-et-Tobago", alpha2: "tt", alpha3: "tto" },
{ id: 788, name: "Tunisie", alpha2: "tn", alpha3: "tun" },
{ id: 795, name: "Turkménistan", alpha2: "tm", alpha3: "tkm" },
{ id: 796, name: "<NAME>", alpha2: "tc", alpha3: "tca" },
{ id: 792, name: "Turquie", alpha2: "tr", alpha3: "tur" },
{ id: 798, name: "Tuvalu", alpha2: "tv", alpha3: "tuv" },
{ id: 804, name: "Ukraine", alpha2: "ua", alpha3: "ukr" },
{ id: 858, name: "Uruguay", alpha2: "uy", alpha3: "ury" },
{ id: 548, name: "Vanuatu", alpha2: "vu", alpha3: "vut" },
{ id: 862, name: "Venezuela", alpha2: "ve", alpha3: "ven" },
{ id: 704, name: "<NAME>", alpha2: "vn", alpha3: "vnm" },
{ id: 876, name: "Wallis-et-Futuna", alpha2: "wf", alpha3: "wlf" },
{ id: 887, name: "Yémen", alpha2: "ye", alpha3: "yem" },
{ id: 894, name: "Zambie", alpha2: "zm", alpha3: "zmb" },
{ id: 716, name: "Zimbabwe", alpha2: "zw", alpha3: "zwe" }];<file_sep>const config = require('config.json');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = require('_helpers/db');
const Article = db.Article;
module.exports = {
getAll,
getById,
create,
update,
delete: _delete
};
async function getAll() {
return await Article.find();
}
async function getById(id) {
return await Article.findById(id);
}
async function create(articleParam) {
const article = new Article({ data: articleParam.dataArticle });
// save article
await article.save();
}
async function update(id, userParam) {
const article = await Article.findById(id);
// validate
if (!article) throw 'User not found';
if (article.username !== userParam.username && await Article.findOne({ username: userParam.username })) {
throw 'Username "' + userParam.username + '" is already taken';
}
// hash password if it was entered
if (userParam.password) {
userParam.hash = bcrypt.hashSync(userParam.password, 10);
}
// copy userParam properties to user
Object.assign(article, userParam);
await article.save();
}
async function _delete(id) {
await Article.findByIdAndRemove(id);
}<file_sep>const config = require('config.json');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = require('_helpers/db');
const Rubrique = db.Rubrique;
const sRubrique = db.sRubrique;
module.exports = {
getAll,
getAllSousRubrique,
getById,
createRubrique,
createSousRubrique,
updateRubrique,
deleteRubrique,
deleteSousRubrique
};
async function getAll() {
return await Rubrique.find();
}
async function getAllSousRubrique() {
return await sRubrique.find();
}
async function getById(id) {
return await Rubrique.findById(id);
}
async function createRubrique(rubriqueParam) {
let rubrique = new Rubrique({
name: rubriqueParam.name, pays: rubriqueParam.pays, sRubrique: rubriqueParam.sRubrique
, data: rubriqueParam.data
});
// save rubrique
await rubrique.save();
}
async function createSousRubrique(sRubriqueParam) {
let rubrique = new sRubrique({ name: sRubriqueParam.dataSRubrique });
// save rubrique
await rubrique.save();
}
async function deleteSousRubrique(id) {
await sRubrique.findByIdAndRemove(id);
}
async function updateRubrique(id, param) {
const rubrique = await Rubrique.findById(id);
// validate
if (!rubrique) throw 'Rubrique non trouvé';
Object.assign(rubrique, param);
await rubrique.save();
}
async function deleteRubrique(id) {
await Rubrique.findByIdAndRemove(id);
}<file_sep>const mongoose = require('mongoose');
const rubriqueSchema = new mongoose.Schema({
name: { type: String, required: false },
pays: { type: String, required: false },
sRubrique: { type: String, required: false },
data: { type: String, required: false }
});
module.exports = mongoose.model('Rubrique', rubriqueSchema); | a338b5808fc0b9c84467796aa8ddb31544e16e12 | [
"JavaScript",
"TypeScript",
"Markdown"
] | 26 | TypeScript | songeur/Stuwell-back-office | c99da899dce13abf366c5fd263ed18cb09b4e699 | 4e4d3d198f510c8b90b5de605045c40909e68099 |
refs/heads/master | <file_sep>import { createApp } from 'vue'
import App from './components/App.vue'
import './stylesheets/main.css'
createApp(App).mount('#app')
<file_sep># website
The JTCC Programming Club website
<!-- Run "npx doctoc README.md" to re-generate this table of contents -->
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
- [Vue](#vue)
- [Project setup](#project-setup)
- [Start the server](#start-the-server)
- [Compile and minify for production](#compile-and-minify-for-production)
- [Lint and fix files](#lint-and-fix-files)
- [Customize configuration](#customize-configuration)
- [Contributors](#contributors)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Vue
This application leverage [Vue.js](https://vuejs.org/) for the component structure you see in `src/`.
If you aren't familiar with Vue, that's okay. Have a look at the [guide](https://v3.vuejs.org/guide) on what it does and getting started.
## Project setup
This application is written using node.js. Download [node.js](https://nodejs.org/en/) to get started.
Once installed, open your terminal in the folder where you downloaded this source code and run the command:
```
npm install
```
This will download the local web server, vue, and all the other dependencies needed to run the project.
### Start the server
This command compiles the source code and serves it up for you in the browser. It also does hot-reloading and basic error checking.
```
npm run serve
```
Once you run the command, copy the url it prints out and open in your browser to see the website
### Compile and minify for production
```
npm run build
```
### Lint and fix files
```
npm run lint
```
## Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).
## Contributors
<table>
<tbody>
<tr>
<td align="center" width="160px">
<img src="https://avatars.githubusercontent.com/avaisali?s=120">
<br />
<a href="https://github.com/avaisali"><NAME></a>
</td>
<td align="center" width="160px">
<img src="https://avatars.githubusercontent.com/jaythomas?s=120">
<br />
<a href="https://github.com/jaythomas"><NAME></a>
</td>
<td align="center" width="160px">
<img src="https://avatars.githubusercontent.com/supershadowplay?s=120">
<br />
<a href="https://github.com/supershadowplay"><NAME></a>
</td>
</tr>
</tbody>
</table>
| 0b323659724c82439764bf593f14ef2fb8ad54ac | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | JTCC-Programming-Club/website | c13ce3bb698e9cf1c97ff62d126c85daee351d2b | 94b9fc6d1e3f8d4bc8b8da843947e004b4ab992a |
refs/heads/main | <repo_name>BarCohenBGU/statistics<file_sep>/statistics.py
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import seaborn as sns #for better and easier plots
import numpy as np
import matplotlib.pyplot as plt
import pingouin as pg
#import scikitplot as skplt
from sklearn.model_selection import cross_val_score,cross_val_predict
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score,precision_score,recall_score, f1_score
from pprint import pprint
import random
# In[75]:
df = pd.read_excel(r'C:\Users\Bar\Desktop\features_grapewine.xlsx') #place "r" before the path string to address special character, such as '\'. Don't forget to put the file name at the end of the path + '.xlsx'
df.head(5)
df1=df.drop(['Y'], axis=1)
df1.info()
# In[43]:
description=df.describe(include='all')
description
# In[101]:
sns.countplot(data=df, x="Y")
plt.show()
s = df['Y'].value_counts()
print(s)
# # Histograms and box-plots
# In[45]:
for i in df1.columns:
# sns.set(rc={'figure.figsize':(15,8.7)}) #setting the size of the figure to make it easier to read.
sns.displot(data=df, x=i, col="Y", kde=True)
# In[70]:
for i in df1.columns:
sns.catplot(x="Y", y=i, data=df,orient="v", palette="Set2",linewidth=2.5, kind="box")
# In[3]:
#data without CWSI4
df=df.drop(['CWSI4'], axis=1)
df1=df.drop(['Y'], axis=1)
df_outliters=pd.read_excel(r'C:\Users\Bar\Desktop\normalized_by_severity.xlsx')
# # Outliers
# In[110]:
df1.boxplot(figsize=(15,5))
plt.ylim(-8, 17)
df1.info()
# In[113]:
for i in df1.columns:
Q1 = np.quantile(df1[i],0.25)
Q3 = np.quantile(df1[i],0.75)
IQR = Q3 - Q1
lower, upper = Q1-1.5*IQR, Q3+1.5*IQR
df_outliters = df_outliters.drop(df_outliters[df_outliters[i] < lower].index)
df_outliters = df_outliters.drop(df_outliters[df_outliters[i] > upper].index)
df_outliters.to_excel("data_without_outlires.xlsx")
# In[4]:
df_out=pd.read_excel(r'C:\Users\Bar\Desktop\features_without_outlires.xlsx') #place "r" before the path string to address special character, such as '\'. Don't forget to put the file name at the end of the path + '.xlsx'
sns.countplot(data=df_out, x="Y")
plt.show()
s = df_out['Y'].value_counts()
print(s)
# In[4]:
df_out1=df_out.drop(['Y'], axis=1)
df_out1.dropna(how='any')
df_out1.boxplot(figsize=(15,5))
plt.ylim(-8, 17)
df_out1.info()
# # Correlation
# In[5]:
fix,ax = plt.subplots(figsize=(10,10))
sns.heatmap(df_out1.corr(),vmax=1,linewidths=0.01,
square=True,annot=True,linecolor="white", cmap='Reds')
bottom,top=ax.get_ylim()
ax.set_ylim(bottom+0.5,top-0.5)
plt.show()
# In[6]:
fix,ax = plt.subplots(figsize=(10,10))
sns.heatmap(df_out.pcorr(),vmax=1,linewidths=0.01,
square=True,annot=True,linecolor="white", cmap='Reds')
bottom,top=ax.get_ylim()
ax.set_ylim(bottom+0.5,top-0.5)
plt.show()
# In[8]:
# Data with selected features
df_data=df_out.drop(['IQR','MAD','Tavg-Tair','Tmin-Tair','Tmax-Tair','median-Tair','perc10-Tair'], axis=1)
#df_data.info()
df_features=df_data.drop(['Y'], axis=1)
#df_features.info()
df_Y=df_data.drop(['MTD','STD','Cv','perc90-Tair','CWSI2'], axis=1)
#df_Y.info()
# In[50]:
df_days=pd.read_excel(r'C:\Users\Bar\Desktop\features_without_outlires_by_days.xlsx') #place "r" before the path string to address special character, such as '\'. Don't forget to put the file name at the end of the path + '.xlsx'
#df_days.info()
df_days_data=df_days.drop(['IQR','MAD','Tavg-Tair','Tmin-Tair','Tmax-Tair','median-Tair','perc10-Tair'], axis=1)
df_days_features=df_days_data.drop(['Y', 'day_after_infection'], axis=1)
# In[26]:
for i in df_days_features.columns:
sns.displot(data=df_days_data, x=i, col="day_after_infection", kde=True)
# In[25]:
for i in df_days_features.columns:
sns.displot(data=df_days_data, x=i, col="day_after_infection",stat="density", common_norm=False,kde=True)
# In[64]:
df_days_data_4=df_days_data['day_after_infection']==4
day_4 = df_days_data[df_days_data_4]
print(day_4)
df_day4_features=day_4.drop(['Y', 'day_after_infection'], axis=1)
for i in df_day4_features.columns:
sns.displot(data=day_4, x=i, col="day_after_infection", kde=True)
# In[86]:
df_day4_features.boxplot(figsize=(10,5))
plt.ylim(-5, 13)
df_day4_features.info()
# In[87]:
df_days_data_1=df_days_data['day_after_infection']==1
day_1 = df_days_data[df_days_data_1]
df_day1_features=day_1.drop(['Y', 'day_after_infection'], axis=1)
df_day1_features.boxplot(figsize=(10,5))
plt.ylim(-5, 13)
# In[82]:
df_days_data_2=df_days_data['day_after_infection']==2
day_2 = df_days_data[df_days_data_2]
df_day2_features=day_2.drop(['Y', 'day_after_infection'], axis=1)
df_day2_features.boxplot(figsize=(10,5))
plt.ylim(-5, 13)
# In[83]:
df_days_data_5=df_days_data['day_after_infection']==5
day_5 = df_days_data[df_days_data_5]
df_day5_features=day_5.drop(['Y', 'day_after_infection'], axis=1)
df_day5_features.boxplot(figsize=(10,5))
plt.ylim(-5, 13)
# In[84]:
df_days_data_6=df_days_data['day_after_infection']==6
day_6 = df_days_data[df_days_data_6]
df_day6_features=day_6.drop(['Y', 'day_after_infection'], axis=1)
df_day6_features.boxplot(figsize=(10,5))
plt.ylim(-5, 13)
# In[85]:
df_days_data_7=df_days_data['day_after_infection']==7
day_7 = df_days_data[df_days_data_7]
df_day7_features=day_7.drop(['Y', 'day_after_infection'], axis=1)
df_day7_features.boxplot(figsize=(10,5))
plt.ylim(-5, 13)
# In[88]:
df_days_data_0=df_days_data['day_after_infection']==0
day_0 = df_days_data[df_days_data_0]
df_day0_features=day_0.drop(['Y', 'day_after_infection'], axis=1)
df_day0_features.boxplot(figsize=(10,5))
plt.ylim(-5, 13)
# In[12]:
df_group=pd.read_excel(r'C:\Users\Bar\Desktop\Data_27_10_2020_daily.xlsx') #place "r" before the path string to address special character, such as '\'. Don't forget to put the file name at the end of the path + '.xlsx'
df_group_data=df_group.drop(['day_after_infection','plot_num','image_name','IQR','MAD','Tavg-Tair','Tmin-Tair','Tmax-Tair','median-Tair','perc10-Tair','perc75-Tair','perc2-Tair','perc25-Tair','perc98-Tair'], axis=1)
df_group_features=df_group_data.drop(['Y', 'group'], axis=1)
df_group_features.info()
# In[13]:
for i in df_group_features.columns:
sns.displot(data=df_group_data, x=i, col="group", kde=True)
# In[46]:
for i in df_group_features.columns:
sns.histplot(data=df_group_data, x=i, kde=True, hue="group")
# In[36]:
for j in df_days_features.columns:
# Create the subplots
fig, axes = plt.subplots(nrows=1, ncols=7, figsize=(10, 20))
for column in enumerate(df_days_data['day_after_infection']):
sns.histplot(df_days_data, x=j)
# In[39]:
# libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
for i in df_days_features.columns:
# set a grey background (use sns.set_theme() if seaborn version 0.11.0 or above)
sns.set(style="darkgrid")
fig, axs = plt.subplots(1, 4, figsize=(7, 7))
sns.histplot(data=df_days_data, x=i, kde=True, hue="day_after_infection",ax=axs[0, 0])
sns.histplot(data=df_days_data, x=i, kde=True, ax=axs[0, 0],hue="day_after_infection")
sns.histplot(data=df_days_data, x=i, kde=True, ax=axs[0, 1])
sns.histplot(data=df_days_data, x=i, kde=True, ax=axs[0, 2])
sns.histplot(data=df_days_data, x=i, kde=True, ax=axs[0, 3])
plt.show()
# # RF
# In[5]:
# Create a based model
rf = RandomForestClassifier(random_state=0)
rf.fit(df_features, df_Y)
y_pred = cross_val_predict(rf, df_features, df_Y, cv=10)
print("acc: \n",accuracy_score(df_Y, y_pred))
print("pres: \n",precision_score(df_Y, y_pred))
print("recall: \n",recall_score(df_Y, y_pred))
# Look at parameters used by our current forest
print('Parameters currently in use:\n')
# pprint(rf.get_params())
# # grid search
# In[19]:
from sklearn.model_selection import GridSearchCV
random.seed(123)
# Create the parameter grid based on the results of random search
#param_grid = {
# 'bootstrap': [True],
# 'max_depth': [80, 90, 100, 110],
# 'max_features': [2, 3, 4],
# 'min_samples_leaf': [2, 3, 4, 5],
# 'min_samples_split': [8 , 10, 12, 14],
# 'n_estimators': [100, 200, 300, 1000]
#}
param_grid = {
'bootstrap': [True],
'max_depth': [80],
'max_features': [2],
'min_samples_leaf': [5],
'min_samples_split': [14],
'n_estimators': [1000]
}
rf = RandomForestClassifier(random_state=0)
#rf.fit(df_features, df_Y)
# Instantiate the grid search model
grid_search = GridSearchCV(estimator = rf, param_grid = param_grid, cv = 10, n_jobs = -1, verbose = 2)
# Fit the grid search to the data
grid_search.fit(df_features, df_Y)
best_grid=grid_search.best_estimator_
print(" ")
print('best_grid:\n')
print(best_grid)
y_pred_grid=best_grid.predict(df_features)
#print(best_grid.predict(df_features))
print(" ")
print('Parameters after gridsearch in use:\n')
grid_search.best_params_
# In[22]:
scores = cross_val_score(best_grid, df_features, df_Y, cv=5)
scores
print("%0.2f accuracy with a standard deviation of %0.2f" % (scores.mean(), scores.std()))
# In[15]:
print("acc: \n",accuracy_score(df_Y, y_pred_grid))
print("F1 score: \n",f1_score(df_Y, y_pred_grid))
print("precision: \n",precision_score(df_Y, y_pred_grid))
print("recall: \n",recall_score(df_Y, y_pred_grid))
# In[ ]:
# In[17]:
# Plot confusion matrix for base model with crossvalidation
cnf = confusion_matrix(df_Y, y_pred)
plt.figure()
#skplt.metrics.plot_confusion_matrix(df_Y, y_pred, normalize=False)
#plt.show()
# In[18]:
# Plot feature importance
feature_importance = rf.feature_importances_
# make importances relative to max importance
plt.figure(figsize=(10, 10))
# feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)
pos = np.arange(sorted_idx.shape[0]) + .5
plt.barh(pos, feature_importance[sorted_idx], align='center')
plt.yticks(pos, df_out1.columns[sorted_idx], fontsize=30)
plt.xlabel('Relative Importance', fontsize=30)
plt.title('variable importance', fontsize=40)
# In[36]:
sns.pairplot(data=df, hue="Y")
# correlation Y and the rest
# split the data if wished
# In[20]:
from sklearn.model_selection import train_test_split
X = df.drop('Y', 1).values
Y = df['Y'].values
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size= 0.2, random_state= 42)#
X_train=pd.DataFrame(X_train)
y_train=pd.DataFrame(y_train)
X_test=pd.DataFrame(X_test)
y_test=pd.DataFrame(y_test)
print(X_train.shape, X_test.shape)
print(y_train.shape,y_test.shape) # let's check the shape of the datasets created
# # GLM
# In[40]:
from scipy import stats
import statsmodels.api as sm
glm_binom = sm.GLM(Y, X, family=sm.families.Binomial())
res = glm_binom.fit()
print(res.summary())
# # data processing
# In[10]:
dataset = pd.read_excel(r'C:\Users\amirc\Desktop\grapevine_statistic.xlsx')
dataset.head()
X = dataset.drop('Y', axis=1)
Y = dataset["Y"]
# In[11]:
X.columns
# In[ ]:
# In[14]:
# X.to_excel(r'C:\Users\amirc\Desktop\DATA.xlsx', index = False)
# In[36]:
sns.pairplot(data=df, hue="Y")
# In[25]:
X = X.drop(['MAD','STD'], axis=1)
# # SVM
# In[6]:
for i in X.columns:
Q1 = np.quantile(X[i],0.25)
Q3 = np.quantile(X[i],0.75)
IQR = Q3 - Q1
lower, upper = Q1-1.5*IQR, Q3+1.5*IQR
X[i] = np.where(X[i] <lower, lower,X[i])
X[i] = np.where(X[i] >=upper, upper,X[i])
X.dropna(how='any')
# X.boxplot()
# In[19]:
amir=X.drop(['MTD', 'STD', 'IQR', 'MAD'],axis=1)
lor=X.drop(['Tmin-Tair', 'Tmax-Tair','median-Tair', 'perc10-Tair', 'perc90-Tair', 'Tavg-Tair'],axis=1)
amir.info()
lor
# In[20]:
amir.boxplot()
# In[21]:
lor.boxplot()
# In[4]:
def remove_less_significant_features(X, Y):
sl = 0.5
regression_ols = None
columns_dropped = np.array([])
regression_ols = sm.OLS(Y, X).fit()
max_col = regression_ols.pvalues.idxmax()
max_val = regression_ols.pvalues.max()
if max_val > sl:
X.drop(max_col, axis='columns', inplace=True)
columns_dropped = np.append(columns_dropped, [max_col])
return columns_dropped
# In[18]:
X.drop(['MTD','median-Tair','Tmin'],axis=1)
# In[9]:
print(remove_less_significant_features(X, Y))
X.columns
# In[7]:
import random
import numpy as np # for handling multi-dimensional array operation
import pandas as pd # for reading data from csv
import statsmodels.api as sm # for finding the p-value
from sklearn.metrics import accuracy_score,precision_score,recall_score
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from sklearn.model_selection import cross_val_score, cross_val_predict
from sklearn import svm
random.seed(10)
clf = svm.SVC(kernel='rbf', C=10, random_state=42)
clf.fit(df_features, df_Y)
y_pred_SVM = cross_val_predict(clf, df_features, df_Y, cv=10)
print("acc: \n",accuracy_score(df_Y, y_pred_SVM))
print("pres: \n",precision_score(df_Y, y_pred_SVM))
print("recall: \n",recall_score(df_Y, y_pred_SVM))
# In[40]:
best = svm.SVC(kernel='rbf', C=10,gamma=1e-2 ,random_state=42)
best.fit(df_features, df_Y)
y_pred_best = cross_val_predict(best, df_features, df_Y, cv=10)
print("acc: \n",accuracy_score(df_Y, y_pred_best))
print("pres: \n",precision_score(df_Y, y_pred_best))
print("recall: \n",recall_score(df_Y, y_pred_best))
# In[21]:
# Plot confusion matrix for base model with crossvalidation
cnf = confusion_matrix(Y, y_pred_best)
plt.figure()
skplt.metrics.plot_confusion_matrix(Y, y_pred_best, normalize=False)
plt.show()
# https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html
# ## svm grid search
# In[8]:
from sklearn.model_selection import GridSearchCV
# Create the parameter grid based on the results of random search
param_grid = {
'kernel': ['rbf', 'linear', 'poly', 'sigmoid'],
'gamma': [1, 0.1, 0.01, 0.001],
'C': [0.1, 1, 10, 100],
'degree':[1,2,3,4]
}
# Instantiate the grid search model
grid_search = GridSearchCV(estimator = svm.SVC(), param_grid = param_grid,
cv = 10, verbose = 2)
# Fit the grid search to the data
grid_search.fit(df_features, df_Y)
grid_search.best_params_
best_grid=grid_search.best_estimator_
y_pred_grid=best_grid.predict(df_features)
print(" ")
print('Parameters after gridsearch in use:\n')
grid_search.best_params_
# In[11]:
# In[12]:
print("acc: \n",accuracy_score(df_Y, y_pred_grid))
print("pres: \n",precision_score(df_Y, y_pred_grid))
print("recall: \n",recall_score(df_Y, y_pred_grid))
| 10154e8359f68854137886b1d19812ccea18d5fe | [
"Python"
] | 1 | Python | BarCohenBGU/statistics | e6af02288681c617f3f5f188005bc15ce7cd57e8 | 115804a7bb5671c7a857a2f7e68b936c50db49f5 |
refs/heads/master | <repo_name>Subject6735/tip-calculator-app<file_sep>/scripts/tip.js
// Get the tip
const tipSelect = document.querySelector('#tipselect');
const customTip = document.querySelector('#customtip');
let tip = 0;
// Previously clicked button
let prevTarget = undefined;
tipSelect.addEventListener('click', (e) => {
if (e.target.matches('button')) {
// Remove clicked state of previously clicked button
if (prevTarget !== undefined) {
prevTarget.classList.remove('btn-clicked');
}
// Save currently and previously clicked button
let curTarget = e.target;
curTarget.classList.add('btn-clicked');
prevTarget = curTarget;
const tipAmount = e.target.getAttribute('data-amount');
tip = parseInt(tipAmount);
// Enable resetbutton
resetButton.disabled = false;
resetButton.classList.remove('disabled');
}
});
// Get the custom tip
tipSelect.addEventListener('input', (e) => {
if (e.target.matches('input')) {
tip = parseFloat(e.target.value);
}
});
// Remove button clicked states if we click on the input
customTip.addEventListener('click', () => {
const btns = document.querySelectorAll('#tipselect button');
btns.forEach((btn) => btn.classList.remove('btn-clicked'));
});
<file_sep>/scripts/validate.js
// Validate form (number of people)
pplNum.addEventListener('input', () => {
if (parseInt(pplNum.value) === 0) {
document.querySelector('#pplerror').hidden = false;
pplNum.style.outlineColor = 'orangered';
} else {
document.querySelector('#pplerror').hidden = true;
pplNum.style.outlineColor = 'hsl(172, 67%, 45%)';
}
});
<file_sep>/README.md
# Frontend Mentor - Tip calculator app solution
This is a solution to the [Tip calculator app challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/tip-calculator-app-ugJNGbJUX).
## Table of contents
- [Overview](#overview)
- [The challenge](#the-challenge)
- [Links](#links)
- [My process](#my-process)
- [Built with](#built-with)
- [Useful resources](#useful-resources)
- [Author](#author)
## Overview
### The challenge
Users should be able to:
- View the optimal layout for the app depending on their device's screen size
- See hover states for all interactive elements on the page
- Calculate the correct tip and total cost of the bill per person
### Links
- [Live Site](https://mdeme01.github.io/tip-calculator-app/)
## My process
### Built with
- HTML5
- SASS
- Tailwind
- JavaScript
### Useful resources
- [Tailwind Documentation](https://tailwindcss.com/docs)
- [SASS Basics](https://sass-lang.com/guide)
## Author
- Frontend Mentor - [@mdeme01](https://www.frontendmentor.io/profile/mdeme01)
<file_sep>/scripts/reset.js
// Reset button
const resetButton = document.querySelector('#reset-button');
// Disable resetbutton by default
resetButton.disabled = true;
resetButton.classList.add('disabled');
resetButton.addEventListener('click', () => {
// Reset variables
bill = 0;
tip = 0;
people = 0;
// Reset inputs
billInput.value = '';
customTip.value = '';
pplNum.value = '';
// Reset output
tipOut.innerHTML = '$0.00';
totalOut.innerHTML = '$0.00';
// Remove form validation error
document.querySelector('#pplerror').hidden = true;
// Remove button clicked states
const btns = document.querySelectorAll('#tipselect button');
btns.forEach((btn) => btn.classList.remove('btn-clicked'));
// Disable resetbutton
resetButton.disabled = true;
resetButton.classList.add('disabled');
});
<file_sep>/scripts/people.js
// Get the number of people
const pplNum = document.querySelector('#number-of-ppl');
let people = 0;
pplNum.addEventListener('input', () => {
people = parseInt(pplNum.value);
});
| 22d10ff9d02a88cd99327de07ac870a3393b10a7 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | Subject6735/tip-calculator-app | 8c37ceca2cc46f08bda327060099cb47767bb153 | 3a3e836dfd98b9570ef474e7a8b0bd3da869300c |
refs/heads/master | <file_sep>apply plugin: 'com.android.application'
apply plugin: 'android-apt'
android {
compileSdkVersion 24
buildToolsVersion "24"
defaultConfig {
applicationId "me.kalehv.popmovie"
minSdkVersion 16
targetSdkVersion 24
versionCode 1
versionName "1.0"
vectorDrawables.useSupportLibrary = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
buildTypes.each {
it.buildConfigField 'String', 'THE_MOVIE_DB_API_KEY', TheMovieDBApiKey
}
packagingOptions {
exclude 'META-INF/services/javax.annotation.processing.Processor'
}
lintOptions {
disable 'InvalidPackage'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// android
compile 'com.android.support:support-v4:24.0.0'
compile 'com.android.support:appcompat-v7:24.0.0'
compile 'com.android.support:preference-v7:24.0.0'
compile 'com.android.support:design:24.0.0'
compile 'com.android.support:palette-v7:24.0.0'
compile 'com.android.support:cardview-v7:24.0.0'
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha1'
// square and jakewharton
compile 'com.squareup.okhttp3:okhttp:3.3.1'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.0.2'
compile 'com.squareup.picasso:picasso:2.5.2'
compile('com.squareup.retrofit2:retrofit:2.1.0') {
// exclude Retrofit’s OkHttp peer-dependency module and define your own module import
exclude module: 'okhttp'
}
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.jakewharton:butterknife:8.1.0'
apt 'com.jakewharton:butterknife-compiler:8.1.0'
// Parceler
compile 'org.parceler:parceler-api:1.1.5'
apt 'org.parceler:parceler:1.1.5'
// debug
debugCompile 'com.facebook.stetho:stetho:1.3.1'
debugCompile 'com.facebook.stetho:stetho-okhttp3:1.3.1'
// test
testCompile 'junit:junit:4.12'
// android test
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support:support-annotations:24.0.0'
}
<file_sep>package me.kalehv.popmovie.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import me.kalehv.popmovie.global.C;
/**
* Created by harshadkale on 5/18/16.
*/
public class MovieDbHelper extends SQLiteOpenHelper {
/* Version */
public static final int DATABASE_VERSION = 2;
/* Database name */
private static final String DATABASE_NAME = C.MOVIE_DATABASE_NAME;
public MovieDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private void addMovieTable(SQLiteDatabase sqLiteDatabase) {
// Movie Table
final String SQL_CREATE_MOVIE_TABLE = "CREATE TABLE " +
MovieContract.MovieEntry.TABLE_NAME + " (" +
MovieContract.MovieEntry._ID + " INTEGER PRIMARY KEY, " +
MovieContract.MovieEntry.COLUMN_MOVIE_KEY + " INTEGER UNIQUE NOT NULL, " +
MovieContract.MovieEntry.COLUMN_POSTER_PATH + " TEXT, " +
MovieContract.MovieEntry.COLUMN_BACKDROP_PATH + " TEXT, " +
MovieContract.MovieEntry.COLUMN_TRAILER_PATH + " TEXT, " +
MovieContract.MovieEntry.COLUMN_ADULT + " INTEGER, " +
MovieContract.MovieEntry.COLUMN_TITLE + " BLOB, " +
MovieContract.MovieEntry.COLUMN_OVERVIEW + " BLOB, " +
MovieContract.MovieEntry.COLUMN_RELEASE_DATE + " INTEGER, " +
MovieContract.MovieEntry.COLUMN_VOTE_AVERAGE + " REAL, " +
MovieContract.MovieEntry.COLUMN_POPULARITY + " REAL, " +
MovieContract.MovieEntry.COLUMN_FAVORITE + " INTEGER, " +
MovieContract.MovieEntry.COLUMN_POPULAR_PAGE_NUMBER + " INTEGER, " +
MovieContract.MovieEntry.COLUMN_RATING_PAGE_NUMBER + " INTEGER" +
" )";
sqLiteDatabase.execSQL(SQL_CREATE_MOVIE_TABLE);
}
private void addTrailerTable(SQLiteDatabase sqLiteDatabase) {
// Review Table
final String SQL_CREATE_REVIEW_TABLE = "CREATE TABLE " +
MovieContract.TrailerEntry.TABLE_NAME + " (" +
MovieContract.TrailerEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
MovieContract.TrailerEntry.COLUMN_MOVIE_KEY + " INTEGER NOT NULL, " +
MovieContract.TrailerEntry.COLUMN_TRAILER_KEY + " INTEGER UNIQUE NOT NULL, " +
MovieContract.TrailerEntry.COLUMN_TRAILER_URL + " TEXT, " +
MovieContract.TrailerEntry.COLUMN_TRAILER_IMAGE_URL + " TEXT, " +
" FOREIGN KEY (" + MovieContract.TrailerEntry.COLUMN_MOVIE_KEY + ") REFERENCES " +
MovieContract.MovieEntry.TABLE_NAME + " (" + MovieContract.MovieEntry._ID + ") )";
sqLiteDatabase.execSQL(SQL_CREATE_REVIEW_TABLE);
}
private void addReviewTable(SQLiteDatabase sqLiteDatabase) {
// Review Table
final String SQL_CREATE_REVIEW_TABLE = "CREATE TABLE " +
MovieContract.ReviewEntry.TABLE_NAME + " (" +
MovieContract.ReviewEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
MovieContract.ReviewEntry.COLUMN_MOVIE_KEY + " INTEGER NOT NULL, " +
MovieContract.ReviewEntry.COLUMN_REVIEW_KEY + " INTEGER UNIQUE NOT NULL, " +
MovieContract.ReviewEntry.COLUMN_AUTHOR + " TEXT, " +
MovieContract.ReviewEntry.COLUMN_CONTENT + " TEXT, " +
" FOREIGN KEY (" + MovieContract.ReviewEntry.COLUMN_MOVIE_KEY + ") REFERENCES " +
MovieContract.MovieEntry.TABLE_NAME + " (" + MovieContract.MovieEntry._ID + ") )";
sqLiteDatabase.execSQL(SQL_CREATE_REVIEW_TABLE);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
addMovieTable(sqLiteDatabase);
addTrailerTable(sqLiteDatabase);
addReviewTable(sqLiteDatabase);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// TODO: Update this method to accommodate for transferring current data.
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + MovieContract.MovieEntry.TABLE_NAME);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + MovieContract.TrailerEntry.TABLE_NAME);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + MovieContract.ReviewEntry.TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
<file_sep>package me.kalehv.popmovie;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import butterknife.BindView;
import butterknife.ButterKnife;
import me.kalehv.popmovie.adapters.ThumbnailsAdapter;
import me.kalehv.popmovie.data.MovieContract;
import me.kalehv.popmovie.data.MovieProvider;
import me.kalehv.popmovie.global.C;
import me.kalehv.popmovie.utils.Utility;
/**
* A placeholder fragment containing a simple view.
*/
public class MainFragment
extends Fragment
implements GridView.OnItemClickListener,
LoaderManager.LoaderCallbacks<Cursor> {
//region ButterKnife Declarations
@BindView(R.id.gridview_thumbnails) GridView gridView;
//endregion
private String filterBy;
private ThumbnailsAdapter thumbnailsAdapter;
private static final int MOVIES_LOADER = 0;
public interface OnMovieItemClickListener {
void onMovieItemClick(Uri uri);
}
@Override
public void onStart() {
super.onStart();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
thumbnailsAdapter = new ThumbnailsAdapter(getActivity(), null, 0);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ButterKnife.bind(this, rootView);
gridView.setOnItemClickListener(this);
filterBy = Utility.getMoviesFilter(getActivity(), R.string.pref_filter_popular);
gridView.setAdapter(thumbnailsAdapter);
gridView.setOnItemClickListener(this);
return rootView;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor != null) {
OnMovieItemClickListener listenerActivity = (OnMovieItemClickListener) getActivity();
if (listenerActivity != null) {
long movieKey = cursor.getLong(MovieContract.MovieEntry.COL_INDEX_MOVIE_KEY);
listenerActivity.onMovieItemClick(MovieContract.MovieEntry.buildMovieUri(movieKey));
}
}
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
getLoaderManager().initLoader(MOVIES_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String sortOrder = null;
String selection;
if (filterBy.equals(getString(R.string.pref_filter_top_rated))) {
selection = MovieProvider.topRatedMoviesSelection;
sortOrder = MovieProvider.topRatedMoviesSortOrder;
} else if (filterBy.equals(getString(R.string.pref_filter_favorite))) {
selection = MovieProvider.favoriteMoviesSelection;
} else {
selection = MovieProvider.popularMoviesSelection;
sortOrder = MovieProvider.popularMoviesSortOrder;
}
return new CursorLoader(
getActivity(),
MovieContract.MovieEntry.CONTENT_URI,
C.SELECT_ALL_COLUMNS,
selection,
null,
sortOrder
);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
thumbnailsAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
thumbnailsAdapter.swapCursor(null);
}
}
<file_sep>package me.kalehv.popmovie.models;
import android.net.Uri;
/**
* Created by harshadkale on 4/9/16.
*/
public class ThumbnailItem {
private Uri imageUri;
private String title;
public ThumbnailItem(Uri poster, String title) {
this.imageUri = poster;
this.title = title;
}
public Uri getImageUri() {
return imageUri;
}
public void setImageUri(Uri imageUri) {
this.imageUri = imageUri;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
<file_sep>package me.kalehv.popmovie.data;
import android.annotation.TargetApi;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.Log;
import me.kalehv.popmovie.global.C;
/**
* Created by hk022893 on 5/20/16.
*/
public class MovieProvider extends ContentProvider {
private static final String TAG = MovieProvider.class.getSimpleName();
private static final UriMatcher uriMatcher = buildUriMatcher();
private MovieDbHelper dbHelper;
private static final int MOVIES = 100;
private static final int MOVIE_WITH_ID = 101;
private static final int TRAILERS = 200;
private static final int REVIEWS = 300;
private static final SQLiteQueryBuilder movieQueryBuilder;
private static final SQLiteQueryBuilder trailerByMovieQueryBuilder;
private static final SQLiteQueryBuilder reviewByMovieQueryBuilder;
static {
movieQueryBuilder = new SQLiteQueryBuilder();
movieQueryBuilder.setTables(
MovieContract.MovieEntry.TABLE_NAME
);
trailerByMovieQueryBuilder = new SQLiteQueryBuilder();
trailerByMovieQueryBuilder.setTables(
MovieContract.TrailerEntry.TABLE_NAME /*+ " INNER JOIN " +
MovieContract.MovieEntry.TABLE_NAME +
" ON " + MovieContract.TrailerEntry.TABLE_NAME +
"." + MovieContract.TrailerEntry.COLUMN_MOVIE_KEY +
" = " + MovieContract.MovieEntry.TABLE_NAME +
"." + MovieContract.MovieEntry._ID */
);
reviewByMovieQueryBuilder = new SQLiteQueryBuilder();
reviewByMovieQueryBuilder.setTables(
MovieContract.ReviewEntry.TABLE_NAME /*+ " INNER JOIN " +
MovieContract.MovieEntry.TABLE_NAME +
" ON " + MovieContract.ReviewEntry.TABLE_NAME +
"." + MovieContract.ReviewEntry.COLUMN_MOVIE_KEY +
" = " + MovieContract.MovieEntry.TABLE_NAME +
"." + MovieContract.MovieEntry._ID */
);
}
// Movie.MovieKey = ?
public static String movieByKeySelection = MovieContract.MovieEntry.TABLE_NAME +
"." + MovieContract.MovieEntry.COLUMN_MOVIE_KEY + " = ? ";
public static String popularMoviesSelection = MovieContract.MovieEntry.TABLE_NAME +
"." + MovieContract.MovieEntry.COLUMN_POPULAR_PAGE_NUMBER + " > 0 ";
public static final String popularMoviesSortOrder = MovieContract.MovieEntry.COLUMN_POPULARITY + " DESC";
public static String topRatedMoviesSelection = MovieContract.MovieEntry.TABLE_NAME +
"." + MovieContract.MovieEntry.COLUMN_RATING_PAGE_NUMBER + " > 0 ";
public static final String topRatedMoviesSortOrder = MovieContract.MovieEntry.COLUMN_VOTE_AVERAGE + " DESC";
public static String favoriteMoviesSelection = MovieContract.MovieEntry.TABLE_NAME +
"." + MovieContract.MovieEntry.COLUMN_FAVORITE + " = 1 ";
public static String trailerByMovieIdSelection = MovieContract.TrailerEntry.TABLE_NAME +
"." + MovieContract.TrailerEntry.COLUMN_MOVIE_KEY + " = ? ";
// Review.MovieKey = ?
public static String reviewByMovieIdSelection = MovieContract.ReviewEntry.TABLE_NAME +
"." + MovieContract.ReviewEntry.COLUMN_MOVIE_KEY + " = ? ";
static UriMatcher buildUriMatcher() {
final String authority = MovieContract.CONTENT_AUTHORITY;
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
// GET Movies
matcher.addURI(authority, MovieContract.PATH_MOVIES, MOVIES);
// GET Movie/Id
matcher.addURI(authority, MovieContract.PATH_MOVIES + "/#", MOVIE_WITH_ID);
// GET Trailers
matcher.addURI(authority, MovieContract.PATH_TRAILER, TRAILERS);
// GET Reviews
matcher.addURI(authority, MovieContract.PATH_REVIEW, REVIEWS);
// GET Trailer/MovieId
matcher.addURI(authority, MovieContract.PATH_TRAILER + "/#", TRAILERS);
// GET Review/MovieId
matcher.addURI(authority, MovieContract.PATH_REVIEW + "/#", REVIEWS);
return matcher;
}
// TODO: NOT SURE IF THIS WILL WORK
private Cursor getMovies(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return movieQueryBuilder.query(dbHelper.getReadableDatabase(),
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
}
private Cursor getMovieByKey(Uri uri) {
String _movieId = String.valueOf(ContentUris.parseId(uri));
String[] selectionArgs = new String[]{_movieId};
String selection = movieByKeySelection;
return movieQueryBuilder.query(dbHelper.getReadableDatabase(),
C.SELECT_ALL_COLUMNS,
selection,
selectionArgs,
null,
null,
null);
}
private Cursor getTrailersByMovie(Uri uri, String[] projection, String sortOrder) {
String _movieId = String.valueOf(ContentUris.parseId(uri));
String[] selectionArgs = new String[]{_movieId};
String selection = trailerByMovieIdSelection;
return trailerByMovieQueryBuilder.query(dbHelper.getReadableDatabase(),
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
}
private Cursor getReviewsByMovie(Uri uri, String[] projection, String sortOrder) {
String _movieId = String.valueOf(ContentUris.parseId(uri));
String[] selectionArgs = new String[]{_movieId};
String selection = reviewByMovieIdSelection;
return reviewByMovieQueryBuilder.query(dbHelper.getReadableDatabase(),
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
}
@Override
public boolean onCreate() {
dbHelper = new MovieDbHelper(getContext());
return true;
}
@Nullable
@Override
public String getType(Uri uri) {
final int match = uriMatcher.match(uri);
switch (match) {
case MOVIES:
return MovieContract.MovieEntry.CONTENT_DIR_TYPE;
case MOVIE_WITH_ID:
return MovieContract.MovieEntry.CONTENT_ITEM_TYPE;
case TRAILERS:
return MovieContract.TrailerEntry.CONTENT_DIR_TYPE;
case REVIEWS:
return MovieContract.ReviewEntry.CONTENT_DIR_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
@Nullable
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor cursor;
switch (uriMatcher.match(uri)) {
case MOVIES:
cursor = getMovies(uri, projection, selection, selectionArgs, sortOrder);
break;
case MOVIE_WITH_ID:
cursor = getMovieByKey(uri);
break;
case TRAILERS:
cursor = getTrailersByMovie(uri, projection, sortOrder);
break;
case REVIEWS:
cursor = getReviewsByMovie(uri, projection, sortOrder);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
Context context = getContext();
if (context != null) {
cursor.setNotificationUri(context.getContentResolver(), uri);
}
return cursor;
}
@Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
final SQLiteDatabase db = dbHelper.getWritableDatabase();
Uri returnUri;
final int match = uriMatcher.match(uri);
switch (match) {
case MOVIES: {
long _id = db.insert(MovieContract.MovieEntry.TABLE_NAME, null, values);
if (_id > 0) {
returnUri = MovieContract.MovieEntry.buildMovieUri(_id);
} else {
throw new UnsupportedOperationException("Unable to insert rows into: " + uri);
}
break;
}
case TRAILERS: {
long _id = db.insert(MovieContract.TrailerEntry.TABLE_NAME, null, values);
if (_id > 0) {
returnUri = MovieContract.TrailerEntry.buildTrailerUri(_id);
} else {
throw new UnsupportedOperationException("Unable to insert rows into: " + uri);
}
break;
}
case REVIEWS: {
long _id = db.insert(MovieContract.ReviewEntry.TABLE_NAME, null, values);
if (_id > 0) {
returnUri = MovieContract.ReviewEntry.buildReviewUri(_id);
} else {
throw new UnsupportedOperationException("Unable to insert rows into: " + uri);
}
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
Context context = getContext();
if (context != null) {
context.getContentResolver().notifyChange(uri, null);
}
return returnUri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
final SQLiteDatabase db = dbHelper.getWritableDatabase();
final int match = uriMatcher.match(uri);
int rowsDeleted;
switch (match) {
case MOVIES: {
rowsDeleted = db.delete(MovieContract.MovieEntry.TABLE_NAME, selection, selectionArgs);
break;
}
case TRAILERS: {
rowsDeleted = db.delete(MovieContract.TrailerEntry.TABLE_NAME, selection, selectionArgs);
break;
}
case REVIEWS: {
rowsDeleted = db.delete(MovieContract.ReviewEntry.TABLE_NAME, selection, selectionArgs);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
Context context = getContext();
if (context != null && rowsDeleted != 0) {
context.getContentResolver().notifyChange(uri, null);
}
return rowsDeleted;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
final SQLiteDatabase db = dbHelper.getWritableDatabase();
final int match = uriMatcher.match(uri);
int rowsUpdated;
switch (match) {
case MOVIES: {
rowsUpdated = db.update(MovieContract.MovieEntry.TABLE_NAME, values, selection, selectionArgs);
break;
}
case TRAILERS: {
rowsUpdated = db.update(MovieContract.TrailerEntry.TABLE_NAME, values, selection, selectionArgs);
break;
}
case REVIEWS: {
rowsUpdated = db.update(MovieContract.ReviewEntry.TABLE_NAME, values, selection, selectionArgs);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
Context context = getContext();
if (context != null && rowsUpdated != 0) {
context.getContentResolver().notifyChange(uri, null);
}
return rowsUpdated;
}
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
final SQLiteDatabase db = dbHelper.getWritableDatabase();
final int match = uriMatcher.match(uri);
int returnCount = 0;
switch (match) {
case MOVIES: {
db.beginTransaction();
try {
for (ContentValues value : values) {
try {
long _id = db.insertOrThrow(MovieContract.MovieEntry.TABLE_NAME, null, value);
if (_id > 0) {
returnCount++;
}
} catch (SQLiteConstraintException constraintException) {
updateExistingRowOnInsert(db, value);
}
}
db.setTransactionSuccessful();
} catch (SQLiteException e) {
Log.e(TAG, "bulkInsert: error :", e);
} finally {
db.endTransaction();
}
break;
}
case TRAILERS: {
db.beginTransaction();
try {
for (ContentValues value : values) {
try {
long _id = db.insertOrThrow(MovieContract.TrailerEntry.TABLE_NAME, null, value);
if (_id > 0) {
returnCount++;
}
} catch (SQLiteConstraintException constraintException) {
Log.d(TAG, "bulkInsert: Trailer already exists in database");
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
break;
}
case REVIEWS: {
db.beginTransaction();
try {
for (ContentValues value : values) {
try {
long _id = db.insertOrThrow(MovieContract.ReviewEntry.TABLE_NAME, null, value);
if (_id > 0) {
returnCount++;
}
} catch (SQLiteConstraintException constraintException) {
Log.d(TAG, "bulkInsert: Review already exists in database");
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
Context context = getContext();
if (context != null) {
context.getContentResolver().notifyChange(uri, null);
}
return returnCount;
}
// This doesn't need to be called from actual code. Only needed for testing code.
// http://developer.android.com/reference/android/content/ContentProvider.html#shutdown()
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void shutdown() {
dbHelper.close();
super.shutdown();
}
private void updateExistingRowOnInsert(SQLiteDatabase db, ContentValues value) {
int movieKey = (int) value.get(MovieContract.MovieEntry.COLUMN_MOVIE_KEY);
Uri movieUri = MovieContract.MovieEntry.buildMovieUri(movieKey);
Cursor cursor = getMovieByKey(movieUri);
if (cursor.moveToFirst()) {
int movieId = cursor.getInt(MovieContract.MovieEntry.COL_INDEX_MOVIE_ID);
int existingPopularPageNumber = cursor.getInt(MovieContract.MovieEntry.COL_INDEX_POPULAR_PAGE_NUMBER);
int existingRatingPageNumber = cursor.getInt(MovieContract.MovieEntry.COL_INDEX_RATING_PAGE_NUMBER);
int existingFavorite = cursor.getInt(MovieContract.MovieEntry.COL_INDEX_FAVORITE);
// Update values
int valuePopularityPageNumber = (int) value.get(MovieContract.MovieEntry.COLUMN_POPULAR_PAGE_NUMBER);
int valueRatingPageNumber = (int) value.get(MovieContract.MovieEntry.COLUMN_RATING_PAGE_NUMBER);
if (valuePopularityPageNumber == 0 && existingPopularPageNumber > 0) {
value.put(MovieContract.MovieEntry.COLUMN_POPULAR_PAGE_NUMBER, existingPopularPageNumber);
} else if (valueRatingPageNumber == 0 && existingRatingPageNumber > 0) {
value.put(MovieContract.MovieEntry.COLUMN_RATING_PAGE_NUMBER, existingRatingPageNumber);
}
value.put(MovieContract.MovieEntry.COLUMN_FAVORITE, existingFavorite);
// Update existing record
String strMovieId = Integer.toString(movieId);
db.update(
MovieContract.MovieEntry.TABLE_NAME,
value,
MovieContract.MovieEntry._ID + " = ? ",
new String[]{strMovieId}
);
cursor.close();
}
}
}
<file_sep>package me.kalehv.popmovie.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import me.kalehv.popmovie.R;
import me.kalehv.popmovie.models.Review;
/**
* Created by harshadkale on 5/15/16.
*/
public class ReviewsAdapter
extends RecyclerView.Adapter<ReviewsAdapter.ViewHolder> {
private final String TAG = ThumbnailsAdapter.class.getSimpleName();
private Context context;
private List<Review> reviewList;
public ReviewsAdapter(Context context, List<Review> data) {
this.context = context;
reviewList = data;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View reviewView = inflater.inflate(R.layout.item_movie_review, parent, false);
return new ViewHolder(reviewView);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Review review = reviewList.get(position);
holder.textViewAuthor.setText(review.getAuthor().toUpperCase());
holder.textViewContent.setText(review.getContent());
}
@Override
public int getItemCount() {
return reviewList.size();
}
static class ViewHolder
extends RecyclerView.ViewHolder {
@BindView(R.id.textview_review_author) TextView textViewAuthor;
@BindView(R.id.textview_review_content) TextView textViewContent;
ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
| c8b37b612bdb313aad8b5abd8b392102f7a5a5ae | [
"Java",
"Gradle"
] | 6 | Gradle | kalehv/PopMovie | 48cb7707e0ba05b94042006f4f218a821614cf17 | aac2f34fab53761bad14bcd851e44c883a1cbbcb |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectFooler : MonoBehaviour
{
//리스트 사용하기
//각 노트에 10개를 담는다. 리스트들의 리스트 이중리스트
public List<GameObject> Notes;
private List<List<GameObject>> poolsOfNotes;
public int noteCount = 10;
private bool more = true;
void Start()
{
poolsOfNotes = new List<List<GameObject>>();
for(int i =0; i<Notes.Count; i++) //4번 반복
{
poolsOfNotes.Add(new List<GameObject>());
for(int n=0; n< noteCount; n++)//10번 반복
{
GameObject obj = Instantiate(Notes[i]);
obj.SetActive(false);
poolsOfNotes[i].Add(obj);
}
}
}
public GameObject getObject(int noteType)
{
foreach(GameObject obj in poolsOfNotes[noteType - 1])
{
if (!obj.activeInHierarchy)
{
return obj;
}
}
if (more)
{
GameObject obj = Instantiate(Notes[noteType - 1]);
poolsOfNotes[noteType - 1].Add(obj);
return obj;
}
return null;
}
// Update is called once per frame
void Update()
{
}
}
| ea1a2ab5b3f035c82d7b125f2c68af2e420673e4 | [
"C#"
] | 1 | C# | choiyunhui/unity-2d-donga | e22bd33411cf01e65b0e15dd13397593d0df4f50 | 9e2f7a508bc13582c2c5f168bf976faf112f2af5 |
refs/heads/master | <file_sep>import copy
from typing import List
def main():
org_sort = [17, 11, 12, 5, 14, 9, 6, 16, 4,
10, 1, 19, 13, 15, 0, 2, 3, 18, 7, 8]
result = selection_sort(org_sort)
assert sorted(org_sort) == result
print("result: {}".format(result))
#######################################################
# 選択ソート アルゴリズム
#
# org_sort = [1, 3, 0, 2, 4, 5] の場合
# org_sortの最小値&org_sortでのindexを調べ、最小値をorg_sortから取り除き、new_sortの末尾に追加していく。
#
# org_sort = [1, 3, 0, 2, 4, 5]
# new_sort = []
#
# -----------------------
# | |
# new_sort[] org_sort[1, 3, 0, 2, 4, 5]
# new_sort[0] org_sort[1, 3, 2, 4, 5]
#
# --------------------
# | |
# new_sort[0] org_sort[1, 3, 2, 4, 5]
# new_sort[0, 1] org_sort[3, 2, 4, 5]
#
# -------------------------
# | |
# new_sort[0, 1] org_sort[3, 2, 4, 5]
# new_sort[0, 1, 2] org_sort[3, 4, 5]
#
# をn(len(org_sort))回繰り返す
#
#######################################################
def selection_sort(org_list: List[int]) -> List[int]:
list = copy.copy(org_list)
new_sort = []
for _ in range(len(list)):
m = min(list)
index = list.index(m)
value = list.pop(index)
new_sort.append(value)
print("m:{}, index:{}, new_sort:{}".format(m, index, new_sort))
print("---------------------------------------------")
return new_sort
if __name__ == "__main__":
main()
<file_sep># python-sort-algorithm
sort algorithm scratch building
<file_sep># ソート(基本)
# Contents
配列 [17, 11, 12, 5, 14, 9, 6, 16, 4, 10, 1, 19, 13, 15, 0, 2, 3, 18, 7, 8] を小さい順に並べ替えてください。(目安時間:30 分)
Python に備え付けのソート機能を使用せず、ソートを実現してください
sorted()関数のように、整列したいリストを引数にとる関数を作ると再利用性が高まるので、
関数を定義する形で、プログラムを作成してください
まずは 1 つ、出来れば 3 つの方法を考えてみてください
| 32a2a65a86db47fac914f78a6ca9e155fa06de87 | [
"Markdown",
"Python"
] | 3 | Python | teitei-tk/python-sort-algorithm | 64a2d79cc893b04e9a0e7784fa4b8b4f6ff90074 | eb45a501fa84740bc4268505521a944b7bb0976e |
refs/heads/master | <file_sep>package game.monkeybananas.entity;
import java.awt.Color;
import java.awt.Graphics;
import game.monkeybananas.Game;
import game.monkeybananas.Handler;
import game.monkeybananas.Id;
import game.monkeybananas.tile.Tile;
public class Player extends Entity{
public Player(int x, int y, int width, int height, boolean solid, Id id, Handler handler) {
super(x, y, width, height, solid, id, handler);
}
public void render(Graphics g){
g.drawImage(Game.player.getBufferedImage(), x, y, width, height, null);
}
public void tick() {
x+=velX;
y+=velY;
if(x<=0) x = 0;
if(y<=0) y = 0;
if(x + width>=1080) x = 1080 - width;
if(y + height>=771) y = 771 - height;
for(Tile t:handler.tile){
if(!t.solid)break;
if(t.getId()==Id.wall){
if(getBoundsTop().intersects(t.getBounds())){
setVelY(0);
if(jumping){
jumping = false;
gravity = 0.0;
falling = true;
}
}
if(getBoundsBottom().intersects(t.getBounds())){
setVelY(0);
if(falling) falling = false;
} else{
if(!falling&&!jumping){
gravity = 0.0;
falling = true;
}
}
if(getBoundsLeft().intersects(t.getBounds())){
setVelX(0);
x = t.getX() + t.width;
}
if(getBoundsRight().intersects(t.getBounds())){
setVelX(0);
x = t.getX() - t.height;
}
}
}
if(jumping){
gravity-=0.1;
setVelY((int)gravity);
if(gravity<=0.0){
jumping = false;
falling = true;
}
}
if(falling){
gravity+=0.1;
setVelY((int)gravity);
}
}
}
<file_sep>package game.monkeybananas;
import java.awt.Graphics;
import java.util.LinkedList;
import game.monkeybananas.entity.Entity;
import game.monkeybananas.tile.Tile;
import game.monkeybananas.tile.Wall;
public class Handler {
public LinkedList<Entity> entity = new LinkedList<Entity>();
public LinkedList<Tile> tile = new LinkedList<Tile>();
public Handler() {
createLevel();
}
public void render(Graphics g){
for(Entity en:entity){
en.render(g);
}
for(Tile ti:tile){
ti.render(g);
}
}
public void tick(){
for(Entity en:entity){
en.tick();
}
for(Tile ti:tile){
ti.tick();
}
}
public void addEntity(Entity en){
entity.add(en);
}
public void removeEntity(Entity en){
entity.remove(en);
}
public void addTile(Tile ti){
tile.add(ti);
}
public void removeTile(Tile ti){
tile.remove(ti);
}
public void createLevel(){
for(int i=0; i<Game.WIDTH * Game.SCALE / 64 + 1; i++){
addTile(new Wall(i * 64, Game.HEIGHT * Game.SCALE - 64, 64, 64, true, Id.wall, this));
if(i!=0&&i!=1&&i!=15&&i!=16&&i!=17)addTile(new Wall (i * 64, 300, 64, 64, true, Id.wall, this));
}
}
}
| 5d405db9aeb3358fff019479219524e8317f3a4d | [
"Java"
] | 2 | Java | RubbleOnTheDouble/MonkeyBanana | 2b630f029188b1eac61ac88e39f9fd21de9132a2 | 8f04f8e3baf187352e9946c3e32a195e629cd3d7 |
refs/heads/master | <repo_name>alexandregromboni/TK-Company-App<file_sep>/Desktop/Treinamento/TK-Company-App/src/pages/login/login.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';
import { TabsPage } from '../tabs/tabs';
import { User } from '../../models/user';
import { AuthServiceProvider } from '../../providers/auth-service/auth-service';
@IonicPage()
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
user: User = new User();
constructor(public navCtrl: NavController, public navParams: NavParams,
public authService: AuthServiceProvider, public alertCtrl: AlertController) {
}
login() {
if (this.user.email && this.user.password) {
this.authService.getData('User/Login', this.user).then((result) => {
if (result) {
localStorage.setItem('user', JSON.stringify(result));
this.showAlert('Sucesso', 'Registro salvo com sucesso!');
this.navCtrl.push(TabsPage);
}
else {
//this.presentToast("Usuário e/ou senha inválido(s).");
this.showAlert('Erro', 'Ocorreu um erro ao cadastrar o usuário');
}
}, (err) => {
// Error log
});
}
else {
this.showAlert('Erro', 'Por favor, preencha os dados.');
}
// Your app login API web service call triggers
this.navCtrl.push(TabsPage, {}, { animate: false });
}
showAlert(title, message) {
const alert = this.alertCtrl.create({
title: title,
subTitle: message,
buttons: ['OK']
});
alert.present();
}
}
<file_sep>/Desktop/Treinamento/TK-Company-App/src/pages/signup/signup.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, AlertController } from 'ionic-angular';
import { TabsPage } from '../tabs/tabs';
import { LoginPage } from '../login/login';
import { AuthServiceProvider } from '../../providers/auth-service/auth-service';
import { User } from '../../models/user';
@IonicPage()
@Component({
selector: 'page-signup',
templateUrl: 'signup.html',
})
export class SignupPage {
responseData: any;
user: User = new User();
constructor(public navCtrl: NavController, public navParams: NavParams,
public authService: AuthServiceProvider, public toastCtrl: ToastController,
public alertCtrl: AlertController) {
}
signup() {
if (this.user.email && this.user.password && this.user.name && this.user.birthDate && this.user.gender) {
this.authService.postData('User/Post', this.user).then((result) => {
this.responseData = result;
if (this.responseData) {
localStorage.setItem('user', JSON.stringify(this.responseData));
this.showAlert('Sucesso', 'Registro salvo com sucesso!');
this.navCtrl.push(TabsPage);
}
else {
//this.presentToast("Usuário e/ou senha inválido(s).");
this.showAlert('Erro', 'Ocorreu um erro ao cadastrar o usuário');
}
}, (err) => {
// Error log
});
}
else {
this.presentToast("Dados não preenchidos");
}
}
login() {
//Login page link
this.navCtrl.push(LoginPage);
}
presentToast(msg) {
let toast = this.toastCtrl.create({
message: msg,
duration: 2000
});
toast.present();
}
showAlert(title, message) {
const alert = this.alertCtrl.create({
title: title,
subTitle: message,
buttons: ['OK']
});
alert.present();
}
}
<file_sep>/Desktop/Treinamento/TK-Company-App/src/models/user.ts
//classe para criar modelos de objetos
export class Model {
constructor(objeto?) {
Object.assign(this, objeto);
}
}
//classe usuario extendendo a classe Model
export class User extends Model {
id: number;
name: string;
email: string;
birthDate: Date;
createData: Date;
password: string;
gender: string;
status: boolean;
cpf: string;
} | c2cf931696e9923b06837e7e7e73465af530cae6 | [
"TypeScript"
] | 3 | TypeScript | alexandregromboni/TK-Company-App | d96b5b391862ab8860106fd7a4d07f103af6da2a | b32dbbc7f6633c9bad07ebaf63ff69c53bf4f209 |
refs/heads/master | <repo_name>dpakshimpo/braccio-study<file_sep>/README.md
# braccio-study
<file_sep>/braccio_arduino_ros_rviz/README.md
Project originally forked from https://github.com/grassjelly/ros_braccio_urdf URL. All copyrights follow the original copyrights.
<file_sep>/braccio_arduino_ros_rviz/parse_and_publish/demo_pick_place.py
import rospy
import std_msgs as msg
class Pick_and_Place(object):
def __init__(self):
""" Constructor """
rospy.init_node('pick_place_node', anonymous=False)
self.joint_arr_pub = rospy.Publisher("joint_array", msg, queue_size=20)
self.joint_state_sub = rospy.Subscriber("joint_states",msg,joint_state_cb)
def joint_state_cb(self):
"Call back for joint_state data published from Rviz"
self.joint_arr_pub.publish(data)
<file_sep>/braccio_arduino_ros_rviz/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3)
project(braccio_arduino_ros_rviz)
## Find catkin and any catkin packages
find_package(catkin REQUIRED COMPONENTS roscpp sensor_msgs rospy)
## Declare a catkin package
catkin_package()
install(DIRECTORY launch urdf stl rviz parse_and_publish
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION})
include_directories(include ${catkin_INCLUDE_DIRS})
add_executable(parse_and_publish parse_and_publish/parse_and_publish.cpp)
target_link_libraries(parse_and_publish ${catkin_LIBRARIES})
add_dependencies(parse_and_publish std_msgs) | a48d7706edaa5fffc594da2547d696fa1a8c35ff | [
"Markdown",
"Python",
"CMake"
] | 4 | Markdown | dpakshimpo/braccio-study | 7d9e9e23ef5096e6468d57807b055d5a4a298961 | cec388be4e45932f5a186bb836422502aee74e72 |
refs/heads/master | <repo_name>byzhang/MACH<file_sep>/amazon_670k/src/eval.py
import os
import sys
import numpy as np
import tensorflow as tf
import time
import glob
import json
import argparse
import math
from multiprocessing import Pool
try:
from util import gather_batch
from util import gather_K
except:
print('**********************CANNOT IMPORT GATHER***************************')
exit()
parser = argparse.ArgumentParser()
parser.add_argument("--R", help="how many repetitions?", default=32, type=int)
parser.add_argument("--R_per_gpu", help="how many repetitions per GPU", default=8, type=int)
parser.add_argument("--B", help="how many buckets?", default=10000, type=int)
parser.add_argument("--gpu", help="which GPU?", default='0,1,2,3', type=str)
parser.add_argument("--batch_size", default=16, type=int)
parser.add_argument("--epoch", default='40', type=str)
parser.add_argument("--parallel_across", default='batch', choices=['batch','classes'], type=str)
parser.add_argument("--n_threads", default=16, type=int)
args = parser.parse_args()
if not args.gpu=='all':
import os
os.environ['CUDA_VISIBLE_DEVICES']=str(args.gpu)
## Training Params
feature_dim = 135909
hidden_dim_1 = 500
hidden_dim_2 = 500
B = args.B
batch_size = args.batch_size
epoch = args.epoch
R = args.R
R_per_gpu = args.R_per_gpu
if R%R_per_gpu==0:
num_gpus = R//R_per_gpu
else:
num_gpus = R//R_per_gpu + 1
num_classes = 670091
lookup = np.empty([R,num_classes], dtype=int)
for r in range(R):
lookup[r] = np.load('../data/b_'+str(B)+'/lookups/bucket_order_'+str(r)+'.npy')
params = [None for r in range(R)]
for r in range(R):
params[r] = np.load('../saved_models/b_'+str(B)+'/r_'+str(r)+'_epoch_'+epoch+'.npz')
x_idxs = tf.placeholder(tf.int64, shape=[None,2])
x_vals = tf.placeholder(tf.float32, shape=[None])
x = tf.SparseTensor(x_idxs, x_vals, [batch_size,feature_dim])
W1_tmp=np.array([params[r]['weights_1'] for r in range(R)])
b1_tmp=np.array([params[r]['bias_1'] for r in range(R)])
W2_tmp=np.array([params[r]['weights_2'] for r in range(R)])
b2_tmp=np.array([params[r]['bias_2'] for r in range(R)])
W3_tmp=np.array([params[r]['weights_3'] for r in range(R)])
b3_tmp=np.array([params[r]['bias_3'] for r in range(R)])
W1 = [None for i in range(R)]
b1 = [None for i in range(R)]
layer_1 = [None for i in range(R)]
W2 = [None for i in range(R)]
b2 = [None for i in range(R)]
layer_2 = [None for i in range(R)]
W3 = [None for i in range(R)]
b3 = [None for i in range(R)]
logits = [None for i in range(R)]
probs = [None for i in range(R)]
for i in range(num_gpus):
with tf.device('/gpu:'+str(i)):
for r in range(R_per_gpu*i,min(R_per_gpu*(i+1),R)):
W1[r] = tf.Variable(W1_tmp[r])
b1[r] = tf.Variable(b1_tmp[r])
layer_1[r] = tf.nn.relu(tf.sparse_tensor_dense_matmul(x,W1[r])+b1[r])
#
W2[r] = tf.Variable(W2_tmp[r])
b2[r] = tf.Variable(b2_tmp[r])
layer_2[r] = tf.nn.relu(tf.matmul(layer_1[r],W2[r])+b2[r])
#
W3[r] = tf.Variable(W3_tmp[r])
b3[r] = tf.Variable(b3_tmp[r])
logits[r] = tf.matmul(layer_2[r],W3[r])+b3[r]
config = tf.ConfigProto(log_device_placement=True)
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
sess.run(tf.global_variables_initializer())
###########################################################
N = num_classes
candidates = np.array(range(num_classes))
candidate_indices = np.ascontiguousarray(lookup[:,candidates])
begin_time = time.time()
with open('../data/test.txt','r',encoding='utf-8') as f:
header = f.readline()
idxs = []
vals = []
labels = []
count = 0
offset = 0
score_sum = [0.0, 0.0, 0.0]
for line in f:
try:
itms = line.strip().split()
labels.append([int(lbl) for lbl in itms[0].split(',')])
idxs += [(count-offset,int(itm.split(':')[0])) for itm in itms[1:]]
vals += [float(itm.split(':')[1]) for itm in itms[1:]]
count += 1
if count%batch_size==0:
output = sess.run(logits,feed_dict={x_idxs:idxs, x_vals:vals})
#
preds = np.reshape(output,[R,batch_size,B])
preds = np.transpose(preds, (1,0,2))
preds = np.ascontiguousarray(preds)
#
scores = np.zeros((batch_size,N), dtype=np.float32)
if args.parallel_across=='batch':
gather_batch(preds, candidate_indices, scores, R, B, N, batch_size, args.n_threads)
else:
gather_K(preds, candidate_indices, scores, R, B, N, batch_size, args.n_threads)
########
top_lbls_1 = np.argmax(scores, axis=-1)
top_lbls_3 = np.argpartition(scores, -3, axis=-1)[:, -3:]
top_lbls_5 = np.argpartition(scores, -5, axis=-1)[:, -5:]
for i in range(batch_size):
#### P@1
if top_lbls_1[i] in labels[i]:
score_sum[0] += 1
#### P@3
score_sum[1] += len(np.intersect1d(top_lbls_3[i],labels[i]))/min(len(labels[i]),3)
#### P@5
score_sum[2] += len(np.intersect1d(top_lbls_5[i],labels[i]))/min(len(labels[i]),5)
#
idxs = []
vals = []
labels = []
offset = count
#
if count%1000==0:
print('precision@1 for',count,'points:',score_sum[0]/count)
print('precision@3 for',count,'points:',score_sum[1]/count)
print('precision@5 for',count,'points:',score_sum[2]/count)
print('time_elapsed: ',time.time()-begin_time)
except KeyboardInterrupt:
print('precision@1 for',count,'points:',score_sum[0]/count)
print('precision@3 for',count,'points:',score_sum[1]/count)
print('precision@5 for',count,'points:',score_sum[2]/count)
print('time_elapsed: ',time.time()-begin_time)
break
print('precision@1 for all',count,'points with '+str(R)+' repetitions:',score_sum[0]/count)
print('precision@3 for all',count,'points with '+str(R)+' repetitions:',score_sum[1]/count)
print('precision@5 for all',count,'points with '+str(R)+' repetitions:',score_sum[2]/count)
print('overall time_elapsed: ',time.time()-begin_time)
<file_sep>/delicious_200k/src/run.sh
##### Enabling the import of a function used in evaluation #####
cd ../../util/
sudo make
export PYTHONPATH=$(pwd)
##### Move into the respective folder #####
cd ../delicious_200k/src
##### Build lookups for classes #####
python3 build_index.py
##### Training multiple repetitions simulataneously #####
tmux new -d -s 0 'python3 train_single.py --repetition=0 --B=5000 --gpu=0 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=1 --B=5000 --gpu=0 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=2 --B=5000 --gpu=0 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=3 --B=5000 --gpu=0 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0'
tmux new -d -s 1 'python3 train_single.py --repetition=4 --B=5000 --gpu=1 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=5 --B=5000 --gpu=1 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=6 --B=5000 --gpu=1 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=7 --B=5000 --gpu=1 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0'
tmux new -d -s 2 'python3 train_single.py --repetition=8 --B=5000 --gpu=2 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=9 --B=5000 --gpu=2 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=10 --B=5000 --gpu=2 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=11 --B=5000 --gpu=2 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0'
tmux new -d -s 3 'python3 train_single.py --repetition=12 --B=5000 --gpu=3 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=13 --B=5000 --gpu=3 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=14 --B=5000 --gpu=3 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=15 --B=5000 --gpu=3 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0'
tmux new -d -s 4 'python3 train_single.py --repetition=16 --B=5000 --gpu=4 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=17 --B=5000 --gpu=4 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=18 --B=5000 --gpu=4 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=19 --B=5000 --gpu=4 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0'
tmux new -d -s 5 'python3 train_single.py --repetition=20 --B=5000 --gpu=5 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=21 --B=5000 --gpu=5 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=22 --B=5000 --gpu=5 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=23 --B=5000 --gpu=5 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0'
tmux new -d -s 6 'python3 train_single.py --repetition=24 --B=5000 --gpu=6 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=25 --B=5000 --gpu=6 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=26 --B=5000 --gpu=6 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=27 --B=5000 --gpu=6 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0'
tmux new -d -s 7 'python3 train_single.py --repetition=28 --B=5000 --gpu=7 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=29 --B=5000 --gpu=7 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=30 --B=5000 --gpu=7 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0;
python3 train_single.py --repetition=31 --B=5000 --gpu=7 --gpu_usage=1.0 --batch_size=1000 --n_epochs=20 --load_epoch=0'
##### Get precision@1,3,5 #####
python3 eval.py --R=32<file_sep>/delicious_200k/src/build_index.py
import numpy as np
from sklearn.utils import murmurhash3_32 as mmh3
import argparse
from multiprocessing import Pool
import time
parser = argparse.ArgumentParser()
parser.add_argument("--n_cores", default=32, type=int)
parser.add_argument("--B", default=5000, type=int)
parser.add_argument("--R", default=32, type=int)
parser.add_argument("--write_loc", default='../data/b_5000/lookups', type=str)
args = parser.parse_args()
num_classes = 205443
B = args.B
R = args.R
def process_r(r):
bucket_order = np.zeros(num_classes, dtype=int)
#
for i in range(num_classes):
bucket = mmh3(i,seed=r)%B
bucket_order[i] = bucket
#
np.save(args.write_loc+'/bucket_order_'+str(r)+'.npy',bucket_order)
del bucket_order
return None
p = Pool(args.n_cores)
begin_time = time.time()
p.map(process_r, range(args.R))
print('time_elapsed:',time.time()-begin_time)
p.close()
p.join()
<file_sep>/amazon_670k/src/preproc.py
count = 0
with open('../data/amazon_test.txt','r',encoding='utf-8') as fr:
with open('../data/test.txt','w',encoding='utf-8') as fw:
for line in fr:
if count==0:
count+=1
continue
else:
print(line.strip(),file=fw)
count = 0
with open('../data/amazon_train.txt','r',encoding='utf-8') as fr:
with open('../data/train.txt','w',encoding='utf-8') as fw:
for line in fr:
if count==0:
count+=1
continue
else:
print(line.strip(),file=fw)
<file_sep>/README.md
## This repo will be updated soon with streamlined codes (modular structure, TFRecords and faster evaluation)
## Download links for datasets
1) Extreme classification repository - http://manikvarma.org/downloads/XC/XMLRepository.html
Please download any of the datasets mentioned the paper, unzip them and and push the files to the the respective data folder (like ./amazon_670k/data/).
2) Download ODP dataset from http://hunch.net/~vw/odp_train.vw.gz and http://hunch.net/~vw/odp_test.vw.gz .
The data format must be changed to match the datasets on Extreme Classification repo.
3) Download ImageNet dataset from http://hunch.net/~jl/datasets/imagenet/training.txt.gz and http://hunch.net/~jl/datasets/imagenet/testing.txt.gz .
Yet again, the data format must be changed to match the datasets on Extreme Classification repo.
# Run MACH
Please move in to src folder for respective dataset, like 'amazon_670k/src/'.
The steps to build indexes, train and evaualte are mentioned sequentially in run.sh
The steps to build indexes, train and evaualte are mentioned sequentially in run.sh
<file_sep>/delicious_200k/src/train_single.py
import tensorflow as tf
import numpy as np
import glob
import time
from itertools import islice
import argparse
import math
parser = argparse.ArgumentParser()
parser.add_argument("--repetition", help="which repetition?", default=0)
parser.add_argument("--B", help="How many buckets?", default=5000)
parser.add_argument("--gpu", help="which GPU?", default=0)
parser.add_argument("--gpu_usage", help="how much GPU memory to use", default=1.0)
parser.add_argument("--batch_size", default=1000)
parser.add_argument("--n_epochs", default=20)
parser.add_argument("--load_epoch", default=0)
args = parser.parse_args()
if not args.gpu=='all':
import os
os.environ['CUDA_VISIBLE_DEVICES']=str(args.gpu)
## Training Params
feature_dim = 782585
n_classes = int(args.B)
hidden_dim_1 = 500
hidden_dim_2 = 500
n_epochs = int(args.n_epochs)
batch_size = int(args.batch_size)
r = int(args.repetition) #which repetition
load_epoch = int(args.load_epoch) # will load weights and biases from this epoch number if found in saved_models folder. If not found or if given 0, we do random initialization
############ load lookups
lookup = np.load('../data/b_'+str(n_classes)+'/lookups/bucket_order_'+str(r)+'.npy')
############ check for saved models and create graph
x_idxs = tf.placeholder(tf.int64, shape=[None,2])
x_vals = tf.placeholder(tf.float32, shape=[None])
x = tf.SparseTensor(x_idxs, x_vals, [batch_size,feature_dim])
y = tf.placeholder(tf.float32, shape=[None,n_classes])
saved_models = glob.glob('../saved_models/b_'+str(n_classes)+'/r_'+str(r)+'_epoch_'+str(load_epoch)+'.npz')
if not saved_models:
W1 = tf.Variable(tf.truncated_normal([feature_dim, hidden_dim_1], stddev=0.05))
b1 = tf.Variable(tf.truncated_normal([hidden_dim_1], stddev=0.05))
layer_1 = tf.nn.relu(tf.sparse_tensor_dense_matmul(x,W1)+b1)
#
W2 = tf.Variable(tf.truncated_normal([hidden_dim_1, hidden_dim_2], stddev=0.05))
b2 = tf.Variable(tf.truncated_normal([hidden_dim_2], stddev=0.05))
layer_2 = tf.nn.relu(tf.matmul(layer_1,W2)+b2)
#
W3 = tf.Variable(tf.truncated_normal([hidden_dim_2, n_classes], stddev=0.05))
b3 = tf.Variable(tf.truncated_normal([n_classes], stddev=0.05))
logits = tf.matmul(layer_2,W3)+b3
else:
params = np.load(saved_models[0])
#
W1_tmp = tf.placeholder(tf.float32, shape=[feature_dim, hidden_dim_1])
b1_tmp = tf.placeholder(tf.float32, shape=[hidden_dim_1])
W1 = tf.Variable(W1_tmp)
b1 = tf.Variable(b1_tmp)
layer_1 = tf.nn.relu(tf.sparse_tensor_dense_matmul(x,W1)+b1)
#
W2_tmp = tf.placeholder(tf.float32, shape=[hidden_dim_1, hidden_dim_2])
b2_tmp = tf.placeholder(tf.float32, shape=[hidden_dim_2])
W2 = tf.Variable(W2_tmp)
b2 = tf.Variable(b2_tmp)
layer_2 = tf.nn.relu(tf.matmul(layer_1,W2)+b2)
#
W3_tmp = tf.placeholder(tf.float32, shape=[hidden_dim_2, n_classes])
b3_tmp = tf.placeholder(tf.float32, shape=[n_classes])
W3 = tf.Variable(W3_tmp)
b3 = tf.Variable(b3_tmp)
logits = tf.matmul(layer_2,W3)+b3
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=y))
train_step = tf.train.AdamOptimizer().minimize(loss)
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = float(args.gpu_usage)
sess = tf.Session(config=config)
if not saved_models:
sess.run(tf.global_variables_initializer())
else:
sess.run(tf.global_variables_initializer(),feed_dict={W1_tmp:params['weights_1'],b1_tmp:params['bias_1'],W2_tmp:params['weights_2'],b2_tmp:params['bias_2'],W3_tmp:params['weights_3'],b3_tmp:params['bias_3']})
########### Load data and train
def data_generator(files, batch_size, feature_dim, n_classes):
while 1:
lines = []
for file in files:
with open(file,'r',encoding='utf-8') as f:
header = f.readline()
while True:
temp = len(lines)
lines += list(islice(f,batch_size-temp))
if len(lines)!=batch_size:
break
idxs = []
vals = []
##
y_idxs = []
y_vals = []
y_batch = np.zeros([batch_size,n_classes], dtype=float)
count = 0
for line in lines:
itms = line.strip().split()
##
y_idxs = [int(itm) for itm in itms[0].split(',')]
y_vals = [1.0 for itm in range(len(y_idxs))]
for i in range(len(y_idxs)):
y_batch[count,lookup[y_idxs[i]]] = y_vals[i]
##
idxs += [(count,int(itm.split(':')[0])) for itm in itms[1:]]
vals += [float(itm.split(':')[1]) for itm in itms[1:]]
count += 1
lines = []
yield (idxs, vals, y_batch)#
train_files = glob.glob('../data/train.txt')
training_data_generator = data_generator(train_files, batch_size, feature_dim, n_classes)
curr_epoch = load_epoch
n_train = 196606
n_steps_per_epoch = n_train//batch_size
n_steps = n_epochs*n_steps_per_epoch
print('******************************************')
print('n_steps:',n_steps)
print('******************************************')
import time
begin_time = time.time()
n_check = 1000
for i in range(n_steps):
idxs_batch, vals_batch, labels_batch = next(training_data_generator) #
sess.run(train_step, feed_dict={x_idxs:idxs_batch, x_vals:vals_batch, y:labels_batch}) #
#
if i%n_check==0:
print('Finished ',i,' steps. Time elapsed for last '+str(n_check)+' batches = ',time.time()-begin_time)
begin_time = time.time()
train_loss = sess.run(loss, feed_dict={x_idxs:idxs_batch, x_vals:vals_batch, y:labels_batch})#
print('train loss: ',train_loss)
print('#######################')
if i%n_steps_per_epoch==0 and i>0:
curr_epoch+=1
if curr_epoch%5==0:
params = sess.run([W1,b1,W2,b2,W3,b3])
np.savez_compressed('../saved_models/b_'+str(n_classes)+'/r_'+str(r)+'_epoch_'+str(curr_epoch)+'.npz',weights_1=params[0],bias_1=params[1],weights_2=params[2],bias_2=params[3],weights_3=params[4],bias_3=params[5])
del params
if i%n_steps_per_epoch!=0:
curr_epoch+=1
if curr_epoch%5==0:
params = sess.run([W1,b1,W2,b2,W3,b3])
np.savez_compressed('../saved_models/b_'+str(n_classes)+'/r_'+str(r)+'_epoch_'+str(curr_epoch)+'.npz',weights_1=params[0],bias_1=params[1],weights_2=params[2],bias_2=params[3],weights_3=params[4],bias_3=params[5])
del params
| fc790466ec817d6a3b5b3e8c7946cfa3d97c9d04 | [
"Markdown",
"Python",
"Shell"
] | 6 | Python | byzhang/MACH | 0fda7dbfe2ca8b27f2460fc5d267403f0c55a300 | a8c6dcbbc984f9caf8970dd4175ecd62976389ee |
refs/heads/master | <file_sep>package com.codepath.apps.restclienttemplate;
import android.content.Intent;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.codepath.apps.restclienttemplate.models.Tweet;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONException;
import org.json.JSONObject;
import org.parceler.Parcels;
import cz.msebera.android.httpclient.Header;
public class ComposeActivity extends AppCompatActivity {
private static final String TAG = ComposeActivity.class.getName();
private static final int MAX_TWEET_LEN = 140;
private TextInputEditText etCompose;
private Button btnTweet;
private TwitterClient twitterClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_compose);
twitterClient = TwitterApp.getRestClient(this);
etCompose = findViewById(R.id.etCompose);
btnTweet = findViewById(R.id.buttonTweet);
// set click listener for the button
btnTweet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String tweetContent = etCompose.getText().toString();
// TODO: do better error handling (remove toasts eventually)
if ( tweetContent.isEmpty() ) {
Toast.makeText(ComposeActivity.this,"Tweet cannot be empty", Toast.LENGTH_LONG).show();
} else if ( tweetContent.length() > MAX_TWEET_LEN ) {
Toast.makeText(ComposeActivity.this, "Tweet is too long", Toast.LENGTH_LONG).show();
} else {
twitterClient.composeTweet(tweetContent, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Log.d(TAG, "onSuccess(int statusCode, Header[] headers, JSONObject response):" +
"successful tweet posted: " + response.toString());
try {
Tweet tweet = Tweet.fromJSON(response);
Intent data = new Intent();
data.putExtra("tweet", Parcels.wrap(tweet));
setResult(RESULT_OK, data);
// close this activity, passing data to parent activity
Log.d(TAG, "Returning to parent activity, tweet posted successfully");
finish();
} catch (JSONException e) {
Log.e(TAG, "Failed to to get tweet from JSON object");
e.printStackTrace();
}
super.onSuccess(statusCode, headers, response);
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.e(TAG, "onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable): " +
"Failed to post tweet: " + responseString, throwable);
super.onFailure(statusCode, headers, responseString, throwable);
}
});
}
}
});
}
}
<file_sep>package com.codepath.apps.restclienttemplate;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.codepath.apps.restclienttemplate.models.Tweet;
import com.loopj.android.http.JsonHttpResponseHandler;
import cz.msebera.android.httpclient.Header;
import org.json.JSONObject;
import java.util.List;
public class TweetAdapter extends RecyclerView.Adapter<TweetAdapter.TweetViewHolder> {
private static final String TAG = TweetAdapter.class.getName();
private Context context;
private List<Tweet> tweets;
private TwitterClient twitterClient;
public TweetAdapter(Context context, List<Tweet> tweets) {
this.context = context;
this.tweets = tweets;
twitterClient = TwitterApp.getRestClient(context);
}
class TweetViewHolder extends RecyclerView.ViewHolder {
ImageView ivProfileImage;
TextView tvScreenName;
TextView tvBody;
TextView tvName;
TextView tvTime;
ImageButton retweetButton;
public TweetViewHolder(View itemView) {
super(itemView);
ivProfileImage = itemView.findViewById(R.id.ivProfileImage);
tvScreenName = itemView.findViewById(R.id.tvScreenName);
tvBody = itemView.findViewById(R.id.tvBody);
tvName = itemView.findViewById(R.id.tvName);
tvTime = itemView.findViewById(R.id.tvTime);
retweetButton = itemView.findViewById(R.id.buttonRetweet);
}
}
@NonNull
@Override
public TweetViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// inflate layout for a tweet for each tweet
View view = LayoutInflater.from(context).inflate(R.layout.item_tweet, parent, false);
return new TweetViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final TweetViewHolder holder, int position) {
// bind values based on position of the elements
final Tweet tweet = tweets.get(position);
holder.retweetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if ( !tweet.isRetweeted() ) {
onClickRetweet(tweet, holder);
} else {
onClickUnretweet(tweet, holder);
}
}
});
holder.tvName.setText(tweet.getUser().getName());
holder.tvScreenName.setText(String.format("@%s", tweet.getUser().getScreenName()));
holder.tvTime.setText(tweet.getCreatedAt());
holder.tvBody.setText(tweet.getBody());
Glide.with(context).load(tweet.getUser().getProfileImageURL())
.apply(RequestOptions.circleCropTransform())
.into(holder.ivProfileImage);
}
@Override
public int getItemCount() {
return tweets.size();
}
// clear current data from Recycler View
public void clear() {
tweets.clear();
notifyDataSetChanged();
}
// add a list of items
public void addTweets(List<Tweet> tweets) {
this.tweets.addAll(tweets);
notifyDataSetChanged();
}
// uses client to request retweet
private void onClickRetweet(final Tweet tweet, final TweetViewHolder holder) {
final long id = tweet.getId();
twitterClient.retweet(id, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.i(TAG, "Retweet request successful with id " + id);
tweet.setRetweeted(true);
changeRetweetButton(holder, tweet.isRetweeted());
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e(TAG, "retweet request failure with status code: " + statusCode + " response: " + responseString, throwable);
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.e(TAG, "retweet request failure with status code: " + statusCode, throwable);
}
});
}
// use client to request undo retweet
private void onClickUnretweet(final Tweet tweet, final TweetViewHolder holder) {
final long id = tweet.getId();
twitterClient.unretweet(id, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.i(TAG, "Unretweet request sucessful with id " + id);
tweet.setRetweeted(false);
changeRetweetButton(holder, tweet.isRetweeted());
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e(TAG, "Unretweet reqeuest failure with status code: " + statusCode + " response: " + responseString, throwable);
}
});
}
// change the appearance of the retweet button if a tweet is retweeted.
private void changeRetweetButton(TweetViewHolder holder, boolean retweeted) {
if ( retweeted ) {
holder.retweetButton.setColorFilter(ResourcesCompat.getColor(context.getResources(), R.color.medium_green, null));
} else {
holder.retweetButton.setColorFilter(ResourcesCompat.getColor(context.getResources(), R.color.medium_gray, null));
}
}
}
| f1c6dcf37d03315018711ce2f57db29846db16e8 | [
"Java"
] | 2 | Java | j5doming/codepath-twitter-android | 5b825ed0772d63519bed1d66bf66e6e1759b48cd | d89385269d4e81eb038174a48df1d9eb537c8b8d |
refs/heads/master | <file_sep><?php
use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\ExceptionHandler;
use Silex\Provider\FormServiceProvider;
ErrorHandler::register();
ExceptionHandler::register();
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
'db.options' => array(
'driver' => 'pdo_mysql',
'charset' => 'utf8',
'host' => 'localhost',
'port' => '3306',
'dbname' => 'IMDB',
'user' => 'alex',
'password' => '<PASSWORD>',
)
));
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__.'/../views',
));
$app->register(new Silex\Provider\AssetServiceProvider(), array(
'assets.version' => 'v1'
));
$app->register(new FormServiceProvider());<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Exo 1 - <NAME> - Braaxe</title>
<!-- <link href="https://fonts.googleapis.com/css?family=Montserrat:300" rel="stylesheet"> -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="interface">
<header class="marches">
<div class="logo"></div>
<h1>Les marchés de Lyon<br><small>LE LIEU - L'ÉVÉNEMENT</small></h1>
<div class="icon-vert"></div>
<p class="lorem">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
<div class="curieux">Je suis curieux</div>
</header>
<div class="house"></div>
<div class="location">
<p class="carte">SITUEZ SUR LA CARTE<br>LA HALLE TONY GARNIER</p>
<div class="pin-container"><div class="pin"></div></div>
<p class="footer">SÉLECTIONNEZ ET DÉPOSEZ<br>LE PIN SUR LA CARTE</p>
</div>
</div>
<div class="profil">
<div class="infos-container">
<div class="croix"></div>
<div class="photo"></div>
<div class="infos">
<p class="name"><NAME>.<br><small>BADGE EXPERT</small></p>
<p class="etapes">Étape 7 sur 20</p>
<p class="connexion"><small>Dernière connexion :<br>25 juin 2016</small></p>
</div>
</div>
<div class="badges">
<p>Badges<br><small>Débloquez tous les badges</small></p>
<div class="badges-content">
<div class="touriste"><img src="touriste.png" alt="" class="icon"><p>TOURISTE</p></div>
<div class="flaneur"><img src="flaneur.png" alt="" class="icon"><p>FLÂNEUR</p></div>
<div class="arpenteur"><img src="arpenteur.png" alt="" class="icon"><p>ARPENTEUR</p></div>
<div class="marathonien"><img src="marathonien.png" alt="" class="icon"><p>MARATHONIEN</p></div>
</div>
</div>
<div class="succes">
<p>Succès<br><small>Débloquez tous les succès cachés</small></p>
<div class="succes-content">
<div class="premiers-pas"><img src="pas.png" alt="" class="icon"><p>Premiers pas</p></div>
<div class="curieux-succes"><img src="curieux.png" alt="" class="icon"><p>Curieux</p></div>
<div class="copains"><img src="curieux.png" alt="" class="icon"><p>Les copains d'abord</p></div>
</div>
</div>
</div>
</body>
</html><file_sep># braaxe-test
Si vous avez des questions, n'hésitez pas !
**Exo 2**
```shell
composer install
```
Bonne lecture
Cordialement
<NAME>
<file_sep>create database if not exists IMDB character set utf8 collate utf8_unicode_ci;
use IMDB;
grant all privileges on IMDB.* to 'alex'@'localhost' identified by 'alex';
drop table if exists actor;
drop table if exists movie;
drop table if exists person;
create table person (
person_id integer not null primary key auto_increment,
person_name varchar(100) not null,
person_firstName varchar(100) not null,
person_birthDate date not null
) engine=innodb character set utf8 collate utf8_unicode_ci;
create table movie (
movie_id integer not null primary key auto_increment,
movie_title varchar(100) not null,
movie_synopsis varchar(2000) not null,
movie_date date not null,
movie_poster varchar(100) null,
movie_director integer not null,
constraint fk_movie_director foreign key(movie_director) references person(person_id)
) engine=innodb character set utf8 collate utf8_unicode_ci;
create table actor (
actor_id integer not null primary key auto_increment,
actor_person integer not null,
actor_movie integer not null,
constraint fk_actor_person foreign key(actor_person) references person(person_id),
constraint fk_actor_movie foreign key(actor_movie) references movie(movie_id)
) engine=innodb character set utf8 collate utf8_unicode_ci;
insert into person values
(1, 'Scott', 'Ridley', '1937-11-30');
insert into person values
(2, 'Cameron', 'James', '1954-08-16');
insert into person values
(3, 'Crowe', 'Russell', '1964-04-07');
insert into person values
(4, 'Phoenix', 'Joaquin', '1974-10-28');
insert into movie values
(1, 'Gladiator', 'When a Roman general is betrayed and his family murdered by an emperor''s corrupt son, he comes to Rome as a gladiator to seek revenge.', '2000-06-01', 'uploads/glad.jpg', 1);
insert into movie values
(2, 'Lorem ipsum', 'Lorem ipsum dolorNunc vitae pulvinar odio, iaculis, hendrerit vulputate lorem vestibulum. Suspendisse pulvinar, purus at rutrum diam et dictum. Sed tellus iolutpat nunc. Praesent nec accumsan nisi, in hendrerit nibh. ', '2017-06-01', 'uploads/fond.jpg', 2);
insert into movie values
(3, 'Lorem ipsum in french', "J’en dis autax devores, et que rien ne nous empêche de faire ce qui peut nous donner le plus de plaisir, nous pouvons nous livrer entièrement à la volupté et chasser toute sorte de douleur ; mais, dans les temps destinés aux devoirs de la société ou à la nécessité des affaires, souvent il faut faire divorce avec la volupté, et ne se point refuser à la peine. La règle que suit en cela un homme sage, c’est de renoncer à de légères voluptés pour en avoir de plus grandes, et de savoir supporter des douleurs légères pour en éviter de plus fâcheuses.", '2017-06-01', '', 1);
insert into actor values
(1, 3, 1);
insert into actor values
(2, 4, 1)<file_sep><?php
use Symfony\Component\HttpFoundation\Request;
/**
* HOME
*/
$app->get('/', function () use ($app) {
$sql = "SELECT * FROM movie ORDER BY movie_date DESC";
$movies = $app['db']->fetchAll($sql);
return $app['twig']->render('index.html.twig', array('movies' => $movies));
})->bind('home');
/**
* SHOW MOVIE
*/
$app->get('/movie/{id}', function ($id) use ($app) {
$sql = "SELECT * FROM movie WHERE movie_id = ?";
$movie = $app['db']->fetchAssoc($sql, array((int) $id));
$director_id = "";
foreach ($movie as $key => $value) {
if ($key == 'movie_director') {
$director_id = $value;
}
}
$director = $app['db']->fetchAssoc("SELECT person_name, person_firstName FROM person WHERE person_id = ?", array((int) $director_id));
$actors_id = $app['db']->fetchAll("SELECT actor_person FROM actor WHERE actor_movie = ?", array((int) $id));
$actors = [];
foreach ($actors_id as $actor_id_array) {
foreach ($actor_id_array as $actor_person => $actor_person_id) {
$actor = $app['db']->fetchAssoc("SELECT person_name, person_firstName, person_id FROM person WHERE person_id = ?", array((int) $actor_person_id));
array_push($actors, $actor);
}
}
return $app['twig']->render('show.html.twig', array('movie' => $movie, 'director' => $director, 'actors' => $actors));
})->bind('show');
/**
* NEW MOVIE
*/
$app->get('/new-movie', function () use ($app) {
$sql = "SELECT * FROM person";
$directors = $app['db']->fetchAll($sql);
return $app['twig']->render('new.html.twig', array('directors' => $directors));
})->bind('new-movie');
/**
* ADD A MOVIE
*/
$app->get('/add', function (Request $request) use ($app) {
$title = $request->get('title');
$synopsis = $request->get('synopsis');
$date = $request->get('date');
$poster = $request->get('poster');
$director = $request->get('director');
move_uploaded_file($poster, "/web/uploads" );
$app['db']->insert('movie', array('movie_title' => $title, 'movie_synopsis' => $synopsis, 'movie_date' => $date, 'movie_poster' =>$poster, 'movie_director' => $director));
$movie_id = $app['db']->lastInsertId();
$actors_array = $request->get('actors');
foreach ($actors_array as $actor) {
$app['db']->insert('actor', array('actor_person' => $actor, 'actor_movie' => $movie_id));
}
return $app->redirect($app['url_generator']->generate('home'));
})->bind('add');
/**
* EDIT A MOVIE
*/
$app->get('/movie/{id}/edit', function ($id) use ($app) {
$sql = "SELECT * FROM movie WHERE movie_id = ?";
$movie = $app['db']->fetchAssoc($sql, array((int)$id));
return $app['twig']->render('edit.html.twig', array('movie' => $movie));
})->bind('edit');
/**
* UPDATE A MOVIE
*/
$app->get('/movie/{id}/update', function ($id, Request $request) use ($app) {
$title = $request->get('title');
$synopsis = $request->get('synopsis');
$app['db']->update('movie', array('movie_title' => $title, 'movie_synopsis' => $synopsis), array('movie_id' => $id));
return $app->redirect($app['url_generator']->generate('home'));
})->bind('update');
/**
* DELETE A MOVIE
*/
$app->get('/movie/{id}/delete', function ($id) use ($app) {
$app['db']->delete('movie', array("movie_id" => $id));
return $app->redirect($app['url_generator']->generate('home'));
})->bind('delete');
/**
* NEW DIRECTOR
*/
$app->get('/new-director', function () use ($app) {
return $app['twig']->render('new_director.html.twig');
})->bind('new-director');
/**
* ADD A DIRECTOR
*/
$app->get('/add-director', function (Request $request) use ($app) {
$name = $request->get('name');
$firstName = $request->get('first_name');
$born = $request->get('born_date');
$app['db']->insert('person', array('person_name' => $name, 'person_firstName' => $firstName, 'person_birthDate' => $born));
return $app->redirect($app['url_generator']->generate('home'));
})->bind('add-director');
/**
* SHOW PERSON
*/
$app->get('/person/{id}', function ($id) use ($app) {
$sql = "SELECT * FROM person WHERE person_id = ?";
$person = $app['db']->fetchAssoc($sql, array((int) $id));
$movies_data = $app['db']->fetchAll("SELECT actor_movie FROM actor WHERE actor_person = ?", array((int) $id));
$movies = [];
foreach ($movies_data as $actor_movie => $actor_movie_id) {
foreach ($actor_movie_id as $key => $value) {
$movie = $app['db']->fetchAssoc("SELECT * FROM movie WHERE movie_id = ?", array((int) $value));
array_push($movies, $movie);
}
}
return $app['twig']->render('actor.html.twig', array('person' => $person, 'movies' => $movies));
})->bind('actor'); | d2ae6c7e7f9779e499694e0a9c86b56a9260e0ae | [
"Markdown",
"SQL",
"HTML",
"PHP"
] | 5 | PHP | alex-tazy/braaxe-test | 6d377f3f6a0e066954a188a7b5adefb50fa48622 | f3d522629b3b9108abe46a04c34559a199ea8ced |
refs/heads/master | <repo_name>vkcldhkd/SHExtension<file_sep>/Rx/UINavigation+Rx.swift
//
// UINavigation+Rx.swift
// Copyright © 2019 <NAME>. All rights reserved.
//
import RxCocoa
extension Reactive where Base: UINavigationItem{
public var rightButton: Binder<UIBarButtonItem>{
return Binder(self.base, binding: { [weak base = self.base] (barButtonItem, item) in
guard let base = base else { return }
base.rightBarButtonItem = item
})
}
}
extension Reactive where Base: UIBarButtonItem{
var image: Binder<UIImage?>{
return Binder(self.base, binding: { [weak base = self.base] (barButtonItem, image) in
guard let base = base else { return }
base.image = image
})
}
}
<file_sep>/Dictionary.swift
//
// Dictionary.swift
//
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
extension Dictionary{
func toString(prettyPrinted: Bool = false) -> String {
var options: JSONSerialization.WritingOptions = []
if prettyPrinted {
options = JSONSerialization.WritingOptions.prettyPrinted
}
do {
let data = try JSONSerialization.data(withJSONObject: self, options: options)
if let string = String(data: data, encoding: String.Encoding.utf8) {
return string
}
} catch {
print(error)
}
return ""
}
}
<file_sep>/Rx/AttributedLabel+Rx.swift
//
// AttributedLabel+Rx.swift
// Copyright © 2019 <NAME>. All rights reserved.
//
import RxCocoa
import RxSwift
import AttributedLabel
extension Reactive where Base: AttributedLabel{
var attributedString: Binder<NSAttributedString?>{
return Binder(self.base, binding: { [weak base = self.base] (label, attribtedString) in
guard let base = base else { return }
base.attributedText = attribtedString
})
}
var text: Binder<String?>{
return Binder(self.base, binding: { [weak base = self.base] (label, text) in
guard let base = base else { return }
base.text = text
})
}
}
<file_sep>/Rx/XLPagerTabStrip+Rx.swift
//
// XLPagerTabStrip+Rx.swift
// Copyright © 2019 <NAME>. All rights reserved.
//
import RxCocoa
import XLPagerTabStrip
extension Reactive where Base: PagerTabStripViewController{
public var moveTo: Binder<Int>{
return Binder(self.base, binding: { [weak base = self.base] (_, index) in
guard let base = base else { return }
base.moveToViewController(at: index, animated: true)
})
}
}
<file_sep>/Rx/UIApplication+Rx.swift
//
// UIApplication+Rx.swift
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import RxCocoa
extension Reactive where Base: UIApplication{
public var isIgnoringInteractionEvents: Binder<Bool> {
return Binder(self.base, binding: { [weak base = self.base] (application, active) in
guard let base = base else { return }
active ? base.beginIgnoringInteractionEvents() : base.endIgnoringInteractionEvents()
})
}
}
<file_sep>/UITabbar.swift
//
// UITabbar.swift
//
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
fileprivate let tabBarItemTag: Int = 4942
extension UITabBar {
public func addItemBadge(atIndex index: Int) {
guard let itemCount = self.items?.count, itemCount > 0 else {
return
}
guard index < itemCount else {
return
}
removeItemBadge(atIndex: index)
let badgeView = UIView()
badgeView.tag = tabBarItemTag
badgeView.layer.cornerRadius = 2.5
badgeView.backgroundColor = UIColor.red
let tabFrame = self.frame
let percentX = (CGFloat(index) + 0.65) / CGFloat(itemCount)
let x = (percentX * tabFrame.size.width).rounded(.up)
let y = (CGFloat(0.2) * tabFrame.size.height).rounded(.up)
badgeView.frame = CGRect(x: x, y: y, width: 5, height: 5)
addSubview(badgeView)
}
//return true if removed success.
@discardableResult
public func removeItemBadge(atIndex index: Int) -> Bool {
for subView in self.subviews {
if subView.tag == (tabBarItemTag) {
subView.removeFromSuperview()
return true
}
}
return false
}
}
<file_sep>/String.swift
//
// String.swift
//
// Created by 1 on 15/10/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
extension String{
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
//emoji 관련! 텍스트 이모지만 허용
var containsEmoji: Bool {
for scalar in unicodeScalars {
switch scalar.value {
case 0x1F600...0x1F64F, // Emoticons
0x1F300...0x1F5FF, // Misc Symbols and Pictographs
0x1F680...0x1F6FF, // Transport and Map
// 0x2600...0x26FF, // Misc symbols
0x2700...0x27BF, // Dingbats
0xFE00...0xFE0F, // Variation Selectors
0x1F900...0x1F9FF, // Supplemental Symbols and Pictographs
0x1F1E6...0x1F1FF: // Flags
return true
default:
continue
}
}
return false
}
}
<file_sep>/Rx/UITableView+Rx.swift
//
// UITableView+Rx.swift
// Copyright © 2019 <NAME>. All rights reserved.
//
import RxCocoa
extension Reactive where Base: UITableView{
public var footerView: Binder<UIView?>{
return Binder(self.base, binding:{ [weak base = self.base] (tableView,view) in
guard let base = base else { return }
base.tableFooterView = view
})
}
var backgroundView: Binder<UIView?>{
return Binder(self.base, binding:{ [weak base = self.base] (tableView,view) in
guard let base = base else { return }
base.backgroundView = view
})
}
}
<file_sep>/Rx/UICollectionView+Rx.swift
//
// UICollectionView+Rx.swift
// Copyright © 2019 <NAME>. All rights reserved.
//
import RxCocoa
import RxCocoa
extension Reactive where Base: UICollectionView{
var backgroundView: Binder<UIView?>{
return Binder(self.base, binding:{ [weak base = self.base] (collectionView,view) in
guard let base = base else { return }
base.backgroundView = view
})
}
}
<file_sep>/Rx/RPCircularProgress+Rx.swift
//
// RPCircularProgress+Rx.swift
// Copyright © 2019 <NAME>. All rights reserved.
//
import RPCircularProgress
import RxCocoa
extension Reactive where Base: RPCircularProgress{
public var progress: Binder<CGFloat>{
return Binder(self.base, binding: { [weak base = self.base] (progressBar, value) in
guard let base = base else { return }
base.updateProgress(value)
})
}
}
<file_sep>/Rx/MXParallaxHeader+Rx.swift
//
// MXParallaxHeader+Rx.swift
// Copyright © 2019 <NAME>. All rights reserved.
//
import RxCocoa
import RxSwift
import MXParallaxHeader
extension Reactive where Base: MXParallaxHeader {
var delegate: DelegateProxy<MXParallaxHeader, MXParallaxHeaderDelegate>{
return RxMXParallaxHeaderDelegateProxy.proxy(for: self.base)
}
}
class RxMXParallaxHeaderDelegateProxy: DelegateProxy<MXParallaxHeader, MXParallaxHeaderDelegate>, DelegateProxyType, MXParallaxHeaderDelegate{
static func registerKnownImplementations() {
self.register { (header) -> RxMXParallaxHeaderDelegateProxy in
RxMXParallaxHeaderDelegateProxy(parentObject: header, delegateProxy: self)
}
}
static func currentDelegate(for object: MXParallaxHeader) -> MXParallaxHeaderDelegate? {
return object.delegate
}
static func setCurrentDelegate(_ delegate: MXParallaxHeaderDelegate?, to object: MXParallaxHeader) {
object.delegate = delegate
}
}
<file_sep>/Rx/RNLoadingButton+Rx.swift
//
// RNLoadingButton+Rx.swift
// Copyright © 2019 <NAME>. All rights reserved.
//
import RNLoadingButton_Swift
import RxCocoa
extension Reactive where Base: RNLoadingButton{
public var isLoading: Binder<Bool>{
return Binder(self.base, binding: { [weak base = self.base] (button, active) in
guard let base = base else { return }
base.isLoading = active
})
}
public var titleColor: Binder<UIColor>{
return Binder(self.base, binding: { [weak base = self.base] (button, color) in
guard let base = base else { return }
base.setTitleColor(color, for: .normal)
})
}
}
<file_sep>/Rx/UILabel+Rx.swift
//
// UILabel+Rx.swift
// Copyright © 2019 <NAME>. All rights reserved.
//
import RxCocoa
extension Reactive where Base: UILabel{
public var textColor: Binder<UIColor>{
return Binder(self.base, binding: { [weak base = self.base] (_, color) in
guard let base = base else { return }
base.textColor = color
})
}
}
<file_sep>/Rx/RxImagePickerDelegateProxy.swift
//
// RxImagePickerDelegateProxy.swift
// Copyright © 2019 <NAME>. All rights reserved.
//
import RxCocoa
import UIKit
open class RxImagePickerDelegateProxy
: RxNavigationControllerDelegateProxy, UIImagePickerControllerDelegate {
public init(imagePicker: UIImagePickerController) {
super.init(navigationController: imagePicker)
}
}
| e23f2ba3f290bf6a494edbe15902bed8ebd6da2a | [
"Swift"
] | 14 | Swift | vkcldhkd/SHExtension | 44c0f8633bfe2e3d4ecea25568c3381896551e4b | 51991f1d853fdf4317e678738cc4e20b468d49f4 |
refs/heads/master | <file_sep>package test;
import java.util.Scanner;
public class BattleShips {
static int[][] board = new int[10][10];
static Scanner input = new Scanner(System.in);
static int x = 0;
static int y = 0;
static int playerLives = 5;
static int compLives = 5;
int random;
public static void main(String[] args) {
BattleShips battleShip = new BattleShips();
battleShip.init();
System.out.println("Deploy your ships:");
battleShip.playerInput(x, y);
battleShip.compInput();
while((playerLives != 0) && (compLives != 0)) {
battleShip.playerTurn();
battleShip.computerTurn();
}
System.out.println("DONE");
}
public void init() {
System.out.println("**** Welcome to Battle ships game ****\n");
System.out.println("Right now, the sea is empty.\n");
printBoard();
}
//check if the coordinates are valid
public void checkCoord(int x, int y, int i) {
if (this.x > 9 || this.y > 9) {
while (this.x > 9 || this.y > 9) {
System.out.println("Out of bonds. Type new values:");
System.out.print("Enter X coordinate for your " + i + ".ship: ");
this.x = input.nextInt();
System.out.print("Enter Y coordinate for your " + i + ".ship: ");
this.y = input.nextInt();
}
}
while (board[this.x][this.y] == 1) {
System.out.println("Occupied");
inputCoord(x, y, i);
}
}
//input the coordinates for ships from player
public void inputCoord(int x, int y, int i) {
System.out.print("Enter X coordinate for your " + i + ".ship: ");
this.x = input.nextInt();
System.out.print("Enter Y coordinate for your " + i + ".ship: ");
this.y = input.nextInt();
checkCoord(x, y, i);
}
//print the board
public void printBoard() {
System.out.println(" 0123456789 ");
for (int r = 0; r < board.length; r++) {
System.out.print(r + " |");
for (int c = 0; c < board[0].length; c++) {
if (board[r][c] == 1) {
System.out.print("@");
} else if(board[r][c] == 10) {
System.out.print("!");
} else if(board[r][c] == 11) {
System.out.print("x");
} else if(board[r][c] == 12) {
System.out.print("-");
}
else {
System.out.print(" ");
}
}
System.out.println("| " + r);
}
System.out.println(" 0123456789 \n");
System.out.println("Your ships: " + playerLives + " | Computer ships: " + compLives);
System.out.println("-----------------------------------------------");
}
public void playerInput(int x, int y) {
for (int i = 1; i <= 5; i++) {
inputCoord(x, y, i);
int a = this.x;
int b = this.y;
//System.out.println("board[" + a + "][" + b + "]: " + board[a][b]);
/*
* while(board[x][y] == 1) { System.out.println("Occupied"); inputCoord(x, y,
* i); }
*/
board[a][b] = 1;
//System.out.println("after board[" + this.x + "][" + this.y + "]: " + board[this.x][this.y]);
}
printBoard();
}
public void compInput() {
System.out.println("Computer is deploying ships");
int randX = (int) (Math.random() * 10);
int randY = (int) (Math.random() * 10);
for (int i = 1; i <= 5; i++) {
randX = (int) (Math.random() * 10);
randY = (int) (Math.random() * 10);
while (board[randX][randY] == 1) {
randX = (int) (Math.random() * 10);
randY = (int) (Math.random() * 10);
}
board[randX][randY] = 2;
//System.out.println("after board[" + randX + "][" + randY + "]: " + board[randX][randY]);
System.out.println(i + ". ship DEPLOYED");
}
}
public void playerTurn() {
System.out.println("YOUR TURN");
System.out.print("Enter X coordinate: ");
int x = input.nextInt();
System.out.print("Enter Y coordinate: ");
int y = input.nextInt();
if(board[x][y] == 2) {
System.out.println("Boom! You sunk the ship!");
board[x][y] = 10;
compLives--;
} else if(board[x][y] == 1) {
System.out.println("Oh no, you sunk your own ship :(");
board[x][y] = 11;
playerLives--;
} else {
System.out.println("Sorry, you missed");
board[x][y] = 12;
}
printBoard();
}
public void computerTurn() {
System.out.println("COMPUTER'S TURN");
int x = (int) (Math.random() * 10);
int y = (int) (Math.random() * 10);
if(board[x][y] == 1) {
System.out.println("The computer sunk one of your ships!");
board[x][y] = 11;
playerLives--;
} else if(board[x][y] == 2) {
System.out.println("The computer sunk one of its own ships");
board[x][y] = 10;
compLives--;
} else {
System.out.println("Computer missed");
}
printBoard();
}
}
| cb231a5cddaac76395f99fb6a0eab7490756cca2 | [
"Java"
] | 1 | Java | dvckbass/battleShips | 90e0c1077a8e9c887893689a0463d9148d29b2ff | 878c924cbced3e778801a6f90cea3230b5f15e62 |
refs/heads/master | <repo_name>rubenGit/mycloudacademy<file_sep>/src/AppBundle/EventSubscriber/EasyAdminEventSubscriber.php
<?php
namespace AppBundle\EventSubscriber;
use AppBundle\Entity\GroupSt;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface;
class EasyAdminEventSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
/**
* EasyAdminEventSubscriber constructor.
* @param EntityManagerInterface $entityManager
* @param TokenStorageInterface $tokenStorage
*/
public function __construct(
EntityManagerInterface $entityManager,
TokenStorageInterface $tokenStorage
) {
$this->em = $entityManager;
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
return [
EasyAdminEvents::POST_PERSIST => ['newEvent'],
EasyAdminEvents::POST_UPDATE => ['updateEvent'],
EasyAdminEvents::POST_REMOVE => ['removeEvent'],
];
}
public function newEvent(GenericEvent $event)
{
return $this->persistEvent($event, 'NEW');
}
public function updateEvent(GenericEvent $event)
{
return $this->persistEvent($event, 'UPDATE');
}
public function removeEvent(GenericEvent $event)
{
return $this->persistEvent($event, 'REMOVE');
}
private function persistEvent(
GenericEvent $event, $action
)
{
$entity = $event->getSubject();
if($entity instanceof GroupSt) {
$this->persistEmployesAndClientes($entity);
}
}
private function persistEmployesAndClientes($entity)
{
$employees = $entity->getEmployees();
$clients = $entity->getClients();
$courses = $entity->getCourses();
$classrooms = $entity->getClassrooms();
$timeTables = $entity->getTimeTables();
foreach ($employees as $employee){
$employee->addGroup($entity);
$this->em->persist($employee);
}
foreach ($clients as $client){
$client->addGroup($entity);
$this->em->persist($client);
}
foreach ($courses as $course){
$course->addGroup($entity);
$this->em->persist($course);
}
foreach ($classrooms as $classroom){
$classroom->addGroup($entity);
$this->em->persist($classroom);
}
foreach ($timeTables as $timeTable){
$timeTable->addGroup($entity);
$this->em->persist($timeTable);
}
$this->em->flush();
}
}
<file_sep>/src/AppBundle/Entity/EventInfo.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* EventInfo
*
* @ORM\Table(name="event_info")
* @ORM\Entity(repositoryClass="AppBundle\Repository\EventInfoRepository")
*/
class EventInfo
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var \DateTime $created
*
* @ORM\Column(name="data_created", type="datetime")
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime")
*/
private $dataCreated;
/**
* @var \DateTime $updated
*
* @ORM\Column(name="data_updated", type="datetime")
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime")
*/
private $dataUpdated;
/**
* @var string
*
* @ORM\Column(name="type", type="string", length=255, nullable=true)
*/
private $type;
/**
* @var array
*
* @ORM\Column(name="entidad", type="json_array", nullable=true)
*/
private $entidad;
/**
* @var string
*
* @ORM\Column(name="operations", type="string", length=255, nullable=true)
*/
private $operations;
/**
*
* @var string
* @ORM\Column(name="log_info", type="string", length=255, nullable=true)
*/
private $logInfo;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set dataCreated
*
* @param \DateTime $dataCreated
*
* @return EventInfo
*/
public function setDataCreated($dataCreated)
{
$this->dataCreated = $dataCreated;
return $this;
}
/**
* Get dataCreated
*
* @return \DateTime
*/
public function getDataCreated()
{
return $this->dataCreated;
}
/**
* Set dataUpdated
*
* @param \DateTime $dataUpdated
*
* @return EventInfo
*/
public function setDataUpdated($dataUpdated)
{
$this->dataUpdated = $dataUpdated;
return $this;
}
/**
* Get dataUpdated
*
* @return \DateTime
*/
public function getDataUpdated()
{
return $this->dataUpdated;
}
/**
* Set type
*
* @param string $type
*
* @return EventInfo
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Set entidad
*
* @param \json $entidad
*
* @return EventInfo
*/
public function setEntidad($entidad)
{
$this->entidad = $entidad;
return $this;
}
/**
* Get entidad
*
* @return string
*/
public function getEntidad()
{
return $this->entidad;
}
/**
* Set operations
*
* @param string $operations
*
* @return EventInfo
*/
public function setOperations($operations)
{
$this->operations = $operations;
return $this;
}
/**
* Get operations
*
* @return string
*/
public function getOperations()
{
return $this->operations;
}
/**
* Set logInfo
*
* @param string $logInfo
*
* @return EventInfo
*/
public function setLogInfo($logInfo)
{
$this->logInfo = $logInfo;
return $this;
}
/**
* Get logInfo
*
* @return string
*/
public function getLogInfo()
{
return $this->logInfo;
}
}
<file_sep>/src/AppBundle/Entity/EmployeeType.php~
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* EmployeeType
*
* @ORM\Table(name="employee_type")
* @ORM\Entity(repositoryClass="AppBundle\Repository\EmployeeTypeRepository")
*/
class EmployeeType
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255, nullable=true, unique=true)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="description", type="string", length=255, nullable=true)
*/
private $description;
/**
*
*@ORM\ManyToOne(targetEntity="AppBundle\Entity\Employee", inversedBy="type", cascade={"persist"})
*/
private $employee;
public function __toString()
{
return (string) $this->name ;
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*
* @return EmployeeType
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* @param string $description
*
* @return EmployeeType
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set employee
*
* @param \AppBundle\Entity\Employee $employee
*
* @return EmployeeType
*/
public function setEmployee(\AppBundle\Entity\Employee $employee = null)
{
$this->employee = $employee;
return $this;
}
/**
* Get employee
*
* @return \AppBundle\Entity\Employee
*/
public function getEmployee()
{
return $this->employee;
}
}
<file_sep>/src/AppBundle/Entity/Attendance.php
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Attendance
*
* @ORM\Table(name="attendance")
* @ORM\Entity(repositoryClass="AppBundle\Repository\AttendanceRepository")
*/
class Attendance
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="teacher", type="string", length=255, nullable=true)
*/
private $teacher;
/**
* @var string
* @ORM\Column(name="observations", type="string", length=255, nullable=true)
*/
private $observations;
/**
* @var \Doctrine\Common\Collections\Collection|Client[]
*
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\Client", inversedBy="attendance")
* @ORM\JoinTable(
* name="attendance_clients",
* joinColumns={
* @ORM\JoinColumn(name="client_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="attendance_id", referencedColumnName="id")
* }
* )
*/
private $clients;
/**
*
*@ORM\ManyToOne(targetEntity="AppBundle\Entity\GroupSt", inversedBy="attendance", cascade={"persist"})
*/
private $groupSt;
/**
* LOG ****************************************
*/
/**
* @var \DateTime $created
*
* @ORM\Column(name="data_created", type="datetime")
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime")
*/
private $dataCreated;
/**
* @var \DateTime $updated
*
* @ORM\Column(name="data_updated", type="datetime")
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime")
*/
private $dataUpdated;
/**
* Client constructor.
*/
public function __construct()
{
$this->clients = new ArrayCollection();
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set client
*
* @param string $client
*
* @return Attendance
*/
public function setClient($client)
{
$this->client = $client;
return $this;
}
/**
* Get client
*
* @return string
*/
public function getClient()
{
return $this->client;
}
/**
* Set groupSt
*
* @param string $groupSt
*
* @return Attendance
*/
public function setGroupSt($groupSt)
{
$this->groupSt = $groupSt;
return $this;
}
/**
* Get groupSt
*
* @return string
*/
public function getGroupSt()
{
return $this->groupSt;
}
/**
* Set teacher
*
* @param string $teacher
*
* @return Attendance
*/
public function setTeacher($teacher)
{
$this->teacher = $teacher;
return $this;
}
/**
* Get teacher
*
* @return string
*/
public function getTeacher()
{
return $this->teacher;
}
/**
* Set dataCreated
*
* @param \DateTime $dataCreated
*
* @return Attendance
*/
public function setDataCreated($dataCreated)
{
$this->dataCreated = $dataCreated;
return $this;
}
/**
* Get dataCreated
*
* @return \DateTime
*/
public function getDataCreated()
{
return $this->dataCreated;
}
/**
* Set dataUpdated
*
* @param \DateTime $dataUpdated
*
* @return Attendance
*/
public function setDataUpdated($dataUpdated)
{
$this->dataUpdated = $dataUpdated;
return $this;
}
/**
* Get dataUpdated
*
* @return \DateTime
*/
public function getDataUpdated()
{
return $this->dataUpdated;
}
/**
* Add client
*
* @param \AppBundle\Entity\Client $client
*
* @return Attendance
*/
public function addClient(\AppBundle\Entity\Client $client)
{
$this->clients[] = $client;
return $this;
}
/**
* Remove client
*
* @param \AppBundle\Entity\Client $client
*/
public function removeClient(\AppBundle\Entity\Client $client)
{
$this->clients->removeElement($client);
}
/**
* Get clients
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getClients()
{
return $this->clients;
}
/**
* Set observations
*
* @param string $observations
*
* @return Attendance
*/
public function setObservations($observations)
{
$this->observations = $observations;
return $this;
}
/**
* Get observations
*
* @return string
*/
public function getObservations()
{
return $this->observations;
}
}
<file_sep>/src/AppBundle/Handlers/Command/SendMailCommand.php
<?php
namespace AppBundle\Handlers\Command;
class SendMailCommand
{
/**
* @var string
*/
private $to;
/**
* @var string
*/
private $toName;
/**
* @var string
*/
private $replyTo;
/**
* @var string
*/
private $replyToName;
/**
* @var string
*/
private $subject;
/**
* @var string
*/
private $text;
/**
* @var string
*/
private $body;
/**
* @var array
*/
private $images;
/**
* SendEmailCommand constructor.
* @param $to
* @param $toName
* @param $subject
* @param $text
* @param $body
* @param $images
* @param null $replyTo
* @param null $replyToName
*/
public function __construct(
$to,
$toName,
$subject,
$text,
$body,
$images,
$replyTo = null,
$replyToName = null
) {
$this->to = $to;
$this->toName = $toName;
if (!$replyTo) {
$this->replyTo = $to;
} else {
$this->replyTo = $replyTo;
}
if (!$replyToName) {
$this->replyToName = $toName;
} else {
$this->replyToName = $replyToName;
}
$this->subject = $subject;
$this->text = $text;
$this->body = $body;
$this->images = $images;
}
/**
* @return string
*/
public function getTo()
{
return $this->to;
}
/**
* @return string
*/
public function getToName()
{
return $this->toName;
}
/**
* @return string
*/
public function getReplyTo()
{
return $this->replyTo;
}
/**
* @return string
*/
public function getReplyToName()
{
return $this->replyToName;
}
/**
* @return string
*/
public function getSubject()
{
return $this->subject;
}
/**
* @return string
*/
public function getText()
{
return $this->text;
}
/**
* @return string
*/
public function getBody()
{
return $this->body;
}
/**
* @return array
*/
public function getImages()
{
return $this->images;
}
}
<file_sep>/src/AppBundle/Repository/GroupStRepository.php
<?php
namespace AppBundle\Repository;
use AppBundle\Entity\GroupSt;
/**
* GroupStRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class GroupStRepository extends \Doctrine\ORM\EntityRepository
{
public function totalGroups(){
$repository = $this->_em->getRepository(GroupSt::class);
$query = $repository->createQueryBuilder('g')
->select('count(g)')
->getQuery();
$resultScalar = $query->getScalarResult();
return $resultScalar[0][1];
}
}
<file_sep>/src/AppBundle/Repository/ClientRepository.php
<?php
namespace AppBundle\Repository;
use AppBundle\Entity\Client;
/**
* GroupStRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ClientRepository extends \Doctrine\ORM\EntityRepository
{
public function totalClients(){
$repository = $this->_em->getRepository(Client::class);
$query = $repository->createQueryBuilder('c')
->select('count(c)')
->where('c.active = :status')
->setParameter('status', true)
->getQuery();
$resultScalar = $query->getScalarResult();
return $resultScalar[0][1];
}
}
<file_sep>/src/AppBundle/Exception/MessageUnderscoredExceptionInterface.php
<?php
namespace AppBundle\Exception;
interface MessageUnderscoredExceptionInterface
{
public function getOriginalMessage();
}
<file_sep>/src/AppBundle/Entity/RepositoryInterface.php
<?php
namespace AppBundle\Entity;
interface RepositoryInterface
{
const COMMIT_CHANGES = true;
const DO_NOT_COMMIT_CHANGES = false;
public function commit();
}
<file_sep>/src/AppBundle/Handlers/LogoutHandler.php
<?php
namespace AppBundle\Handlers;
use FOS\OAuthServerBundle\Model\AccessTokenManagerInterface;
use FOS\OAuthServerBundle\Model\RefreshTokenManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
class LogoutHandler implements LogoutSuccessHandlerInterface
{
/**
* @var AccessTokenManagerInterface
*/
private $accessTokenManager;
/**
* @var RefreshTokenManagerInterface
*/
private $refreshTokenManager;
/**
* LogoutHandler constructor.
* @param AccessTokenManagerInterface $accessTokenManager
* @param RefreshTokenManagerInterface $refreshTokenManager
*/
public function __construct(
AccessTokenManagerInterface $accessTokenManager,
RefreshTokenManagerInterface $refreshTokenManager
) {
$this->accessTokenManager = $accessTokenManager;
$this->refreshTokenManager = $refreshTokenManager;
}
/**
* Creates a Response object to send upon a successful logout.
*
* @param Request $request
*
* @return Response
*/
public function onLogoutSuccess(Request $request)
{
if ($accessToken = $this->accessTokenManager
->findTokenByToken($request->get('access_token'))) {
$this->accessTokenManager->deleteToken($accessToken);
}
$this->accessTokenManager->deleteExpired();
if ($refreshToken = $this->refreshTokenManager
->findTokenByToken($request->get('refresh_token'))) {
$this->refreshTokenManager->deleteToken($refreshToken);
}
$this->refreshTokenManager->deleteExpired();
return new Response();
}
}<file_sep>/src/AppBundle/Event/TimestampedEvent.php
<?php
namespace AppBundle\Event;
abstract class TimestampedEvent
{
/**
* @var \DateTime
*/
protected $occuredOn;
/**
* TimestampedEvent constructor.
*/
public function __construct()
{
$this->occuredOn = new \DateTime();
}
/**
* @return \DateTime
*/
public function occuredOn()
{
return $this->occuredOn;
}
}<file_sep>/src/AppBundle/Event/UserPasswordReset.php
<?php
namespace AppBundle\Event;
use AppBundle\Entity\User;
class UserPasswordReset extends TimestampedEvent
{
/**
* @var User
*/
private $user;
/**
* MachineUpdated constructor.
* @param User $user
*/
public function __construct(User $user)
{
$this->user = $user;
parent::__construct();
}
/**
* @return User
*/
public function getUser()
{
return $this->user;
}
}<file_sep>/src/AppBundle/Repository/EmployeeRepository.php
<?php
namespace AppBundle\Repository;
use AppBundle\Entity\Employee;
/**
* TeacherRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class EmployeeRepository extends \Doctrine\ORM\EntityRepository
{
public function totalActiveEmployees(){
$repository = $this->_em->getRepository(Employee::class);
$query = $repository->createQueryBuilder('e')
->select('count(e)')
->where('e.active = true')
->getQuery();
$resultScalar = $query->getScalarResult();
return $resultScalar[0][1];
}
}
<file_sep>/src/AppBundle/Handlers/CommandHandler/SendResetPasswordHandler.php
<?php
namespace AppBundle\Handlers\CommandHandler;
use AppBundle\Entity\User;
use AppBundle\Exception\EmailNotFoundException;
use AppBundle\Handlers\Command\SendMailCommand;
use AppBundle\Handlers\Command\SendResetPasswordCommand;
use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\TwigBundle\TwigEngine;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\TranslatorInterface;
class SendResetPasswordHandler
{
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var ObjectRepository
*/
private $userRepository;
/**
* @var SendMailHandler
*/
private $sendEmailHandler;
/**
* @var TwigEngine
*/
private $templating;
/**
* SendResetPasswordHandler constructor.
* @param EntityManagerInterface $entityManager
* @param SendMailHandler $sendEmailHandler
* @param TwigEngine $twigEngine
*/
public function __construct(
EntityManagerInterface $entityManager,
SendMailHandler $sendEmailHandler,
TwigEngine $twigEngine,
TranslatorInterface $translator
) {
$this->em = $entityManager;
$this->userRepository = $entityManager->getRepository('AppBundle:User');
$this->sendEmailHandler = $sendEmailHandler;
$this->templating = $twigEngine;
$this->translator = $translator;
}
public function handle(SendResetPasswordCommand $command)
{
/** @var User $user */
$email = $command->getEmail();
$user = $this->userRepository->findOneBy(
[
'email' => $email
]
);
if (!$user) {
throw new EmailNotFoundException($email);
}
$subject = $this->translator->trans('reset password');
$user->setResetToken();
$this->em->persist($user);
$this->em->flush();
$this->sendEmailHandler->handle(
new SendMailCommand(
$user->getEmail(),
$user->getName(),
$subject,
"Text",
$this->templating->render(
'@App/users/reset-password.html.twig',
['reset_url' => $command->getUrl() . $user->getResetToken(),
'user'=> $user
]
),
[]
)
);
}
}<file_sep>/src/AppBundle/Entity/ClientType.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* TypeClient
*
* @ORM\Table(name="type_client")
* @ORM\Entity(repositoryClass="AppBundle\Repository\ClientTypeRepository")
*/
class ClientType
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255, nullable=true, unique=true, options={"default" : ""})
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="description", type="string", length=255, nullable=true)
*/
private $description;
/**
*
*@ORM\ManyToOne(targetEntity="AppBundle\Entity\Client", inversedBy="type", cascade={"persist"})
*/
private $client;
public function __toString()
{
return (string) $this->name ;
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*
* @return ClientType
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* @param string $description
*
* @return ClientType
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set client
*
* @param \AppBundle\Entity\Client $client
*
* @return ClientType
*/
public function setClient(\AppBundle\Entity\Client $client = null)
{
$this->client = $client;
return $this;
}
/**
* Get client
*
* @return \AppBundle\Entity\Client
*/
public function getClient()
{
return $this->client;
}
}
<file_sep>/src/AppBundle/Repository/InvoiceRepository.php
<?php
namespace AppBundle\Repository;
use AppBundle\Entity\Expense;
use AppBundle\Entity\Income;
use AppBundle\Entity\Invoice;
use Twig\Node\IncludeNode;
/**
* InvoiceRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class InvoiceRepository extends \Doctrine\ORM\EntityRepository
{
public function pedingInvoicesWithDates($startDate, $endDate){
$repository = $this->_em->getRepository(Invoice::class);
$query = $repository->createQueryBuilder('i')
->select('count(i)')
->where('i.status = :status')
->andwhere('i.dataCreated >= :startDate')
->andwhere('i.dataCreated <= :endDate')
->setParameter('status', Invoice::PENDING_OF_PAID)
->setParameter('startDate', $startDate)
->setParameter('endDate', $endDate)
->getQuery();
$resultScalar = $query->getScalarResult();
$re = $query->getSQL();
return $resultScalar[0][1];
}
public function paidInvoicesWithDates($startDate, $endDate){
$repository = $this->_em->getRepository(Invoice::class);
$query = $repository->createQueryBuilder('i')
->select('count(i)')
->where('i.status = :status')
->andwhere('i.dataCreated >= :startDate')
->andwhere('i.dataCreated <= :endDate')
->setParameter('status', Invoice::PAID)
->setParameter('startDate', $startDate)
->setParameter('endDate', $endDate)
->getQuery();
$resultScalar = $query->getScalarResult();
return $resultScalar[0][1];
}
/**
* @return mixed
* INVOICES PAID + INCOMES
*/
public function incomeRecivedWithDates($startDate, $endDate){
$repository = $this->_em->getRepository(Invoice::class);
$query = $repository->createQueryBuilder('i')
->select('sum(i.total)')
->where('i.status = :status')
->andwhere('i.dataCreated >= :startDate')
->andwhere('i.dataCreated <= :endDate')
->setParameter('status', Invoice::PAID)
->setParameter('startDate', $startDate)
->setParameter('endDate', $endDate)
->getQuery();
$resultScalarInvoices = $query->getScalarResult();
$repository = $this->_em->getRepository(Income::class);
$query = $repository->createQueryBuilder('i')
->select('sum(i.import)')
->andwhere('i.dataCreated >= :startDate')
->andwhere('i.dataCreated <= :endDate')
->setParameter('startDate', $startDate)
->setParameter('endDate', $endDate)
->getQuery();
$resultScalarIncome = $query->getScalarResult();
$total = $resultScalarIncome[0][1] + $resultScalarInvoices[0][1];
return $total;
}
}
<file_sep>/src/AppBundle/Event/EmailSent.php
<?php
namespace AppBundle\Event;
class EmailSent extends TimestampedEvent
{
/**
* @var array
*/
private $result;
/**
* EmailSent constructor.
* @param $result
*/
public function __construct($result)
{
$this->result = $result;
parent::__construct();
}
/**
* @return mixed
*/
public function getResult()
{
return $this->result;
}
}<file_sep>/src/AppBundle/Entity/Client.php
<?php
namespace AppBundle\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* TODO: FUNCIONALITY IMPORT FROM EXCEL OR CSV
*/
/**
* Cliente
*
* @ORM\Table(name="client")
* @ApiResource
* @ORM\Entity(repositoryClass="AppBundle\Repository\ClientRepository")
*/
class Client
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* ••••••••••••••••••••••••••••••••••[ PERSONAL DATA INIT ]••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* @var string
* @ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* @var string
* @ORM\Column(name="surname", type="string", length=255, nullable=false)
*/
private $surname;
/**
* @var string
* @ORM\Column(name="level_of_studies", type="string", length=255, nullable=true)
*/
private $levelOfStudies;
/**
* @var string
* @ORM\Column(name="level_of_knowledge", type="string", length=255, nullable=true)
*/
private $levelOfknowledge;
/**
* @var string
* @ORM\Column(name="job", type="string", length=255, nullable=true)
*/
private $job;
/**
* @var string
* @ORM\Column(name="allergies", type="string", length=255, nullable=true)
*/
private $allergies;
/**
* @var \DateTime
* @ORM\Column(name="birth_date", type="date", length=255, nullable=true)
*/
private $birthDate;
/**
* @var string
* @ORM\Column(name="identification_document", type="string", length=255, nullable=false)
*/
private $identificationDocument;
/**
* @var string
* @ORM\Column(name="identification_number", type="string", length=255, nullable=false)
*/
private $identificationNumber;
/**
* @var string
* @ORM\Column(name="mother_tongue", type="string", length=255, nullable=true, unique=true)
*/
private $motherTongue;
/**
* @var string
* @ORM\Column(name="province", type="string", length=255, nullable=true)
*/
private $province;
/**
* @var string
* @ORM\Column(name="phone", type="string", length=255, nullable=true)
*/
private $phone;
/**
* @var integer
* @ORM\Column(name="phone2", type="string", length=255, nullable=true)
*/
private $phone2;
/**
* @var string
* @ORM\Column(name="Mail", type="string", length=255, nullable=true)
*/
private $mail;
/**
* ••••••••••••••••••••••••••••••••••[ PERSONAL DATA END ]••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* ••••••••••••••••••••••••••••••••••[ geographical DATA INIT ]••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* @var string
* @ORM\Column(name="address", type="string", length=255, nullable=true)
*/
private $address;
/**
* @var integer
* @ORM\Column(name="postal_code", type="string", length=255, nullable=true)
*/
private $postalCode;
/**
* @var string
* @ORM\Column(name="location", type="string", length=255, nullable=true)
*/
private $location;
/**
* @var string
* @ORM\Column(name="country", type="string", length=255, nullable=true)
*/
private $country;
/**
* @var string
* @ORM\Column(name="nationality", type="string", length=255, nullable=true)
*/
private $nationality;
/**
* ••••••••••••••••••••••••••••••••••[ geographicalL DATA END ]••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* ••••••••••••••••••••••••••••••••••[ FAMILY DATA INIT ]••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* @var string
* @ORM\Column(name="father_name", type="string", length=255, nullable=true)
*/
private $fatherName;
/**
* @var string
* @ORM\Column(name="father_surname", type="string", length=255, nullable=true)
*/
private $fatherSurname;
/**
* @var string
* @ORM\Column(name="father_phone", type="string", length=255, nullable=true)
*/
private $phoneFather;
/**
* @var string
* @ORM\Column(name="mother_name", type="string", length=255, nullable=true)
*/
private $motherName;
/**
* @var string
* @ORM\Column(name="mother_surname", type="string", length=255, nullable=true)
*/
private $motherSurname;
/**
* @var string
* @ORM\Column(name="mother_phone", type="string", length=255, nullable=true)
*/
private $motherPhone;
/**
* ••••••••••••••••••••••••••••••••••[ FAMILY DATA END ]••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* ••••••••••••••••••••••••••••••••••[ EXTRA INFO INIT ]••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* @var string
* @ORM\Column(name="time_availability", type="string", length=255, nullable=true)
*/
private $timeAvailability;
/**
* @var string
* @ORM\Column(name="you_met_us_from", type="string", length=255, nullable=true)
*/
private $youMetUsFrom;
/**
* @var boolean
* @ORM\Column(name="payment", type="boolean", nullable=true)
*/
private $payment;
/**
* @var \Doctrine\Common\Collections\Collection|Attendance[]
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\Attendance", mappedBy="clients")
*/
private $attendance;
/**
*
*@ORM\OneToMany(targetEntity="AppBundle\Entity\ClientType", mappedBy="client", cascade={"persist"})
*@ORM\JoinColumn(name="type_id", referencedColumnName="id", nullable=true)
*/
private $type;
/**
* @var \Doctrine\Common\Collections\Collection|GroupSt
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\GroupSt", mappedBy="clients")
*/
private $groups;
/**
* @var string
* @ORM\Column(name="observations", type="string", length=255, nullable=true)
*/
private $observations;
/**
* @var string
* @ORM\Column(name="active", type="boolean", nullable=false)
*/
private $active;
/**
* ••••••••••••••••••••••••••••••••••[ EXTRA INFO INIT ]••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* Client constructor.
*/
public function __construct()
{
$this->attendance = new ArrayCollection();
$this->type = new ArrayCollection();
$this->groups = new ArrayCollection();
}
public function __toString()
{
return (string) $this->identificationNumber.
' '. $this->name .
' ' . $this->surname;
}
/**
* LOG ****************************************
*/
/**
* @var \DateTime $created
*
* @ORM\Column(name="data_created", type="datetime")
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime")
*/
private $dataCreated;
/**
* @var \DateTime $updated
*
* @ORM\Column(name="data_updated", type="datetime")
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime")
*/
private $dataUpdated;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*
* @return Client
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set surname
*
* @param string $surname
*
* @return Client
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* @return string
*/
public function getSurname()
{
return $this->surname;
}
/**
* Set address
*
* @param string $address
*
* @return Client
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set birthDate
*
* @param \DateTime $birthDate
*
* @return Client
*/
public function setBirthDate($birthDate)
{
$this->birthDate = $birthDate;
return $this;
}
/**
* Get birthDate
*
* @return \DateTime
*/
public function getBirthDate()
{
return $this->birthDate;
}
/**
* Set postalCode
*
* @param string $postalCode
*
* @return Client
*/
public function setPostalCode($postalCode)
{
$this->postalCode = $postalCode;
return $this;
}
/**
* Get postalCode
*
* @return string
*/
public function getPostalCode()
{
return $this->postalCode;
}
/**
* Set location
*
* @param string $location
*
* @return Client
*/
public function setLocation($location)
{
$this->location = $location;
return $this;
}
/**
* Get location
*
* @return string
*/
public function getLocation()
{
return $this->location;
}
/**
* Set country
*
* @param string $country
*
* @return Client
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* @return string
*/
public function getCountry()
{
return $this->country;
}
/**
* Set province
*
* @param string $province
*
* @return Client
*/
public function setProvince($province)
{
$this->province = $province;
return $this;
}
/**
* Get province
*
* @return string
*/
public function getProvince()
{
return $this->province;
}
/**
* Set identificationDocument
*
* @param string $identificationDocument
*
* @return Client
*/
public function setIdentificationDocument($identificationDocument)
{
$this->identificationDocument = $identificationDocument;
return $this;
}
/**
* Get identificationDocument
*
* @return string
*/
public function getIdentificationDocument()
{
return $this->identificationDocument;
}
/**
* Set identificationNumber
*
* @param string $identificationNumber
*
* @return Client
*/
public function setIdentificationNumber($identificationNumber)
{
$this->identificationNumber = $identificationNumber;
return $this;
}
/**
* Get identificationNumber
*
* @return string
*/
public function getIdentificationNumber()
{
return $this->identificationNumber;
}
/**
* Set phone
*
* @param string $phone
*
* @return Client
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* @return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set mobilePhone
*
* @param string $phone2
*
* @return Client
*/
public function setPhone2($phone2)
{
$this->phone2 = $phone2;
return $this;
}
/**
* Get mobilePhone
*
* @return string
*/
public function getPhone2()
{
return $this->phone2;
}
/**
* Set mail
*
* @param string $mail
*
* @return Client
*/
public function setMail($mail)
{
$this->mail = $mail;
return $this;
}
/**
* Get mail
*
* @return string
*/
public function getMail()
{
return $this->mail;
}
/**
* Set dataCreated
*
* @param \DateTime $dataCreated
*
* @return Client
*/
public function setDataCreated($dataCreated)
{
$this->dataCreated = $dataCreated;
return $this;
}
/**
* Get dataCreated
*
* @return \DateTime
*/
public function getDataCreated()
{
return $this->dataCreated;
}
/**
* Set dataUpdated
*
* @param \DateTime $dataUpdated
*
* @return Client
*/
public function setDataUpdated($dataUpdated)
{
$this->dataUpdated = $dataUpdated;
return $this;
}
/**
* Get dataUpdated
*
* @return \DateTime
*/
public function getDataUpdated()
{
return $this->dataUpdated;
}
/**
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* @param string $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Set payment
*
* @param boolean $payment
*
* @return Client
*/
public function setPayment($payment)
{
$this->payment = $payment;
return $this;
}
/**
* Get payment
*
* @return boolean
*/
public function getPayment()
{
return $this->payment;
}
/**
* Add attendance
*
* @param \AppBundle\Entity\Attendance $attendance
*
* @return Client
*/
public function addAttendance(\AppBundle\Entity\Attendance $attendance)
{
$this->attendance[] = $attendance;
return $this;
}
/**
* Remove attendance
*
* @param \AppBundle\Entity\Attendance $attendance
*/
public function removeAttendance(\AppBundle\Entity\Attendance $attendance)
{
$this->attendance->removeElement($attendance);
}
/**
* Get attendance
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getAttendance()
{
return $this->attendance;
}
/**
* Set levelOfStudies
*
* @param string $levelOfStudies
*
* @return Client
*/
public function setLevelOfStudies($levelOfStudies)
{
$this->levelOfStudies = $levelOfStudies;
return $this;
}
/**
* Get levelOfStudies
*
* @return string
*/
public function getLevelOfStudies()
{
return $this->levelOfStudies;
}
/**
* Set levelOfknowledge
*
* @param string $levelOfknowledge
*
* @return Client
*/
public function setLevelOfknowledge($levelOfknowledge)
{
$this->levelOfknowledge = $levelOfknowledge;
return $this;
}
/**
* Get levelOfknowledge
*
* @return string
*/
public function getLevelOfknowledge()
{
return $this->levelOfknowledge;
}
/**
* Set allergies
*
* @param string $allergies
*
* @return Client
*/
public function setAllergies($allergies)
{
$this->allergies = $allergies;
return $this;
}
/**
* Get allergies
*
* @return string
*/
public function getAllergies()
{
return $this->allergies;
}
/**
* Set motherTongue
*
* @param string $motherTongue
*
* @return Client
*/
public function setMotherTongue($motherTongue)
{
$this->motherTongue = $motherTongue;
return $this;
}
/**
* Get motherTongue
*
* @return string
*/
public function getMotherTongue()
{
return $this->motherTongue;
}
/**
* Set nationality
*
* @param string $nationality
*
* @return Client
*/
public function setNationality($nationality)
{
$this->nationality = $nationality;
return $this;
}
/**
* Get nationality
*
* @return string
*/
public function getNationality()
{
return $this->nationality;
}
/**
* Set fatherName
*
* @param string $fatherName
*
* @return Client
*/
public function setFatherName($fatherName)
{
$this->fatherName = $fatherName;
return $this;
}
/**
* Get fatherName
*
* @return string
*/
public function getFatherName()
{
return $this->fatherName;
}
/**
* Set fatherSurname
*
* @param string $fatherSurname
*
* @return Client
*/
public function setFatherSurname($fatherSurname)
{
$this->fatherSurname = $fatherSurname;
return $this;
}
/**
* Get fatherSurname
*
* @return string
*/
public function getFatherSurname()
{
return $this->fatherSurname;
}
/**
* Set phoneFather
*
* @param string $phoneFather
*
* @return Client
*/
public function setPhoneFather($phoneFather)
{
$this->phoneFather = $phoneFather;
return $this;
}
/**
* Get phoneFather
*
* @return string
*/
public function getPhoneFather()
{
return $this->phoneFather;
}
/**
* Set motherName
*
* @param string $motherName
*
* @return Client
*/
public function setMotherName($motherName)
{
$this->motherName = $motherName;
return $this;
}
/**
* Get motherName
*
* @return string
*/
public function getMotherName()
{
return $this->motherName;
}
/**
* Set motherSurname
*
* @param string $motherSurname
*
* @return Client
*/
public function setMotherSurname($motherSurname)
{
$this->motherSurname = $motherSurname;
return $this;
}
/**
* Get motherSurname
*
* @return string
*/
public function getMotherSurname()
{
return $this->motherSurname;
}
/**
* Set motherPhone
*
* @param string $motherPhone
*
* @return Client
*/
public function setMotherPhone($motherPhone)
{
$this->motherPhone = $motherPhone;
return $this;
}
/**
* Get motherPhone
*
* @return string
*/
public function getMotherPhone()
{
return $this->motherPhone;
}
/**
* Set youMetUsFrom
*
* @param string $youMetUsFrom
*
* @return Client
*/
public function setYouMetUsFrom($youMetUsFrom)
{
$this->youMetUsFrom = $youMetUsFrom;
return $this;
}
/**
* Get youMetUsFrom
*
* @return string
*/
public function getYouMetUsFrom()
{
return $this->youMetUsFrom;
}
/**
* Set job
*
* @param string $job
*
* @return Client
*/
public function setJob($job)
{
$this->job = $job;
return $this;
}
/**
* Get job
*
* @return string
*/
public function getJob()
{
return $this->job;
}
/**
* Add type
*
* @param \AppBundle\Entity\ClientType $type
*
* @return Client
*/
public function addType(\AppBundle\Entity\ClientType $type)
{
$this->type[] = $type;
return $this;
}
/**
* Remove type
*
* @param \AppBundle\Entity\ClientType $type
*/
public function removeType(\AppBundle\Entity\ClientType $type)
{
$this->type->removeElement($type);
}
/**
* @return string
*/
public function getTimeAvailability()
{
return $this->timeAvailability;
}
/**
* @param string $timeAvailability
*/
public function setTimeAvailability($timeAvailability)
{
$this->timeAvailability = $timeAvailability;
}
/**
* Set observations
*
* @param string $observations
*
* @return Client
*/
public function setObservations($observations)
{
$this->observations = $observations;
return $this;
}
/**
* Get observations
*
* @return string
*/
public function getObservations()
{
return $this->observations;
}
/**
* Set active
*
* @param boolean $active
*
* @return Client
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
/**
* Get active
*
* @return boolean
*/
public function getActive()
{
return $this->active;
}
/**
* Add group
*
* @param \AppBundle\Entity\GroupSt $group
*
* @return Client
*/
public function addGroup(\AppBundle\Entity\GroupSt $group)
{
$this->groups[] = $group;
return $this;
}
/**
* Remove group
*
* @param \AppBundle\Entity\GroupSt $group
*/
public function removeGroup(\AppBundle\Entity\GroupSt $group)
{
$this->groups->removeElement($group);
}
/**
* Get groups
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getGroups()
{
return $this->groups;
}
}
<file_sep>/src/AppBundle/Repository/CourseRepository.php
<?php
namespace AppBundle\Repository;
use AppBundle\Entity\Course;
/**
* CourseRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class CourseRepository extends \Doctrine\ORM\EntityRepository
{
public function totalCourses(){
$repository = $this->_em->getRepository(Course::class);
$query = $repository->createQueryBuilder('c')
->select('count(c)')
->getQuery();
$resultScalar = $query->getScalarResult();
return $resultScalar[0][1];
}
}
<file_sep>/src/AppBundle/Command/CreateOAuthClientCommand.php
<?php
namespace AppBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class CreateOAuthClientCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('oauth:client:create')
->setDescription('Create OAuth Client')
->addArgument(
'name',
InputArgument::REQUIRED,
'Client Name?'
)
->addArgument(
'redirectUri',
InputArgument::REQUIRED,
'Redirect URI?'
)
->addArgument(
'grantType',
InputArgument::OPTIONAL,
'Grant type'
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$container = $this->getContainer();
$redirectUri = $input->getArgument('redirectUri');
$clientManager = $container->get('fos_oauth_server.client_manager.default');
$client = $clientManager->createClient();
$client->setRedirectUris([$redirectUri]);
if (!$grantType = $input->getArgument('grantType')) {
$grantTypes = ["password", "refresh_token"];
} else {
$grantTypes = [$grantType];
}
$client->setAllowedGrantTypes($grantTypes);
$clientManager->updateClient($client);
$output->writeln(sprintf("<info>The client was created with <comment>%s</comment> as public id and <comment>%s</comment> as secret</info>",
$client->getPublicId(),
$client->getSecret()));
}
}
<file_sep>/src/AppBundle/Handlers/CommandHandler/ResetPasswordHandler.php
<?php
namespace AppBundle\Handlers\CommandHandler;
use AppBundle\Event\UserPasswordReset;
use AppBundle\Handlers\Command\ResetPasswordCommand;
use AppBundle\Handlers\Command\SendMailCommand;
use FOS\UserBundle\Doctrine\UserManager;
use SimpleBus\Message\Recorder\RecordsMessages;
use Symfony\Bundle\TwigBundle\TwigEngine;
use Symfony\Component\Translation\TranslatorInterface;
class ResetPasswordHandler
{
/**
* @var UserManager
*/
private $userManager;
/**
* @var SendMailHandler
*/
private $sendEmailHandler;
/**
* @var TwigEngine
*/
private $templating;
/**
* @var RecordsMessages
*/
private $eventRecorder;
/**
* ResetPasswordHandler constructor.
* @param UserManager $userManager
* @param SendMailHandler $sendEmailHandler
* @param TwigEngine $templating
* @param RecordsMessages $eventRecorder
*/
public function __construct(
UserManager $userManager,
SendMailHandler $sendEmailHandler,
TwigEngine $templating,
RecordsMessages $eventRecorder,
TranslatorInterface $translator
) {
$this->userManager = $userManager;
$this->sendEmailHandler = $sendEmailHandler;
$this->templating = $templating;
$this->eventRecorder = $eventRecorder;
$this->translator = $translator;
}
/**
* @param ResetPasswordCommand $command
* @throws \Twig_Error
*/
public function handle(ResetPasswordCommand $command)
{
$user = $command->getUser();
$password = $<PASSWORD>();
$user
->setPlainPassword($password)
->setResetToken();
$subject = $this->translator->trans('new password');
$this->userManager->updateUser($user);
$this->sendEmailHandler->handle(
new SendMailCommand(
$user->getEmail(),
$user->getName(),
$subject,
"Text",
$this->templating->render(
'@App/users/new-password.html.twig',
['password' => $password]
),
[]
)
);
$this->eventRecorder->record(new UserPasswordReset($user));
}
private function random_password( $length = 8 ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?";
$password = substr( str_shuffle( $chars ), 0, $length );
return $password;
}
}<file_sep>/src/AppBundle/Entity/User.php~
<?php
namespace AppBundle\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use FOS\UserBundle\Model\User as BaseUser;
/**
* User
* @ApiResource(attributes={
* "normalization_context"={"groups"={"user", "user-read"}},
* "denormalization_context"={"groups"={"user", "user-write"}}
* })
* @ORM\Table(name="fos_user")
* @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
*/
class User extends BaseUser
{
public function __construct()
{
parent::__construct();
}
public function __toString()
{
return (string) $this->id .
' ' . $this->username .
' ' . $this->email ;
}
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* LOG ****************************************
*/
/**
* @var \DateTime $created
*
* @ORM\Column(name="fecha_creacion", type="datetime")
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime")
*/
private $dataCreated;
/**
* @var \DateTime $updated
*
* @ORM\Column(name="fecha_actualizacion", type="datetime")
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime")
*/
private $dataUpdated;
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Set dataCreated
*
* @param \DateTime $dataCreated
*
* @return User
*/
public function setDataCreated($dataCreated)
{
$this->dataCreated = $dataCreated;
return $this;
}
/**
* Get dataCreated
*
* @return \DateTime
*/
public function getDataCreated()
{
return $this->dataCreated;
}
/**
* Set dataUpdated
*
* @param \DateTime $dataUpdated
*
* @return User
*/
public function setDataUpdated($dataUpdated)
{
$this->dataUpdated = $dataUpdated;
return $this;
}
/**
* Get dataUpdated
*
* @return \DateTime
*/
public function getDataUpdated()
{
return $this->dataUpdated;
}
}
<file_sep>/src/AppBundle/Services/HomeQueryManager.php
<?php
/**
* Created by PhpStorm.
* User: ruben
* Date: 13/05/18
* Time: 18:16
*/
namespace AppBundle\Services;
use AppBundle\Entity\Client;
use AppBundle\Entity\Course;
use AppBundle\Entity\Employee;
use AppBundle\Entity\Expense;
use AppBundle\Entity\GroupSt;
use AppBundle\Entity\Invoice;
use Doctrine\ORM\EntityManager;
class HomeQueryManager
{
private $em;
private $clientRepository;
private $invoiceRepository;
/**
* HomeQueryManager constructor.
* @param $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
$this->clientRepository = $this->em->getRepository(Client::class);
$this->employeeRepository = $this->em->getRepository(Employee::class);
$this->groupRepository = $this->em->getRepository(GroupSt::class);
$this->expenseRepository = $this->em->getRepository(Expense::class);
$this->coursesRepository = $this->em->getRepository(Course::class);
$this->invoiceRepository = $this->em->getRepository(Invoice::class);
}
public function getTotalActiveClients(){
return $this->clientRepository->totalClients();
}
public function getTotalEmployees(){
return $this->employeeRepository->totalActiveEmployees();
}
public function getTotalGroups(){
return $this->groupRepository->totalGroups();
}
public function getTotalCourses(){
return $this->coursesRepository->totalCourses();
}
public function getPedingInvoicesWithDate($startDate, $endDate){
return $this->invoiceRepository->pedingInvoicesWithDates($startDate, $endDate);
}
public function getPaidInvoicesWithDates($startDate, $endDate){
return $this->invoiceRepository->paidInvoicesWithDates($startDate, $endDate);
}
public function getIncomesWithDate($startDate, $endDate){
return $this->invoiceRepository->incomeRecivedWithDates($startDate, $endDate);
}
public function getExpensesWithDate($startDate, $endDate){
return $this->expenseRepository->expenseWithDates($startDate, $endDate);
}
}<file_sep>/src/AppBundle/Controller/LoginController.php
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\User;
use OAuth2\OAuth2ServerException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class LoginController extends Controller
{
private $translationTable = [
'Missing parameters. "username" and "password" required' =>
'{"errorCode":201,"errorMsg":"Falta usuario o contraseña"}',
'The client credentials are invalid' =>
'{"errorCode":202,"errorMsg":"Las credenciales del cliente no son válidas"}',
'Invalid username and password combination' =>
'{"errorCode":203,"errorMsg":"Contraseña incorrecta"}',
'Invalid refresh token' =>
'{"errorCode":204,"errorMsg":"Vuelva a introducir los datos, la sesión ha caducado."}',
];
/**
* @Route("/v2/token", methods={"GET", "POST"})
* @param Request $request
* @return Response
*/
public function getTokenAction(Request $request)
{
$userRequest = $request->request->all();
if (isset($userRequest['username'])) {
/** @var User $user */
$user = $this->get('doctrine')->getRepository('AppBundle:User')->findOneBy(
[
'emailCanonical' => $userRequest['username'],
'enabled' => 1
]
);
if (!$user) {
$response = new Response(
'{"errorCode":205,"errorMsg":"Usuario incorrecto"}',
400
);
return $response;
}
}
try {
return $this->get('fos_oauth_server.server')->grantAccessToken($request);
} catch (OAuth2ServerException $e) {
$response = new Response(
$this->translationTable[$e->getDescription()],
$e->getHttpCode(),
$e->getResponseHeaders()
);
return $response;
}
}
}<file_sep>/src/AppBundle/Handlers/Command/ResetPasswordCommand.php
<?php
namespace AppBundle\Handlers\Command;
use AppBundle\Entity\User;
class ResetPasswordCommand
{
/**
* @var User
*/
private $user;
/**
* ResetPasswordCommand constructor.
* @param $user
*/
public function __construct($user)
{
$this->user = $user;
}
/**
* @return User
*/
public function getUser()
{
return $this->user;
}
}<file_sep>/src/AppBundle/Entity/Course.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Course
*
* @ORM\Table(name="course")
* @ORM\Entity(repositoryClass="AppBundle\Repository\CourseRepository")
*/
class Course
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="academicYear", type="string", length=255, nullable=false)
*/
private $academicYear;
/**
* @var string
*
* @ORM\Column(name="color", type="string", length=255, nullable=true)
*/
private $color;
/**
* @var string
*
* @ORM\Column(name="type", type="string", length=255, nullable=true)
*/
private $type;
/**
* @var string
*
* @ORM\Column(name="category", type="string", length=255)
*/
private $category;
/**
* @var string
*
* @ORM\Column(name="periodicPrice", type="decimal", precision=10, scale=5, nullable=true)
*/
private $periodicPrice;
/**
* @var string
*
* @ORM\Column(name="priceHour", type="decimal", precision=10, scale=5, nullable=true)
*/
private $priceHour;
/**
* @var int
*
* @ORM\Column(name="discount", type="integer", nullable=true)
*/
private $discount;
/**
* @var string
*
* @ORM\Column(name="finalPrice", type="decimal", precision=10, scale=5, nullable=true)
*/
private $finalPrice;
/**
*
*@ORM\OneToMany(targetEntity="AppBundle\Entity\GroupSt", mappedBy="courses", cascade={"persist"})
*/
/**
* @var \Doctrine\Common\Collections\Collection|GroupSt
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\GroupSt", mappedBy="courses")
*/
private $groups;
/**
* @var string
* @ORM\Column(name="observations", type="string", length=255, nullable=true)
*/
private $observations;
/**
* Constructor
*/
public function __construct()
{
$this->groups = new \Doctrine\Common\Collections\ArrayCollection();
}
public function __toString()
{
return (string)
' ' . $this->name .
' ' . $this->type .
' ' . $this->academicYear;
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*
* @return Course
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set academicYear
*
* @param string $academicYear
*
* @return Course
*/
public function setAcademicYear($academicYear)
{
$this->academicYear = $academicYear;
return $this;
}
/**
* Get academicYear
*
* @return string
*/
public function getAcademicYear()
{
return $this->academicYear;
}
/**
* Set color
*
* @param string $color
*
* @return Course
*/
public function setColor($color)
{
$this->color = $color;
return $this;
}
/**
* Get color
*
* @return string
*/
public function getColor()
{
return $this->color;
}
/**
* Set type
*
* @param string $type
*
* @return Course
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Set category
*
* @param string $category
*
* @return Course
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* @return string
*/
public function getCategory()
{
return $this->category;
}
/**
* Set periodicPrice
*
* @param string $periodicPrice
*
* @return Course
*/
public function setPeriodicPrice($periodicPrice)
{
$this->periodicPrice = $periodicPrice;
return $this;
}
/**
* Get periodicPrice
*
* @return string
*/
public function getPeriodicPrice()
{
return $this->periodicPrice;
}
/**
* Set priceHour
*
* @param string $priceHour
*
* @return Course
*/
public function setPriceHour($priceHour)
{
$this->priceHour = $priceHour;
return $this;
}
/**
* Get priceHour
*
* @return string
*/
public function getPriceHour()
{
return $this->priceHour;
}
/**
* Set discount
*
* @param integer $discount
*
* @return Course
*/
public function setDiscount($discount)
{
$this->discount = $discount;
return $this;
}
/**
* Get discount
*
* @return int
*/
public function getDiscount()
{
return $this->discount;
}
/**
* Set finalPrice
*
* @param string $finalPrice
*
* @return Course
*/
public function setFinalPrice($finalPrice)
{
$this->finalPrice = $finalPrice;
return $this;
}
/**
* Get finalPrice
*
* @return string
*/
public function getFinalPrice()
{
return $this->finalPrice;
}
/**
* Add group
*
* @param \AppBundle\Entity\GroupSt $group
*
* @return Course
*/
public function addGroup(\AppBundle\Entity\GroupSt $group)
{
$this->groups[] = $group;
return $this;
}
/**
* Remove group
*
* @param \AppBundle\Entity\GroupSt $group
*/
public function removeGroup(\AppBundle\Entity\GroupSt $group)
{
$this->groups->removeElement($group);
}
/**
* Get groups
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getGroups()
{
return $this->groups;
}
/**
* Set observations
*
* @param string $observations
*
* @return Course
*/
public function setObservations($observations)
{
$this->observations = $observations;
return $this;
}
/**
* Get observations
*
* @return string
*/
public function getObservations()
{
return $this->observations;
}
}
<file_sep>/src/AppBundle/Entity/Expense.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Expense
*
* @ORM\Table(name="expense")
* @ORM\Entity(repositoryClass="AppBundle\Repository\ExpenseRepository")
*/
class Expense
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var decimal
*
* @ORM\Column(name="import", type="decimal", precision=10, scale=2, nullable=true)
*/
private $import;
/**
* @var string
*
* @ORM\Column(name="type", type="string", length=255, nullable=true)
*/
private $type;
/**
* LOG ****************************************
*/
/**
* @var \DateTime $created
*
* @ORM\Column(name="data_created", type="datetime")
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime")
*/
private $dataCreated;
/**
* @var \DateTime $updated
*
* @ORM\Column(name="data_updated", type="datetime")
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime")
*/
private $dataUpdated;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set tipo
*
* @param string $type
*
* @return Expense
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get tipo
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Set fecha
*
* @param string $fecha
*
* @return Expense
*/
public function setFecha($fecha)
{
$this->fecha = $fecha;
return $this;
}
/**
* Get fecha
*
* @return string
*/
public function getFecha()
{
return $this->fecha;
}
/**
* Set dataCreated
*
* @param \DateTime $dataCreated
*
* @return Expense
*/
public function setDataCreated($dataCreated)
{
$this->dataCreated = $dataCreated;
return $this;
}
/**
* Get dataCreated
*
* @return \DateTime
*/
public function getDataCreated()
{
return $this->dataCreated;
}
/**
* Set dataUpdated
*
* @param \DateTime $dataUpdated
*
* @return Expense
*/
public function setDataUpdated($dataUpdated)
{
$this->dataUpdated = $dataUpdated;
return $this;
}
/**
* Get dataUpdated
*
* @return \DateTime
*/
public function getDataUpdated()
{
return $this->dataUpdated;
}
/**
* @return decimal
*/
public function getImport()
{
return $this->import;
}
/**
* @param decimal $import
*/
public function setImport($import)
{
$this->import = $import;
}
}
<file_sep>/src/AppBundle/Entity/TimeTable.php
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* TimeTable
*
* @ORM\Table(name="time_table")
* @ORM\Entity(repositoryClass="AppBundle\Repository\TimeTableRepository")
*/
class TimeTable
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="days", type="string", length=255, nullable=false)
*/
private $days;
/**
* @var string
*
* @ORM\Column(name="Hours", type="string", length=255, nullable=false)
*/
private $hours;
/**
* @var string
* @ORM\Column(name="observations", type="string", length=255, nullable=true)
*/
private $observations;
/**
* @var \Doctrine\Common\Collections\Collection|GroupSt
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\GroupSt", mappedBy="timeTables")
*/
private $groups;
/**
* TimeTable constructor.
*/
public function __construct()
{
$this->groups = new ArrayCollection();
}
public function __toString()
{
return (string) $this->days .
' ' . $this->hours;
}
/**
* LOG ****************************************
*/
/**
* @var \DateTime $created
*
* @ORM\Column(name="data_created", type="datetime")
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime")
*/
private $dataCreated;
/**
* @var \DateTime $updated
*
* @ORM\Column(name="data_updated", type="datetime")
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime")
*/
private $dataUpdated;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set days
*
* @param string $days
*
* @return TimeTable
*/
public function setDays($days)
{
$this->days = $days;
return $this;
}
/**
* Get days
*
* @return string
*/
public function getDays()
{
return $this->days;
}
/**
* Set hours
*
* @param string $hours
*
* @return TimeTable
*/
public function setHours($hours)
{
$this->hours = $hours;
return $this;
}
/**
* Get hours
*
* @return string
*/
public function getHours()
{
return $this->hours;
}
/**
* Set dataCreated
*
* @param \DateTime $dataCreated
*
* @return TimeTable
*/
public function setDataCreated($dataCreated)
{
$this->dataCreated = $dataCreated;
return $this;
}
/**
* Get dataCreated
*
* @return \DateTime
*/
public function getDataCreated()
{
return $this->dataCreated;
}
/**
* Set dataUpdated
*
* @param \DateTime $dataUpdated
*
* @return TimeTable
*/
public function setDataUpdated($dataUpdated)
{
$this->dataUpdated = $dataUpdated;
return $this;
}
/**
* Get dataUpdated
*
* @return \DateTime
*/
public function getDataUpdated()
{
return $this->dataUpdated;
}
/**
* Add group
*
* @param \AppBundle\Entity\GroupSt $group
*
* @return TimeTable
*/
public function addGroup(\AppBundle\Entity\GroupSt $group)
{
$this->groups[] = $group;
return $this;
}
/**
* Remove group
*
* @param \AppBundle\Entity\GroupSt $group
*/
public function removeGroup(\AppBundle\Entity\GroupSt $group)
{
$this->groups->removeElement($group);
}
/**
* Get groups
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getGroups()
{
return $this->groups;
}
/**
* Set observations
*
* @param string $observations
*
* @return TimeTable
*/
public function setObservations($observations)
{
$this->observations = $observations;
return $this;
}
/**
* Get observations
*
* @return string
*/
public function getObservations()
{
return $this->observations;
}
}
<file_sep>/src/AppBundle/Entity/ClientOauth.php
<?php
/**
* Created by PhpStorm.
* User: ruben
* Date: 27/6/18
* Time: 21:59
*/
namespace AppBundle\Entity;
use FOS\OAuthServerBundle\Entity\Client as BaseClient;
use Doctrine\ORM\Mapping as ORM;
class ClientOauth extends BaseClient
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
// your own logic
}
}
<file_sep>/src/AppBundle/Entity/Invoice.php~
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Invoice
*
* @ORM\Table(name="invoice")
* @ORM\Entity(repositoryClass="AppBundle\Repository\InvoiceRepository")
*/
class Invoice
{
const DRAFT = 'DRAFT';
const PENDING_OF_PAID = 'PENDING';
const PAID = 'PAID';
const CANCELLED = 'CANCELLED';
/**
* @var int
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="status", type="string", length=255, nullable=true)
*/
private $status;
/**
* @var string
*
* @ORM\Column(name="discount", type="string", length=255, nullable=true)
*/
private $discount;
/**
*
*@ORM\ManyToOne(targetEntity="AppBundle\Entity\Client", inversedBy="invoices", cascade={"persist"})
*/
private $client;
/**
* @var string
*
* @ORM\Column(name="total", type="decimal", precision=10, scale=2, nullable=true)
*/
private $total;
/**
* @var \DateTime $created
*
* @ORM\Column(name="data_created", type="datetime")
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime")
*/
private $dataCreated;
/**
* @var \DateTime $updated
*
* @ORM\Column(name="data_updated", type="datetime")
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime")
*/
private $dataUpdated;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set status
*
* @param string $status
*
* @return Invoice
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* Set total
*
* @param string $total
*
* @return Invoice
*/
public function setTotal($total)
{
$this->total = $total;
return $this;
}
/**
* Get total
*
* @return string
*/
public function getTotal()
{
return $this->total;
}
/**
* Set client
*
* @param \AppBundle\Entity\Client $client
*
* @return Invoice
*/
public function setClient(\AppBundle\Entity\Client $client = null)
{
$this->client = $client;
return $this;
}
/**
* Get client
*
* @return \AppBundle\Entity\Client
*/
public function getClient()
{
return $this->client;
}
/**
* Set dataCreated
*
* @param \DateTime $dataCreated
*
* @return Invoice
*/
public function setDataCreated($dataCreated)
{
$this->dataCreated = $dataCreated;
return $this;
}
/**
* Get dataCreated
*
* @return \DateTime
*/
public function getDataCreated()
{
return $this->dataCreated;
}
/**
* Set dataUpdated
*
* @param \DateTime $dataUpdated
*
* @return Invoice
*/
public function setDataUpdated($dataUpdated)
{
$this->dataUpdated = $dataUpdated;
return $this;
}
/**
* Get dataUpdated
*
* @return \DateTime
*/
public function getDataUpdated()
{
return $this->dataUpdated;
}
/**
* Set discount
*
* @param string $discount
*
* @return Invoice
*/
public function setDiscount($discount)
{
$this->discount = $discount;
return $this;
}
/**
* Get discount
*
* @return string
*/
public function getDiscount()
{
return $this->discount;
}
}
<file_sep>/src/AppBundle/Exception/EmailNotFoundException.php
<?php
namespace AppBundle\Exception;
class EmailNotFoundException extends \Exception implements MessageUnderscoredExceptionInterface
{
/**
* @var string
*/
private $email;
/**
* @var array
*/
private $parameters;
/**
* @var string
*/
private $messageTemplate = 'El email %s no existe en la base de datos';
/**
* EmailNotFoundException constructor.
* @param string $email
*/
public function __construct($email)
{
$this->parameters = [
$email
];
parent::__construct(sprintf($this->messageTemplate, $email));
$this->email = $email;
}
public function getOriginalMessage()
{
return sprintf($this->messageTemplate, $this->email);
}
public function getErrorCode()
{
return 'E106';
}
public function getErrorParameters()
{
return $this->parameters;
}
}<file_sep>/src/AppBundle/Entity/GroupSt.php
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* GroupSt
*
* @ORM\Table(name="group_st")
* @ORM\Entity(repositoryClass="AppBundle\Repository\GroupStRepository")
*/
class GroupSt
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255, nullable=false, unique=true)
*/
private $name;
/**
* @var string
* @ORM\Column(name="observations", type="string", length=255, nullable=true)
*/
private $observations;
/**
* @var \Doctrine\Common\Collections\Collection|TimeTable[]
*
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\TimeTable", inversedBy="groups")
* @ORM\JoinTable(
* name="groups_timetables",
* joinColumns={
* @ORM\JoinColumn(name="timetable_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="group_id", referencedColumnName="id")
* }
* )
*/
private $timeTables;
/**
* @var \Doctrine\Common\Collections\Collection|Client[]
*
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\Client", inversedBy="groups")
* @ORM\JoinTable(
* name="groups_clients",
* joinColumns={
* @ORM\JoinColumn(name="client_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="group_id", referencedColumnName="id")
* }
* )
*/
private $clients;
/**
* @var \Doctrine\Common\Collections\Collection|Employee[]
*
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\Employee", inversedBy="groups")
* @ORM\JoinTable(
* name="groups_employees",
* joinColumns={
* @ORM\JoinColumn(name="employee_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="group_id", referencedColumnName="id")
* }
* )
*/
private $employees;
/**
* @var \Doctrine\Common\Collections\Collection|Course[]
*
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\Course", inversedBy="groups")
* @ORM\JoinTable(
* name="groups_courses",
* joinColumns={
* @ORM\JoinColumn(name="course_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="group_id", referencedColumnName="id")
* }
* )
*/
private $courses;
/**
* @var \Doctrine\Common\Collections\Collection|Classroom[]
*
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\Classroom", inversedBy="groups")
* @ORM\JoinTable(
* name="groups_classrooms",
* joinColumns={
* @ORM\JoinColumn(name="course_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="classrom_id", referencedColumnName="id")
* }
* )
*/
private $classrooms;
public function __construct()
{
$this->clients = new ArrayCollection();
$this->employees = new ArrayCollection();
$this->courses = new ArrayCollection();
$this->timeTables = new ArrayCollection();
$this->classrooms = new ArrayCollection();
}
public function __toString()
{
return (string) $this->name ;
}
/**
* LOG ****************************************
*/
/**
* @var \DateTime $created
*
* @ORM\Column(name="data_created", type="datetime")
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime")
*/
private $dataCreated;
/**
* @var \DateTime $updated
*
* @ORM\Column(name="data_updated", type="datetime")
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime")
*/
private $dataUpdated;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*
* @return GroupSt
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set surname
*
* @param string $surname
*
* @return GroupSt
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* @return string
*/
public function getSurname()
{
return $this->surname;
}
/**
* Set phone
*
* @param string $phone
*
* @return GroupSt
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* @return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set email
*
* @param string $email
*
* @return GroupSt
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set address
*
* @param string $address
*
* @return GroupSt
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set dataCreated
*
* @param \DateTime $dataCreated
*
* @return GroupSt
*/
public function setDataCreated($dataCreated)
{
$this->dataCreated = $dataCreated;
return $this;
}
/**
* Get dataCreated
*
* @return \DateTime
*/
public function getDataCreated()
{
return $this->dataCreated;
}
/**
* Set dataUpdated
*
* @param \DateTime $dataUpdated
*
* @return GroupSt
*/
public function setDataUpdated($dataUpdated)
{
$this->dataUpdated = $dataUpdated;
return $this;
}
/**
* Get dataUpdated
*
* @return \DateTime
*/
public function getDataUpdated()
{
return $this->dataUpdated;
}
/**
* Add attendance
*
* @param \AppBundle\Entity\Attendance $attendance
*
* @return GroupSt
*/
public function addAttendance(\AppBundle\Entity\Attendance $attendance)
{
$this->attendance[] = $attendance;
return $this;
}
/**
* Remove attendance
*
* @param \AppBundle\Entity\Attendance $attendance
*/
public function removeAttendance(\AppBundle\Entity\Attendance $attendance)
{
$this->attendance->removeElement($attendance);
}
/**
* Get attendance
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getAttendance()
{
return $this->attendance;
}
/**
* Add course
*
* @param \AppBundle\Entity\Course $course
*
* @return GroupSt
*/
public function addCourse(\AppBundle\Entity\Course $course)
{
$this->courses[] = $course;
return $this;
}
/**
* Remove course
*
* @param \AppBundle\Entity\Course $course
*/
public function removeCourse(\AppBundle\Entity\Course $course)
{
$this->courses->removeElement($course);
}
/**
* Get courses
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getCourses()
{
return $this->courses;
}
/**
* Set observations
*
* @param string $observations
*
* @return GroupSt
*/
public function setObservations($observations)
{
$this->observations = $observations;
return $this;
}
/**
* Get observations
*
* @return string
*/
public function getObservations()
{
return $this->observations;
}
/**
* Add timeTable
*
* @param \AppBundle\Entity\TimeTable $timeTable
*
* @return GroupSt
*/
public function addTimeTable(\AppBundle\Entity\TimeTable $timeTable)
{
$this->timeTables[] = $timeTable;
return $this;
}
/**
* Remove timeTable
*
* @param \AppBundle\Entity\TimeTable $timeTable
*/
public function removeTimeTable(\AppBundle\Entity\TimeTable $timeTable)
{
$this->timeTables->removeElement($timeTable);
}
/**
* Get timeTables
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getTimeTables()
{
return $this->timeTables;
}
/**
* Add client
*
* @param \AppBundle\Entity\Client $client
*
* @return GroupSt
*/
public function addClient(\AppBundle\Entity\Client $client)
{
$this->clients[] = $client;
return $this;
}
/**
* Remove client
*
* @param \AppBundle\Entity\Client $client
*/
public function removeClient(\AppBundle\Entity\Client $client)
{
$this->clients->removeElement($client);
}
/**
* Get clients
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getClients()
{
return $this->clients;
}
/**
* Add employee
*
* @param \AppBundle\Entity\Employee $employee
*
* @return GroupSt
*/
public function addEmployee(\AppBundle\Entity\Employee $employee)
{
$this->employees[] = $employee;
return $this;
}
/**
* Remove employee
*
* @param \AppBundle\Entity\Employee $employee
*/
public function removeEmployee(\AppBundle\Entity\Employee $employee)
{
$this->employees->removeElement($employee);
}
/**
* Get employees
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getEmployees()
{
return $this->employees;
}
/**
* Add classroom
*
* @param \AppBundle\Entity\Classroom $classroom
*
* @return GroupSt
*/
public function addClassroom(\AppBundle\Entity\Classroom $classroom)
{
$this->classrooms[] = $classroom;
return $this;
}
/**
* Remove classroom
*
* @param \AppBundle\Entity\Classroom $classroom
*/
public function removeClassroom(\AppBundle\Entity\Classroom $classroom)
{
$this->classrooms->removeElement($classroom);
}
/**
* Get classrooms
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getClassrooms()
{
return $this->classrooms;
}
}
<file_sep>/src/AppBundle/Handlers/CommandHandler/SendMailHandler.php
<?php
namespace AppBundle\Handlers\CommandHandler;
use AppBundle\Event\EmailSent;
use AppBundle\Handlers\Command\SendMailCommand;
use SimpleBus\Message\Recorder\RecordsMessages;
use Symfony\Component\Translation\Translator;
class SendMailHandler
{
/**
* @var \Swift_Mailer
*/
private $mailer;
/**
* @var string
*/
private $companyName;
/**
* @var string
*/
private $companyEmail;
/**
* @var Translator
*/
private $translator;
/**
* @var RecordsMessages
*/
private $eventRecorder;
/**
* SendEmailHandler constructor.
* @param \Swift_Mailer $mailer
* @param Translator $translator
* @param $companyName
* @param $companyEmail
* @param RecordsMessages $eventRecorder
*/
public function __construct(
\Swift_Mailer $mailer,
Translator $translator,
$companyName,
$companyEmail,
RecordsMessages $eventRecorder
) {
$this->mailer = $mailer;
$this->translator = $translator;
$this->companyName = $companyName;
$this->companyEmail = $companyEmail;
$this->eventRecorder = $eventRecorder;
}
public function handle(SendMailCommand $command)
{
$message = (new \Swift_Message($this->translator->trans($command->getSubject())))
->setFrom($this->companyEmail, $this->companyName)
->setTo($command->getTo(), $command->getToName())
->setBody($command->getBody(), 'text/html');
$result = $this->mailer->send($message);
$this->eventRecorder->record(new EmailSent($result));
}
}<file_sep>/src/AppBundle/Repository/ExpenseRepository.php
<?php
namespace AppBundle\Repository;
use AppBundle\Entity\Expense;
/**
* ExpenseRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ExpenseRepository extends \Doctrine\ORM\EntityRepository
{
/**
* @return mixed
* INVOICES PAID + INCOMES
*/
public function expenseWithDates($startDate, $endDate){
$repository = $this->_em->getRepository(Expense::class);
$query = $repository->createQueryBuilder('e')
->select('sum(e.import)')
->andwhere('e.dataCreated >= :startDate')
->andwhere('e.dataCreated <= :endDate')
->setParameter('startDate', $startDate)
->setParameter('endDate', $endDate)
->getQuery();
$resultScalarInvoices = $query->getScalarResult();
return $resultScalarInvoices[0][1];
}
}
<file_sep>/src/AppBundle/Entity/AbstractRepository.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\EntityRepository;
abstract class AbstractRepository extends EntityRepository
{
protected function persist($entity, $commit = RepositoryInterface::COMMIT_CHANGES)
{
$this->_em->persist($entity);
if ($commit) {
$this->commit();
}
}
public function commit()
{
$this->_em->flush();
}
protected function removeCacheResult($resultCacheId)
{
$resultCache = $this->_em->getConfiguration()->getResultCacheImpl();
$resultCache->delete($resultCacheId);
}
}
<file_sep>/src/AppBundle/Handlers/Command/SendResetPasswordCommand.php
<?php
namespace AppBundle\Handlers\Command;
class SendResetPasswordCommand
{
/**
* @var string
*/
private $email;
/**
* @var string
*/
private $url;
/**
* SendResetPassword constructor.
* @param $email
* @param $url
*/
public function __construct($email, $url)
{
$this->email = $email;
$this->url = $url;
}
/**
* @return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* @return string
*/
public function getUrl()
{
return $this->url;
}
}<file_sep>/src/AppBundle/Controller/EasyAdmin/AdminController.php
<?php
namespace AppBundle\Controller\EasyAdmin;
use AppBundle\Services\HomeQueryManager;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AdminController as BaseController;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class AdminController extends BaseController
{
/**
* @Route("/", name="easyadmin")
*/
public function indexAction(Request $request)
{
return parent::indexAction($request);
}
/**
* @Route("/init_home", name="init_home")
*/
public function InitHomeAction(HomeQueryManager $service, Request $request)
{
$startDate=""; $endDate="";
//FORM
$defaultData = array('message' => 'Type your message here');
$form = $this->createFormBuilder($defaultData)
->add('startDate', DateType::class, array(
'data' => new \DateTime('now')
))
->add('endDate', DateType::class, array(
'data' => new \DateTime('now')
))
->add('show data', SubmitType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// data is an array with "name", "email", and "message" keys
$data = $form->getData();
$startDate = $data['startDate'];
$endDate = $data['endDate'];
}
//FORM
$totalClients = $service->getTotalActiveClients();
$totalGroups = $service->getTotalGroups();
$totalEmployees = $service->getTotalEmployees();
$totalCourses = $service->getTotalCourses();
$incomeRecivedWithDate = $service->getIncomesWithDate($startDate, $endDate);
$expensesWithDate = $service->getExpensesWithDate($startDate, $endDate);
$pendingInvoicesWithDate = $service->getPedingInvoicesWithDate($startDate, $endDate);
$paidInvoicesWithDate = $service->getPaidInvoicesWithDates($startDate, $endDate);
return $this->render(
'@App/easyadmin/menu_home.html.twig',
[
'pendingInvoices' => $pendingInvoicesWithDate,
'incomeRecived' => $incomeRecivedWithDate,
'expensesWithDate' => $expensesWithDate,
'paidInvoices' => $paidInvoicesWithDate,
'totalClients' => $totalClients,
'totalEmployees' => $totalEmployees,
'totalGroups' => $totalGroups,
'totalCourses' => $totalCourses,
'form' => $form->createView(),
]
);
}
/**
* @Route("/redirectInvoicesFilterStatus", name="invoices_filter_status")
*/
public function redirectInvoicesWithStatusFilter(Request $request)
{
return $this->redirectToRoute('easyadmin', array('entity' => 'Invoice', 'action' => 'list', 'dql_filter' => 'entity.status=1'));
}
/**
* @Route("/dashboard", name="dashboard")
*/
public function dashboardAction()
{
return $this->render(
'@App/easyadmin/menu_dashboard.html.twig'
);
}
}
<file_sep>/src/AppBundle/Entity/Employee.php
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Employee
*
* @ORM\Table(name="employee")
* @ORM\Entity(repositoryClass="AppBundle\Repository\EmployeeRepository")
*/
class Employee
{
/**
* @var int
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* ••••••••••••••••••••••••••••••••••[ PERSONAL DATA INIT ]••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* @var string
* @ORM\Column(name="Name", type="string", length=255, nullable=false)
*/
private $name;
/**
* @var string
* @ORM\Column(name="surname", type="string", length=255, nullable=false)
*/
private $surname;
/**
* @var string
* @ORM\Column(name="identification_document", type="string", length=255, nullable=false)
*/
private $identificationDocument;
/**
* @var string
* @ORM\Column(name="identification_number", type="string", length=255, nullable=false)
*/
private $identificationNumber;
/**
* @var string
* @ORM\Column(name="email", type="string", length=255, nullable=false)
*/
private $email;
/**
* @var string
* @ORM\Column(name="address", type="string", length=255, nullable=true)
*/
private $address;
/**
* @var string
* @ORM\Column(name="country", type="string", length=255, nullable=true)
*/
private $country;
/**
* @var integer
* @ORM\Column(name="postal_code", type="string", length=255, nullable=true)
*/
private $postalCode;
/**
* @var string
* @ORM\Column(name="province", type="string", length=255, nullable=true)
*/
private $province;
/**
* @var string
* @ORM\Column(name="location", type="string", length=255, nullable=true)
*/
private $location;
/**
* @var string
* @ORM\Column(name="phone", type="string", length=255, nullable=true)
*/
private $phone;
/**
* @var string
* @ORM\Column(name="phone2", type="string", length=255, nullable=true)
*/
private $phone2;
/**
* @var \DateTime
* @ORM\Column(name="birth_date", type="date", length=255, nullable=true)
*/
private $birthDate;
/**
* @var string
* @ORM\Column(name="nationality", type="string", length=255, nullable=true)
*/
private $nationality;
/**
* ••••••••••••••••••••••••••••••••••[ PERSONAL DATA END ]••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* ••••••••••••••••••••••••••••••••••[ ECONOMIC DATA INIT ] ••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* @var decimal
* @ORM\Column(name="amount_per_hour", type="decimal", precision=10, scale=5, nullable=true)
*/
private $amountPerHour;
/**
* @var decimal
* @ORM\Column(name="fixed_month_amount", type="decimal", precision=10, scale=5, nullable=true)
*/
private $fixedMonthAmount;
/**
* @var decimal
* @ORM\Column(name="percentage_for_debts_or_charges", type="decimal", precision=10, scale=5, nullable=true)
*/
private $percentageForDebtsOrCharges;
/**
* @var string
* @ORM\Column(name="bank_entity", type="string", length=255, nullable=true)
*/
private $bankEntity;
/**
* @var string
* @ORM\Column(name="bank_account_number", type="string", length=255, nullable=true)
*/
private $bankAccountNumber;
/**
* @var string
* @ORM\Column(name="iban", type="string", length=255, nullable=true)
*/
private $iban;
/**
* @var string
* @ORM\Column(name="swift_bic", type="string", length=255, nullable=true)
*/
private $swiftBic;
/**
* ••••••••••••••••••••••••••••••••••[ ECONOMIC DATA END ] ••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* ••••••••••••••••••••••••••••••••••[ WORK DATA INIT ] ••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* @var string
* @ORM\Column(name="curriculum", type="string", length=255, nullable=true)
*/
private $curriculum;
/**
* @var string
* @ORM\Column(name="number_social_security", type="string", length=255, nullable=true)
*/
private $numberSocialSecurity;
/**
* @var string
* @ORM\Column(name="type_contract", type="string", length=255, nullable=true)
*/
private $typeContract;
/**
* @var string
* @ORM\Column(name="seniority_in_company", type="string", length=255, nullable=true)
*/
private $seniorityInCompany;
/**
* @var string
* @ORM\Column(name="contract_hours", type="string", length=255, nullable=true)
*/
private $contractHours;
/**
* @var boolean
* @ORM\Column(name="time_off_temporary", type="boolean", length=255, nullable=true)
*/
private $timeOffTemporary;
/**
* @var boolean
* @ORM\Column(name="time_off_definitive", type="boolean", length=255, nullable=true)
*/
private $timeOffDefinitive;
/**
* ••••••••••••••••••••••••••••••••••[ WORK DATA END ] ••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
* ••••••••••••••••••••••••••••••••••[ EXTRA INFO END ] ••••••••••••••••••••••••••••••••••••••••••••••••
*/
/**
*
*@ORM\OneToMany(targetEntity="AppBundle\Entity\EmployeeType", mappedBy="employee", cascade={"persist"})
* @ORM\JoinColumn(name="type_id", referencedColumnName="id", nullable=true)
*/
private $type;
/**
* @var \Doctrine\Common\Collections\Collection|GroupSt
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\GroupSt", mappedBy="employees")
*/
private $groups;
/**
* @var string
* @ORM\Column(name="observations", type="string", length=255, nullable=true)
*/
private $observations;
/**
* @var string
* @ORM\Column(name="active", type="boolean", nullable=false)
*/
private $active;
/**
* ••••••••••••••••••••••••••••••••••[ EXTRA INFO END ] ••••••••••••••••••••••••••••••••••••••••••••••••
*/
public function __toString()
{
return (string) $this->name .
' ' . $this->surname.
' ' . $this->email.
' ' . $this->identificationNumber;
}
public function __construct()
{
$this->attendance = new ArrayCollection();
$this->type = new ArrayCollection();
$this->groups = new ArrayCollection();
}
/**
* LOG ****************************************
*/
/**
* @var \DateTime $created
*
* @ORM\Column(name="data_created", type="datetime")
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime")
*/
private $dataCreated;
/**
* @var \DateTime $updated
*
* @ORM\Column(name="data_updated", type="datetime")
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime")
*/
private $dataUpdated;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*
* @return Employee
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set surname
*
* @param string $surname
*
* @return Employee
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* @return string
*/
public function getSurname()
{
return $this->surname;
}
/**
* Set phone
*
* @param string $phone
*
* @return Employee
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* @return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set email
*
* @param string $email
*
* @return Employee
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set dataCreated
*
* @param \DateTime $dataCreated
*
* @return Employee
*/
public function setDataCreated($dataCreated)
{
$this->dataCreated = $dataCreated;
return $this;
}
/**
* Get dataCreated
*
* @return \DateTime
*/
public function getDataCreated()
{
return $this->dataCreated;
}
/**
* Set dataUpdated
*
* @param \DateTime $dataUpdated
*
* @return Employee
*/
public function setDataUpdated($dataUpdated)
{
$this->dataUpdated = $dataUpdated;
return $this;
}
/**
* Get dataUpdated
*
* @return \DateTime
*/
public function getDataUpdated()
{
return $this->dataUpdated;
}
/**
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* @param string $address
*/
public function setAddress($address)
{
$this->address = $address;
}
/**
* @return decimal
*/
public function getAmountPerHour()
{
return $this->amountPerHour;
}
/**
* @param decimal $amountPerHour
*/
public function setAmountPerHour($amountPerHour)
{
$this->amountPerHour = $amountPerHour;
}
/**
* Set identificationDocument
*
* @param string $identificationDocument
*
* @return Employee
*/
public function setIdentificationDocument($identificationDocument)
{
$this->identificationDocument = $identificationDocument;
return $this;
}
/**
* Get identificationDocument
*
* @return string
*/
public function getIdentificationDocument()
{
return $this->identificationDocument;
}
/**
* Set identificationNumber
*
* @param string $identificationNumber
*
* @return Employee
*/
public function setIdentificationNumber($identificationNumber)
{
$this->identificationNumber = $identificationNumber;
return $this;
}
/**
* Get identificationNumber
*
* @return string
*/
public function getIdentificationNumber()
{
return $this->identificationNumber;
}
/**
* Set country
*
* @param string $country
*
* @return Employee
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* @return string
*/
public function getCountry()
{
return $this->country;
}
/**
* Set postalCode
*
* @param string $postalCode
*
* @return Employee
*/
public function setPostalCode($postalCode)
{
$this->postalCode = $postalCode;
return $this;
}
/**
* Get postalCode
*
* @return string
*/
public function getPostalCode()
{
return $this->postalCode;
}
/**
* Set province
*
* @param string $province
*
* @return Employee
*/
public function setProvince($province)
{
$this->province = $province;
return $this;
}
/**
* Get province
*
* @return string
*/
public function getProvince()
{
return $this->province;
}
/**
* Set location
*
* @param string $location
*
* @return Employee
*/
public function setLocation($location)
{
$this->location = $location;
return $this;
}
/**
* Get location
*
* @return string
*/
public function getLocation()
{
return $this->location;
}
/**
* Set phone2
*
* @param string $phone2
*
* @return Employee
*/
public function setPhone2($phone2)
{
$this->phone2 = $phone2;
return $this;
}
/**
* Get phone2
*
* @return string
*/
public function getPhone2()
{
return $this->phone2;
}
/**
* Set birthDate
*
* @param \DateTime $birthDate
*
* @return Employee
*/
public function setBirthDate($birthDate)
{
$this->birthDate = $birthDate;
return $this;
}
/**
* Get birthDate
*
* @return \DateTime
*/
public function getBirthDate()
{
return $this->birthDate;
}
/**
* Set nationality
*
* @param string $nationality
*
* @return Employee
*/
public function setNationality($nationality)
{
$this->nationality = $nationality;
return $this;
}
/**
* Get nationality
*
* @return string
*/
public function getNationality()
{
return $this->nationality;
}
/**
* Set fixedMonthAmount
*
* @param string $fixedMonthAmount
*
* @return Employee
*/
public function setFixedMonthAmount($fixedMonthAmount)
{
$this->fixedMonthAmount = $fixedMonthAmount;
return $this;
}
/**
* Get fixedMonthAmount
*
* @return string
*/
public function getFixedMonthAmount()
{
return $this->fixedMonthAmount;
}
/**
* Set percentageForDebtsOrCharges
*
* @param string $percentageForDebtsOrCharges
*
* @return Employee
*/
public function setPercentageForDebtsOrCharges($percentageForDebtsOrCharges)
{
$this->percentageForDebtsOrCharges = $percentageForDebtsOrCharges;
return $this;
}
/**
* Get percentageForDebtsOrCharges
*
* @return string
*/
public function getPercentageForDebtsOrCharges()
{
return $this->percentageForDebtsOrCharges;
}
/**
* Set bankEntity
*
* @param string $bankEntity
*
* @return Employee
*/
public function setBankEntity($bankEntity)
{
$this->bankEntity = $bankEntity;
return $this;
}
/**
* Get bankEntity
*
* @return string
*/
public function getBankEntity()
{
return $this->bankEntity;
}
/**
* Set bankAccountNumber
*
* @param string $bankAccountNumber
*
* @return Employee
*/
public function setBankAccountNumber($bankAccountNumber)
{
$this->bankAccountNumber = $bankAccountNumber;
return $this;
}
/**
* Get bankAccountNumber
*
* @return string
*/
public function getBankAccountNumber()
{
return $this->bankAccountNumber;
}
/**
* Set iban
*
* @param string $iban
*
* @return Employee
*/
public function setIban($iban)
{
$this->iban = $iban;
return $this;
}
/**
* Get iban
*
* @return string
*/
public function getIban()
{
return $this->iban;
}
/**
* Set swiftBic
*
* @param string $swiftBic
*
* @return Employee
*/
public function setSwiftBic($swiftBic)
{
$this->swiftBic = $swiftBic;
return $this;
}
/**
* Get swiftBic
*
* @return string
*/
public function getSwiftBic()
{
return $this->swiftBic;
}
/**
* Set curriculum
*
* @param string $curriculum
*
* @return Employee
*/
public function setCurriculum($curriculum)
{
$this->curriculum = $curriculum;
return $this;
}
/**
* Get curriculum
*
* @return string
*/
public function getCurriculum()
{
return $this->curriculum;
}
/**
* Set numberSocialSecurity
*
* @param string $numberSocialSecurity
*
* @return Employee
*/
public function setNumberSocialSecurity($numberSocialSecurity)
{
$this->numberSocialSecurity = $numberSocialSecurity;
return $this;
}
/**
* Get numberSocialSecurity
*
* @return string
*/
public function getNumberSocialSecurity()
{
return $this->numberSocialSecurity;
}
/**
* Set typeContract
*
* @param string $typeContract
*
* @return Employee
*/
public function setTypeContract($typeContract)
{
$this->typeContract = $typeContract;
return $this;
}
/**
* Get typeContract
*
* @return string
*/
public function getTypeContract()
{
return $this->typeContract;
}
/**
* Set seniorityInCompany
*
* @param string $seniorityInCompany
*
* @return Employee
*/
public function setSeniorityInCompany($seniorityInCompany)
{
$this->seniorityInCompany = $seniorityInCompany;
return $this;
}
/**
* Get seniorityInCompany
*
* @return string
*/
public function getSeniorityInCompany()
{
return $this->seniorityInCompany;
}
/**
* Set contractHours
*
* @param string $contractHours
*
* @return Employee
*/
public function setContractHours($contractHours)
{
$this->contractHours = $contractHours;
return $this;
}
/**
* Get contractHours
*
* @return string
*/
public function getContractHours()
{
return $this->contractHours;
}
/**
* Set timeOffTemporary
*
* @param boolean $timeOffTemporary
*
* @return Employee
*/
public function setTimeOffTemporary($timeOffTemporary)
{
$this->timeOffTemporary = $timeOffTemporary;
return $this;
}
/**
* Get timeOffTemporary
*
* @return boolean
*/
public function getTimeOffTemporary()
{
return $this->timeOffTemporary;
}
/**
* Set timeOffDefinitive
*
* @param boolean $timeOffDefinitive
*
* @return Employee
*/
public function setTimeOffDefinitive($timeOffDefinitive)
{
$this->timeOffDefinitive = $timeOffDefinitive;
return $this;
}
/**
* Get timeOffDefinitive
*
* @return boolean
*/
public function getTimeOffDefinitive()
{
return $this->timeOffDefinitive;
}
/**
* Add type
*
* @param \AppBundle\Entity\ClientType $type
*
* @return Employee
*/
public function addType(\AppBundle\Entity\ClientType $type)
{
$this->type[] = $type;
return $this;
}
/**
* Remove type
*
* @param \AppBundle\Entity\ClientType $type
*/
public function removeType(\AppBundle\Entity\ClientType $type)
{
$this->type->removeElement($type);
}
/**
* Get type
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getType()
{
return $this->type;
}
/**
* Set observations
*
* @param string $observations
*
* @return Employee
*/
public function setObservations($observations)
{
$this->observations = $observations;
return $this;
}
/**
* Get observations
*
* @return string
*/
public function getObservations()
{
return $this->observations;
}
/**
* Add group
*
* @param \AppBundle\Entity\GroupSt $group
*
* @return Employee
*/
public function addGroup(\AppBundle\Entity\GroupSt $group)
{
$this->groups[] = $group;
return $this;
}
/**
* Remove group
*
* @param \AppBundle\Entity\GroupSt $group
*/
public function removeGroup(\AppBundle\Entity\GroupSt $group)
{
$this->groups->removeElement($group);
}
/**
* Get groups
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getGroups()
{
return $this->groups;
}
/**
* @return string
*/
public function getActive()
{
return $this->active;
}
/**
* @param string $active
*/
public function setActive($active)
{
$this->active = $active;
}
}
| f16fa2a90024af3a54ffdf6a1540781cccd18c62 | [
"PHP"
] | 38 | PHP | rubenGit/mycloudacademy | 205f45664d24185a4c8641627ac3c1620090749a | 5f4b6bff2f34a5bd88cab621f32c9f0d53c5c7d1 |
refs/heads/master | <repo_name>petercla0119/tmb-data-processing<file_sep>/adversity_recoding_function.R
##recode data from testmybrain for social cognitive measures
#any "decline to answer" or "dunno" responses are recoded as missing
#"no" coded as 0
#"yes" coded as 1
#find variable names by doing colnames(adversity)
#variables need to all be entered here in the form: adversity$varname
#you can look at d by doing head(d) or head(adversity)
#head(d$maternaled) or head(adversity$maternaled) willl show first five lines
#d$maternaled[c(10:20)] or adversity$maternaled[c(10:20)]
# create function "d" and assign it "recode_adversity"
recode_adversity <- function (d) {
#demographic data recoded
# recognizes pattern of specified strings, replaces it with indicated numeric value, location of where substitution should be made
# in this case, anytime middle shows up, replace it with 2 within the d$education column
d$education <- gsub("middle",2, d$education)
d$education <- gsub("high",3,d$education)
d$education <- gsub("some_college",4,d$education)
d$education <- gsub("college",5,d$education)
d$education <- gsub("grad",6,d$education)
d$education <- gsub("none",NA,d$education)
d$education <- gsub("decline",NA,d$education)
# orginal dataframe being used had values as integers, to make value into number, coerce column into character then coerce character column into numbers and assign it
d$education <- as.numeric(as.character(d$education))
#adversity data recoded
d$maternaled <- gsub("lessthanHS",2,d$maternaled)
d$maternaled <- gsub("highschool",3,d$maternaled)
d$maternaled <- gsub("BA",4,d$maternaled)
d$maternaled <- gsub("MA",5,d$maternaled)
d$maternaled <- gsub("Prof",6,d$maternaled)
d$maternaled <- gsub("DR",6,d$maternaled)
d$maternaled <- gsub("dunno",NA,d$maternaled)
d$maternaled <- gsub("decline",NA,d$maternaled)
d$maternaled <- as.numeric(as.character(d$maternaled))
d$paternaled <- gsub("lessthanHS",2,d$paternaled)
d$paternaled <- gsub("highschool",3,d$paternaled)
d$paternaled <- gsub("BA",4,d$paternaled)
d$paternaled <- gsub("MA",5,d$paternaled)
d$paternaled <- gsub("Prof",6,d$paternaled)
d$paternaled <- gsub("DR",6,d$paternaled)
d$paternaled <- gsub("dunno",NA,d$paternaled)
d$paternaled <- gsub("decline",NA,d$paternaled)
d$paternaled <- as.numeric(as.character(d$paternaled))
#NEW VARIABLE
make_parental <- function(d) {
pared = c() #empty vector
for (i in 1:length(d$maternaled)) {
newed <- ifelse(is.na(d$maternaled[i]),d$paternaled[i],ifelse(is.na(d$paternaled[i]),d$maternaled[i],max(d$maternaled[i],d$paternaled[i])))
pared <- c(pared,newed)
}
return(pared)
}
# for rows within the maternaled column
# starting at the first row,
# if the maternaled row value is NA, recode it to the paternaled row value, if not,
#create pared by combining
d$parentaled <- make_parental(d)
d$relativeSES <- gsub("muchhigher",6,d$relativeSES)
d$relativeSES <- gsub("muchlower",2,d$relativeSES)
d$relativeSES <- gsub("higher",5,d$relativeSES)
d$relativeSES <- gsub("same",4,d$relativeSES)
d$relativeSES <- gsub("lower",3,d$relativeSES)
d$relativeSES <- gsub("decline",NA,d$relativeSES)
d$relativeSES <- gsub("dunno",NA,d$relativeSES)
d$relativeSES <- as.numeric(as.character(d$relativeSES))
# Parental Death ---------------------------------------------------------- #
d$parentdeath <- gsub("dunno",NA,d$parentdeath) # substitutes "NA" wherever "dunno" is
d$parentdeath <- gsub("decline",NA,d$parentdeath) # substitutes "NA" wherever "decline" is
d$parentdeath <- gsub("no",0,d$parentdeath) # substitutes "0" wherever "no" is
d$parentdeath <- gsub("yes",1,d$parentdeath) # substitutes "1" wherever "yes" is
d$parentdeath <- as.numeric(as.character(d$parentdeath)) #ensures value is recognized as integer
d$parentdeathAGE <- gsub("none",NA,d$parentdeathAGE)
d$parentdeathAGE <- gsub("dunno",NA,d$parentdeathAGE)
d$parentdeathAGE <- gsub("decline",NA,d$parentdeathAGE)
d$parentdeathAGE <- as.numeric(as.character(d$parentdeathAGE)) #ensures value is recognized as integer
# Divorce -----------------------------------------------------------------
d$parentdivorce <- gsub("dunno",NA,d$parentdivorce)
d$parentdivorce <- gsub("decline",NA,d$parentdivorce)
d$parentdivorce <- gsub("yes",1,d$parentdivorce)
d$parentdivorce <- gsub("no",0,d$parentdivorce)
d$parentdivorce <- as.numeric(as.character(d$parentdivorce))
d$parentdivorceAGE <- gsub("none",NA,d$parentdivorceAGE)
d$parentdivorceAGE <- gsub("dunno",NA,d$parentdivorceAGE)
d$parentdivorceAGE <- gsub("decline",NA,d$parentdivorceAGE)
d$parentdivorceAGE <- as.numeric(as.character(d$parentdivorceAGE))
# Foster/Institutionalization --------------------------------------------
d$foster <- gsub("dunno",NA,d$foster)
d$foster <- gsub("decline",NA,d$foster)
d$foster <- gsub("no",0,d$foster)
d$foster <- gsub("yes",1,d$foster)
d$foster <- as.numeric(as.character(d$foster))
d$fosterAGE <- gsub("none",NA,d$fosterAGE)
d$fosterAGE <- gsub("dunno",NA,d$fosterAGE)
d$fosterAGE <- gsub("decline",NA,d$fosterAGE)
d$fosterAGE <- as.numeric(as.character(d$fosterAGE))
d$fosterDUR <- gsub("none",NA,d$fosterDUR)
d$fosterDUR <- gsub("dunno",NA,d$fosterDUR)
d$fosterDUR <- gsub("decline",NA,d$fosterDUR)
d$fosterDUR <- gsub("0-1",0,d$fosterDUR)
d$fosterDUR <- as.numeric(as.character(d$fosterDUR))
d$institution <- gsub("dunno",NA,d$institution)
d$institution <- gsub("decline",NA,d$institution)
d$institution <- gsub("no",0,d$institution)
d$institution <- gsub("yes",1,d$institution)
d$institution <- as.numeric(as.character(d$institution))
d$institutionAGE <- gsub("none",NA,d$institutionAGE)
d$institutionAGE <- gsub("dunno",NA,d$institutionAGE)
d$institutionAGE <- gsub("decline", NA,d$institutionAGE)
d$institutionAGE <- as.numeric(as.character(d$institutionAGE))
d$institutionDUR <- gsub("none",NA,d$institutionDUR)
d$institutionDUR <- gsub("dunno",NA,d$institutionDUR)
d$institutionDUR <- gsub("decline",NA,d$institutionDUR)
d$institutionDUR <- gsub("0-1",0,d$institutionDUR)
d$institutionDUR <- as.numeric(as.character(d$institutionDUR))
# Alcohol/Drugs -----------------------------------------------------------
d$alcoholism <- gsub("dunno",NA,d$alcoholism)
d$alcoholism <- gsub("decline",NA,d$alcoholism)
d$alcoholism <- gsub("no",0,d$alcoholism)
d$alcoholism <- gsub("yes",1,d$alcoholism)
d$alcoholism <- as.numeric(as.character(d$alcoholism))
d$drugs <- gsub("dunno",NA,d$drugs)
d$drugs <- gsub("decline",NA,d$drugs)
d$drugs <- gsub("no",0,d$drugs)
d$drugs <- gsub("yes",1,d$drugs)
d$drugs <- as.numeric(as.character(d$drugs))
# Mental Illness/Suicide ----------------------------------------------------------
d$mentalillness <- gsub("dunno",NA,d$mentalillness)
d$mentalillness <- gsub("decline",NA,d$mentalillness)
d$mentalillness <- gsub("no",0,d$mentalillness)
d$mentalillness <- gsub("yes",1,d$mentalillness)
d$mentalillness <- as.numeric(as.character(d$mentalillness))
d$suicide <- gsub("dunno",NA,d$suicide)
d$suicide <- gsub("decline",NA,d$suicide)
d$suicide <- gsub("no",0,d$suicide)
d$suicide <- gsub("yes",1,d$suicide)
d$suicide <- as.numeric(as.character(d$suicide))
d$suicideAGE <- gsub("none",NA,d$suicideAGE)
d$suicideAGE <- gsub("dunno",NA,d$suicideAGE)
d$suicideAGE <- gsub("decline",NA,d$suicideAGE)
d$suicideAGE <- as.numeric(as.character(d$suicideAGE))
# Prison and Criminal Activity --------------------------------------------
d$prison <- gsub("dunno",NA,d$prison)
d$prison <- gsub("decline",NA,d$prison)
d$prison <- gsub("no",0,d$prison)
d$prison <- gsub("yes",1,d$prison)
d$prison <- as.numeric(as.character(d$prison))
d$prisonAGE <- gsub("none",NA,d$prisonAGE)
d$prisonAGE <- gsub("dunno",NA,d$prisonAGE)
d$prisonAGE <- gsub("decline",NA,d$prisonAGE)
d$prisonAGE <- as.numeric(as.character(d$prisonAGE))
d$criminal <- gsub("never",0,d$criminal)
d$criminal <- gsub("rarely",1,d$criminal)
d$criminal <- gsub("sometimes",2,d$criminal)
d$criminal <- gsub("often",3,d$criminal)
d$criminal <- gsub("dunno",NA,d$criminal)
d$criminal <- gsub("decline",NA,d$criminal)
d$criminal <- as.numeric(as.character(d$criminal))
#NEW VARIABLE
d$criminal.d <- ifelse(d$criminal > 1,1,0) #creates criminal.d var when frequency was rarely or more
# Welfare/Poverty/Hunger -----------------------------------------------------------------
d$welfare <- gsub("never",0,d$welfare)
d$welfare <- gsub("rarely",1,d$welfare)
d$welfare <- gsub("sometimes",2,d$welfare)
d$welfare <- gsub("often",3,d$welfare)
d$welfare <- gsub("dunno",NA,d$welfare)
d$welfare <- gsub("decline",NA,d$welfare)
d$welfare <- as.numeric(as.character(d$welfare))
#NEW VARIABLE
d$welfare.d <- ifelse(d$welfare > 1,1,0)
d$welfareDUR <- gsub("none",NA,d$welfareDUR)
d$welfareDUR <- gsub("dunno",NA,d$welfareDUR)
d$welfareDUR <- gsub("decline",NA,d$welfareDUR)
d$welfareDUR <- gsub("0-1",0,d$welfareDUR)
d$welfareDUR <- as.numeric(as.character(d$welfareDUR))
d$hunger_poverty <- gsub("never",0,d$hunger_poverty)
d$hunger_poverty <- gsub("rarely",1,d$hunger_poverty)
d$hunger_poverty <- gsub("sometimes",2,d$hunger_poverty)
d$hunger_poverty <- gsub("often",3,d$hunger_poverty)
d$hunger_poverty <- gsub("dunno",NA,d$hunger_poverty)
d$hunger_poverty <- gsub("decline",NA,d$hunger_poverty)
d$hunger_poverty <- as.numeric(as.character(d$hunger_poverty))
#NEW VARIABLE
d$hunger_poverty.d <- ifelse(d$hunger_poverty > 1,1,0)
# Verbal Abuse ------------------------------------------------------------
d$verbalabuse <- gsub("never",0,d$verbalabuse)
d$verbalabuse <- gsub("rarely",1,d$verbalabuse)
d$verbalabuse <- gsub("sometimes",2,d$verbalabuse)
d$verbalabuse <- gsub("often",3,d$verbalabuse)
d$verbalabuse <- gsub("dunno",NA,d$verbalabuse)
d$verbalabuse <- gsub("decline",NA,d$verbalabuse)
d$verbalabuse <- as.numeric(as.character(d$verbalabuse))
#NEW VARIABLE
d$verbalabuse.d <- ifelse(d$verbalabuse >= 1,1,0) #creates verbalabuse.d var. responses = 1 if adversity was experiences rarely (inclusive) or more often
# Verbal Abuse ------------------------------------------------------------
d$verbalAGE1 <- gsub("none",NA,d$verbalAGE1)
d$verbalAGE1 <- gsub("dunno",NA,d$verbalAGE1)
d$verbalAGE1 <- gsub("decline",NA,d$verbalAGE1)
d$verbalAGE1 <- as.numeric(as.character(d$verbalAGE1))
d$verbalAGE2 <- gsub("none",NA,d$verbalAGE2)
d$verbalAGE2 <- gsub("dunno",NA,d$verbalAGE2)
d$verbalAGE2 <- gsub("decline",NA,d$verbalAGE2)
d$verbalAGE2 <- as.numeric(as.character(d$verbalAGE2))
# Fear of Abuse -----------------------------------------------------------
d$fearabuse <- gsub("never",0,d$fearabuse)
d$fearabuse <- gsub("rarely",1,d$fearabuse)
d$fearabuse <- gsub("sometimes",2,d$fearabuse)
d$fearabuse <- gsub("often",3,d$fearabuse)
d$fearabuse <- gsub("dunno",NA,d$fearabuse)
d$fearabuse <- gsub("decline",NA,d$fearabuse)
d$fearabuse <- as.numeric(as.character(d$fearabuse))
#NEW VARIABLE
d$fearabuse.d <- ifelse(d$fearabuse >= 1,1,0)
d$fearabuseAGE1 <- gsub("none",NA,d$fearabuseAGE1)
d$fearabuseAGE1 <- gsub("dunno",NA,d$fearabuseAGE1)
d$fearabuseAGE1 <- gsub("decline",NA,d$fearabuseAGE1)
d$fearabuseAGE1 <- as.numeric(as.character(d$fearabuseAGE1))
d$fearabuseAGE2 <- gsub("none",NA,d$fearabuseAGE2)
d$fearabuseAGE2 <- gsub("dunno",NA,d$fearabuseAGE2)
d$fearabuseAGE2 <- gsub("decline",NA,d$fearabuseAGE2)
d$fearabuseAGE2 <- as.numeric(as.character(d$fearabuseAGE2))
# Physical Abuse ----------------------------------------------------------
d$physabuse1 <- gsub("never",0,d$physabuse1)
d$physabuse1 <- gsub("rarely",1,d$physabuse1)
d$physabuse1 <- gsub("sometimes",2,d$physabuse1)
d$physabuse1 <- gsub("often",3,d$physabuse1)
d$physabuse1 <- gsub("dunno",NA,d$physabuse1)
d$physabuse1 <- gsub("decline",NA,d$physabuse1)
d$physabuse1 <- as.numeric(as.character(d$physabuse1))
#NEW VARIABLE
d$physabuse1.d <- ifelse(d$physabuse1 >= 1,1,0)
d$physabuse1AGE1 <- gsub("none",NA,d$physabuse1AGE1)
d$physabuse1AGE1 <- gsub("dunno",NA,d$physabuse1AGE1)
d$physabuse1AGE1 <- gsub("decline",NA,d$physabuse1AGE1)
d$physabuse1AGE1 <- as.numeric(as.character(d$physabuse1AGE1))
d$physabuse1AGE2 <- gsub("none",NA,d$physabuse1AGE2)
d$physabuse1AGE2 <- gsub("dunno",NA,d$physabuse1AGE2)
d$physabuse1AGE2 <- gsub("decline",NA,d$physabuse1AGE2)
d$physabuse1AGE2 <- as.numeric(as.character(d$physabuse1AGE2))
d$physabuse2 <- gsub("never",0,d$physabuse2)
d$physabuse2 <- gsub("rarely",1,d$physabuse2)
d$physabuse2 <- gsub("sometimes",2,d$physabuse2)
d$physabuse2 <- gsub("often",3,d$physabuse2)
d$physabuse2 <- gsub("dunno",NA,d$physabuse2)
d$physabuse2 <- gsub("decline",NA,d$physabuse2)
d$physabuse2 <- as.numeric(as.character(d$physabuse2))
#NEW VARIABLE
d$physabuse2.d <- ifelse(d$physabuse2 >= 1,1,0)
d$physabuse2AGE1 <- gsub("none",NA,d$physabuse2AGE1)
d$physabuse2AGE1 <- gsub("dunno",NA,d$physabuse2AGE1)
d$physabuse2AGE1 <- gsub("decline",NA,d$physabuse2AGE1)
d$physabuse2AGE1 <- as.numeric(as.character(d$physabuse2AGE1))
d$physabuse2AGE2 <- gsub("none",NA,d$physabuse2AGE2)
d$physabuse2AGE2 <- gsub("dunno",NA,d$physabuse2AGE2)
d$physabuse2AGE2 <- gsub("decline",NA,d$physabuse2AGE2)
d$physabuse2AGE2 <- as.numeric(as.character(d$physabuse2AGE2))
d$physinjury <- gsub("never",0,d$physinjury)
d$physinjury <- gsub("rarely",1,d$physinjury)
d$physinjury <- gsub("sometimes",2,d$physinjury)
d$physinjury <- gsub("often",3,d$physinjury)
d$physinjury <- gsub("dunno",NA,d$physinjury)
d$physinjury <- gsub("decline",NA,d$physinjury)
d$physinjury <- as.numeric(as.character(d$physinjury))
#NEW VARIABLE
d$physinjury.d <- ifelse(d$physinjury >= 1,1,0)
d$physinjuryAGE1 <- gsub("none",NA,d$physinjuryAGE1)
d$physinjuryAGE1 <- gsub("dunno",NA,d$physinjuryAGE1)
d$physinjuryAGE1 <- gsub("decline",NA,d$physinjuryAGE1)
d$physinjuryAGE1 <- as.numeric(as.character(d$physinjuryAGE1))
d$physinjuryAGE2 <- gsub("none",NA,d$physinjuryAGE2)
d$physinjuryAGE2 <- gsub("dunno",NA,d$physinjuryAGE2)
d$physinjuryAGE2 <- gsub("decline",NA,d$physinjuryAGE2)
d$physinjuryAGE2 <- as.numeric(as.character(d$physinjuryAGE2))
# Sexual Abuse ------------------------------------------------------------
d$sexabuse1 <- gsub("dunno",NA,d$sexabuse1)
d$sexabuse1 <- gsub("decline",NA,d$sexabuse1)
d$sexabuse1 <- gsub("no",0,d$sexabuse1)
d$sexabuse1 <- gsub("yes",1,d$sexabuse1)
d$sexabuse1 <- as.numeric(as.character(d$sexabuse1))
d$sexabuse1AGE1 <- gsub("none",NA,d$sexabuse1AGE1)
d$sexabuse1AGE1 <- gsub("dunno",NA,d$sexabuse1AGE1)
d$sexabuse1AGE1 <- gsub("decline",NA,d$sexabuse1AGE1)
d$sexabuse1AGE1 <- as.numeric(as.character(d$sexabuse1AGE1))
d$sexabuse1AGE2 <- gsub("none",NA,d$sexabuse1AGE2)
d$sexabuse1AGE2 <- gsub("dunno",NA,d$sexabuse1AGE2)
d$sexabuse1AGE2 <- gsub("decline",NA,d$sexabuse1AGE2)
d$sexabuse1AGE2 <- as.numeric(as.character(d$sexabuse1AGE2))
#sexabuse1FREQ is a text response.
d$sexabuse1FREQ <- gsub("^$",NA,d$sexabuse1FREQ)
d$sexabuse1FREQ <- as.factor(d$sexabuse1FREQ)
d$sexabuse1WHO <- gsub("relhome",2,d$sexabuse1WHO)
d$sexabuse1WHO <- gsub("reloutside",3,d$sexabuse1WHO)
d$sexabuse1WHO <- gsub("unrelated",4,d$sexabuse1WHO)
d$sexabuse1WHO <- gsub("dunno",NA,d$sexabuse1WHO)
d$sexabuse1WHO <- gsub("decline",NA,d$sexabuse1WHO)
d$sexabuse1WHO <- as.numeric(as.character(d$sexabuse1WHO))
#d$sexabuse1WHO not to be recodedd$sexabuse2 <- gsub("no",0,d$sexabuse2)
d$sexabuse2 <- gsub("dunno",NA,d$sexabuse2)
d$sexabuse2 <- gsub("decline",NA,d$sexabuse2)
d$sexabuse2 <- gsub("yes",1,d$sexabuse2)
d$sexabuse2 <- gsub("no",0,d$sexabuse2)
d$sexabuse2 <- as.numeric(as.character(d$sexabuse2))
d$sexabuse2AGE1 <- gsub("none",NA,d$sexabuse2AGE1)
d$sexabuse2AGE1 <- gsub("dunno",NA,d$sexabuse2AGE1)
d$sexabuse2AGE1 <- gsub("decline",NA,d$sexabuse2AGE1)
d$sexabuse2AGE1 <- as.numeric(as.character(d$sexabuse2AGE1))
d$sexabuse2AGE2 <- gsub("none",NA,d$sexabuse2AGE2)
d$sexabuse2AGE2 <- gsub("dunno",NA,d$sexabuse2AGE2)
d$sexabuse2AGE2 <- gsub("decline",NA,d$sexabuse2AGE2)
d$sexabuse2AGE2 <- as.numeric(as.character(d$sexabuse2AGE2))
#sexabuse2FREQ is a text response.
d$sexabuse2FREQ <- gsub("^$",NA,d$sexabuse2FREQ)
d$sexabuse2FREQ <- as.factor(d$sexabuse2FREQ)
#d$sexabuse2WHO not to be recoded
d$dangerouschores <- gsub("never",0,d$dangerouschores)
d$dangerouschores <- gsub("rarely",1,d$dangerouschores)
d$dangerouschores <- gsub("sometimes",2,d$dangerouschores)
d$dangerouschores <- gsub("often",3,d$dangerouschores)
d$dangerouschores <- gsub("dunno",NA,d$dangerouschores)
d$dangerouschores <- gsub("decline",NA,d$dangerouschores)
d$dangerouschores <- as.numeric(as.character(d$dangerouschores))
#NEW VARIABLE
d$dangerouschores.d <- ifelse(d$dangerouschores > 1,1,0)
d$unsupervised <- gsub("never",0,d$unsupervised)
d$unsupervised <- gsub("rarely",1,d$unsupervised)
d$unsupervised <- gsub("sometimes",2,d$unsupervised)
d$unsupervised <- gsub("often",3,d$unsupervised)
d$unsupervised <- gsub("dunno",NA,d$unsupervised)
d$unsupervised <- gsub("decline",NA,d$unsupervised)
d$unsupervised <- as.numeric(as.character(d$unsupervised))
#NEW VARIABLE
d$unsupervised.d <- ifelse(d$unsupervised > 1,1,0)
d$neglect_clothing <- gsub("never",0,d$neglect_clothing)
d$neglect_clothing <- gsub("rarely",1,d$neglect_clothing)
d$neglect_clothing <- gsub("sometimes",2,d$neglect_clothing)
d$neglect_clothing <- gsub("often",3,d$neglect_clothing)
d$neglect_clothing <- gsub("dunno",NA,d$neglect_clothing)
d$neglect_clothing <- gsub("decline",NA,d$neglect_clothing)
d$neglect_clothing <- as.numeric(as.character(d$neglect_clothing))
#NEW VARIABLE
d$neglect_clothing.d <- ifelse(d$neglect_clothing > 1,1,0)
d$neglect_hunger <- gsub("never",0,d$neglect_hunger)
d$neglect_hunger <- gsub("rarely",1,d$neglect_hunger)
d$neglect_hunger <- gsub("sometimes",2,d$neglect_hunger)
d$neglect_hunger <- gsub("often",3,d$neglect_hunger)
d$neglect_hunger <- gsub("dunno",NA,d$neglect_hunger)
d$neglect_hunger <- gsub("decline",NA,d$neglect_hunger)
d$neglect_hunger <- as.numeric(as.character(d$neglect_hunger))
#NEW VARIABLE
d$neglect_hunger.d <- ifelse(d$neglect_hunger > 1,1,0)
d$neglect_medical <- gsub("never",0,d$neglect_medical)
d$neglect_medical <- gsub("rarely",1,d$neglect_medical)
d$neglect_medical <- gsub("sometimes",2,d$neglect_medical)
d$neglect_medical <- gsub("often",3,d$neglect_medical)
d$neglect_medical <- gsub("dunno",NA,d$neglect_medical)
d$neglect_medical <- gsub("decline",NA,d$neglect_medical)
d$neglect_medical <- as.numeric(as.character(d$neglect_medical))
#NEW VARIABLE
d$neglect_medical.d <- ifelse(d$neglect_medical > 1,1,0)
# Domestic Violence -------------------------------------------------------
d$domesticviolence1 <- gsub("never",0,d$domesticviolence1)
d$domesticviolence1 <- gsub("rarely",1,d$domesticviolence1)
d$domesticviolence1 <- gsub("sometimes",2,d$domesticviolence1)
d$domesticviolence1 <- gsub("often",3,d$domesticviolence1)
d$domesticviolence1 <- gsub("dunno",NA,d$domesticviolence1)
d$domesticviolence1 <- gsub("decline",NA,d$domesticviolence1)
d$domesticviolence1 <- as.numeric(as.character(d$domesticviolence1))
#NEW VARIABLE
d$domesticviolence1.d <- ifelse(d$domesticviolence1 >= 1,1,0)
d$domesticviolence1AGE1 <- gsub("none",NA,d$domesticviolence1AGE1)
d$domesticviolence1AGE1 <- gsub("dunno",NA,d$domesticviolence1AGE1)
d$domesticviolence1AGE1 <- gsub("decline",NA,d$domesticviolence1AGE1)
d$domesticviolence1AGE1 <- as.numeric(as.character(d$domesticviolence1AGE1))
d$domesticviolence1AGE2 <- gsub("none",NA,d$domesticviolence1AGE2)
d$domesticviolence1AGE2 <- gsub("dunno",NA,d$domesticviolence1AGE2)
d$domesticviolence1AGE2 <- gsub("decline",NA,d$domesticviolence1AGE2)
d$domesticviolence1AGE2 <- as.numeric(as.character(d$domesticviolence1AGE2))
d$domesticviolence2 <- gsub("never",0,d$domesticviolence2)
d$domesticviolence2 <- gsub("rarely",1,d$domesticviolence2)
d$domesticviolence2 <- gsub("sometimes",2,d$domesticviolence2)
d$domesticviolence2 <- gsub("often",3,d$domesticviolence2)
d$domesticviolence2 <- gsub("dunno",NA,d$domesticviolence2)
d$domesticviolence2 <- gsub("decline",NA,d$domesticviolence2)
d$domesticviolence2 <- as.numeric(as.character(d$domesticviolence2))
#NEW VARIABLE
d$domesticviolence2.d <- ifelse(d$domesticviolence2 >= 1,1,0)
d$domesticviolence2AGE1 <- gsub("none",NA,d$domesticviolence2AGE1)
d$domesticviolence2AGE1 <- gsub("dunno",NA,d$domesticviolence2AGE1)
d$domesticviolence2AGE1 <- gsub("decline",NA,d$domesticviolence2AGE1)
d$domesticviolence2AGE1 <- as.numeric(as.character(d$domesticviolence2AGE1))
d$domesticviolence2AGE2 <- gsub("none",NA,d$domesticviolence2AGE2)
d$domesticviolence2AGE2 <- gsub("dunno",NA,d$domesticviolence2AGE2)
d$domesticviolence2AGE2 <- gsub("decline",NA,d$domesticviolence2AGE2)
d$domesticviolence2AGE2 <- as.numeric(as.character(d$domesticviolence2AGE2))
# Demographic Info --------------------------------------------------------
d$additionalinfo <- as.character(d$additionalInfo)
d <- d[d$age >= 18 & d$age <= 70,]
d$age <- as.numeric(as.character(d$age))
d$hispanic <- gsub(3,NA,d$hispanic)
d$hispanic <- gsub(2,NA,d$hispanic)
d$hispanic <- as.numeric(d$hispanic)
d$gender <- gsub("female",0,d$gender)
d$gender <- gsub("male",1,d$gender)
d$gender <- as.numeric(d$gender)
d$ethnicity <- gsub("decline",NA,d$ethnicity)
d$ethnicity <- gsub("none",NA,d$ethnicity)
d$ethnicity<- factor(d$ethnicity, levels = c("europe","africa","east_asia","west_asia","pacific_asia","americas","two","more_than_two"))
# factors d$ethnicity column and seperates it into with 8 specified levels
# new variable - handedness
d$handedness <- gsub("right",1,d$handedness)
d$handedness <- gsub("left",0,d$handedness)
# create new variable
d$race.ethnicity[d$hispanic == 1] <- "hispanic"
d$race.ethnicity[d$hispanic == 0 & d$ethnicity == "europe"] <- "nonhispanic_white" #non-hispanic/european descent = non-hispanic white
d$race.ethnicity[d$hispanic == 0 & d$ethnicity == "africa"] <- "nonhispanic_black" #non-hispanic/african descent = non-hispanic black
d$race.ethnicity[d$hispanic == 0 & d$ethnicity != "europe" & d$ethnicity != "africa"] <- "other" #non-hispanic, not european or african descent = other
d$race.ethnicity <- factor(d$race.ethnicity, levels=c("nonhispanic_white","nonhispanic_black","hispanic","other"))
d$caucasian[d$hispanic == 0 & d$ethnicity == "europe"] <- 1
d$caucasian[d$hispanic == 1 | d$ethnicity != "europe"] <- 0
d$caucasian <- as.numeric(d$caucasian)
# native_language recoding ####
#languages were recoded into numeric values by region of the world
#language responses were typed in by user --> variations of different spelling for same language are coded as same respective numeric value
#responses which had more than one language listed (i.e. english and russian), were coded into whatever group the first language typed would fit in
#languages are seperated by continent and sub-separated by region
#next to direction (i.e. south) lists countries considered to be in region
# english
d$native_language <- gsub("english", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("english.", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("american", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("american english", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("australian", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("asl", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("british", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("british english", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("eng", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("endlish", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("englis", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("england", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("english and russian", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("english-french", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("english.", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("englsh", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("engrish", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("enlish", 1, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("enlgish", 1, d$native_language, ignore.case = TRUE)
#### EUROPEAN LANGUAGES ####
# north - iceland, ireland, UK, denmark, norway, sweden, finand, estonia, latvia, lithuania
d$native_language <- gsub("danish", 2, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("danish.", 2, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("deutsch", 2, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("dutch", 2, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("estonian", 2, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("finnish", 2, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("icelandic", 2, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("irish", 2, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("latvian", 2, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("lithuanian", 2, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("norwegian", 2, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("swedish", 2, d$native_language, ignore.case = TRUE)
#east - poland, belarus, ukraine, moldova, bulgaria, romania, hungary, slovakia, poland, czech republic
d$native_language <- gsub("bulgarian", 3, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("czech", 3, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("hungarian", 3, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("polish", 3, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("romanian", 3, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("roumanian", 3, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("slovak", 3, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("slovenian", 3,d$native_language, ignore.case = TRUE)
d$native_language <- gsub("slovene", 3, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("ukranian", 3, d$native_language, ignore.case = TRUE)
# south - portugal, spain, italy, albania, greece, macedonia, serbia, kosovo, montenergro, croatia, slovenia, bosnia
d$native_language <- gsub("albanian", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("albania", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("bosnian", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("catalan", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("croatian", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("croatian.", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("greek", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("italian", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("italiano", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("macedonian", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("maltese", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("spanish", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("espanol", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("portugese", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("serbian", 4, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("portuguese", 4, d$native_language, ignore.case = TRUE)
# west - neatherlands, germany, belgium, france, luxembourg, austria,
d$native_language <- gsub("france", 5, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("french", 5, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("german", 5, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("amharic", 5, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("luxembourish", 5, d$native_language, ignore.case = TRUE)
#### ASIAN LANGUAGES ####
# north - russian
d$native_language <- gsub("russian", 6, d$native_language, ignore.case = TRUE)
# east - china, japan, north korea, mongolia, taiwan
d$native_language <- gsub("cantonese", 7, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("chinese", 7, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("japanese", 7, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("korean", 7, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("mandarin", 7, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("hangul", 7, d$native_language, ignore.case = TRUE)
# southeastern - brunei, cambodia, indonesia, laos, malaysia, myanmar, philippines, singapore, thailand, vietnam
d$native_language <- gsub("filipino", 8, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("filipino.", 8, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("ilonggo", 8, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("indonesian", 8, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("indonesia", 8, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("malay", 8, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("tagalog", 8, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("thai", 8, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("vietnamese", 8, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("visaya", 8, d$native_language, ignore.case = TRUE)
# central - kazakhstan, kyrgyzstan, tajikistan, turkmenistan, uzbekistan
d$native_language <- gsub("kazakh", 9, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("kyrgyz", 9, d$native_language, ignore.case = TRUE)
# south - afghanistan, bagladesh, bhutan, india, pakistan
d$native_language <- gsub("badaga", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("bahasa", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("bahasa indonesia", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("bangla", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("bahasa melayu", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("bangali", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("dzongkha", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("gujarati", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("hindi", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("indian", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("kannada", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("khasi", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("konkani", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("malayalam", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("malaysian", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("malyalam", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("marathi", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("mara", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("nepali", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("nepal", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("pashto", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("punjabi", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("sindhi", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("sinhala", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("sinhalese", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("tamil", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("telugu", 10, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("urdu", 10, d$native_language, ignore.case = TRUE)
# west - turkey, bahrain, kuwait, qatar, saudi, UAE, armenia, azerbaijan, iraq, israel, jordan, palestine, lebanon, syria, iran, egypt, cyprus
d$native_language <- gsub("azari", 11, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("azerbaijani", 11, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("azeri-turkish", 11, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("assamese", 11, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("arab",11, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("arabic",11, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("ar", 11, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("armenian", 11, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("farsi", 11, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("hebrew", 11, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("kurdish", 11, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("lebanese", 11, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("persian", 11, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("turkish", 11, d$native_language, ignore.case = TRUE)
#### AFRICAN LANGUAGES ####
d$native_language <- gsub("africaans", 12, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("creole", 12, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("dholuo", 12, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("isizulu", 12, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("kikuyu", 12, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("malagasy", 12, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("somali", 12, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("swahili", 12, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("tswana", 12, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("uhrobo", 12, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("venda", 12, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("oshiwambo", 12, d$native_language, ignore.case = TRUE)
d$native_language <- gsub("afrikaans", 12, d$native_language, ignore.case = TRUE)
d$native_language <- ifelse(d$native_language >= 1 | d$native_language <= 12, d$native_language, "NA" ) #recodes any other languages not above as missing
d$native_language <- as.numeric(as.character(d$native_language))
return(d)
}
head(recode_adversity) # name of function to be called to apply to dataframes
<file_sep>/more_adversity_recoding.R
# adversity_processed_data.csv contains all demographic information, raw ages, and scores across RMET and MSPSS tests
#user responses has been recoded to numeric values
origin.data <-read.csv("adversity_processed_data.csv")
# replace 9999 with NA
origin.data[origin.data==9999] <- NA
#df recoded from "adversity_recoding_function.R"
#26 variables total are yes/no responses
# c(parentdeath,parentdivorce,foster,institution,alcoholism,drugs,mentalillness,suicide,prison,criminal.d,welfare.d,hunger_poverty.d,verbalabuse.d,fearabuse.d,physabuse1.d,physabuse2.d,unsupervised.d,neglect_clothing,neglect_hunger.d,neglect_medical.d,domesticviolence1.d,domesticviolence2.d)
#WE WILL ONLY USE ADVERSITY VARS WHICH HAVE ASSOCIATED AGES - yes/no
#### exposed/unexposed vars with associated ages - 15 variables
exposed.unexposed <- origin.data[,c("parentdeath","parentdivorce","foster","institution","suicide","prison","verbalabuse.d","fearabuse.d","physabuse1.d","physabuse2.d","physinjury.d","sexabuse1", "sexabuse2", "domesticviolence1.d","domesticviolence2.d")]
# df for columns with just raw age values - 24 raw AGE columns
# verbal, fear, physabuse1/2, physinjury, sexabuse1/2, domesticviolence1/2 all have BOTH age 1 and age 2
# c("parentdeathAGE","parentdivorceAGE","fosterAGE","institutionAGE","suicideAGE","prisonAGE","verbalAGE1","verbalAGE2","fearabuseAGE1","fearabuseAGE2","physabuse1AGE1","physabuse1AGE2","physabuse2AGE1","physabuse2AGE2","physinjuryAGE1","physinjuryAGE2","sexabuse1AGE1","sexabuse1AGE2","sexabuse2AGE1","sexabuse2AGE2","domesticviolence1AGE1","domesticviolence1AGE2","domesticviolence2AGE1","domesticviolence2AGE2")
#WE WILL ONLY FOCUS ON "AGE1"
#### RAW age 1 exposure vars - 15 variables
age <- origin.data[,c("parentdeathAGE","parentdivorceAGE","fosterAGE","institutionAGE","suicideAGE","prisonAGE","verbalAGE1","fearabuseAGE1","physabuse1AGE1","physabuse2AGE1","physinjuryAGE1","sexabuse1AGE1","sexabuse2AGE1","domesticviolence1AGE1","domesticviolence2AGE1")]
# no associated ages for 11 vars: c("alcoholism","drugs","mentalillness","criminal.d","welfare.d","hunger_poverty.d","dangerouschores.d","unsupervised.d","neglect_clothing.d","neglect_hunger.d","neglect_medical.d")
# therefore, there are 24 columns for AGEs
# of those, 9, do not have yes/no vars (verbalAGE2, fearabuseAGE2, physabuse1AGE2, physabuse2AGE2, physinjuryAGE2 sexabuse1AGE2, sexabuse2AGE2, domesticviolence1AGE2, domesticviolence2AGE2)
#columns with demographic data - 7 variables
demographics <- origin.data[,c("id","birth_year","age", "gender","handedness","education", "parentaled", "native_language", "race.ethnicity", "relativeSES")]
demographics$age <- as.numeric(as.character(demographics$age))
demographics$birth_year <- as.numeric(as.character(demographics$birth_year))
# columns with score and test duration (only RMET and MSPSS)
scores <- origin.data[,c("duration_rmet", "rmet")] #subsets RMET scores into df "scores"
age_group <- age
####### GROUPING BY AGE #########
#all adversity vars broken down into 1 of 4 different age groups based off age partcipant indicated
#all age group vars end in "_AG#" numbers are 1-4
# AG1 = ages 0-5, AG2 = ages 6-11, AG3 = ages 11-17, AG4 = ages 18+
#### parentdeathAGE #
age_group$parentdeath_AG1 <- ifelse(age_group$parentdeathAGE >= 0 & age_group$parentdeathAGE <= 5,1,0)
age_group$parentdeath_AG2 <- ifelse(age_group$parentdeathAGE >= 6 & age_group$parentdeathAGE <= 11,1,0)
age_group$parentdeath_AG3 <- ifelse(age_group$parentdeathAGE >= 12 & age_group$parentdeathAGE <= 17,1,0)
age_group$parentdeath_AG4 <- ifelse(age_group$parentdeathAGE >= 18,1,0)
#### parentdivorceAGE #
age_group$parentdivorce_AG1 <- ifelse(age_group$parentdivorceAGE >= 0 & age_group$parentdivorceAGE <= 5,1,0)
age_group$parentdivorce_AG2 <- ifelse(age_group$parentdivorceAGE >= 6 & age_group$parentdivorceAGE <= 11,1,0)
age_group$parentdivorce_AG3 <- ifelse(age_group$parentdivorceAGE >= 12 & age_group$parentdivorceAGE <= 17,1,0)
age_group$parentdivorce_AG4 <- ifelse(age_group$parentdivorceAGE >= 18,1,0)
#### fosterAGE #
age_group$foster_AG1 <- ifelse(age_group$fosterAGE >= 0 & age_group$fosterAGE <= 5,1,0)
age_group$foster_AG2 <- ifelse(age_group$fosterAGE >= 6 & age_group$fosterAGE <= 11,1,0)
age_group$foster_AG3 <- ifelse(age_group$fosterAGE >= 12 & age_group$fosterAGE <= 17,1,0)
age_group$foster_AG4 <- ifelse(age_group$fosterAGE >= 18 ,1,0)
#### institutionAGE #
age_group$institution_AG1 <- ifelse(age_group$institutionAGE >= 0 & age_group$institutionAGE <= 5,1,0)
age_group$institution_AG2 <- ifelse(age_group$institutionAGE >= 6 & age_group$institutionAGE <= 11,1,0)
age_group$institution_AG3 <- ifelse(age_group$institutionAGE >= 12 & age_group$institutionAGE <= 17,1,0)
age_group$institution_AG4 <- ifelse(age_group$institutionAGE >= 18 ,1,0)
#### suicideAGE #
age_group$suicide_AG1 <- ifelse(age_group$suicideAGE >= 0 & age_group$suicideAGE <= 5,1,0)
age_group$suicide_AG2 <- ifelse(age_group$suicideAGE >= 6 & age_group$suicideAGE <= 11,1,0)
age_group$suicide_AG3 <- ifelse(age_group$suicideAGE >= 12 & age_group$suicideAGE <= 17,1,0)
age_group$suicide_AG4 <- ifelse(age_group$suicideAGE >= 18 ,1,0)
#### prisonAGE #
age_group$prison_AG1 <- ifelse(age_group$prisonAGE >= 0 & age_group$prisonAGE <= 5,1,0)
age_group$prison_AG2 <- ifelse(age_group$prisonAGE >= 6 & age_group$prisonAGE <= 11,1,0)
age_group$prison_AG3 <- ifelse(age_group$prisonAGE >= 12 & age_group$prisonAGE <= 17,1,0)
age_group$prison_AG4 <- ifelse(age_group$prisonAGE >= 18 ,1,0)
#### verbalAGE1 #
age_group$verbalAGE1_AG1 <- ifelse(age_group$verbalAGE1 >= 0 & age_group$verbalAGE1 <= 5,1,0)
age_group$verbalAGE1_AG2 <- ifelse(age_group$verbalAGE1 >= 6 & age_group$verbalAGE1 <= 11,1,0)
age_group$verbalAGE1_AG3 <- ifelse(age_group$verbalAGE1 >= 12 & age_group$verbalAGE1 <= 17,1,0)
age_group$verbalAGE1_AG4 <- ifelse(age_group$verbalAGE1 >= 18 ,1,0)
#### fearabuseAGE1 #
age_group$fearabuseAGE1_AG1 <- ifelse(age_group$fearabuseAGE1 >= 0 & age_group$fearabuseAGE1 <= 5,1,0)
age_group$fearabuseAGE1_AG2 <- ifelse(age_group$fearabuseAGE1 >= 6 & age_group$fearabuseAGE1 <= 11,1,0)
age_group$fearabuseAGE1_AG3 <- ifelse(age_group$fearabuseAGE1 >= 12 & age_group$fearabuseAGE1 <= 17,1,0)
age_group$fearabuseAGE1_AG4 <- ifelse(age_group$fearabuseAGE1 >= 18 ,1,0)
#### physabuse1AGE1 #
age_group$physabuse1AGE1_AG1 <- ifelse(age_group$physabuse1AGE1 >= 0 & age_group$physabuse1AGE1 <= 5,1,0)
age_group$physabuse1AGE1_AG2 <- ifelse(age_group$physabuse1AGE1 >= 6 & age_group$physabuse1AGE1 <= 11,1,0)
age_group$physabuse1AGE1_AG3 <- ifelse(age_group$physabuse1AGE1 >= 12 & age_group$physabuse1AGE1 <= 17,1,0)
age_group$physabuse1AGE1_AG4 <- ifelse(age_group$physabuse1AGE1 >= 18 ,1,0)
#### physabuse2AGE1 #
age_group$physabuse2AGE1_AG1 <- ifelse(age_group$physabuse2AGE1 >= 0 & age_group$physabuse2AGE1 <= 5,1,0)
age_group$physabuse2AGE1_AG2 <- ifelse(age_group$physabuse2AGE1 >= 6 & age_group$physabuse2AGE1 <= 11,1,0)
age_group$physabuse2AGE1_AG3 <- ifelse(age_group$physabuse2AGE1 >= 12 & age_group$physabuse2AGE1 <= 17,1,0)
age_group$physabuse2AGE1_AG4 <- ifelse(age_group$physabuse2AGE1 >= 18 ,1,0)
#### physinjuryAGE1 #
age_group$physinjuryAGE1_AG1 <- ifelse(age_group$physinjuryAGE1 >= 0 & age_group$physinjuryAGE1 <= 5,1,0)
age_group$physinjuryAGE1_AG2 <- ifelse(age_group$physinjuryAGE1 >= 6 & age_group$physinjuryAGE1 <= 11,1,0)
age_group$physinjuryAGE1_AG3 <- ifelse(age_group$physinjuryAGE1 >= 12 & age_group$physinjuryAGE1 <= 17,1,0)
age_group$physinjuryAGE1_AG4 <- ifelse(age_group$physinjuryAGE1 >= 18 ,1,0)
#### sexabuse1AGE1 #
age_group$sexabuse1AGE1_AG1 <- ifelse(age_group$sexabuse1AGE1 >= 0 & age_group$sexabuse1AGE1 <= 5,1,0)
age_group$sexabuse1AGE1_AG2 <- ifelse(age_group$sexabuse1AGE1 >= 6 & age_group$sexabuse1AGE1 <= 11,1,0)
age_group$sexabuse1AGE1_AG3 <- ifelse(age_group$sexabuse1AGE1 >= 12 & age_group$sexabuse1AGE1 <= 17,1,0)
age_group$sexabuse1AGE1_AG4 <- ifelse(age_group$sexabuse1AGE1 >= 18 ,1,0)
#### sexabuse2AGE1 #
age_group$sexabuse2AGE1_AG1 <- ifelse(age_group$sexabuse2AGE1 >= 0 & age_group$sexabuse2AGE1 <= 5,1,0)
age_group$sexabuse2AGE1_AG2 <- ifelse(age_group$sexabuse2AGE1 >= 6 & age_group$sexabuse2AGE1 <= 11,1,0)
age_group$sexabuse2AGE1_AG3 <- ifelse(age_group$sexabuse2AGE1 >= 12 & age_group$sexabuse2AGE1 <= 17,1,0)
age_group$sexabuse2AGE1_AG4 <- ifelse(age_group$sexabuse2AGE1 >= 18 ,1,0)
#### domesticviolence1AGE1 #
age_group$domesticviolence1AGE1_AG1 <- ifelse(age_group$domesticviolence1AGE1 >= 0 & age_group$domesticviolence1AGE1 <= 5,1,0)
age_group$domesticviolence1AGE1_AG2 <- ifelse(age_group$domesticviolence1AGE1 >= 6 & age_group$domesticviolence1AGE1 <= 11,1,0)
age_group$domesticviolence1AGE1_AG3 <- ifelse(age_group$domesticviolence1AGE1 >= 12 & age_group$domesticviolence1AGE1 <= 17,1,0)
age_group$domesticviolence1AGE1_AG4 <- ifelse(age_group$domesticviolence1AGE1 >= 18 ,1,0)
#### domesticviolence2AGE1 #
age_group$domesticviolence2AGE1_AG1 <- ifelse(age_group$domesticviolence2AGE1 >= 0 & age_group$domesticviolence2AGE1 <= 5,1,0)
age_group$domesticviolence2AGE1_AG2 <- ifelse(age_group$domesticviolence2AGE1 >= 6 & age_group$domesticviolence2AGE1 <= 11,1,0)
age_group$domesticviolence2AGE1_AG3 <- ifelse(age_group$domesticviolence2AGE1 >= 12 & age_group$domesticviolence2AGE1 <= 17,1,0)
age_group$domesticviolence2AGE1_AG4 <- ifelse(age_group$domesticviolence2AGE1 >= 18 ,1,0)
# age_group has 15 adversities sorted by adversity
# reorder columns so that AG1-4 are next to respective adversity
age_group <- age_group[c(1, 16:19, 2, 20:23, 3, 24:27, 4, 28:31, 5, 32:35, 6, 36:39, 7, 40:43, 8, 44:47, 9, 48:51, 10, 52:55, 11, 56:59, 12, 60:63, 13, 64:67, 14, 68:71, 15, 72:75)]
# alldata includes demographics, raw ages, recoded groups, and scores for all participants and tests
alldata <- cbind.data.frame(demographics, age_group, scores, exposed.unexposed)
################### ONLY LOOKS AT RMET OUTCOME ######################
# rmet.all df contains RAW ages, grouped ages, demographic info and scores
rmet.all <- subset(alldata,!is.na(alldata$rmet))
# in rmet.all, col 1-7 = demographic, col 8,13,18,23,28,33,38,43,48,53,58,63,68,73,78
# AG1 recoded values rmet.all <- [ , seq(9, 82, by = 5)]
# col 85-99 = exposed/unexposed
##################### RECODING DEMOGRAPHIC INFO #########################
# gender, hispanic, education, maternaled, paternaled, caucasian and native_language are all numeric
# need to recode handedness, race,ethnicity, ethnicity
# handedness - 1=right 0=left
rmet.all$handedness <- gsub("right", 1, rmet.all$handedness)
rmet.all$handedness <- gsub("left", 0, rmet.all$handedness)
rmet.all$handedness <- gsub("both", 1, rmet.all$handedness)
# race.ethnicity
rmet.all$race.ethnicity <- gsub("hispanic", 1, rmet.all$race.ethnicity)
rmet.all$race.ethnicity <- gsub("non1_white", 2, rmet.all$race.ethnicity)
rmet.all$race.ethnicity <- gsub("non1_black", 3, rmet.all$race.ethnicity)
rmet.all$race.ethnicity <- gsub("other", 4, rmet.all$race.ethnicity)
#converts handedness, ethnicity and race.ethnicity to numbers
rmet.all$handedness <- as.numeric(as.character(rmet.all$handedness))
rmet.all$race.ethnicity <- as.numeric(as.character(rmet.all$race.ethnicity))
# converts integers to numerics
indx <- sapply(age, is.integer)
age[indx] <- lapply(age[indx], function(x) as.numeric(as.character(x)))
# CSV file contains: demographics, raw ages, groups recoded, scores, exposed/unexposed
write.csv(rmet.all, "rmet_all_raw.csv")
# should be noted that this data has undergone no transformations and is NOT normally distributed
summary(rmet.all$rmet)
# identifies minimum duration, anything less than 120s is to be excluded
min(rmet.all$duration_rmet)
# no values were below 120s
# calculates Z scores for all rmet scores
score_scaled <- scale(rmet.all$rmet)
# identifies any scores greater than 3.5 sd of the mean
apply(score_scaled, 2, function(x) which(x >= 3.5))
# identifies any scores less than -3.5 sd of the mean
apply(score_scaled, 2, function(x) which(x <= -3.5))
# 8 values identified, --> values are to be recoded so that
rmet.scaled <- rmet.all
#adds score_scaled values to rmet.scaled DF
rmet.scaled$score_scaled <- c(score_scaled)
# sets all scores less than -3.5 to -3.5
rmet.scaled[110,100] = (-3.5)
rmet.scaled[737,100] = (-3.5)
rmet.scaled[1384,100] = (-3.5)
rmet.scaled[2770,100] = (-3.5)
rmet.scaled[2872,100] = (-3.5)
rmet.scaled[2877,100] = (-3.5)
rmet.scaled[3191,100] = (-3.5)
rmet.scaled[3487,100] = (-3.5)
# creates rmet_winzor.csv which contains raw AGE, demographics, scaled scores, raw score, and age groups
#write.csv(rmet.scaled, "rmet_winzor.csv")
| fa1d1c3ad758f0c88511578d358528c95407e38d | [
"R"
] | 2 | R | petercla0119/tmb-data-processing | bff83faa28dfe4ee2e9e03e7af9b9a9cfec6050d | a2e62a602cfee9b20af2a2e7817c5985f201df26 |
refs/heads/master | <repo_name>beasonshu/QuickSand<file_sep>/demo/src/main/java/com/blundell/quicksand/demo/amazeanimation/ExplodeAnimation.java
package com.blundell.quicksand.demo.amazeanimation;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.TimeInterpolator;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.blundell.quicksand.Quicksand;
import java.util.concurrent.TimeUnit;
/**
* original author SiYao of https://github.com/2359media/EasyAndroidAnimations
* <p/>
* It doesn't matter what this animation is or how it works. This is just an example of a complex animation.
* See the {@link #monitor(ImageView[])}} method for how you integrate with Quicksand.
*/
public class ExplodeAnimation {
public static final String KEY_ANIMATION_SET = "NewKey";
private static final int MATRIX_3X3 = 33;
private static final long DURATION_LONG = TimeUnit.SECONDS.toMillis(2);
private final View view;
private int xParts;
private int yParts;
private ViewGroup parentView;
private TimeInterpolator interpolator;
private long duration;
private AnimationListener listener;
public interface AnimationListener {
/**
* This method is called when the animation ends.
*
* @param animation The Animation object.
*/
void onAnimationEnd(ExplodeAnimation animation);
}
/**
* This animation creates a bitmap of the view, divides them into
* customizable number of X and Y parts and translates the parts away from
* the center of the view to mimic an explosion. The number of parts can
* vary from 1x2 to 3x3. The view is set to invisible and added back for
* reuse.
*
* @param view The view to be animated.
*/
ExplodeAnimation(View view) {
this.view = view;
setExplodeMatrix(MATRIX_3X3);
interpolator = new AccelerateDecelerateInterpolator();
duration = DURATION_LONG;
listener = null;
}
public void animate() {
final LinearLayout explodeLayout = new LinearLayout(view.getContext());
LinearLayout[] layouts = new LinearLayout[yParts];
parentView = (ViewGroup) view.getParent();
explodeLayout.setLayoutParams(view.getLayoutParams());
explodeLayout.setOrientation(LinearLayout.VERTICAL);
explodeLayout.setClipChildren(false);
view.setDrawingCacheEnabled(true);
Bitmap viewBmp = view.getDrawingCache(true);
int totalParts = xParts * yParts, bmpWidth = viewBmp.getWidth()
/ xParts, bmpHeight = viewBmp.getHeight() / yParts, widthCount = 0, heightCount = 0, middleXPart = (xParts - 1) / 2;
int[] translation;
ImageView[] imageViews = new ImageView[totalParts];
for (int i = 0; i < totalParts; i++) {
int translateX = 0, translateY = 0;
if (i % xParts == 0) {
if (i != 0) {
heightCount++;
}
widthCount = 0;
layouts[heightCount] = new LinearLayout(view.getContext());
layouts[heightCount].setClipChildren(false);
translation = sideTranslation(
heightCount, bmpWidth, bmpHeight,
yParts);
translateX = translation[0];
translateY = translation[1];
} else if (i % xParts == xParts - 1) {
translation = sideTranslation(
heightCount, -bmpWidth,
bmpHeight, yParts);
translateX = translation[0];
translateY = translation[1];
} else {
if (widthCount == middleXPart) {
if (heightCount == 0) {
translateX = 0;
if (yParts != 1) {
translateY = -bmpHeight;
}
} else if (heightCount == yParts - 1) {
translateX = 0;
translateY = bmpHeight;
}
}
}
if (xParts == 1) {
translation = sideTranslation(
heightCount, 0, bmpHeight,
yParts);
translateX = translation[0];
translateY = translation[1];
}
imageViews[i] = new ImageView(view.getContext());
imageViews[i]
.setImageBitmap(
Bitmap.createBitmap(
viewBmp, bmpWidth
* widthCount, bmpHeight * heightCount, bmpWidth,
bmpHeight));
imageViews[i].animate().translationXBy(translateX)
.translationYBy(translateY).alpha(0)
.setInterpolator(interpolator).setDuration(duration);
layouts[heightCount].addView(imageViews[i]);
widthCount++;
}
monitor(imageViews);
for (int i = 0; i < yParts; i++) {
explodeLayout.addView(layouts[i]);
}
final int positionView = parentView.indexOfChild(view);
parentView.removeView(view);
parentView.addView(explodeLayout, positionView);
ViewGroup rootView = (ViewGroup) explodeLayout.getRootView();
while (!parentView.equals(rootView)) {
parentView.setClipChildren(false);
parentView = (ViewGroup) parentView.getParent();
}
rootView.setClipChildren(false);
imageViews[0].animate().setListener(
new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
parentView = (ViewGroup) explodeLayout.getParent();
view.setLayoutParams(explodeLayout.getLayoutParams());
view.setVisibility(View.INVISIBLE);
parentView.removeView(explodeLayout);
parentView.addView(view, positionView);
if (getListener() != null) {
getListener().onAnimationEnd(ExplodeAnimation.this);
}
}
});
}
/**
* This is the line of interest below. It doesn't matter how you create your animation
* as long as those views which want to be animated are added to Quicksand as a set.
* <p/>
* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
* vvvvvvvvvvvvvvvvvvvv
* vvvvvvvvvv
* vvvv
* vv
* v
*/
private void monitor(ImageView[] imageViews) {
Quicksand.trap(KEY_ANIMATION_SET, imageViews);
}
private int[] sideTranslation(int heightCount, int bmpWidth, int bmpHeight, int yParts) {
int[] translation = new int[2];
int middleYPart = (yParts - 1) / 2;
if (heightCount == 0) {
translation[0] = -bmpWidth;
translation[1] = -bmpHeight;
} else if (heightCount == yParts - 1) {
translation[0] = -bmpWidth;
translation[1] = bmpHeight;
}
if (yParts % 2 != 0) {
if (heightCount == middleYPart) {
translation[0] = -bmpWidth;
translation[1] = 0;
}
}
return translation;
}
/**
* @param matrix The matrix that determines the number of X and Y parts to set.
* @return This object, allowing calls to methods in this class to be
* chained.
*/
private ExplodeAnimation setExplodeMatrix(int matrix) {
xParts = matrix / 10;
yParts = matrix % 10;
return this;
}
private AnimationListener getListener() {
return listener;
}
/**
* @param listener The listener to set for the end of the animation.
* @return This object, allowing calls to methods in this class to be
* chained.
*/
public ExplodeAnimation setListener(AnimationListener listener) {
this.listener = listener;
return this;
}
}
<file_sep>/settings.gradle
include ':demo'
include ':core'
<file_sep>/core/build.gradle
apply plugin: 'com.android.library'
apply plugin: 'bintray-release'
android {
compileSdkVersion 22
buildToolsVersion "23.0.1"
defaultConfig {
minSdkVersion 19
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
publish {
userOrg = 'blundell'
groupId = 'com.blundell'
artifactId = 'quicksand'
version = '1.0.2'
description = 'Monitor and automatically adjust animation durations based on view count.'
website = 'https://github.com/blundell/QuickSand'
}
dependencies {
compile 'com.novoda:notils:2.2.11'
testCompile 'junit:junit:4.11'
testCompile 'org.easytesting:fest-assert-core:2.0M10'
testCompile 'org.mockito:mockito-core:1.10.19'
}
<file_sep>/core/src/main/java/com/blundell/quicksand/viscosity/NoChangeViscosityInterpolator.java
package com.blundell.quicksand.viscosity;
/**
* Will never change the duration always returning the current duration
*/
public class NoChangeViscosityInterpolator implements ViscosityInterpolator {
@Override
public long calculateDuration(long currentDuration, long viewCount) {
return currentDuration;
}
}
<file_sep>/core/src/main/java/com/blundell/quicksand/DurationCalculator.java
package com.blundell.quicksand;
import com.blundell.quicksand.viscosity.ViscosityInterpolator;
import com.novoda.notils.logger.simple.Log;
class DurationCalculator {
public long calculateNewDuration(ViscosityInterpolator viscosity, long timesAnimationViewed, long currentDuration) {
if (currentDuration == 0) {
Log.e("duration was zero");
return 0;
}
if (timesAnimationViewed == 0) {
Log.v("first time viewing so no duration change");
return currentDuration;
}
return viscosity.calculateDuration(currentDuration, timesAnimationViewed);
}
}
<file_sep>/core/src/test/java/com/blundell/quicksand/ViscosityInterpolatorMapTest.java
package com.blundell.quicksand;
import com.blundell.quicksand.viscosity.ViscosityInterpolator;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import static org.fest.assertions.api.Assertions.assertThat;
public class ViscosityInterpolatorMapTest {
@Test
public void givenAKnownViscosityWhenWeRetrieveItByTheCorrectKeyThenTheCorrectViscosityIsReturned() throws Exception {
Map<String, ViscosityInterpolator> viscosities = new HashMap<>();
String key = "TestKey";
StubViscosityInterpolator expectedViscosity = new StubViscosityInterpolator();
viscosities.put(key, expectedViscosity);
ViscosityInterpolatorMap collection = new ViscosityInterpolatorMap(viscosities, new StubViscosityInterpolator());
ViscosityInterpolator actualViscosity = collection.getFor(key);
assertThat(actualViscosity).isEqualTo(expectedViscosity);
}
@Test
public void givenAKnownViscosityWhenWeRetrieveItByAnIncorrectKeyThenTheCorrectViscosityIsNotReturned() throws Exception {
Map<String, ViscosityInterpolator> viscosities = new HashMap<>();
StubViscosityInterpolator expectedViscosity = new StubViscosityInterpolator();
viscosities.put("TestKey", expectedViscosity);
ViscosityInterpolatorMap collection = new ViscosityInterpolatorMap(viscosities, new StubViscosityInterpolator());
ViscosityInterpolator actualViscosity = collection.getFor("WrongTestKey");
assertThat(actualViscosity).isNotEqualTo(expectedViscosity);
}
@Test
public void givenAKnownViscosityWhenWeRetrieveItByAnIncorrectKeyThenTheDefaultViscosityIsReturned() throws Exception {
Map<String, ViscosityInterpolator> viscosities = new HashMap<>();
StubViscosityInterpolator expectedViscosity = new StubViscosityInterpolator();
viscosities.put("TestKey", expectedViscosity);
StubViscosityInterpolator defaultViscosity = new StubViscosityInterpolator();
ViscosityInterpolatorMap collection = new ViscosityInterpolatorMap(viscosities, defaultViscosity);
ViscosityInterpolator actualViscosity = collection.getFor("WrongTestKey");
assertThat(actualViscosity).isEqualTo(defaultViscosity);
}
@Test
public void givenAnEmptyCollectionWhenWeRetrieveByAnyKeyThenTheDefaultViscosityIsReturned() throws Exception {
Map<String, ViscosityInterpolator> viscosities = Collections.emptyMap();
StubViscosityInterpolator defaultViscosity = new StubViscosityInterpolator();
ViscosityInterpolatorMap collection = new ViscosityInterpolatorMap(viscosities, defaultViscosity);
ViscosityInterpolator actualViscosity = collection.getFor("AnyTestKey");
assertThat(actualViscosity).isEqualTo(defaultViscosity);
}
private static class StubViscosityInterpolator implements ViscosityInterpolator {
@Override
public long calculateDuration(long currentDuration, long viewCount) {
return 0;
}
}
}
<file_sep>/README.MD
QuickSand
=========
When showing a really enchanting explanatory animation to your users, but you know that after a while it'll get tedious and would stop users wanting to use your app. QuickSand is here to solve that problem.
Automatically manipulates the duration of animations depending on how many times the user has viewed them.
Simple Use
----------
This is the setup needed to define how you change the animation duration between views:
```java
Map<String, ViscosityInterpolator> modifiers = new HashMap<>();
modifiers.put("MyAnimationSetKey", TwoStepViscosityInterpolator.defaultInstance());
Quicksand.create(this, modifiers);
```
This is "trapping" an animation, meaning when this view is animated `Quicksand` will determine how many times it has been viewed and vary the animation duration according to the `ViscosityInterpolator` set above:
```java
View myView = findViewById(R.id.my_view);
QuickSand.trap("MyAnimationSetKey", myView);
myView.animate().alpha();
```
Also works for multiple view animation:
```java
View myView = findViewById(R.id.my_view);
View myOtherView = findViewById(R.id.my_view);
View myThirdView = findViewById(R.id.my_view);
QuickSand.trap("MyAnimationSetKey", myView, myOtherView, myThirdView);
myView.animate().alpha();
myOtherView.animate().alpha();
myThirdView.animate().alpha();
```
Some viscosities already defined [see the code here](https://github.com/blundell/QuickSand/tree/master/core/src/main/java/com/blundell/quicksand/viscosity):
- [AllOrNothing](https://github.com/blundell/QuickSand/blob/master/core/src/main/java/com/blundell/quicksand/viscosity/AllOrNothingViscosityInterpolator.java) - you can run your animation for X seconds X times and then 0 seconds after that
- [LinearChange](https://github.com/blundell/QuickSand/blob/master/core/src/main/java/com/blundell/quicksand/viscosity/LinearChangeViscosityInterpolator.java) - speed up the animation each time it is viewed until X views
- [TwoStep](https://github.com/blundell/QuickSand/blob/master/core/src/main/java/com/blundell/quicksand/viscosity/TwoStepViscosityInterpolator.java) - run animation at X speed for X times then it will run at half X
See the [demo project](https://github.com/blundell/QuickSand/tree/master/demo) for more examples.
Adding to your project
--------
```groovy
dependencies {
compile 'com.blundell:quicksand:1.0.2'
}
```
--------
See it to believe it
--------
|15 second gif below|
|---|
Notice how the animation duration decreases each time it is ran until eventually it does not animate (only touch feedback), `Quicksand` integration is done with 2 lines of code.|
||
Download
--------
[Release Notes](https://github.com/blundell/QuickSand/blob/master/releases/RELEASE-NOTES.MD)
Get [the latest version here](https://github.com/blundell/QuickSand/raw/master/releases/)
License
-------
[Apache 2](LICENSE.txt)
<file_sep>/releases/RELEASE-NOTES.MD
1.0.2
-----
Renames Velocity > VelocityInterpolator
1.0.1
-----
- Fix for compile errors if client application is using same resource names (ic_launcher)
1.0.0
-----
- Initial release
<file_sep>/core/src/main/java/com/blundell/quicksand/ActManipulator.java
package com.blundell.quicksand;
import com.blundell.quicksand.act.Act;
import com.blundell.quicksand.viscosity.ViscosityInterpolator;
class ActManipulator {
private final AnimationTracker animationTracker;
private final DurationCalculator durationCalculator;
private final ViscosityInterpolatorMap viscosityCollection;
private boolean preRunDurationSet = true;
ActManipulator(AnimationTracker animationTracker, DurationCalculator durationCalculator, ViscosityInterpolatorMap viscosityCollection) {
this.animationTracker = animationTracker;
this.durationCalculator = durationCalculator;
this.viscosityCollection = viscosityCollection;
}
/**
* Called in two potential scenarios:
* - S1 once every time the act is created (before starting); therefore we need to maintain current duration ourselves external to act
* - S2 once only when act is created; therefore we need to increment the duration in the listener on act finish ready for next time
* <p/>
* onFinishUpdate means first time manipulate() is called it will skip the setDuration in onFinish ()
*/
public void manipulate(String key, Act act) {
updateDurationPreRun(key, act);
monitorAct(key, act);
}
private void updateDurationPreRun(String key, Act act) {
updateDuration(key, act);
if (act.isLast()) {
preRunDurationSet = true;
}
}
private void updateDuration(String key, Act act) {
long duration = getViscosityAffectedDuration(key, act);
act.setDuration(duration);
animationTracker.saveDuration(key + act.getId(), duration);
}
private long getViscosityAffectedDuration(String key, Act act) {
ViscosityInterpolator viscosity = viscosityCollection.getFor(key);
long viewCount = animationTracker.getCount(key);
long currentDuration = getCurrentDuration(key, act);
return durationCalculator.calculateNewDuration(viscosity, viewCount, currentDuration);
}
private long getCurrentDuration(String key, Act act) {
return animationTracker.getCurrentDuration(key + act.getId(), act);
}
private void monitorAct(final String key, Act act) {
act.addListener(
new Act.StartListener() {
@Override
public void onStart(Act act) {
if (act.isLast()) { // (animationTracker.isTheStartOfANewAnimationSet(key, act.getDuration())) {
animationTracker.incrementAnimationViewCount(key);
}
}
@Override
public void onFinish(Act act) {
updateDurationPostRun(act, key);
if (act.isLast()) {
preRunDurationSet = false;
}
}
}
);
}
private void updateDurationPostRun(Act act, String key) {
if (preRunDurationSet) {
return;
}
updateDuration(key, act);
}
public void resetTransition(String key) {
animationTracker.reset(key);
}
}
<file_sep>/core/src/test/java/com/blundell/quicksand/AnimationTrackerTest.java
package com.blundell.quicksand;
import android.os.CountDownTimer;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class AnimationTrackerTest {
private static final long ANY_DURATION = 1L;
@Mock
private AnimationCounter mockCounter;
@Mock
private CountDownTimerFactory mockTimerFactory;
@Mock
private CountDownTimer mockTimer;
private AnimationTracker tracker;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
tracker = new AnimationTracker(mockCounter, mockTimerFactory);
when(mockTimerFactory.getTimer(anyLong(), any(Runnable.class))).thenReturn(mockTimer);
}
@Test
public void givenAnAnimationIsNotPartOfASetWhenWeAskThenItSaysItsANewAnimation() throws Exception {
boolean startOfANewAnimation = tracker.isTheStartOfANewAnimationSet("TestKey", ANY_DURATION);
assertThat(startOfANewAnimation).isTrue();
}
@Test
public void givenAnAnimationIsPartOfASetWhenWeAskThenThereItSaysItIsNotANewAnimation() throws Exception {
String setKey = "TestKey";
tracker.isTheStartOfANewAnimationSet(setKey, ANY_DURATION);
boolean startOfANewAnimation = tracker.isTheStartOfANewAnimationSet(setKey, ANY_DURATION);
assertThat(startOfANewAnimation).isFalse();
}
@Test
public void givenTwoAnimationsAreNotPartOfASetWhenWeAskThenThereIsTwoIncrements() throws Exception {
tracker.isTheStartOfANewAnimationSet("TestKey1", ANY_DURATION);
boolean startOfANewAnimation = tracker.isTheStartOfANewAnimationSet("TestKey2", ANY_DURATION);
assertThat(startOfANewAnimation).isTrue();
}
@Test
public void whenIncrementViewCountThenDelegatesToCounter() throws Exception {
String expectedKey = "TestKey";
tracker.incrementAnimationViewCount(expectedKey);
verify(mockCounter).incrementCount(expectedKey);
}
@Test
public void whenGetCountThenDelegatesToCounter() throws Exception {
String expectedKey = "TestKey";
tracker.getCount(expectedKey);
verify(mockCounter).getCount(expectedKey);
}
@Test
public void whenResetCountThenDelegatesToCounter() throws Exception {
String expectedKey = "TestKey";
tracker.reset(expectedKey);
verify(mockCounter).reset(expectedKey);
}
}
<file_sep>/demo/src/main/java/com/blundell/quicksand/demo/simpleanimation/SimpleAnimationActivity.java
package com.blundell.quicksand.demo.simpleanimation;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewPropertyAnimator;
import com.blundell.quicksand.Quicksand;
import com.blundell.quicksand.demo.R;
public class SimpleAnimationActivity extends Activity {
public static final String KEY_SIMPLE_ANIMATE_TEXT = "SimpleAnimateText";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_anim);
ViewPropertyAnimator animateText = findViewById(R.id.simple_anim_text)
.animate()
.setDuration(5000)
.scaleXBy(.5f);
Quicksand.trap(KEY_SIMPLE_ANIMATE_TEXT, animateText);
}
}
<file_sep>/core/src/test/java/com/blundell/quicksand/ActManipulatorTest.java
package com.blundell.quicksand;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.verify;
public class ActManipulatorTest {
@Mock
private AnimationTracker mockAnimationTracker;
@Mock
private DurationCalculator mockDurationCalculator;
private ActManipulator manipulator;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void whenResetTransitionIsCalledThenWeDelegateToTheAnimationTracker() throws Exception {
ActManipulator manipulator = new ActManipulator(mockAnimationTracker, null, null);
String expectedKey = "ExpectedKey";
manipulator.resetTransition(expectedKey);
verify(mockAnimationTracker).reset(expectedKey);
}
}
<file_sep>/demo/README.md
This demo project shows how you can integrate your animations and transitions with Quicksand.
It is comprised of 4 packages:
activitytransition
Shows Quicksand integration with transitions you use to animate between two activities.
amazetransition
Shows Quicksand integration when you have a complex custom animation of your own creation.
viewanimation
Shows Quicksand integration when using ViewPropertyAnimator and chaining animations
simpleanimation
Shows Quicksand integration when using ViewPropertyAnimator
Each animation you create is controlled by a ViscosityInterpolator, this class determines how the animation duration changes over time.
If you look in DemoApplication.java you can toggle different Interpolators for the demo animations.
<file_sep>/core/src/main/java/com/blundell/quicksand/viscosity/LinearChangeViscosityInterpolator.java
package com.blundell.quicksand.viscosity;
/**
* Speeds up over time until 0 duration
*/
public class LinearChangeViscosityInterpolator implements ViscosityInterpolator {
private static final int DEFAULT_MAX_VIEWS = 10;
private final int maxViews;
public static ViscosityInterpolator defaultInstance() {
return new LinearChangeViscosityInterpolator(DEFAULT_MAX_VIEWS);
}
public LinearChangeViscosityInterpolator(int maxViews) {
this.maxViews = maxViews;
}
@Override
public long calculateDuration(long currentDuration, long viewCount) {
if (viewCount >= maxViews) {
return 0;
}
if (viewCount == 1) {
return currentDuration;
}
double viewCountAsPercent = (double) maxViews / viewCount;
return (long) (currentDuration - (currentDuration / viewCountAsPercent));
}
}
<file_sep>/core/src/test/java/com/blundell/quicksand/DurationCalculatorTest.java
package com.blundell.quicksand;
import com.blundell.quicksand.viscosity.ViscosityInterpolator;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
public class DurationCalculatorTest {
@Mock
ViscosityInterpolator mockViscosity;
private DurationCalculator calc;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
calc = new DurationCalculator();
}
@Test
public void givenActHasDurationZeroWhenDurationCalculatedThenCalculatedDurationIsZero() throws Exception {
long currentDuration = 0L;
long duration = calc.calculateNewDuration(mockViscosity, 0, currentDuration);
assertThat(duration).isEqualTo(0L);
}
@Test
public void givenActViewedForFirstTimeWhenDurationCalculatedThenCalculatedDurationIsCurrentDuration() throws Exception {
long currentDuration = 50L;
long duration = calc.calculateNewDuration(mockViscosity, 0, currentDuration);
assertThat(duration).isEqualTo(currentDuration);
}
@Test
public void givenAnActWhenDurationCalculatedThenCalculatedDurationIsDelegatedToTheViscosity() throws Exception {
int timesTransitionViewed = 1;
long currentDuration = 50L;
calc.calculateNewDuration(mockViscosity, timesTransitionViewed, currentDuration);
verify(mockViscosity).calculateDuration(currentDuration, timesTransitionViewed);
}
}
<file_sep>/demo/src/main/java/com/blundell/quicksand/demo/MainActivity.java
package com.blundell.quicksand.demo;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.blundell.quicksand.Quicksand;
import com.blundell.quicksand.demo.activitytransition.FromHereActivity;
import com.blundell.quicksand.demo.amazeanimation.ExplodeAnimation;
import com.blundell.quicksand.demo.simpleanimation.SimpleAnimationActivity;
import com.blundell.quicksand.demo.viewanimation.ViewAnimateActivity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button_main_simple_demo).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SimpleAnimationActivity.class);
startActivity(intent);
}
});
findViewById(R.id.button_main_view_property_demo).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ViewAnimateActivity.class);
startActivity(intent);
}
});
findViewById(R.id.button_main_transition_demo).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
String message = getString(R.string.message_feature_unavailable_below_X, "Lollipop");
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(MainActivity.this, FromHereActivity.class);
startActivity(intent);
}
}
});
findViewById(R.id.button_main_reset_all).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Quicksand.resetTrap(ExplodeAnimation.KEY_ANIMATION_SET);
Quicksand.resetTrap(FromHereActivity.KEY_MY_ACTIVITY_TRANSITION);
Quicksand.resetTrap(ViewAnimateActivity.KEY_ANIM_SHOW_HIDE);
Toast.makeText(MainActivity.this, R.string.message_reset_traps, Toast.LENGTH_SHORT).show();
}
});
}
}
| 2e7950d3da119d070a52823fd20902fc11427e4e | [
"Markdown",
"Java",
"Gradle"
] | 16 | Java | beasonshu/QuickSand | 5837d32f641d48ce4f784df7a1a7933c50ab5fd3 | 6cb46e3393907cd880293edee3f9339c672f72f2 |
refs/heads/master | <repo_name>sfdevelop/isupport<file_sep>/bitrix/templates/is/js/custom3860.js
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
$(document).ready(function() {
$('.modalbox').fancybox({
afterLoad: function (instance, current) {
//$(document).on('click', '.filter__title', function () {
$(".opdebdel").remove();
if($("#is-order-block2 .pt30").hasClass("hideformaac"))
$("#is-order-block2 .pt30").removeClass("hideformaac");
//});
}
});
// $(".modalbox").fancybox();
/*$("#f_contact").submit(function(){ return false; });
$("#f_send").on("click", function(){
// тут дальнейшие действия по обработке формы
// закрываем окно, как правило делать это нужно после обработки данных
$("#f_contact").fadeOut("fast", function(){
$(this).before("<p><strong>Ваше сообщение отправлено!</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
});*/
//init
//$('[data-toggle="popover"]').popover();
$('.is-order-input[name="user_phone"]').mask("+7 (999) 999-99-99");
$('.callback-phone').mask("+7 (999) 999-99-99");
/*
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
$.fn.setCursorPosition = function(pos) {
if ($(this).get(0).setSelectionRange) {
console.log($(this).get(0));
$(this).get(0).setSelectionRange(pos, pos);
} else if ($(this).get(0).createTextRange) {
console.log($(this).get(0));
var range = $(this).get(0).createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
};
$('.is-order-input[name="user_phone"]').click(function() {
console.log($(this).getCursorPosition());
var countCursor = 4;
var valphone = $(this).val();
var valphone = replaceAll(valphone, "_", "");
var valphone = replaceAll(valphone, "-", "");
var valphone = replaceAll(valphone, "(", "");
var valphone = replaceAll(valphone, ")", "");
var valphone = replaceAll(valphone, " ", "");
var countphone = valphone.length;
countCursor = countphone+2;
if(countCursor>=7)
countCursor = countCursor+2;
if(countCursor>=12)
countCursor = countCursor+1;
if(countCursor>=15)
countCursor = countCursor+1;
console.log(valphone+"-"+countCursor);
$(this).setCursorPosition(countCursor); // set position number
});*/
/*$('.is-order-input[name="user_phone"]').focus(function() {
$(this).target.setSelectionRange(0,0);
console.log( "Handler for .focus() called." );
});*/
var _problem_id=0;
if ($(window).width() < 768){
$('.is-main-header').append($('.is-main-header .is-slider-layer'));
}
if ($(".tag_item").length > 0 && $(window).width() > 767) {
setTimeout(function() {
maxItemHeight = 0;
$(".tag_item").each(function(){
heightItem = $(this).height();
if (heightItem > maxItemHeight) {
maxItemHeight = heightItem;
}
});
$(".tag_item").each(function(){
$(this).css("height", maxItemHeight+40 + "px");
});
}, 1000);
}
// --------------------------------------------------------------------------
$('.menu-mb').on('click', function(event)
{
$('.menu-mb-wrapper').toggleClass('menu-active');
$(this).toggleClass('active');
if ($(this).hasClass('active'))
{
$('body').css({'overflow':'hidden'});
}else{
$('body').css({'overflow':'auto'});
}
});
$(".vacancy-item-title-h3").on("click", function(){
$(this).parent().toggleClass("active");
})
// --------------------------------------------------------------------------
$('body').click(function(e){
var el = e.target.parentElement;
if (e.target.className != 'is-problems-img' && e.target.className != 'is-problems-text')
{
$('.is-problems li .is-problems-img').popover('hide');
}
if ($(el).parents('.is-iphone-slide').length==0)
{
$('.is-iphone-slider .is-iphone-slide-a').popover('hide');
}
});
// -------------------------------------------------------------------------
/*var gallery_iphone_opt = {"prevNextButtons":true, "pageDots": false, "freeScroll": true, "cellAlign": 'left', "contain": true, 'arrowShape': 'M70,8c0.5,0,1,0.2,1.4,0.6c0.8,0.8,0.8,2,0,2.8L32.8,49.9l38.6,38.7c0.8,0.8,0.8,2,0,2.8c-0.8,0.8-2,0.8-2.8,0l-40-40.1c-0.4-0.4-0.6-0.9-0.6-1.4c0-0.5,0.2-1,0.6-1.4l40-39.9C69,8.2,69.5,8,70,8z'};
var $gallery_iphone = $('.is-iphone-slider').flickity(gallery_iphone_opt);
var isFlickity = true;
if ($('.is-iphone-slider').data('count')>10 || $(window).width() < 768){
//$('[data-toggle="popover"]').popover();
$gallery_iphone.flickity(gallery_iphone_opt);
isFlickity = true;
}else{
$gallery_iphone.flickity('destroy');
isFlickity = false;
}*/
/*$gallery_iphone.on( 'staticClick', function( event, pointer, cellElement, cellIndex ) {
if ( !cellElement ) {
return;
}*/
//window.location.href = $( cellElement ).data('detail');
/*});*/
/* window.onresize = function(event) {
if ($(window).width() < 768){
if (!isFlickity) $gallery_iphone.flickity(gallery_iphone_opt);
isFlickity = true;
}else{
if (isFlickity) $gallery_iphone.flickity('destroy');
isFlickity = false;
}
}; */
// ========================================================================
//animation
/*if ($('.is-animation-appear').length)
{
//isScrolledIntoView
delay = 200;
var timerx = [];
$.each($('.is-animation-appear:not(.is-animation-appear-active)'),function(index)
{
var elem = $(this);
if (isScrolledIntoView(elem))
{
setTimeout(function(){elem.addClass('is-animation-appear-active'); }, delay+=150);
}
});
}*/
// ========================================================================
$(window).on('scroll', function()
{
if ($('.is-prlx').length && $(window).width() > 800){
var scroll = $(window).scrollTop();
var pos = $('.is-prlx').offset().top;
if (Math.abs(scroll-pos) < 1000){
/*var bgpos = $('.is-prlx').css('background-position').split(" ");*/
var val = 0;
if($('.is-prlx').get(0).tagName == 'IMG')
{
direction = $('.is-prlx').data('direction');
val = direction + scroll*0.25;
$('.is-prlx').css({'bottom': val + 'px'});
}else
{
val = pos - scroll*0.5;
$('.is-prlx').css({'background-position': '50% ' + val + 'px'});
}
}
}
/*if ($('.is-animation-appear:not(.is-animation-appear-active)').length)
{
delay = 200;
$.each($('.is-animation-appear:not(.is-animation-appear-active)'), function(index)
{
var elem = $(this);
if (isScrolledIntoView(elem))
{
setTimeout(function(){elem.addClass('is-animation-appear-active');}, delay+=150);
}
});
}*/
});
// ========================================================================
// iPhone slider
/*
$('.is-iphone-slider .is-iphone-slide ').on('click', function()
{
var id = $(this).data('id');
var name = $(this).data('name');
var detail = $(this).data('detail');
var el = $(this);
if (_problem_id == 0)
{
window.location.href = detail;
}else{
$('.is-iphone-slider .is-iphone-slide ').find('.is-iphone-slide-a').popover('destroy');
$('.is-iphone-slider .is-iphone-slide ').removeClass('active').addClass('inactive');
$(el).removeClass('inactive').addClass('active');
$('.is-order-btn').on('click', order_btn_click);
$.ajax({
method: 'POST',
url: '/remont/ajax.php',
data: {id:id, name:name, detail:detail, problem:_problem_id},
cache: false,
success:function(data){
if (data){
var d = JSON.parse(data);
console.log(d);
$(el).find('.is-iphone-slide-a').popover({trigger: 'manual',content: d});
$(el).find('.is-iphone-slide-a').popover('toggle');
$('.is-order-btn').on('click', order_btn_click);
}
}
});
}
});
*/
// ===========================================================================
// REPAIR
$('.courier-input').on('click', function() {
if($(this).is(':checked')) {
$('.address-input').attr('style', 'display: block;');
$('.mobile-address .mobile-checkbox').addClass('mobile-checkbox-pos');
} else {
$('.address-input').attr('style', 'display: none;');
$('.mobile-address .mobile-checkbox').removeClass('mobile-checkbox-pos');
}
});
if(window.location.href.match('problem') && $('.is-order-form .is-order-textarea[name="MESSAGE"]').val() == '') {
$('.is-order-form .is-order-textarea[name="MESSAGE"]').val($('.service-problem-post .text-center h1').html());
}
$('.problem-item-btn').on('click', function() {
$('.is-order-form .is-order-input[name="user_model"]').val($(this).data('service'));
$('html, body').animate({
scrollTop: $('#is-order-block ').offset().top - 50
}, 700);
});
// problems
/*
$('.is-problems li ').on('click', function()
{
_problem_id = $(this).data('id');
$(this).find('.is-problems-img').popover('toggle');
$('.is-problems li ').not(this).find('.is-problems-img').popover('hide');
if ($(this).hasClass('active')){
$('.is-problems li').removeClass('inactive active');
_problem_id = 0;
}else{
$('.is-problems li').removeClass('active').addClass('inactive');
$(this).removeClass('inactive').addClass('active');
}
});
*/
$('.is-problems.is-inner li ').on('click', function()
{
var flag = 0, loc;
var element = $(this);
var problem_id = element.data('id');
var product_id = element.data('product-id');
problem_id = problem_id.toString();
//console.log(_problem_id);
var el = $(this).find('.is-problems-img');
$('.is-problems.is-inner li .is-problems-img').popover('destroy');
$('.service-price-list .service-item').removeClass('active');
// count of service item
$('.service-price-list .service-item').each(function()
{
var arr_id = $(this).data('problems_id');
arr_id = arr_id.toString().split(',');
if ($.inArray(problem_id, arr_id) >= 0)
{
flag++;
$(this).addClass('active');
loc = $(this);
}
});
if (flag == 1)
{
$('html, body').animate({
scrollTop: loc.parent('.service-price-block-content').parent('.service-price-block').offset().top - 60
}, 700);
}else
if (flag > 1){
$.ajax({
method: 'POST',
url: '/remont/ajax_service.php',
data: {id:product_id, problem:problem_id},
cache: false,
success:function(data){
if (data){
var d = JSON.parse(data);
$(el).popover({trigger: 'manual',content: d});
$(el).popover('toggle');
$('.is-pop-link').on('click', function()
{
$('html, body').animate({
scrollTop: $('.service-item.active').parent('.service-price-block-content').parent('.service-price-block').offset().top - 60
}, 700);
});
}
}
});
}
});
//order button
$('.service-price-list .service-item-btn').click(function()
{
var product_name = $(this).data('product');
var service_title= $(this).parent('.service-item').find('.service-item-content').find('.service-item-text').find('.service-item-title').text();
$('.is-order-form .is-order-input[name="user_model"]').attr('placeholder', '');
$('.is-order-form .is-order-input[name="user_model"]').val(product_name);
$('.is-order-form .is-order-textarea').val($('.is-order-form .is-order-textarea').val() + '- ' + service_title + '\n');
$('html, body').animate({
scrollTop: $('#is-order-block ').offset().top - 50
}, 700);
});
$('.is-order-form .is-order-input[name="user_model"]').change(function() {
if($(this).val() == '') {
$(this).attr('placeholder', 'Модель телефона')
}else {
$(this).attr('placeholder', '')
}
});
$('.is-order-form .is-order-input[name="user_phone"]').change(function() {
if($(this).val() == '') {
$(this).attr('placeholder', 'Контактный телефон')
}else {
$(this).attr('placeholder', '')
}
});
// collapsible service item block
$('.service-block-collapse').on('click', function()
{
$('.service-price-block-content[data-id=' + $(this).data('id') + ']').slideToggle();
text = $(this).data('text');
$(this).data('text', $(this).text());
$(this).text(text);
});
var startTime = new Date();
$('.is-order-form').on('submit', function() {
endTime = new Date();
if((endTime - startTime) < 10000) return false;
});
// ===========================================================================
// MODDING
var overflag = false;
$('.is-modding-select-colors .is-modding-color').click(function()
{
$('.is-modding-select-colors .is-modding-color').removeClass('active');
$(this).addClass('active');
$('#is-phone-color').text($(this).data('color'));
$('.is-modding-phones > img').attr('src', '/images/modding/color-iphone-' + $(this).data('id') + '.jpg');
$('.is-order-input[name="MESSAGE"]').val($(this).data('color'));
});
/*$('.is-modding-select-colors .is-modding-color').on('mouseover',function()
{
overflag = true;
var thisid = $(this).data("id");
$('#is-phone-color').text($(this).data('color'));
// $('.is-modding-clone img').hide();
// $('.is-modding-clone img[data-id=' + thisid + ']').show();
$('.is-modding-clone img[data-id=' + thisid + ']').addClass('active');
setTimeout(function()
{
$('.is-modding-helper img').remove();
$('.is-modding-helper').append('<img src="/images/modding/color-iphone-' + thisid + '.jpg" />');
}, 1000);
});*/
/*$('.is-modding-select-colors .is-modding-color').on('mouseout',function()
{
overflag = false;
$('.is-modding-clone img').removeClass('active');
//-----------------------------------------
setTimeout(function()
{
$('.is-modding-helper img').fadeOut();
if (overflag == false){
$('#is-phone-color').text($('.is-modding-select-colors .is-modding-color.active').data('color'));
}
}, 1000);
});*/
$('.is-modding-phones img').click(function()
{
id = $('.is-modding-select-colors .is-modding-color.active').data('id');
if($('.is-modding-select-colors .is-modding-color.active').is(':last-child'))
{
id_next = $('.is-modding-select-colors .is-modding-color:first-child').data('id');
}else{
id_next = $('.is-modding-select-colors .is-modding-color.active').next().data('id');
}
$('.is-modding-phones > img').attr('src', '/images/modding/color-iphone-' + id_next + '.jpg');
$('.is-modding-clone').removeClass('active');
setTimeout(function()
{
$('.is-modding-clone img').hide();
$('.is-modding-clone img[data-id=' + id_next + ']').show();
$('.is-modding-clone').addClass('active');
}, 500);
$('.is-modding-select-colors .is-modding-color').removeClass('active');
$('.is-modding-select-colors .is-modding-color[data-id=' + id_next + ']').addClass('active');
$('#is-phone-color').text($('.is-modding-select-colors .is-modding-color.active').data('color'));
$('.is-order-input[name="MESSAGE"]').val($('.is-modding-select-colors .is-modding-color.active').data('color'));
});
// ===========================================================================
// ABOUT PAGE
if ($('#is-about-diagram').length)
{
new Chartist.Line('#is-about-diagram', {
labels: ['2014', '8', '9', '10', '11', '12', '2015', '2', '3', '4', '5', '6'],
series: [
{
name: 'Посещаемость',
data: [475, 706, 1376, 1805, 1815, 1591, 1449, 1470, 1783, 1941, 1491, 1674]
}
]
});
var $chart = $('.ct-chart');
var $toolTip = $chart
.append('<div class="tooltip"></div>')
.find('.tooltip')
.hide();
$chart.on('mouseenter', '.ct-point', function() {
var $point = $(this),
value = $point.attr('ct:value'),
seriesName = $point.parent().attr('ct:series-name');
$toolTip.html(seriesName + '<br>' + value).show();
});
$chart.on('mouseleave', '.ct-point', function() {
$toolTip.hide();
});
$chart.on('mousemove', function(event) {
$toolTip.css({
left: (event.offsetX || event.originalEvent.layerX) - $toolTip.width() / 2 - 12,
top: (event.offsetY || event.originalEvent.layerY) - $toolTip.height() - 40
});
});
}
if($('#is-about-chart').length)
{
var data = {
labels: ['Bananas', 'Apples', 'Grapes'],
series: [20, 15, 40]
};
var options = {
labelInterpolationFnc: function(value) {
return value[0]
}
};
var responsiveOptions = [
['screen and (min-width: 640px)', {
chartPadding: 30,
labelOffset: 100,
labelDirection: 'explode',
labelInterpolationFnc: function(value) {
return value;
}
}],
['screen and (min-width: 1024px)', {
labelOffset: 80,
chartPadding: 20
}]
];
new Chartist.Pie('#is-about-chart', data, options, responsiveOptions);
}
// ================================================================================
// SHOP FILTER
$('.is-shop-filter-link').click(function()
{
if (!$(this).data('status'))
{
$('.is-shop-products').removeClass('col-sm-12').addClass('col-sm-8');
$('.is-shop-products .col-sm-4').addClass('col-sm-6').removeClass('col-sm-4');
$('.is-shop-products .clearfix').remove();
$('.is-shop-products .col-sm-6:nth-child(2n)').after('<div class="clearfix"></div>');
if ($(window).width() < 768){
$('.is-shop-products').before($('.is-shop-filter-wrapper'));
}else{
$('.is-shop-products').after($('.is-shop-filter-wrapper'));
}
$('.is-shop-filter-wrapper').fadeIn(200).removeClass('dn');
$(this).data('status', 1);
}else{
$('.is-shop-products').removeClass('col-sm-8').addClass('col-sm-12');
$('.is-shop-products .col-sm-6').addClass('col-sm-4').removeClass('col-sm-6');
$('.is-shop-products .clearfix').remove();
$('.is-shop-products .col-sm-4:nth-child(3n)').after('<div class="clearfix"></div>');
$('.is-shop-filter-wrapper').fadeOut(200);
$(this).data('status', 0);
}
});
$('.is-filter-clear').click(function()
{
$('.is-shop-filter input[type="checkbox"]').attr('checked', false);
});
// ================================================================================
// PRODUCT CARD
$('.is-bxslider').bxSlider({
pagerCustom: '#bx-pager',
onSliderLoad: function(){
$('.is-bxslider').animate({
opacity: 1,
}, 200);
}
});
$('.is-shop-order-btn').click(function()
{
var p = $(this).data('product');
$('.is-order-input[name="user_model"]').val(p.price);
$('.is-order-textarea').val(p.name);
});
$('.is-order-form-ajax').submit(function(e) { // Обработка отправки данных формы
e.preventDefault(); // Сброс стандартного обработчика формы
formData = $(this).serialize() + "&submit=Отправить"; // Сохраняем массив введенных данных включая значение кнопки "Отправить", без этого компонент Битрикса не примет данные
target = $(this).data('target');
$.post( // Отправим POST запрос серверу
$(this).attr('action'), // Текущая страница с дописанным параметром - по нему подключается пустой шаблон с одним #WORK_AREA#
formData,
function(response){
$('body').append('<div class="tmp dn"></div>');
$('.tmp').html(response);
//console.log(response);
if ($('.tmp').find('.okText').length){
$('#' + target + ' .is-response').html($('.tmp').find('.okText'));
$('.is-order-input[name="user_model"]').val('');
$('.is-order-textarea').val('');
}
if ($('.tmp').find('.errortext').length)
$('#' + target + ' .is-response').html($('.tmp').find('.errortext'));
$('.tmp').remove();
}
);
return false;
});
// =================================================================================================
$('.is-order-btn').on('click', order_btn_click);
$('.is-remont-status-btn').on('click', status_btn_click);
function order_btn_click(){
if ($('#is-order-block').length)
{
$('html, body').animate({
scrollTop: $('#is-order-block').offset().top - 50
}, 600);
//console.log('exist');
}else{
if ($(window).width() < 768)
{
window.location.href = 'order-form/index.html';
}else
{
$('.is-order-input[name="user_model"]').val('');
$('.is-order-textarea').val('');
$('#remontOrderModal').modal('show');
}
}
if ($(this).data('product'))
{
$('.is-order-input[name="user_model"]').val($(this).data('product'));
}
if (typeof $(this).data('detail') !== typeof undefined)
{
$('.is-order-textarea[name="MESSAGE"]').val($(this).data('detail'));
}
}
function status_btn_click(){
if ($('.is-remont-status').length)
{
$('html, body').animate({
scrollTop: $('.is-remont-status').offset().top - 180
}, 600);
//console.log('exist');
}else{
$('#remontStatusModal').modal('show');
}
}
});
function isScrolledIntoView(elem)
{
var $elem = elem;
var $window = $(window);
var docViewTop = $window.scrollTop();
var docViewBottom = docViewTop + $window.height();
var elemTop = $elem.offset().top;
var elemBottom = elemTop + $elem.height();
/* console.log('elemTop ' + elemTop);
console.log('elemBottom ' + elemBottom);
console.log('docViewTop ' + docViewTop);
console.log('docViewBottom ' + docViewBottom); */
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
/* function mapinit(ymaps){
var xy = $('#YMapsID').data('xy').split(',');
var pin = $('#YMapsID').data('pin');
var sizes = $('#YMapsID').data('pinsizes').split(',');
var shift = [-sizes[0]/2,-sizes[1]];
var linecolor = $('#YMapsID').data('linecolor');
//var placemark = new YMaps.Placemark(new YMaps.GeoPoint(xy[1], xy[0]));
var myPlacemark = new ymaps.Placemark(xy, {}, {
iconLayout: 'default#image',
iconImageHref: pin,
iconImageSize: sizes,
iconImageOffset: shift
});
myMap = new ymaps.Map("YMapsID", {
center: xy,
zoom: 17
});
var myPolyline = new ymaps.Polyline(
[[55.758514,37.624391],[55.759309,37.625433],[55.7594,37.62554],[55.758792,37.626582]],
{},
{
strokeWidth: 5,
strokeColor: linecolor,
}
);
myMap.geoObjects.add(myPlacemark);
myMap.geoObjects.add(myPolyline);
myMap.behaviors.disable('scrollZoom');
} */
$(document).ready(function() {
$(".is-header-callback-link").on("click", function(){
$('#callback-modal').modal('show');
})
$("#callback-form").submit(function(e){
var form = $(this);
var name = $("input[name='callback-name']").val();
var phone = $("input[name='callback-phone']").val();
e.preventDefault();
var data = form.serialize();
if( phone!="" && name!="" ){
$.ajax({
type: 'POST',
url: '/seo/callback-handler.php',
data: data,
dataType : "json",
beforeSend: function(data) {
form.find('input[type="submit"]').attr('disabled', 'disabled');
},
success: function(data){
if (data.status != 1) {
form.find('#error-obr-zvon').replaceWith('<span class="err-send">'+data.msg+'</span>');
} else { // eсли всe прoшлo oк
gtag('event', 'custom', { 'event_category': 'zakazali_zvonok', 'event_action': document.URL, }); yaCounter15693190.reachGoal('zakazali_zvonok');console.log('zakazali_zvonok');
$("#callback-modal").modal('hide');
$("#sent").modal('show');
setTimeout(function() {
$("#sent").modal('hide');
}, 3000);
}
},
complete: function(data) {
form.find('input[type="submit"]').prop('disabled', false);
}
});
}
return false;
});
})
function showAddForm(nameClass, hideClass) {
$("."+nameClass).show("slow");
$("."+hideClass).hide();
}
$( function()
{
if($( 'audio' ).length > 0) {
$( 'audio' ).audioPlayer();
}
});
$(document).ready(function(){
if($(".serviceHashLink").length > 0) {
$(".serviceHashLink").on("click", function (event) {
event.preventDefault();
var id = $(this).attr('href'),
top = $(id).offset().top - 65;
$('body,html').animate({scrollTop: top}, 1500);
});
}
$("#back-top").hide();
windowHeight = $(window).height();
windowWidth = $(window).width();
$(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > windowHeight / 2 && windowWidth > 980) {
$('#back-top').fadeIn();
} else {
$('#back-top').fadeOut();
}
});
$('#back-top').click(function () {
$('body, html').animate({
scrollTop: 0
}, "slow");
return false;
});
});
$("form.addCommentReply").on("submit", function(e){
var form = $(this);
e.preventDefault();
var data = form.serialize();
$.ajax({
type: 'POST',
url: '/ajax/addReply.php',
data: data,
dataType : "json",
beforeSend: function(data) {
form.find('input[type="submit"]').attr('disabled', 'disabled');
},
success: function(data){
if (data.status != 1) {
form.append('<span class="err-send">'+data.msg+'</span>');
} else { // eсли всe прoшлo oк
form.replaceWith('<span class="ok-send">'+data.msg+'</span>');
}
},
complete: function(data) {
form.find('input[type="submit"]').prop('disabled', false);
}
});
return false;
})
})
<file_sep>/bitrix/js/star.notification/notif_scripts.js
var screenw = $(window).width();
var screenh = $(window).height();
var scrolltop = $(window).scrollTop();
var last_scrolltop = 0;
// Popups
var pop_scr_m_t;
var pop_scr_auto_m_t;
$('.notif_popup_close, .notif_popup_back').click(function(){
$('.notif_popup, .notif_popup_back').removeClass('opened').fadeOut(300);
});
function pop_scr_func() {
if ( screenw < 750 ) { pop_scr_m_t = 20; } ;
if ( screenw > 750 && screenw < 1100 ) { pop_scr_m_t = 30; };
if ( screenw > 1100 ) { pop_scr_m_t = 50; };
};
function pop_scr_sizes() {
var popup_opened = $('.notif_popup.opened');
popup_opened.css('height','auto');
var pop_scr_auto_h = popup_opened.outerHeight();
var pop_scr_auto_h_w_m = pop_scr_auto_h + ( pop_scr_m_t * 2 );
var pop_scr_top = scrolltop + pop_scr_m_t;
popup_opened.attr('pop_scr_top',''+pop_scr_top+'');
if ( pop_scr_auto_h_w_m > screenh ) {
popup_opened.css({
'position':'absolute',
'top':''+pop_scr_top+'px',
'margin-top':'0'
});
} else {
pop_scr_auto_m_t = pop_scr_auto_h / 2;
popup_opened.css({
'position':'fixed',
'top':'50%',
'margin-top':'-'+pop_scr_auto_m_t+'px'
});
}
};
function pop_scr_scroll() {
var popup_opened = $('.notif_popup.opened');
var pop_scr_top = parseInt(popup_opened.attr('pop_scr_top'));
var pop_scr_auto_h = popup_opened.outerHeight();
var pop_scr_auto_h_w_m = pop_scr_auto_h + ( pop_scr_m_t * 2 );
if ( last_scrolltop > scrolltop && pop_scr_auto_h_w_m > screenh && scrolltop < ( pop_scr_top - pop_scr_m_t ) ) {
var new_pop_scr_top = scrolltop + pop_scr_m_t;
popup_opened.css({
'position':'absolute',
'top':''+pop_scr_top+'px'
}).attr('pop_scr_top',''+new_pop_scr_top+'');
};
};
$(document).ready(function(){
screenw = $(window).width();
screenh = $(window).height();
scrolltop = $(window).scrollTop();
pop_scr_func();
pop_scr_sizes();
pop_scr_scroll();
});
$(window).scroll(function() {
scrolltop = $(window).scrollTop();
pop_scr_scroll();
last_scrolltop = scrolltop;
});
$(window).on('resize', function(){
screenw = $(window).width();
screenh = $(window).height();
scrolltop = $(window).scrollTop();
pop_scr_func();
pop_scr_sizes();
});
| 6e96d0d081e9dfde340990ee1b776083da2aadba | [
"JavaScript"
] | 2 | JavaScript | sfdevelop/isupport | 0af15903af694aeecdf54ce8f9802cb7a63c905d | 4dc86f878ff5db9be36cb18af878eac70d7af417 |
refs/heads/development | <file_sep>import React from 'react';
import { addMinutes } from 'date-fns';
import { connect } from 'react-redux';
import { PropTypes } from 'prop-types';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Options from '../Components/Options';
import BookRoom from '../Components/BookRoom';
import ConferenceRooms from './ConferenceRooms';
import UserBookings from './UserBookings';
import AllBookings from './AllBookings';
import RoomBookings from './RoomBookings';
import Welcome from '../Components/Welcome';
import {
logIn,
logOut,
loadRooms,
loadBookings,
createBooking,
clearBookings,
deleteBooking,
} from '../actions/index';
import Login from '../Components/Login';
class App extends React.Component {
constructor() {
super();
this.logOut = this.logOut.bind(this);
this.handleChangeSelectedRoom = this.handleChangeSelectedRoom.bind(this);
this.handleLogIn = this.handleLogIn.bind(this);
this.handleBooking = this.handleBooking.bind(this);
this.handleBookingChange = this.handleBookingChange.bind(this);
this.handleSearchBookingChange = this.handleSearchBookingChange.bind(this);
this.searchBookingByDate = this.searchBookingByDate.bind(this);
this.clearLocalBookings = this.clearLocalBookings.bind(this);
this.deleteBooking = this.deleteBooking.bind(this);
this.changeActivePage = this.changeActivePage.bind(this);
this.state = {
activePage: 'home',
newBooking: {
bookingId: '',
room: '',
date: '',
time: '',
duration: '30',
},
searchBooking: {
bookingId: '',
userId: '',
roomId: '',
start: '',
finish: '',
},
};
}
changeActivePage(newActivePage) {
this.setState({
activePage: newActivePage,
});
}
logOut() {
const { logOut } = this.props;
this.setState({
newBooking: {
bookingId: '',
room: '',
date: '',
time: '',
duration: '30',
},
searchBooking: {
bookingId: '',
userId: '',
roomId: '',
start: '',
finish: '',
},
});
logOut();
}
handleLogIn() {
const { logIn } = this.props;
const username = document.getElementById('user-name').value;
const password = document.getElementById('user-password').value;
logIn(username, password);
}
searchBooking(roomId = null, userId = null,
lowLimit = null,
highLimit = null) {
const { searchBooking } = this.props;
searchBooking(roomId, userId, lowLimit, highLimit);
}
searchBookingByDate(event) {
const { searchBooking } = this.state;
this.searchBooking(searchBooking.roomId, null, searchBooking.start, searchBooking.finish);
event.preventDefault();
}
clearLocalBookings() {
const { clearBookings } = this.props;
clearBookings();
}
handleBooking(event) {
const { bookRoom, user } = this.props;
const { newBooking } = this.state;
const { date } = newBooking;
const { room } = newBooking;
const { time } = newBooking;
const { duration } = newBooking;
const start = new Date(Date.parse(`${date} ${time}`));
const finish = addMinutes(start, duration);
bookRoom(room, user.id, start, finish);
event.preventDefault();
}
deleteBooking(bookingId) {
const { deleteBooking } = this.props;
deleteBooking(bookingId);
}
handleChangeSelectedRoom(roomId) {
this.setState({
newBooking: {
room: roomId,
},
});
}
handleChangeSelectedBooking(bookingId) {
this.setState({
newBooking: {
booking: bookingId,
},
});
}
handleBookingChange(event) {
const { newBooking } = this.state;
let newState = {};
switch (event.target.id) {
case 'book-date':
newState = {
...newBooking,
date: event.target.value,
};
break;
case 'book-time':
newState = {
...newBooking,
time: event.target.value,
};
break;
case 'book-duration':
newState = {
...newBooking,
duration: event.target.value,
};
break;
default:
newState = {
...newBooking,
};
}
this.setState({
newBooking: newState,
});
}
handleSearchBookingChange(event) {
const { searchBooking } = this.state;
let newState = {};
switch (event.target.id) {
case 'start-book-date':
newState = {
...searchBooking,
start: event.target.value,
};
break;
case 'finish-book-date':
newState = {
...searchBooking,
finish: event.target.value,
};
break;
case 'user-id-search':
newState = {
...searchBooking,
userId: event.target.value,
};
break;
case 'room-id-search':
newState = {
...searchBooking,
roomId: event.target.value,
};
break;
default:
newState = {
userId: '',
roomId: '',
start: '',
finish: '',
};
}
this.setState({
searchBooking: newState,
});
}
render() {
const {
user,
rooms,
bookings,
loadRooms,
searchBooking,
} = this.props;
const { activePage, newBooking } = this.state;
return (
<Router>
{
user.loggedIn ? (
<div className="App">
<Options
activePage={activePage}
switchPage={this.changeActivePage}
logOut={this.logOut}
clearBookings={this.clearLocalBookings}
/>
<Switch>
<Route path="/" exact component={Welcome} />
<Route
path="/conference_rooms"
render={() => (
<ConferenceRooms
loadRooms={loadRooms}
conferenceRooms={rooms.rooms}
/>
)}
/>
<Route
path="/search_bookings"
render={() => (
<AllBookings
loadBookings={this.searchBookingByDate}
bookings={bookings.bookings}
handleChange={this.handleSearchBookingChange}
user={user}
deleteBooking={this.deleteBooking}
changeBooking={this.handleChangeSelectedBooking}
/>
)}
/>
<Route
path="/my_bookings"
render={() => (
<UserBookings
user={user}
loadBookings={searchBooking}
bookings={bookings.bookings}
deleteBooking={this.deleteBooking}
changeBooking={this.handleChangeSelectedBooking}
/>
)}
/>
{rooms.rooms.length > 0 && rooms.rooms.map(room => (
<Route
key={`book-room-${room.id}-link`}
path={`/book_room_${room.id}`}
render={() => (
<BookRoom
submit={this.handleBooking}
handleChange={this.handleBookingChange}
room={room}
bookData={newBooking}
posted={bookings.posted}
changeRoom={this.handleChangeSelectedRoom}
/>
)}
/>
))}
{rooms.rooms.length > 0 && rooms.rooms.map(room => (
<Route
key={`bookings-room-${room.id}-link`}
path={`/bookings_room_${room.id}`}
render={() => (
<RoomBookings
room={room}
loadBookings={searchBooking}
bookings={bookings.bookings}
deleteBooking={this.deleteBooking}
changeBooking={this.handleChangeSelectedBooking}
user={user}
/>
)}
/>
))}
</Switch>
</div>
) : (
<div className="App">
<Login clickLogIn={this.handleLogIn} user={user} />
</div>
)
}
</Router>
);
}
}
App.propTypes = {
user: PropTypes.shape({
loggedIn: PropTypes.bool.isRequired,
pending: PropTypes.bool.isRequired,
name: PropTypes.string,
id: PropTypes.number,
}).isRequired,
rooms: PropTypes.shape({
pending: PropTypes.bool,
rooms: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number,
size: PropTypes.number,
projector: PropTypes.bool,
})),
}).isRequired,
bookings: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number,
userId: PropTypes.number,
roomId: PropTypes.number,
start: PropTypes.string,
finish: PropTypes.string,
})).isRequired,
logOut: PropTypes.func.isRequired,
logIn: PropTypes.func.isRequired,
loadRooms: PropTypes.func.isRequired,
clearBookings: PropTypes.func.isRequired,
searchBooking: PropTypes.func.isRequired,
bookRoom: PropTypes.func.isRequired,
deleteBooking: PropTypes.func.isRequired,
};
const mapStateToProps = state => ({
user: state.user,
rooms: state.rooms,
bookings: state.bookings,
});
const mapDispatchToProps = dispatch => ({
logIn: (username, password) => dispatch(logIn(username, password)),
logOut: () => dispatch(logOut()),
loadRooms: () => dispatch(loadRooms()),
clearBookings: () => dispatch(clearBookings()),
searchBooking: (roomId = null,
userId = null,
lowLimit = null,
highLimit = null) => dispatch(loadBookings(roomId, userId, lowLimit, highLimit)),
bookRoom: (roomId,
userId,
start,
finish) => dispatch(createBooking(roomId, userId, start, finish)),
deleteBooking: bookingId => dispatch(deleteBooking(bookingId)),
});
export default connect(mapStateToProps, mapDispatchToProps)(App);
<file_sep>export const GET_ROOMS_SUCCESS = 'GET_ROOMS_SUCCESS';
export const GET_ROOMS_PENDING = 'GET_ROOMS_PENDING';
export const GET_ROOMS_ERROR = 'GET_ROOMS_ERROR';
export const INITIAL_GET_ROOM_STATE = {
pending: false,
rooms: [],
};
export const CLEAR_LOCAL_BOOKINGS = 'CLEAR_LOCAL_BOOKINGS';
export const GET_BOOKINGS_SUCCESS = 'GET_BOOKINGS_SUCCESS';
export const GET_BOOKINGS_PENDING = 'GET_BOOKINGS_PENDING';
export const GET_BOOKINGS_ERROR = 'GET_BOOKINGS_ERROR';
export const POST_BOOKING_SUCCESS = 'POST_BOOKING_SUCCESS';
export const POST_BOOKING_PENDING = 'POST_BOOKING_PENDING';
export const POST_BOOKING_ERROR = 'POST_BOOKING_ERROR';
export const DELETE_BOOKING_ERROR = 'DELETE_BOOKING_ERROR';
export const DELETE_BOOKING_PENDING = 'DELETE_BOOKING_PENDING';
export const DELETE_BOOKING_SUCCESS = 'DELETE_BOOKING_SUCCESS';
export const INITIAL_GET_BOOKING_STATE = {
pending: false,
bookings: [],
posted: {},
};
export const LOG_IN_SUCCESS = 'LOG_IN_SUCCESS';
export const LOG_IN_PENDING = 'LOG_IN_PENDING';
export const LOG_IN_ERROR = 'LOG_IN_ERROR';
export const LOG_OUT = 'LOG_OUT';
export const INITIAL_USER_STATE = {
pending: false,
loggedIn: false,
name: '',
id: null,
};
export const INITIAL_STORE_STATE = {
rooms: INITIAL_GET_ROOM_STATE,
bookings: INITIAL_GET_BOOKING_STATE,
user: INITIAL_USER_STATE,
};
<file_sep>import {
LOG_IN_ERROR,
LOG_IN_PENDING,
LOG_IN_SUCCESS,
GET_ROOMS_ERROR,
GET_ROOMS_PENDING,
GET_ROOMS_SUCCESS,
GET_BOOKINGS_ERROR,
GET_BOOKINGS_PENDING,
GET_BOOKINGS_SUCCESS,
POST_BOOKING_SUCCESS,
POST_BOOKING_PENDING,
POST_BOOKING_ERROR,
DELETE_BOOKING_ERROR,
DELETE_BOOKING_PENDING,
DELETE_BOOKING_SUCCESS,
LOG_OUT,
CLEAR_LOCAL_BOOKINGS,
} from '../constants';
import {
ApiLogIn,
ApiGetRooms,
ApiGetBookings,
ApiCreateBooking,
ApiDeleteBooking,
} from '../ApiCalls';
const LogInPending = pending => ({
type: LOG_IN_PENDING,
pending,
});
const LogInError = user => ({
type: LOG_IN_ERROR,
name: user.name,
id: user.id,
});
const LogInSuccess = user => ({
type: LOG_IN_SUCCESS,
name: user.name,
id: user.id,
});
export const logIn = (username, password) => async dispatch => {
dispatch(LogInPending());
const response = await ApiLogIn(username, password);
if (response.name) {
return dispatch(LogInSuccess(response));
}
return dispatch(LogInError({ name: null, id: null }));
};
export const logOut = () => ({
type: LOG_OUT,
});
const LoadRoomsPending = pending => ({
type: GET_ROOMS_PENDING,
pending,
});
const LoadRoomsError = error => ({
type: GET_ROOMS_ERROR,
error,
});
const LoadRoomsSuccess = rooms => ({
type: GET_ROOMS_SUCCESS,
rooms,
});
export const loadRooms = () => async dispatch => {
dispatch(LoadRoomsPending());
const response = await ApiGetRooms();
if (response) {
return dispatch(LoadRoomsSuccess(response));
}
return dispatch(LoadRoomsError({
message: 'Could not find rooms',
}));
};
export const clearBookings = () => ({
type: CLEAR_LOCAL_BOOKINGS,
});
const loadBookingsPending = pending => ({
type: GET_BOOKINGS_PENDING,
pending,
});
const loadBookingsSuccess = bookings => ({
type: GET_BOOKINGS_SUCCESS,
bookings,
});
const loadBookingsError = error => ({
type: GET_BOOKINGS_ERROR,
error,
});
export const loadBookings = (roomId = null, userId = null,
lowLimit = null,
highLimit = null) => async dispatch => {
dispatch(loadBookingsPending());
const response = await ApiGetBookings(roomId, userId, lowLimit, highLimit);
if (response) {
return dispatch(loadBookingsSuccess(response));
}
return dispatch(loadBookingsError({
message: 'Could not find any bookings with your parameters',
}));
};
const createBookingPending = pending => ({
type: POST_BOOKING_PENDING,
pending,
});
const createBookingSuccess = posted => ({
type: POST_BOOKING_SUCCESS,
posted,
});
const createBookingError = error => ({
type: POST_BOOKING_ERROR,
error,
});
export const createBooking = (userId, roomId, start, finish) => async dispatch => {
dispatch(createBookingPending());
const response = await ApiCreateBooking(roomId, userId, start, finish);
if (response) {
return dispatch(createBookingSuccess(response));
}
return dispatch(createBookingError({
message: 'Could not find any bookings with your parameters',
}));
};
const deleteBookingPending = pending => ({
type: DELETE_BOOKING_PENDING,
pending,
});
const deleteBookingSuccess = deleted => ({
type: DELETE_BOOKING_SUCCESS,
deleted,
});
const deleteBookingError = error => ({
type: DELETE_BOOKING_ERROR,
error,
});
export const deleteBooking = bookingId => async dispatch => {
dispatch(deleteBookingPending());
const response = await ApiDeleteBooking(bookingId);
if (response) {
return dispatch(deleteBookingSuccess(response));
}
return dispatch(deleteBookingError({
message: 'Could not find any bookings with your parameters',
}));
};
<file_sep># Conference Room Booking Application
This project simulates a conference room booking application from a ficticious company who owns a building. The employees have accounts which can book a conference room at certain hour and day, and their bookings are saved in the system. Each user can create as many bookings as they like, but only the owner of the booking can delete the booking. This projects makes use of an external API created by me, you can find it's repositofy [here](https://github.com/MiguelDP4/meeting-booker-api).
Important note:
There's 20 default users saved in the API. To log in and test the application, simply use one of the 20 default usernames. The default usernames are called tester, plus their user id. For example:
- 'tester1'
- 'tester2'
- 'tester3'
- 'tester4'
The password for all of them is '<PASSWORD>'
## Built With:
- Javascript
- React
- Redux
## Author
👤 **<NAME>**
- Github: [@MiguelDP4](https://github.com/MiguelDP4)
- Twitter: [@Mike_DP4](https://twitter.com/Mike_DP4)
- LinkedIn [<NAME>](https://www.linkedin.com/in/miguel-angel-dubois)
## Features
- The user can log-in using their username and password.
- The user can create a booking to book a meeting room at their preferred time and date.
- The user can check existing bookings.
- The user can search existing bookings by date and room number.
- The user can delete only their own bookings.
## Planned future features
- Secure log-in.
- Use cookies to keep user logged-in.
- Make an admin account to be able to delete anyone's booking.
- Prevent meeting overlap.
## Live Demo
You can check a demo version of the project in [this link](https://meeting-booker.herokuapp.com/).

# 🤝 Contributing
This project is for learning purposes only, I wont accept contributions, though suggestions are welcome.
## Show your support
Give a ⭐️ if you like this project!
## Acknowledgments
- I'm thankful to Microverse for the opportunity to learn.
- Thank you to <NAME>, the author of the user interface, you can check it in [this link](https://www.behance.net/gallery/26425031/Vespa-Responsive-Redesign)
## Running the program
To run the application, you need to run the command
### `npm run dev`
This runs the application in development mode. In this mode, you can open [http://localhost:3000](http://localhost:3000) to view it in the browser and the page will reload automatically if you make changes to the code.
To run the tests of the application you can run
### `npm test`
Which will launch the test runner in the interactive watch mode.
### `npm build`
Builds the app for production to the `build` folder.
It correctly bundles React in production mode and optimizes the build for the best performance.<file_sep>import React from 'react';
import room2 from '../RoomImages/room2.jpg';
const Welcome = () => (
<div className="welcome-page">
<div className="welcome-content">
<h2>WELCOME TO FICTICIOUS ENTERPRISES MEETING ROOM BOOKING UTILITY</h2>
<img src={room2} className="welcome-page-image" alt="welcome_page_background" />
</div>
</div>
);
export default Welcome;
<file_sep>import React, { useEffect } from 'react';
import { format } from 'date-fns';
import { PropTypes } from 'prop-types';
const BookRoom = props => {
const {
handleChange,
submit,
room,
bookData,
changeRoom,
posted,
} = props;
useEffect(() => {
changeRoom(room.id);
}, [room.id, changeRoom]);
const bookingDate = posted.start ? Date.parse(posted.start) : Date.now();
return (
<div className="book-room-window">
<div className="book-room-container">
<form className="book-creation-bar" onSubmit={submit}>
<input type="hidden" id="room-id" name="room-id" value={room.id} />
<label htmlFor="book-date">
Date:
<input
type="date"
id="book-date"
name="book-date"
onChange={handleChange}
value={bookData.date}
/>
</label>
<label htmlFor="book-time">
Time:
<input
type="time"
id="book-time"
name="book-time"
onChange={handleChange}
value={bookData.time}
/>
</label>
<label htmlFor="book-duration">
How many minutes will you use the conference room?
<input
type="number"
id="book-duration"
name="book-duration"
onChange={handleChange}
value={bookData.duration}
/>
</label>
<input className="book-button" type="submit" value="Book This Room" />
</form>
{posted.start && (
<div>
<h3>Posted!</h3>
<div>
Room
{posted.roomId}
</div>
<div>
Booked for
{format(new Date(bookingDate),
'EEEE, MMMM d, yyyy | p')}
</div>
</div>
)}
</div>
</div>
);
};
BookRoom.propTypes = {
room: PropTypes.shape({
id: PropTypes.number,
size: PropTypes.number,
projector: PropTypes.bool,
}).isRequired,
bookData: PropTypes.shape({
id: PropTypes.number,
userId: PropTypes.number,
roomId: PropTypes.number,
duration: PropTypes.number,
time: PropTypes.string,
date: PropTypes.string,
}).isRequired,
posted: PropTypes.shape({
id: PropTypes.number,
userId: PropTypes.number,
roomId: PropTypes.number,
start: PropTypes.string,
finish: PropTypes.string,
}).isRequired,
changeRoom: PropTypes.func.isRequired,
handleChange: PropTypes.func.isRequired,
submit: PropTypes.func.isRequired,
};
export default BookRoom;
<file_sep>import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import Booking from '../Components/Booking';
const UserBookings = props => {
const {
user, loadBookings, bookings, deleteBooking,
} = props;
useEffect(() => { loadBookings(null, user.id); }, [loadBookings, user.id]);
return (
<div className="bookings-container">
{bookings.length > 0 ? bookings.map(booking => (
<Booking
key={`user-${user.id}-booking-${booking.id}`}
bookingsList={bookings}
bookingInfo={booking}
user={user}
deleteBooking={deleteBooking}
/>
)) : (<div>Searching user bookings</div>)}
</div>
);
};
UserBookings.propTypes = {
user: PropTypes.shape({
loggedIn: PropTypes.bool.isRequired,
pending: PropTypes.bool.isRequired,
name: PropTypes.string,
id: PropTypes.number,
}).isRequired,
bookings: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number,
userId: PropTypes.number,
roomId: PropTypes.number,
start: PropTypes.string,
finish: PropTypes.string,
})).isRequired,
loadBookings: PropTypes.func.isRequired,
deleteBooking: PropTypes.func.isRequired,
};
export default UserBookings;
<file_sep>import React, { useEffect } from 'react';
import { Link } from 'react-router-dom';
import { PropTypes } from 'prop-types';
import room1 from '../RoomImages/room1.jpg';
import room2 from '../RoomImages/room2.jpg';
import room3 from '../RoomImages/room3.jpg';
import room4 from '../RoomImages/room4.jpg';
import room5 from '../RoomImages/room5.jpg';
import room6 from '../RoomImages/room6.jpg';
import room7 from '../RoomImages/room7.jpg';
const ConferenceRooms = props => {
const { conferenceRooms, loadRooms } = props;
useEffect(() => { loadRooms(); }, [loadRooms]);
const chooseRoomImage = roomId => {
switch (roomId) {
case 1:
return room1;
case 2:
return room2;
case 3:
return room3;
case 4:
return room4;
case 5:
return room5;
case 6:
return room6;
case 7:
return room7;
default:
return room1;
}
};
return (
<div className="conference-room-container">
<div className="conference-room-list">
{
conferenceRooms.map(room => (
<div key={`room-${room.id}`} className="conference-room">
<div className="conference-room-info">
<h3>
<b>Room</b>
{' '}
{room.id}
</h3>
<div>
<b>Size:</b>
{' '}
{room.size}
</div>
<div>
<b>Projector:</b>
{' '}
{room.projector ? 'yes' : 'no'}
</div>
</div>
<div className="conference-room-image">
<img src={chooseRoomImage(room.id)} alt={`room_${room.id}_image`} />
</div>
<div className="conference-room-buttons">
<Link key={`room-${room.id}-booker-link`} to={`/book_room_${room.id}`}>
Book This Room
</Link>
<Link key={`room-${room.id}-bookings-link`} to={`/bookings_room_${room.id}`}>
Check this room's bookings
</Link>
</div>
</div>
))
}
</div>
</div>
);
};
ConferenceRooms.propTypes = {
conferenceRooms: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number,
size: PropTypes.number,
projector: PropTypes.bool,
})).isRequired,
loadRooms: PropTypes.func.isRequired,
};
export default ConferenceRooms;
<file_sep>import React from 'react';
import { PropTypes } from 'prop-types';
import Booking from '../Components/Booking';
const AllBookings = props => {
const {
loadBookings,
bookings,
handleChange,
user,
deleteBooking,
} = props;
const orderedBookings = () => {
const newArray = bookings.sort((a, b) => {
const numA = parseInt(a.roomId, 10);
const numB = parseInt(b.roomId, 10);
if (numA < numB) {
return -1;
}
if (numA > numB) {
return 1;
}
return 0;
});
return newArray;
};
return (
<div className="booking-search-window">
<div className="booking-search-container">
<div className="booking-search-menu">
<form className="booking-search-bar" onSubmit={loadBookings}>
<h3>Search Bookings</h3>
<label htmlFor="start-book-date">
From:
<br />
<input
type="date"
id="start-book-date"
name="start-book-date"
onChange={handleChange}
/>
</label>
<label htmlFor="finish-book-date">
To:
<br />
<input
type="date"
id="finish-book-date"
name="finish-book-date"
onChange={handleChange}
/>
</label>
<label htmlFor="room-id-search">
Room:
<br />
<input
type="number"
id="room-id-search"
name="room-id-search"
min="1"
max="7"
onChange={handleChange}
/>
</label>
<button type="submit">
Search
</button>
</form>
</div>
<div className="booking-search-result-list">
{bookings.length > 0 && orderedBookings().map(booking => (
<Booking
key={`booking-${booking.id}-found`}
bookingInfo={booking}
user={user}
deleteBooking={deleteBooking}
/>
))}
</div>
</div>
</div>
);
};
AllBookings.propTypes = {
user: PropTypes.shape({
loggedIn: PropTypes.bool.isRequired,
pending: PropTypes.bool.isRequired,
name: PropTypes.string,
id: PropTypes.number,
}).isRequired,
bookings: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number,
userId: PropTypes.number,
roomId: PropTypes.number,
start: PropTypes.string,
finish: PropTypes.string,
})).isRequired,
deleteBooking: PropTypes.func.isRequired,
handleChange: PropTypes.func.isRequired,
loadBookings: PropTypes.func.isRequired,
};
export default AllBookings;
<file_sep>import {
GET_BOOKINGS_SUCCESS,
GET_BOOKINGS_PENDING,
GET_BOOKINGS_ERROR,
INITIAL_GET_BOOKING_STATE,
POST_BOOKING_ERROR,
POST_BOOKING_PENDING,
POST_BOOKING_SUCCESS,
DELETE_BOOKING_ERROR,
DELETE_BOOKING_PENDING,
DELETE_BOOKING_SUCCESS,
CLEAR_LOCAL_BOOKINGS,
} from '../constants';
function bookings(state = INITIAL_GET_BOOKING_STATE, action) {
let newBookingsArray = [];
let indexToDelete;
switch (action.type) {
case GET_BOOKINGS_PENDING:
return {
...state,
pending: true,
};
case GET_BOOKINGS_SUCCESS:
return {
...state,
pending: false,
bookings: action.bookings,
};
case GET_BOOKINGS_ERROR:
return {
...state,
pending: false,
error: action.error,
};
case POST_BOOKING_ERROR:
return {
...state,
pending: false,
error: action.error,
};
case POST_BOOKING_PENDING:
return {
...state,
pending: true,
};
case POST_BOOKING_SUCCESS:
return {
...state,
pending: false,
posted: action.posted,
};
case CLEAR_LOCAL_BOOKINGS:
return {
...state,
bookings: [],
posted: {},
};
case DELETE_BOOKING_SUCCESS:
newBookingsArray = [...state.bookings];
indexToDelete = newBookingsArray
.indexOf(newBookingsArray.find(booking => booking.id === action.deleted.id));
newBookingsArray.splice(indexToDelete, 1);
return {
...state,
pending: false,
bookings: newBookingsArray,
};
case DELETE_BOOKING_PENDING:
return {
...state,
pending: true,
};
case DELETE_BOOKING_ERROR:
return {
...state,
pending: false,
error: action.error,
};
default:
return state;
}
}
export default bookings;
<file_sep>import React from 'react';
import { format } from 'date-fns';
import { PropTypes } from 'prop-types';
const Booking = props => {
const { bookingInfo, user, deleteBooking } = props;
const deleteMethod = () => {
deleteBooking(bookingInfo.id);
};
const bookingStartDate = Date.parse(bookingInfo.start);
const bookingFinishDate = Date.parse(bookingInfo.finish);
return (
<div className="booking">
<div className="booking-info">
<div>
<b>Room:</b>
{' '}
{bookingInfo.roomId}
</div>
<div>
<b>Meeting Start:</b>
{' '}
{format(new Date(bookingStartDate), 'EEEE, MMMM d, yyyy | p')}
</div>
<div>
<b>Meeting End:</b>
{' '}
{format(new Date(bookingFinishDate), 'EEEE, MMMM d, yyyy | p')}
</div>
</div>
{ bookingInfo.userId === user.id && (
<div className="delete-booking-button">
<button
key={`booking-${bookingInfo.id}-delete`}
type="button"
href="#"
onClick={deleteMethod}
>
Delete This Booking
</button>
</div>
)}
</div>
);
};
Booking.propTypes = {
user: PropTypes.shape({
loggedIn: PropTypes.bool.isRequired,
pending: PropTypes.bool.isRequired,
name: PropTypes.string,
id: PropTypes.number,
}).isRequired,
bookingInfo: PropTypes.shape({
id: PropTypes.number,
userId: PropTypes.number,
roomId: PropTypes.number,
start: PropTypes.string,
finish: PropTypes.string,
}).isRequired,
deleteBooking: PropTypes.func.isRequired,
};
export default Booking;
<file_sep>import user from '../user';
import {
LOG_IN_PENDING,
LOG_IN_SUCCESS,
LOG_IN_ERROR,
INITIAL_USER_STATE,
} from '../../constants';
const pendingLogInRequest = {
type: LOG_IN_PENDING,
pending: true,
};
const pendingLogInResult = {
pending: true,
loggedIn: false,
name: '',
id: null,
};
const successfulLogInRequest = {
type: LOG_IN_SUCCESS,
name: 'tester1',
id: 1,
};
const successfulLogInRequestResult = {
pending: false,
loggedIn: true,
name: 'tester1',
id: 1,
};
const errorLogInRequest = {
type: LOG_IN_ERROR,
id: null,
name: '',
};
const errorLogInRequestResult = {
pending: false,
name: '',
id: null,
loggedIn: false,
};
it('changes status of request to pending true', () => {
expect(user(INITIAL_USER_STATE, pendingLogInRequest)).toEqual(
pendingLogInResult,
);
});
it('changes status of request to pending false and payload contains rooms', () => {
expect(user(INITIAL_USER_STATE, successfulLogInRequest)).toEqual(
successfulLogInRequestResult,
);
});
it('changes status of request to pending false and payload is empty', () => {
expect(user(INITIAL_USER_STATE, errorLogInRequest)).toEqual(
errorLogInRequestResult,
);
});
<file_sep>import React, { useEffect } from 'react';
import { PropTypes } from 'prop-types';
import Booking from '../Components/Booking';
const RoomBookings = props => {
const {
room, loadBookings, bookings, deleteBooking, user,
} = props;
useEffect(() => { loadBookings(room.id); }, [loadBookings, room.id]);
return (
<div className="bookings-container">
{bookings.length > 0 && bookings.map(booking => (
<Booking
key={`booking-${booking.id}-room-${room.id}`}
bookingsList={bookings}
bookingInfo={booking}
deleteBooking={deleteBooking}
user={user}
/>
))}
</div>
);
};
RoomBookings.propTypes = {
user: PropTypes.shape({
loggedIn: PropTypes.bool.isRequired,
pending: PropTypes.bool.isRequired,
name: PropTypes.string,
id: PropTypes.number,
}).isRequired,
bookings: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number,
userId: PropTypes.number,
roomId: PropTypes.number,
start: PropTypes.string,
finish: PropTypes.string,
})).isRequired,
room: PropTypes.shape({
id: PropTypes.number,
size: PropTypes.number,
projector: PropTypes.bool,
}).isRequired,
loadBookings: PropTypes.func.isRequired,
deleteBooking: PropTypes.func.isRequired,
};
export default RoomBookings;
<file_sep>import React from 'react';
import { PropTypes } from 'prop-types';
const Login = props => {
const { clickLogIn, user } = props;
return (
<div className="login-background">
<div className="login-container">
<div className="login-inputs-container">
<input
type="text"
id="user-name"
placeholder="Username"
className="input-text"
/>
<input
type="<PASSWORD>"
id="user-password"
placeholder="<PASSWORD>"
className="input-text"
/>
<div>
<button type="button" onClick={clickLogIn} className="login-button">Log In</button>
{user.pending && <span>Loading...</span>}
</div>
</div>
</div>
</div>
);
};
Login.propTypes = {
user: PropTypes.shape({
loggedIn: PropTypes.bool.isRequired,
pending: PropTypes.bool.isRequired,
name: PropTypes.string,
id: PropTypes.number,
}).isRequired,
clickLogIn: PropTypes.func.isRequired,
};
export default Login;
<file_sep>const getRequest = async endpoint => {
const response = await fetch(endpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
return response;
}
};
const postRequest = async (endpoint, body) => {
const response = await fetch(endpoint, {
mode: 'cors',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
.then(response => response.json())
.catch(error => error.message);
return response;
};
const deleteRequest = async endpoint => {
const response = await fetch(endpoint, {
mode: 'cors',
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
})
.then(response => response.json())
.catch(error => error.message);
return response;
};
export const ApiLogIn = async (username, password) => {
const body = {
name: username,
password,
};
const endpoint = 'https://meeting-booker-api.herokuapp.com/api/login';
const loggedUser = {};
await postRequest(endpoint, body)
.then(data => {
if (data.user.name) {
loggedUser.id = data.user.id;
loggedUser.name = data.user.name;
}
});
return loggedUser;
};
export const ApiGetRooms = async () => {
const foundRooms = [];
const endpoint = 'https://meeting-booker-api.herokuapp.com/api/conference_rooms';
await getRequest(endpoint)
.then(data => data.json())
.then(rooms => {
rooms.data.forEach(room => {
foundRooms.push({
id: room.id,
size: room.size,
projector: room.projector,
});
});
});
return foundRooms.sort((a, b) => {
const numA = a.id;
const numB = b.id;
if (numA < numB) {
return -1;
}
if (numB < numA) {
return 1;
}
return 0;
});
};
export const ApiGetBookings = async (roomId = null, userId = null,
lowLimit = null,
highLimit = null) => {
const foundBookings = [];
const roomParam = roomId ? `conference_room_id=${roomId}&` : '';
const userParam = userId ? `user_id=${userId}&` : '';
const lowLimitParam = lowLimit ? `low_limit=${lowLimit}&` : '';
const highLimitParam = highLimit ? `high_limit=${highLimit}&` : '';
const endpoint = `https://meeting-booker-api.herokuapp.com/api/booking?${roomParam}${userParam}${lowLimitParam}${highLimitParam}`;
await getRequest(endpoint)
.then(data => data.json())
.then(bookings => {
bookings.data.forEach(booking => {
foundBookings.push({
id: booking.id,
userId: booking.user_id,
roomId: booking.conference_room_id,
start: booking.start,
finish: booking.finish,
});
});
});
return foundBookings;
};
export const ApiCreateBooking = async (userId, roomId, start, finish) => {
const body = {
user_id: userId,
conference_room_id: roomId,
start,
finish,
};
const endpoint = 'https://meeting-booker-api.herokuapp.com/api/booking';
const createdBooking = {};
await postRequest(endpoint, body)
.then(booking => {
createdBooking.id = booking.data.id;
createdBooking.userId = booking.data.user_id;
createdBooking.roomId = booking.data.conference_room_id;
createdBooking.start = booking.data.start;
createdBooking.finish = booking.data.finish;
});
return createdBooking;
};
export const ApiDeleteBooking = async bookingId => {
const body = {
id: bookingId,
};
const endpoint = `https://meeting-booker-api.herokuapp.com/api/booking/${bookingId}`;
const deletedBooking = {};
await deleteRequest(endpoint, body)
.then(booking => {
deletedBooking.id = booking.data.id;
deletedBooking.userId = booking.data.user_id;
deletedBooking.roomId = booking.data.conference_room_id;
deletedBooking.start = booking.data.start;
deletedBooking.finish = booking.data.finish;
});
return deletedBooking;
};
<file_sep>import bookings from '../bookings';
import {
GET_BOOKINGS_SUCCESS,
GET_BOOKINGS_PENDING,
GET_BOOKINGS_ERROR,
INITIAL_GET_BOOKING_STATE,
POST_BOOKING_ERROR,
POST_BOOKING_PENDING,
POST_BOOKING_SUCCESS,
DELETE_BOOKING_ERROR,
DELETE_BOOKING_PENDING,
DELETE_BOOKING_SUCCESS,
} from '../../constants';
const bookingsList = [
{
id: 1,
userId: 1,
roomId: 1,
start: '2020-10-13T15:30:00.000Z',
finish: '2020-10-13T16:30:00.000Z',
},
{
id: 2,
userId: 2,
roomId: 2,
start: '2020-10-13T15:30:00.000Z',
finish: '2020-10-13T16:30:00.000Z',
},
{
id: 3,
userId: 3,
roomId: 3,
start: '2020-10-13T15:30:00.000Z',
finish: '2020-10-13T16:30:00.000Z',
},
{
id: 4,
userId: 4,
roomId: 4,
start: '2020-10-13T15:30:00.000Z',
finish: '2020-10-13T16:30:00.000Z',
},
];
const pendingBookingRequest = {
type: GET_BOOKINGS_PENDING,
};
const pendingBookingResult = {
bookings: [],
pending: true,
posted: {},
};
const successfulBookingRequest = {
type: GET_BOOKINGS_SUCCESS,
bookings: bookingsList,
pending: false,
};
const successfulBookingRequestResult = {
pending: false,
bookings: bookingsList,
posted: {},
};
const errorBookingRequest = {
type: GET_BOOKINGS_ERROR,
bookings: [],
pending: false,
error: 'not found',
};
const errorBookingRequestResult = {
bookings: [],
pending: false,
error: 'not found',
posted: {},
};
it('changes status of request to pending true', () => {
expect(bookings(INITIAL_GET_BOOKING_STATE, pendingBookingRequest))
.toEqual(pendingBookingResult);
});
it('changes status of request to pending false and payload contains bookings', () => {
expect(bookings(INITIAL_GET_BOOKING_STATE, successfulBookingRequest))
.toEqual(successfulBookingRequestResult);
});
it('changes status of request to pending false and payload is empty', () => {
expect(bookings(INITIAL_GET_BOOKING_STATE, errorBookingRequest))
.toEqual(errorBookingRequestResult);
});
const newBooking = {
userId: 4,
roomId: 6,
start: '2020-15-13T15:30:00.000Z',
finish: '2020-15-13T16:30:00.000Z',
};
const pendingPostBookingRequest = {
type: POST_BOOKING_PENDING,
newBooking,
};
const pendingPostBookingResult = {
bookings: [],
pending: true,
posted: {},
};
const successfulPostBookingRequest = {
type: POST_BOOKING_SUCCESS,
posted: newBooking,
pending: false,
};
const successfulPostBookingRequestResult = {
pending: false,
bookings: [],
posted: newBooking,
};
const errorPostBookingRequest = {
type: POST_BOOKING_ERROR,
bookings: [],
pending: false,
error: 'Could not post',
};
const errorPostBookingRequestResult = {
bookings: [],
pending: false,
error: 'Could not post',
posted: {},
};
it('changes status of request to pending true', () => {
expect(bookings(INITIAL_GET_BOOKING_STATE, pendingPostBookingRequest))
.toEqual(pendingPostBookingResult);
});
it('changes status of request to pending false and payload contains bookings', () => {
expect(bookings(INITIAL_GET_BOOKING_STATE, successfulPostBookingRequest))
.toEqual(successfulPostBookingRequestResult);
});
it('changes status of request to pending false and payload is empty', () => {
expect(bookings(INITIAL_GET_BOOKING_STATE, errorPostBookingRequest))
.toEqual(errorPostBookingRequestResult);
});
const delBooking = {
id: 2,
userId: 2,
roomId: 2,
start: '2020-10-13T15:30:00.000Z',
finish: '2020-10-13T16:30:00.000Z',
};
const bookingsListAfterDelete = [
{
id: 1,
userId: 1,
roomId: 1,
start: '2020-10-13T15:30:00.000Z',
finish: '2020-10-13T16:30:00.000Z',
},
{
id: 3,
userId: 3,
roomId: 3,
start: '2020-10-13T15:30:00.000Z',
finish: '2020-10-13T16:30:00.000Z',
},
{
id: 4,
userId: 4,
roomId: 4,
start: '2020-10-13T15:30:00.000Z',
finish: '2020-10-13T16:30:00.000Z',
},
];
const pendingDeleteBookingRequest = {
type: DELETE_BOOKING_PENDING,
deleted: delBooking,
};
const pendingDeleteBookingResult = {
bookings: bookingsList,
pending: true,
posted: {},
};
const successfulDeleteBookingRequest = {
type: DELETE_BOOKING_SUCCESS,
posted: newBooking,
pending: false,
deleted: delBooking,
};
const successfulDeleteBookingRequestResult = {
pending: false,
bookings: bookingsListAfterDelete,
posted: {},
};
const errorDeleteBookingRequest = {
type: DELETE_BOOKING_ERROR,
bookings: bookingsList,
pending: false,
error: 'Could not delete',
};
const errorDeleteBookingRequestResult = {
bookings: bookingsList,
pending: false,
error: 'Could not delete',
posted: {},
};
const INITIAL_DEL_STATE = {
pending: false,
bookings: bookingsList,
posted: {},
};
it('changes status of request to pending true', () => {
expect(bookings(INITIAL_DEL_STATE, pendingDeleteBookingRequest))
.toEqual(pendingDeleteBookingResult);
});
it('changes status of request to pending false and payload has removed the booking', () => {
expect(bookings(INITIAL_DEL_STATE, successfulDeleteBookingRequest))
.toEqual(successfulDeleteBookingRequestResult);
});
it('changes status of request to pending false and payload has not removed the booking', () => {
expect(bookings(INITIAL_DEL_STATE, errorDeleteBookingRequest))
.toEqual(errorDeleteBookingRequestResult);
});
<file_sep>import {
LOG_IN_PENDING,
LOG_IN_SUCCESS,
LOG_IN_ERROR,
LOG_OUT,
INITIAL_USER_STATE,
} from '../constants';
function user(state = INITIAL_USER_STATE, action) {
switch (action.type) {
case LOG_IN_PENDING:
return {
...state,
pending: true,
loggedIn: false,
};
case LOG_IN_SUCCESS:
return {
pending: false,
loggedIn: true,
name: action.name,
id: action.id,
};
case LOG_IN_ERROR:
return {
pending: false,
loggedIn: false,
name: action.name,
id: action.id,
};
case LOG_OUT:
return {
pending: false,
loggedIn: false,
name: null,
id: null,
};
default:
return state;
}
}
export default user;
<file_sep>import rooms from '../rooms';
import {
GET_ROOMS_SUCCESS,
GET_ROOMS_PENDING,
GET_ROOMS_ERROR,
INITIAL_GET_ROOM_STATE,
} from '../../constants';
const roomsList = [
{
id: 1,
size: 7,
projector: true,
created_at: '2020-10-06T21:48:27.076Z',
updated_at: '2020-10-08T16:05:02.163Z',
},
{
id: 2,
size: 5,
projector: false,
created_at: '2020-10-06T21:48:27.087Z',
updated_at: '2020-10-06T21:48:27.087Z',
},
{
id: 3,
size: 8,
projector: false,
created_at: '2020-10-06T21:48:27.093Z',
updated_at: '2020-10-06T21:48:27.093Z',
},
{
id: 4,
size: 10,
projector: true,
created_at: '2020-10-06T21:48:27.110Z',
updated_at: '2020-10-06T21:48:27.110Z',
},
{
id: 5,
size: 50,
projector: true,
created_at: '2020-10-06T21:48:27.116Z',
updated_at: '2020-10-06T21:48:27.116Z',
},
{
id: 6,
size: 15,
projector: false,
created_at: '2020-10-06T21:48:27.122Z',
updated_at: '2020-10-06T21:48:27.122Z',
},
{
id: 7,
size: 15,
projector: true,
created_at: '2020-10-06T21:48:27.128Z',
updated_at: '2020-10-06T21:48:27.128Z',
},
];
const pendingRoomsRequest = {
type: GET_ROOMS_PENDING,
};
const pendingRoomsResult = {
rooms: [],
pending: true,
};
const successfulRoomsRequest = {
type: GET_ROOMS_SUCCESS,
rooms: roomsList,
pending: false,
};
const successfulRoomsRequestResult = {
pending: false,
rooms: roomsList,
};
const errorRoomsRequest = {
type: GET_ROOMS_ERROR,
rooms: [],
pending: false,
error: 'not found',
};
const errorRoomsRequestResult = {
rooms: [],
pending: false,
error: 'not found',
};
it('changes status of request to pending true', () => {
expect(rooms(INITIAL_GET_ROOM_STATE, pendingRoomsRequest)).toEqual(
pendingRoomsResult,
);
});
it('changes status of request to pending false and payload contains rooms', () => {
expect(rooms(INITIAL_GET_ROOM_STATE, successfulRoomsRequest)).toEqual(
successfulRoomsRequestResult,
);
});
it('changes status of request to pending false and payload is empty', () => {
expect(rooms(INITIAL_GET_ROOM_STATE, errorRoomsRequest)).toEqual(
errorRoomsRequestResult,
);
});
| 53a6425d61c5e166ef4d8c05c08807d7b6e39f31 | [
"JavaScript",
"Markdown"
] | 18 | JavaScript | MiguelDP4/meeting-booker | 16aab2121427de6e1062ae04680513555eb1a3c8 | 4674c1e1b0504a5d48ace809e8971c9345d053eb |
refs/heads/master | <file_sep>import { Transform, TransformCallback } from 'stream';
import { FRAME_CHARS } from './constants';
class FrameParser extends Transform {
private incompletedFrame: number[];
constructor() {
super();
this.incompletedFrame = [];
}
public _transform(
chunk: any,
_encoding: string,
callback: TransformCallback,
) {
if (typeof chunk === 'string') {
chunk = Buffer.from(chunk);
}
const stxIndex = chunk.indexOf(FRAME_CHARS.STX);
const etxIndex = chunk.indexOf(FRAME_CHARS.ETX);
if (
this.incompletedFrame.length !== 0 &&
-1 < etxIndex &&
etxIndex < stxIndex
) {
const frame = [...this.incompletedFrame, ...chunk.slice(0, etxIndex)];
this.push(frame);
}
let frame = [];
for (let i = stxIndex + 1; i < chunk.length; i++) {
if (chunk[i] === FRAME_CHARS.ETX) {
if (this.incompletedFrame.length > 0) {
frame = [...this.incompletedFrame, ...frame];
this.incompletedFrame = [];
}
this.push(Buffer.from(frame));
frame = [];
} else if (chunk[i] !== FRAME_CHARS.STX) {
frame.push(chunk[i]);
}
}
if (chunk[chunk.length - 1] !== FRAME_CHARS.ETX) {
this.incompletedFrame = [...this.incompletedFrame, ...frame];
}
callback();
}
}
export default FrameParser;
<file_sep>import debug from 'debug';
import intelHex from 'node-intelhex';
import SerialPort from 'serialport';
import Connection from './connection';
import {
AUTOBAUD_BUFFER,
COMMANDS,
DEFAULT_PORT_OPTIONS,
MAX_DATA_LEN,
SUCCESS_RESPONSE,
} from './constants';
import { timify } from './utils';
import logger from '../loggger';
const d = debug('updater:client');
class Client {
private connection?: Connection;
public onFlashing?: (progress: number) => void;
public async connect() {
const ports = await this.getAvailablePorts();
ports.forEach(port => d('Found port: %s', port.path));
const candidates = await Promise.all(ports.map(port => this.listen(port)));
const connections = candidates.filter(Boolean);
// For now we handle just a single connection
this.connection = connections[0] as Connection;
if (connections.length === 0) {
return Promise.reject('Unable to connect');
}
logger.info('Succesfully connected');
return this.getDeviceData();
}
public async getDeviceData(): Promise<DeviceData> {
const hwData = await this.send(COMMANDS.READ_VERSION_BOOTLOADER);
const fwData = await this.send(COMMANDS.READ_VERSION_FIRMWARE);
const hwVersion = hwData
.slice(0, 2)
.reverse()
.join('.');
const model = `HP${hwData[2]}00`;
const fwVersion = fwData.reverse().join('.');
return {
model,
hwVersion,
fwVersion,
};
}
public async setFlashAddress(addr: number) {
const data = [(addr >> 24) & 0xff, (addr >> 16) & 0xff, (addr >> 8) & 0xff, (addr >> 0) & 0xff];
return this.send(COMMANDS.SET_ADDRESS, data);
}
public async flash(filename: string) {
const { address, data } = await intelHex.readFile(filename);
const size = data.length;
await this.setFlashAddress(address);
let chunkCursor = 0,
dataCursor = 0;
let chunk = [];
while (dataCursor < size) {
chunk[chunkCursor++] = data[dataCursor++];
if (chunkCursor === MAX_DATA_LEN) {
await this.send(COMMANDS.FLASH_WRITE_DATA, chunk);
chunk = [];
chunkCursor = 0;
}
if (this.onFlashing) {
const progress = Math.round((dataCursor / size) * 100);
this.onFlashing(progress);
}
}
await this.send(COMMANDS.FLASH_WRITE_DATA, chunk); // send remaining data
// We have to send another packet in order to fill last flash page
// TODO: what does this mean? Ask it to Rod
await this.send(COMMANDS.FLASH_WRITE_DATA);
}
private async getAvailablePorts() {
const infos = await SerialPort.list();
return infos.map(portInfo => new SerialPort(portInfo.path, DEFAULT_PORT_OPTIONS));
}
private async listen(port: SerialPort) {
const timedPromise = timify(
new Promise(resolve => {
port.open(err => {
if (err) {
logger.info('Cannot open port', { port: port.path, reason: err.message });
return;
}
port.once('data', (data: Buffer) => {
data = data.slice(1, -1);
data.equals(SUCCESS_RESPONSE) && resolve(port);
});
port.write(AUTOBAUD_BUFFER);
});
}),
1000,
);
try {
const port = (await timedPromise()) as SerialPort;
return new Connection(port);
} catch {
return false;
}
}
private send(command: number, data?: number[]) {
if (this.connection == null) {
throw new TypeError('Connection#send called on a null object.');
}
return this.connection.send(command, data || []);
}
}
export default Client;
export { default as MockClient } from './mock';
<file_sep>import debug from 'debug';
import logger from './loggger';
import * as app from './app';
const d = debug('updater:main');
process
.on('uncaughtException', error => {
d('UNCAUGHT EXCEPTION', error);
logger.error('UNCAUGHT EXCEPTION', { kind: error.name, reason: error.message, error });
})
.on('unhandledRejection', (reason, promise) => {
d('UNHANDLED REJECTION', reason);
logger.error('UNHANDLED REJECTION', { reason, promise });
});
app.start();
<file_sep>/// <reference types="node" />
// Auxliary Types and Interfaces
interface WriteOptions {
progress?: (value: number) => void;
}
interface ReadOptions extends WriteOptions {
info?: (msg: string) => void;
}
interface BufferReader {
getNextRecord: () => string;
eof: () => boolean;
length: () => number;
bytesRead: () => number;
}
type WriteCallback = (err?: Error) => void;
type ReadCallback = (err?: Error, result?: Result) => void;
// Exports
export interface Result {
address: number;
data: Buffer;
}
export function setLineBytes(mlb: number): void;
export function writeFile(
filename: string,
address: number,
data: Buffer,
options?: WriteOptions,
callback?: WriteCallback,
): Promise<void>;
export function readFile(
filename: string,
options?: ReadOptions,
callback?: ReadCallback,
): Promise<Result>;
export function bufferReader(address: number, data: Buffer): BufferReader;
<file_sep>import { app } from 'electron';
import { autoUpdater } from 'electron-updater';
import debug from 'debug';
import logger from './loggger';
import * as window from './window';
import * as ipc from './ipc';
import { ENV } from './constants';
const d = debug('updater:main');
autoUpdater.logger = logger;
export function start() {
d('Application started in %s', ENV);
logger.info('Application started', { ENV });
app.on('ready', async () => {
try {
logger.info('Checking for updates...');
const result = await autoUpdater.checkForUpdatesAndNotify();
// logger.info('Checking completed.', result);
} catch (err) {
d('Error while updating the updater -.-');
logger.error('An error occure while updating the app', err);
}
d('Creating main window');
window.create();
d('Initializing IPC');
ipc.init();
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
app.on('activate', () => {
d('Creating main window');
window.create();
});
}
<file_sep>import { COMMANDS } from './constants';
const cmdNames = Object.keys(COMMANDS);
const cmdValues = Object.values(COMMANDS);
class ConnectionError extends Error {
constructor(cmd: number, message: string) {
super(`[${cmdNames[cmdValues.indexOf(cmd)]}]: ${message}`);
}
}
export default ConnectionError;
<file_sep>import path from 'path';
import winston from 'winston';
import { LOG_PATH } from './constants';
const consoleFormat = winston.format.combine(
winston.format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss',
}),
winston.format.prettyPrint({ colorize: true }),
);
const MAX_LOG_SIZE = 1000 * 10; // Size must be specified in bytes, so we have 1000B = 1MB
const MAX_LOG_FILES = 5;
const transports = [
new winston.transports.File({
filename: path.join(LOG_PATH, 'combined.log'),
maxsize: MAX_LOG_SIZE,
maxFiles: MAX_LOG_FILES,
tailable: true,
}),
new winston.transports.File({
level: 'error',
filename: path.join(LOG_PATH, 'error.log'),
maxsize: MAX_LOG_SIZE,
maxFiles: MAX_LOG_FILES,
tailable: true,
}),
new winston.transports.Console({
format: consoleFormat,
}),
];
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(consoleFormat, winston.format.uncolorize()),
transports,
});
export default logger;
<file_sep>import debug from 'debug';
import { ipcMain, app } from 'electron';
import * as window from './window';
import * as update from './update';
import logger from './loggger';
import Client from './bootloader';
const d = debug('updater:ipc');
const client = new Client();
let deviceData: DeviceData | undefined;
export function init() {
ipcMain.on('connection/start', async event => {
try {
deviceData = await client.connect();
event.reply('connection/connected', deviceData);
d('Device %o successfully connected', deviceData);
// logger.info(`Device ${JSON.stringify(deviceData)} successfully connected`);
} catch (err) {
d('Connection failed due to %O', err);
// logger.warn(`Connection failed due to: ${err}`);
event.reply('connection/failed');
}
});
ipcMain.on('update/check', async event => {
const info = await update.checkFirmwareUpdates(deviceData!);
if (info.available) {
const version = update.getUpdateVersion();
event.reply('update/available', { version });
} else if (info.cached == null) {
event.reply('update/cache-empty');
} else {
event.reply('update/unavailable');
}
});
ipcMain.on('update/install', async event => {
const mainWindow = window.getWindow();
client.onFlashing = progress => {
mainWindow?.webContents.send('update/installing', { progress });
};
try {
await client.flash(update.getFilePath()!);
event.reply('update/installed');
} catch (err) {
console.log(err);
event.reply('update/failed');
}
});
ipcMain.on('app/quit', () => app.quit());
}
<file_sep>import { OpenOptions } from 'serialport';
// Connection Initialization
export const AUTOBAUD_BUFFER = Buffer.alloc(16, 'U');
export const SUCCESS_RESPONSE = Buffer.from('c45b3');
// Packet Format
export const MAX_DATA_LEN = 64;
export const FRAME_CHARS = {
STX: 0x02,
ETX: 0x03,
ESC: 0x1b,
};
export const DEFAULT_PORT_OPTIONS: OpenOptions = {
baudRate: 57600,
autoOpen: false,
};
export const CRC_SETTINGS = {
initialValue: 0xffff,
polynomial: 0x1021,
};
export const COMMANDS = {
READ_VERSION_BOOTLOADER: 0x11,
READ_VERSION_FIRMWARE: 0x12,
READ_VERSION_EEPROM: 0x13,
START_APPLICATION: 0x18,
SET_ADDRESS: 0x21,
FLASH_WRITE_DATA: 0x22,
FLASH_READ_DATA: 0x23,
EEPROM_WRITE_DATA: 0x24,
EEPROM_READ_DATA: 0x25,
};
<file_sep>import SerialPort from 'serialport';
import ConnectionError from './connection-error';
import { CRC_SETTINGS, FRAME_CHARS } from './constants';
import FrameParser from './frame-parser';
class Connection {
private txChannel: SerialPort;
private rxChannel: FrameParser;
constructor(serialPort: SerialPort) {
this.txChannel = serialPort;
this.rxChannel = serialPort.pipe(new FrameParser());
}
public send(cmd: number, data: number[] = []) {
const requestPacket = this.createPacket(cmd, data);
if (!this.txChannel.write(requestPacket)) {
this.txChannel.drain();
}
return new Promise<number[]>((resolve, reject) => {
this.rxChannel.once('readable', () => {
const responsePacket = Array.from<number>(this.rxChannel.read());
try {
const data = this.parsePacket(responsePacket, cmd);
resolve(data);
} catch (err) {
reject(err);
}
});
});
}
private createPacket(cmd: number, data: number[]) {
const crc = this.computeCrc([cmd, ...data]);
const crcValues = [(crc >> 8) & 0xff, crc & 0xff]; // [CRC_MSB, CRC_LSB]
return [
FRAME_CHARS.STX,
...this.normalizePacket([cmd, ...data, ...crcValues]),
FRAME_CHARS.ETX,
];
}
private parsePacket(packet: number[], cmdSent: number) {
packet = this.removeEscape(packet);
const actualCrc = packet.pop()! + packet.pop()! * 256; // CRC_LSB + CRC_MSB
const expectedCrc = this.computeCrc(packet);
if (actualCrc !== expectedCrc) {
throw new ConnectionError(cmdSent, 'Invalid packet received: wrong CRC.');
}
if (packet.shift()! - 0x80 !== cmdSent) {
throw new ConnectionError(
cmdSent,
'Invalid packet received: command error.',
);
}
return packet;
}
private computeCrc(data: number[]) {
let crc = CRC_SETTINGS.initialValue;
for (const byte of data) {
for (let i = 0; i < 8; i++) {
const bit = ((byte >> (7 - i)) & 1) == 1;
const c15 = ((crc >> 15) & 1) == 1;
crc <<= 1;
if (c15 !== bit) {
crc ^= CRC_SETTINGS.polynomial;
}
}
}
return crc & 0xffff;
}
private normalizePacket(packet: number[]) {
return packet.reduce<number[]>((acc, byte) => {
if (Object.values(FRAME_CHARS).includes(byte)) {
return acc.concat([FRAME_CHARS.ESC, byte | 0x80]);
}
return acc.concat(byte);
}, []);
}
private removeEscape(packet: number[]) {
let offset = 0x00;
return packet.reduce<number[]>((acc, byte) => {
if (byte === FRAME_CHARS.ESC) {
offset = 0x80;
return acc;
}
acc.push(byte - offset);
offset = 0x00;
return acc;
}, []);
}
}
export default Connection;
<file_sep>// Type definitions for serialport 7.0
// Project: https://github.com/node-serialport/node-serialport
// Definitions by: <NAME> <https://github.com/codefoster>
// <NAME> <https://github.com/apearson>
// <NAME> <https://github.com/cinderblock>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import * as Stream from 'stream';
declare class SerialPort extends Stream.Duplex {
constructor(path: string, callback?: SerialPort.ErrorCallback);
constructor(
path: string,
options?: SerialPort.OpenOptions,
callback?: SerialPort.ErrorCallback,
);
readonly baudRate: number;
readonly binding: SerialPort.BaseBinding;
readonly isOpen: boolean;
readonly path: string;
open(callback?: SerialPort.ErrorCallback): void;
update(
options: SerialPort.UpdateOptions,
callback?: SerialPort.ErrorCallback,
): void;
write(
data: string | number[] | Buffer,
callback?: (error: Error | null | undefined, bytesWritten: number) => void,
): boolean;
write(
buffer: string | number[] | Buffer,
encoding?:
| 'ascii'
| 'utf8'
| 'utf16le'
| 'ucs2'
| 'base64'
| 'binary'
| 'hex',
callback?: (error: Error | null | undefined, bytesWritten: number) => void,
): boolean;
read(size?: number): string | Buffer | null;
close(callback?: (error?: Error | null) => void): void;
set(
options: SerialPort.SetOptions,
callback?: SerialPort.ErrorCallback,
): void;
get(callback?: SerialPort.ModemBitsCallback): void;
flush(callback?: SerialPort.ErrorCallback): void;
drain(callback?: SerialPort.ErrorCallback): void;
pause(): this;
resume(): this;
on(event: string, callback: (data?: any) => void): this;
static Binding: SerialPort.BaseBinding;
static list(
callback?: SerialPort.ListCallback,
): Promise<SerialPort.PortInfo[]>;
}
declare namespace SerialPort {
// Callbacks Type Defs
type ErrorCallback = (error?: Error | null) => void;
type ModemBitsCallback = (
error: Error | null | undefined,
status: { cts: boolean; dsr: boolean; dcd: boolean },
) => void;
type ListCallback = (error: Error | null | undefined, ports: any[]) => void;
// Options Type Defs
interface OpenOptions {
autoOpen?: boolean;
baudRate?:
| 115200
| 57600
| 38400
| 19200
| 9600
| 4800
| 2400
| 1800
| 1200
| 600
| 300
| 200
| 150
| 134
| 110
| 75
| 50
| number;
dataBits?: 8 | 7 | 6 | 5;
highWaterMark?: number;
lock?: boolean;
stopBits?: 1 | 2;
parity?: 'none' | 'even' | 'mark' | 'odd' | 'space';
rtscts?: boolean;
xon?: boolean;
xoff?: boolean;
xany?: boolean;
binding?: BaseBinding;
bindingOptions?: {
vmin?: number;
vtime?: number;
};
}
interface UpdateOptions {
baudRate?:
| 115200
| 57600
| 38400
| 19200
| 9600
| 4800
| 2400
| 1800
| 1200
| 600
| 300
| 200
| 150
| 134
| 110
| 75
| 50
| number;
}
interface SetOptions {
brk?: boolean;
cts?: boolean;
dsr?: boolean;
dtr?: boolean;
rts?: boolean;
}
interface PortInfo {
path: string;
manufacturer?: string;
serialNumber?: string;
pnpId?: string;
locationId?: string;
productId?: string;
vendorId?: string;
}
namespace parsers {
class ByteLength extends Stream.Transform {
constructor(options: { length: number });
}
class CCTalk extends Stream.Transform {
constructor();
}
class Delimiter extends Stream.Transform {
constructor(options: {
delimiter: string | Buffer | number[];
includeDelimiter?: boolean;
});
}
class Readline extends Delimiter {
constructor(options: {
delimiter: string | Buffer | number[];
encoding?:
| 'ascii'
| 'utf8'
| 'utf16le'
| 'ucs2'
| 'base64'
| 'binary'
| 'hex';
includeDelimiter?: boolean;
});
}
class Ready extends Stream.Transform {
constructor(options: { delimiter: string | Buffer | number[] });
}
class Regex extends Stream.Transform {
constructor(options: { regex: RegExp });
}
}
// Binding Type Defs
type win32Binding = BaseBinding;
type darwinBinding = BaseBinding;
type linuxBinding = BaseBinding;
// Binding Type Def
class BaseBinding {
constructor(options: any);
open(path: string, options: OpenOptions): Promise<any>;
close(): Promise<any>;
read(data: Buffer, offset: number, length: number): Promise<any>;
write(data: Buffer): Promise<any>;
update(options?: UpdateOptions): Promise<any>;
set(options?: SetOptions): Promise<any>;
get(): Promise<any>;
flush(): Promise<any>;
drain(): Promise<any>;
static list(): Promise<PortInfo[]>;
}
}
export = SerialPort;
<file_sep>export function timify<T>(promise: Promise<T>, ms: number) {
return () => {
const timer = new Promise((_resolve, reject) => setTimeout(reject, ms));
return Promise.race([promise, timer]);
};
}
<file_sep>import path from 'path';
import debug from 'debug';
import { BrowserWindow } from 'electron';
import * as constants from './constants';
const d = debug('updater:window');
let window: BrowserWindow | null;
export function create() {
// Create the browser window.
window = new BrowserWindow({
width: 600,
height: 212,
useContentSize: true,
backgroundColor: '#1e1e24',
autoHideMenuBar: true,
titleBarStyle: 'hidden',
maximizable: false,
fullscreenable: false,
show: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
});
window.loadURL(constants.START_URL);
if (constants.DEV) {
window.webContents.openDevTools({ mode: 'detach' });
}
window.on('closed', () => {
d('App Window closed');
window = null;
});
window.on('ready-to-show', () => {
d('Window is ready to show');
window!.show();
});
}
export function getWindow() {
return window;
}
export function emit(event: string, ...args: any[]) {
if (!window) return;
window.webContents.send(event, ...args);
}
<file_sep>import path from 'path';
import { app } from 'electron';
// App Environment
export const ENV = process.env.NODE_ENV || 'production';
export const DEV = ENV === 'development';
// Platform
export const PLATFORM = process.platform;
export const MAC = PLATFORM === 'darwin';
export const WIN = PLATFORM === 'win32';
export const LINUX = PLATFORM === 'linux';
// App Paths
export const USER_PATH = app.getPath('userData');
export const LOG_PATH = path.join(USER_PATH, 'logs');
export const CACHE_PATH = path.join(USER_PATH, 'updates-cache');
export const UPDATES_REPO_URL = 'https://bitbucket.org/AWEL-GmbH/updates/get/master.zip';
export const START_URL = DEV
? 'http://localhost:3000'
: `file://${path.join(__dirname, 'index.html')}`;
<file_sep>export default class MockClient {
public onFlashing?: (progress: number) => void;
static mockedDeviceData: DeviceData = {
model: 'HP100',
hwVersion: '1.0',
fwVersion: '1.2',
};
public constructor(private delay: number) {}
public async connect(fail = false) {
return new Promise((resolve, reject) => {
setTimeout(
() => (fail ? reject() : resolve(MockClient.mockedDeviceData)),
this.delay,
);
});
}
public async flash(path: string, fail = false) {
return new Promise((resolve, reject) => {
let progress = 0;
const interval = setInterval(
() => this.onFlashing!(progress == 100 ? 100 : progress++),
this.delay / 200,
);
setTimeout(() => {
clearInterval(interval);
fail ? reject() : resolve();
}, this.delay);
});
}
}
<file_sep>import { ipcRenderer } from 'electron';
window.emitBackendEvent = (event: BackendEvent) => {
ipcRenderer.send(event);
};
window.addBackendListener = (
event: BackendEvent,
listener: BackendListener,
) => {
ipcRenderer.on(event, (_, args) => listener(args));
};
<file_sep>import path from 'path';
import fs from 'fs';
import debug from 'debug';
import isOnline from 'is-online';
import { fetch, extract } from 'gitly';
import rimraf from 'rimraf';
import * as window from './window';
import logger from './loggger';
import { CACHE_PATH } from './constants';
const d = debug('updater:update');
type UpdateData = {
file: string;
version: string;
checksum: string;
};
export type UpdateInfo = Partial<UpdateData> & {
available: boolean;
cached?: boolean | null;
};
const REPO = 'bitbucket:AWEL-GmbH/updates';
let updateInfo: UpdateInfo;
export async function checkFirmwareUpdates({
model,
hwVersion,
fwVersion,
}: DeviceData): Promise<UpdateInfo> {
const online = await isOnline();
if (online) {
logger.info('App online, start cache update');
await updateCache();
} else {
logger.info('App is offline, try to use cached updates');
window.emit('app/is-offline');
}
const manifestJson = path.join(CACHE_PATH, `${model}/${hwVersion}/manifest.json`);
if (!fs.existsSync(manifestJson)) {
logger.info('Cache is empty or manifest file was deleted');
return { available: false, cached: null };
}
const content = fs.readFileSync(manifestJson);
const updates: [UpdateData] = JSON.parse(content.toString());
if (updates[0].version == fwVersion) {
logger.info('Update unavailable');
return { available: false, cached: !online };
} else {
const file = path.join(CACHE_PATH, `${model}/${hwVersion}/${updates[0].file}`);
updateInfo = { available: true, cached: !online, ...updates[0], file };
logger.info('Update available', updateInfo);
return updateInfo;
}
}
export function getUpdateVersion() {
return updateInfo?.version;
}
export function getFilePath() {
return updateInfo.file;
}
async function updateCache() {
logger.info('Fetching firmware update...');
const fetchPath = await fetch(REPO, { temp: CACHE_PATH });
await extract(fetchPath, CACHE_PATH, {
extract: {
filter: path => !path.includes('.gitignore'),
},
});
rimraf.sync(path.join(CACHE_PATH, 'bitbucket'));
}
<file_sep>/// <reference path="../backend/node_modules/electron/electron.d.ts" />
type BackendEvent =
// Connection events
| 'connection/start'
| 'connection/connected'
| 'connection/failed'
// Update events
| 'update/check'
| 'update/cache-empty'
| 'update/available'
| 'update/unavailable'
| 'update/install'
| 'update/installing'
| 'update/installed'
| 'update/failed'
// Others
| 'app/quit'
| 'app/is-offline';
type BackendListener = (...args: any[]) => void;
type DeviceData = {
hwVersion: string;
fwVersion: string;
model: string;
};
interface Window {
emitBackendEvent: (event: BackendEvent) => void;
addBackendListener: (event: BackendEvent, listener: BackendListener) => void;
}
| d20d09fca38f4a031c395153f8ef4d9e7bb0613f | [
"TypeScript"
] | 18 | TypeScript | helvest-systems/updater | c0b165986f1e16dd72f2c94993d0de73499e9e7f | e04d231d3107923b423ff85f64d0f0ccf00c4c4d |
refs/heads/master | <repo_name>Nat14/upcase_shouter<file_sep>/app/models/photo_shout.rb
class PhotoShout < ApplicationRecord
has_attached_file :image, styles: {
shout: "200x200>"
}
end
<file_sep>/app/models/search.rb
class Search < ApplicationController
attr_reader :term
def initialize(options = {})
@term = options.fetch(:term, '')
end
def shouts
Shout.text_shouts.where(content_id: text_shouts)
end
private
def text_shouts
TextShout.where('body LIKE ?', search_term)
end
def search_term
"%##{term}%"
end
end
| d2af5bc110a95fc80f01fac4cfbd67e28ea2fab1 | [
"Ruby"
] | 2 | Ruby | Nat14/upcase_shouter | 3c60ed7db595597da4f06e541712a3fe794b2ef6 | 7ee0edd8296b6fe7452e3441d8638d178b8d63d0 |
refs/heads/master | <repo_name>MoraruStefan/FirefoxOS-lyrics-application<file_sep>/app/js/main.js
$(document).ready(function() {
var api_url;
var artist;
var input;
var text, length;
var height;
var document_height;
var songs_array = [ ];
var songs_array_clean = [ ];
var songs_array_ind = 0;
var iframe;
input = $(".input #artist");
api_url = "http://lyrics.wikia.com/api.php?fmt=json&artist=";
artist = "";
$xhr = "";
$data = "";
$artist = "";
$i = 0;
$value = "";
$(".top").on("click", function(event) {
window.scrollTo(0, 0);
});
$(window).scroll(function() {
scroll = $(window).scrollTop();
if (scroll > 150) {
if ($(".top").is(":visible") == false) {
$(".top").stop().slideToggle("slow");
}
}
else {
if ($(".top").is(":visible") == true) {
$(".top").stop().slideToggle("slow");
}
}
});
//Fitting text and the iframe.
$(window).resize(function() {
resize();
});
resize();
input.on("keydown", function(event) {
keydown_handler(event.keyCode);
});
function resize() {
document_height = $(document).height();
height = document_height - $("header").height();
$i++;
$(".start").fitText(1);
$(".iframe").height(document_height);
$(".forms").css("min-height", height);
}
function fit_text() {
$(".artist-title").fitText(0.35);
$(".album-title").each(function(index) {
text = $(this).text();
length = text.length;
if (length > 24) {
text = text.substr(0, 22) + "..";
}
$(this).text(text);
});
}
function search(value) {
//Songs with id:
//lowercase, no symbols
//8milefreestyle
//5starsgeneral
//whenimgone
//keeptalking
//anyman
//searchvalue: when
//start with when, loop trough id (ids are storred in an id array which is generated
//at runtime): songs_array / songs_array_clean then reduce string length by one.
value = stringclean(value);
console.log("Searched for " + value);
$value = value;
var len, results, results_ind;
results = [ ];
results_ind = 0;
len = songs_array_clean.length;
for (i = 0; i < len; i++) {
if (songs_array_clean[i].indexOf(value) != -1) {
results[results_ind] = songs_array[i];
results_ind++;
}
}
len = results.length;
$(".song").on("click", function() {
song = $(this).children().text();
song_click(song);
});
$("#search-results").remove();
$resultsdiv = "<div class='album' id='search-results'>";
$resultsdiv += "<div class='album-title'> <span>Search results: </span> </div>";
for (i = 0; i < len; i++) {
$resultsdiv += "<div class='song'> <span>" + results[i] + "</span> </div>";
}
$resultsdiv += "</div>";
$(".search").after($resultsdiv);
$(".song").on("click", function() {
song = $(this).children().text();
song_click(song);
});
}
function stringclean(string) {
var cleanstring = "", len;
string = string.toLowerCase();
len = string.length;
for (i = 0; i < len; i++) {
charcode = string.charCodeAt(i);
if (charcode > 96 && charcode < 123) {
cleanstring += string[i];
}
}
return cleanstring;
}
//Song clicking.
function song_click(song) {
url = "http://lyrics.wikia.com/" + $artist + ":" + song;
url = url.replace("'", "%27");
window.scrollTo(0, 0);
$("body").append("<div class='iframe'><iframe src='" + url + "' frameborder='0'/></div>");
$("body").css("overflow", "hidden");
iframe = $(".iframe");
iframe.height(iframe.height() - $(".header").height());
$(".close").show();
$(".close").click(function() {
$(".iframe").remove();
$(".close").hide();
$("body").css("overflow", "visible");
});
}
function cssclean(string) {
string = string.substr(0, string.indexOf('px'));
string = Number(string);
return string;
}
function keydown_handler(keyCode) {
if (keyCode == 13) {
artist = input.val();
//TODO: prettify artist's name.
if (artist != "") {
get_song_from_artist(artist);
}
}
}
function get_song_from_artist(artist) {
//Send the artist name trough the API.
url = api_url + artist;
$artist = artist;
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: "json",
contentType: "text/plain",
error: function(xhr, status, error) {
$xhr = xhr;
}
}).done(function(data) {
$data = data;
if (data.albums.length == 0) {
$(".start").text("No songs found.");
}
else {
$(".start").remove();
recieved_data(data);
}
});
}
function recieved_data(data) {
var i, j;
artist = data.artist;
albums = data.albums;
$(".results .artist").empty();
window.scrollTo(0, 0);
$(".results .artist").append("<div class='artist-title'><span>" + artist + "</span></div>");
$(".results .artist").append("<div class='search'> <input type='text' placeholder='Search a song by " + artist + " (to search, submit)' /> </div>");
for (i = albums.length - 1; i >= 0; i--) {
$album = "";
albumtitle = albums[i].album;
$album += "<div class='album'>";
$album += "<div class='album-title'>Album name: " + albumtitle + "</div>";
songs = albums[i].songs;
for (j = 0; j < songs.length; j++) {
song = songs[j];
song = song.substr(song.indexOf(':') + 1, song.length);
$("#songs").append("<option value='" + song + "' />");
songs_array[songs_array_ind] = song;
songs_array_clean[songs_array_ind] = stringclean(song);
songs_array_ind++;
$album += "<div class='song' id='" + song + "'>";
$album += "<span>" + song + "</span>";
$album += "</div>";
}
$album += "</div>";
$(".results .artist").append($album);
}
// Currently not working on FirefoxOS.
// $(".search input").attr("list", "songs");
$(".search input").on("change", function(event) {
search($(".search input").val());
});
$(".search input").focus();
fit_text();
$(".song").on("click", function() {
song = $(this).children().text();
song_click(song);
});
//artist
//albums array
//each album has album (name), amazonLink, songs (array)
}
});
<file_sep>/README.md
FirefoxOS-lyrics-application
============================
FirefoxOS lyrics application.
The application is in the Firefox Marketplace at https://marketplace.firefox.com/app/lyrics.
Development
-----------
The application is written in HTML5, JavaScript and jQuery. Lyrics are avalible only trough iframes, because there
isn't an public API that can offer lyrics.
Screenshots
-----------
<div align="center">
<img src="screenshots/screenshot.png" />
<span></span>
<img src="screenshots/screenshot1.png" />
<span></span>
<img src="screenshots/screenshot2.png" />
</div>
| 1590f40df92dbc53dc24b107f9ee23f0251461d4 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | MoraruStefan/FirefoxOS-lyrics-application | 634d8d0f26e08f0b35da6e0deda0b79582e66551 | 8a603996c156905d14d670a53f6ab5079de7de73 |
refs/heads/master | <file_sep># sallyhall.github.io
<file_sep>(function() {
'use strict';
$(".workItem").on("click",".fa",function(){
$(this).toggleClass("fa-plus");
$(this).toggleClass("fa-minus");
$(this).siblings("ul").children().toggleClass("hidden");
});
}());
| d1f0adc637af5e955799bf71ebe62d91bde66faa | [
"Markdown",
"JavaScript"
] | 2 | Markdown | sallykingston/sallykingston.github.io | 01706423f6fb4dbd4bdff8deca561195a38f499f | 65adead3b54bdb7e280031accc2ae63b0a294617 |
refs/heads/master | <file_sep>package com.bchd.user.controller;
import com.bchd.common.entity.Result;
import com.bchd.common.utils.JWTUtil;
import com.bchd.user.entity.User;
import com.bchd.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: yth
* @Date: 2019-07-28 11:04
* @Version 1.0
* @Description
*/
@RefreshScope
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService iUserService;
@Autowired
private JWTUtil jwtUtil;
@Value("${jwt.config.key}")
private String jwt;
/**
* 用户登录
* @param user 用户
* @return
*/
@PostMapping("/login")
public Result login(@RequestBody User user){
User userLogin = iUserService.login(user.getMobile(), user.getPassword());
if (StringUtils.isEmpty(userLogin)){
return Result.fail();
}
String token = jwtUtil.createJWT(userLogin.getId(), userLogin.getMobile(), "user");
Map<String,Object> map = new HashMap();
map.put("token",token);
map.put("roles","user");
return Result.success(map);
}
/**
* 用户注册
* @param code 短信验证码
* @param user 用户
* @return
*/
@PostMapping(value = "/register/{code}")
public Result register(@PathVariable String code, @RequestBody User user){
iUserService.addUser(user);
return Result.success();
}
@PostMapping(value = "/test")
public Result test(){
return Result.success(jwt);
}
}
<file_sep>package com.bchd.user.service;
/**
* @Author: yth
* @Date: 2019-07-28 12:11
* @Version 1.0
* @Description
*/
public interface ISendMessageService {
/**
* 向消息队列发送消息
* @param message 消息
*/
void sendMessage(String message);
}
<file_sep>package com.bchd.common.entity;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Data;
import java.io.Serializable;
/**
* @Author: yth
* @Date: 2019-07-28 10:04
* @Version 1.0
* @Description
*/
@Data
@Builder
public class Result implements Serializable {
private String status;
@Builder.Default
private String timestamp = String.valueOf(System.currentTimeMillis());
private String message;
@JsonInclude(JsonInclude.Include.NON_NULL)
private Object data;
public static Result success() {
return Result.builder().status("200").message("执行成功").build();
}
public static Result success(Object object) {
return Result.builder().status("200").message("执行成功").data(object).build();
}
public static Result fail() {
return Result.builder().status("500").message("执行失败").build();
}
public static Result fail(String message) {
return Result.builder().status("500").message(message).build();
}
}
<file_sep>version=1.0-SNAPSHOT
groupId=com.bchd
artifactId=microservice_common
<file_sep>package org.bchd.im;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @Author: yth
* @Date: 2019-04-20 16:45
* @Version 1.0
* @Description
*/
@SpringBootApplication
@EnableDiscoveryClient
public class IMApplication {
public static void main(String[] args) {
SpringApplication.run(IMApplication.class, args);
}
}
<file_sep>package org.bchd.im.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: yth
* @Date: 2019-08-26 20:27
* @Version 1.0
* @Description
*/
@RestController
@RefreshScope
public class test {
@Value("${name}")
public String name;
@PostMapping("/test")
public String test(){
return name;
}
}
| 106507b169755f9fcc67f5f2a9ded0f8bfe515b1 | [
"Java",
"INI"
] | 6 | Java | yutenghui/microservice | 136f1bff42d1671f839211bfdf9cbda428e8bd9e | 717561e30435bd35fdc32f398d98e54b08e56952 |
refs/heads/master | <file_sep># mars-rover-python
## Challenge
You are on a team programming the remotely controlled Mars Rover robot.
Given an initial starting point (x,y), an initial direction the robot is facing, and a list of commands, you want to be able to calculate what the end point (x’, y’) will be.
The robot can move forward and backward, as well as turn left and right. Turning does not change the position of the rover, but the action must update the cardinal direction of the rover.
Using the test file as guidance, please develop a program that will calculate the final location of the rover after it has executed a list of commands.
### Available commands
"L" -> turn left
"R" -> turn right
"F" -> go forward
"B" -> go backward
Note: These are not simple Up, Down, Left, Right commands! In order to go up, the rover must face up (either by turning left or right, depending on its direction) and then execute a "F" command. Keep this in mind while designing tests.
### Cardinal Directions
East
North
West
South
## To Execute tests
Run `python tests.py`
## Advanced Post Passing Tests Tasks
1. Imagine the grid is infinite -- if the rover receives an "F" command when it is facing right on the rightmost edge of the grid, the rover should appear on the leftmost edge of the grid in the same Y positon in the grid, still facing right. This "wrapping" should hold for all corners of the board.
2. Implement a visualization that shows the user where they are at each stage of the string of commands. You have a lot of freedom here! You may start with printing positions to the command line, and ideally you will wire up a Flask app that gives users a frontend from the web!
<file_sep>import unittest
from rover import Rover
from position import Position
from direction import Direction
class RoverTest(unittest.TestCase):
def test_west_turn_left(self):
direction = Direction.W
position = Position(0,0)
rover = Rover(position, direction)
commands = ('l')
rover.execute(commands)
self.assertEquals(Position(0, 0), rover.get_position())
self.assertEquals(Direction.S, rover.get_direction())
@unittest.skip("unskip this line when you are ready for the next test")
def test_west_turn_right(self):
direction = Direction.W
position = Position(0,0)
rover = Rover(position, direction)
commands = ('r')
rover.execute(commands)
self.assertEquals(Position(0, 0), rover.get_position())
self.assertEquals(Direction.N, rover.get_direction())
@unittest.skip("unskip this line when you are ready for the next test")
def test_east_turn_left(self):
direction = Direction.E
position = Position(0,0)
rover = Rover(position, direction)
commands = ('l')
rover.execute(commands)
self.assertEquals(Position(0, 0), rover.get_position())
self.assertEquals(Direction.N, rover.get_direction())
@unittest.skip("unskip this line when you are ready for the next test")
def test_east_turn_right(self):
direction = Direction.E
position = Position(0,0)
rover = Rover(position, direction)
commands = ('r')
rover.execute(commands)
self.assertEquals(Position(0, 0), rover.get_position())
self.assertEquals(Direction.S, rover.get_direction())
@unittest.skip("unskip this line when you are ready for the next test")
def test_move_one_forward(self):
direction = Direction.N
position = Position(0,0)
rover = Rover(position, direction)
commands = ('f')
rover.execute(commands)
self.assertEquals(Position(0, 1), rover.get_position())
self.assertEquals(Direction.N, rover.get_direction())
@unittest.skip("unskip this line when you are ready for the next test")
def test_move_one_forward_one_backward(self):
direction = Direction.N
position = Position(0,0)
rover = Rover(position, direction)
commands = ('f', 'b')
rover.execute(commands)
self.assertEquals(Position(0, 0), rover.get_position())
self.assertEquals(Direction.N, rover.get_direction())
@unittest.skip("unskip this line when you are ready for the next test")
def test_move_one_forward_two_backward_north(self):
direction = Direction.N
position = Position(0,0)
rover = Rover(position, direction)
commands = ('f', 'b', 'b')
rover.execute(commands)
self.assertEquals(Position(0, -1), rover.get_position())
self.assertEquals(Direction.N, rover.get_direction())
@unittest.skip("unskip this line when you are ready for the next test")
def test_move_one_forward_two_backward_turn_left(self):
direction = Direction.N
position = Position(0,0)
rover = Rover(position, direction)
commands = ('f', 'b', 'b', 'l')
rover.execute(commands)
self.assertEquals(Position(0, -1), rover.get_position())
self.assertEquals(Direction.W, rover.get_direction())
@unittest.skip("unskip this line when you are ready for the next test")
def test_turn_left_and_go_forward(self):
direction = Direction.N
position = Position(0,0)
rover = Rover(position, direction)
commands = ('l', 'f', 'f', 'f')
rover.execute(commands)
self.assertEquals(Position(-3, 0), rover.get_position())
self.assertEquals(Direction.W, rover.get_direction())
@unittest.skip("unskip this line when you are ready for the next test")
def test_turn_right_and_go_forward(self):
direction = Direction.N
position = Position(0,0)
rover = Rover(position, direction)
commands = ('r', 'f', 'f', 'f')
rover.execute(commands)
self.assertEquals(Position(3, 0), rover.get_position())
self.assertEquals(Direction.E, rover.get_direction())
@unittest.skip("unskip this line when you are ready for the next test")
def test_do_a_lot_of_silly_stuff(self):
direction = Direction.S
position = Position(0,0)
rover = Rover(position, direction)
commands = ('r', 'f', 'f', 'f', 'b', 'r')
rover.execute(commands)
self.assertEquals(Position(-2, 0), rover.get_position())
self.assertEquals(Direction.N, rover.get_direction())
if __name__ == '__main__':
unittest.main()
<file_sep>class Direction:
def todo():
print("implement")
<file_sep>class Rover:
def execute(self, commands):
print("implement me!")
| e25929e1f5f6d1fe9e8338bee2f0a6f97ff6ba7d | [
"Markdown",
"Python"
] | 4 | Markdown | kre64/mars-rover-python | a4db2f5177d59bc1b6553e75d791a7f89c60543c | 193c9337da68cdcc641c5938687daa1eadb4b2c8 |
refs/heads/master | <repo_name>haojian/InformationVisualization<file_sep>/python/signalprocessing/wchirp.py
#from pylab import *
#X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
#C,S = np.cos(X), np.sin(X)
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x[0:5])
y = np.cos(x[5:10])
plt.plot(x, y)
plt.show()<file_sep>/python/matplotlib_pydata2013-master/notebooks/soln/cube_combined.py
from tutorial_lib.simple_cube import Cube
c = Cube()
fig, ax = plt.subplots(figsize=(8, 8),
subplot_kw=dict(xticks=[], yticks=[]))
c.add_to_ax(ax)
c.rotate(c.x - c.y, -np.pi / 6)
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
def zoom(val):
c.set_view((0, 0, val))
ax.set_xlim(-val, val)
ax.set_ylim(-val, val)
fig.canvas.draw()
slider_ax = fig.add_axes((0.2, 0.05, 0.6, 0.02))
slider = Slider(slider_ax, "perspective", 1, 20, valinit=10, color='#AAAAAA')
slider.on_changed(zoom)
def button_press(event):
c.xy_click = (event.x, event.y)
if event.inaxes is ax:
c.mouse_down = True
def button_release(event):
c.mouse_down = False
def motion_notify(event):
if c.mouse_down:
dx = event.x - c.xy_click[0]
dy = event.y - c.xy_click[1]
c.xy_click = (event.x, event.y)
c.rotate(c.y, -1E-2 * dx)
c.rotate(c.x, 1E-2 * dy)
fig.canvas.draw()
fig.canvas.mpl_connect('button_press_event', button_press)
fig.canvas.mpl_connect('button_release_event', button_release)
fig.canvas.mpl_connect('motion_notify_event', motion_notify)
<file_sep>/python/signalprocessing/lowpass.py
# run it with 'python script.py <infile.wav> <outfile.wav>'
import wave, sys
from scipy.signal import convolve, remez
from scipy import array
from struct import *
# design the filter coefficents
filt = remez(400, array([0, 100, 110, 500, 550, 22050]),
array([0, 1, 0]), Hz = 44100)
# set up the input and output files
inFileName, outFileName = sys.argv[1:]
inFile = wave.open(inFileName, 'r')
outFile = wave.open(outFileName, 'w')
outFile.setparams(inFile.getparams())
# load each channel into a list
left = []; right = []
for x in xrange(inFile.getnframes()):
inData = inFile.readframes(1)
leftData, rightData = unpack('hh', inData)
left.append(leftData); right.append(rightData)
# do the convolution (i.e. apply the filter)
newLeft = convolve(filt, array(left))
newRight = convolve(filt, array(right))
# write the new file out
for x in xrange(len(newLeft)):
if x % 10000 is 0:
print x, 'of', inFile.getnframes()
outFile.writeframes(pack('hh', newLeft[x], newRight[x]))<file_sep>/python/matplotlib_pydata2013-master/notebooks/soln/circles.py
N = 30
fig, ax = plt.subplots()
ax.set_xlim(-0.3, 1.3)
ax.set_ylim(-0.3, 1.3)
for i in range(N):
circ = plt.Circle(np.random.random(2), 0.1 * (1 + np.random.random()),
alpha=0.5, picker=True)
ax.add_patch(circ)
def on_pick(event):
artist = event.artist
artist.set_color(np.random.random(3))
fig.canvas.draw()
fig.canvas.mpl_connect('pick_event', on_pick)
| 070c44575fb34c3865b8ae05e1f5803541857834 | [
"Python"
] | 4 | Python | haojian/InformationVisualization | 624c2a5c4859958880bf522b80de39e55cd0f4c3 | f0ba842c6acac1d38dc2b5796430a2e88ac16f30 |
refs/heads/master | <repo_name>JuniorBSilva/dadosClimaREST<file_sep>/dadosClimaREST/www/js/dadosClimaRESTCtrl.js
var dadosClimaREST = angular.module('dadosClimaREST', ["ionic"]);
dadosClimaREST.controller('dadosClimaRESTCtrl', function($scope, $http){
$scope.url = "http://api.openweathermap.org/data/2.5/weather?q=";
$scope.temperatura = "";
$scope.humidade = "";
$scope.velVento = "";
$scope.nomeCidade = "";
$scope.pressao = "";
$scope.lat = "";
$scope.lon = "";
$scope.cidade = "Lins";
$scope.icone = "";
$scope.descricaoTempo = "";
$scope.mostrarDados = false;
$scope.loadDados = function(){
$http
.get($scope.url+$scope.cidade+"&units=metric&lang=pt")
.success(function(resultado){
console.log(resultado);
$scope.temperatura = resultado.main.temp;
$scope.humidade = resultado.main.humidity;
$scope.velVento = resultado.wind.speed;
$scope.nomeCidade = resultado.name;
$scope.pressao = resultado.main.pressure;
$scope.lat = resultado.coord.lat;
$scope.lon = resultado.coord.lon;
$scope.icone = resultado.weather[0].icon;
$scope.descricaoTempo = resultado.weather[0].description;
$scope.mostrarDados = true;
})
.error(function(){
alert("Não foi possível carregar os dados");
});
}
}); | 407e2fac62ce5b4508ed97aa71fa42e647c323ee | [
"JavaScript"
] | 1 | JavaScript | JuniorBSilva/dadosClimaREST | fe6abb2cab69a88f900415b6cfa27a97781751c9 | ccd6ed6c9f58399b190d83aba15dd8b7fec44f34 |
refs/heads/master | <file_sep>using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using UnityEngine;
namespace UnityEditor
{
public class Pipeline
{
[MenuItem("Pipeline/Build: Android")]
public static void BuildAndroid()
{
UpdateBuildNumberIdentifier();
Directory.CreateDirectory(pathname);
var report = BuildPipeline.BuildPlayer(new BuildPlayerOptions
{
locationPathName = Path.Combine(pathname, filename),
scenes = EditorBuildSettings.scenes.Where(n =>
n.enabled).Select(n => n.path).ToArray(),
target = BuildTarget.Android
});
UnityEngine.Debug.Log(report);
}
/*
* This is a static property which will return a string, representing a
* build folder on the desktop. This does not create the folder when it
* doesn't exists, it simply returns a suggested path. It is put on the
* desktop, so it's easier to find but you can change the string to any
* path really. Path combine is used, for better cross platform support
*/
public static string pathname
{
get
{
return @"C:\Users\<NAME>\Google Drive\DADIU 2019\builds\" + repoBranchName;
//return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), @"Builds\" + repoBranchName);
}
}
/*
* This returns the filename that the build should spit it. For a start
* this just returns a current date, in a simple lexicographical format
* with the apk extension appended. Later on, you can customize this to
* include more information, such as last person to commit, what branch
* were used, version of the game, or what git-hash the game were using
*/
public static string filename
{
get
{
return (DateTime.Now.ToString("yyyyMMddHHmm") + repoBranchName + ".apk");
}
}
public static string repoBranchName
{
get
{
ProcessStartInfo startInfo = new ProcessStartInfo("git.exe");
startInfo.UseShellExecute = false;
startInfo.WorkingDirectory = @"C:\Users\<NAME>\.jenkins\workspace\DADIU MP2 by Team 1\All Branches\Detective_Switch";
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.Arguments = "rev-parse --abbrev-ref HEAD";
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
string branchname = process.StandardOutput.ReadLine();
return branchname;
}
}
public static void UpdateBuildNumberIdentifier()
{
int buildNum = 0;
string text = "";
string number = "";
string buildNumFilePath = Application.dataPath + "/Resources/buildNumbers.txt";
FileStream file = File.Open(buildNumFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
file.Close();
TextAsset buildNRFile = Resources.Load("buildNumbers") as TextAsset;
string allLines = buildNRFile.text;
string[] everyLine = new string[2];
if (allLines.Count<Char>() > 0)
{
everyLine = allLines.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
}
//string[] everyLine = File.ReadAllLines(buildNumFilePath);
if (everyLine.Length > 0)
{
UnityEngine.Debug.Log("The build number file contains: \n" + everyLine[0] + " " + everyLine[1]);
text = everyLine[0];
number = everyLine[1];
}
try
{
buildNum = int.Parse(number);
}
catch (Exception e)
{
}
int curBuildNum = buildNum + 1;
if (number == "")
{
buildNum = 1;
}
string[] debugString = new string[2];
debugString[0] = "The current build number of the project is";
debugString[1] = curBuildNum.ToString();
UnityEngine.Debug.Log("Cur build nr = " + curBuildNum);
File.WriteAllLines(buildNumFilePath, debugString);
UnityEngine.Debug.Log("I have updated the build number");
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Blacklight : MonoBehaviour
{
public Vector2 initSize;
public Transform effector;
Renderer rend;
/* Static setting of AlphaClipThreshold in the appropriate shader is required,
* depending on size of circle. For 0.5, a threshold of 1.5 is suitable
* There might be a correlation, like 1 from size, but this is yet untested.
*/
void Start()
{
rend = GetComponent<Renderer>();
if (initSize == new Vector2(0,0))
{
initSize = rend.sharedMaterial.GetVector("_size");
}
Debug.Log(initSize);
}
void Update()
{
RaycastHit hit;
Ray ray = new Ray(effector.position, effector.forward);
if (Physics.Raycast(ray, out hit))
{
//Debug.Log(hit.collider.gameObject);
if (hit.collider.gameObject == gameObject)
{
rend.sharedMaterial.SetVector("_blacklightpos", hit.point);
rend.sharedMaterial.SetVector("_size", new Vector4(initSize.x, initSize.y, 0, 0));
Debug.Log("Hit the plane");
}
else
{
Debug.Log("Didn't hit plane");
rend.sharedMaterial.SetVector("_size", new Vector4(0, 0, 0, 0));
}
}
}
}<file_sep># MP2-Detective_Switch
By DADIU 2019 Team 1 "En'vision"
| 6da25267185e6da5c1aaa460d36b77aa94493e67 | [
"Markdown",
"C#"
] | 3 | C# | DADIU-2019-Team-1/MP2-Detective_Switch | cf66c380a659ec73ddc0f29c3b6bd57cb59fab0f | 08f87da973cfb8e9208beb50215f45dee095edd6 |
refs/heads/master | <file_sep>var express = require("express");
// var logger = require("morgan");
var mongoose = require("mongoose");
// Our scraping tools
// Axios is a promised-based http library, similar to jQuery's Ajax method
// It works on the client and on the server
var axios = require("axios");
var cheerio = require("cheerio");
// Require all models
var db = require("./models");
var PORT = process.env.PORT || 3000;
// Initialize Express
var app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
var exphbs = require("express-handlebars");
app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");
// Configure middleware
// // Use morgan logger for logging requests
// app.use(logger("dev"));
// Make public a static folder
app.use(express.static("public"));
// Connect to the Mongo DB
// mongoose.connect("mongodb://localhost/unit18Populater", { useNewUrlParser: true });
// If deployed, use the deployed database. Otherwise use the local mongoHeadlines database
var MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost/twosense";
mongoose.connect(MONGODB_URI);
// Routes
// A GET route for scraping the echoJS website
app.get("/scrape", function(req, res) {
// First, we grab the body of the html with axios
axios.get("http://www.wsj.com/").then(function(response) {
// Then, we load that into cheerio and save it to $ for a shorthand selector
var $ = cheerio.load(response.data);
// Now, we grab every h2 within an article tag, and do the following:
$("article").each(function(i, element) {
// Save an empty result object
var result = [];
// Add the text and href of every link, and save them as properties of the result object
var title = $(this).find("h3").find("a").text();
var link = $(this).find("h3").find("a").attr("href");
var summary = $(this).find("p").text();
result.push({
title: title,
link: link,
summary: summary
});
console.log(result);
// Create a new Article using the `result` object built from scraping
db.Article.create(result)
.then(function(dbArticle) {
// View the added result in the console
// console.log(dbArticle);
// console.log(result);
console.log("articles added to database")
})
.catch(function(err) {
// If an error occurred, log it
console.log(err);
});
});
// Send a message to the client
console.log("articles added to database")
});
});
// Route for getting all Articles from the db
app.get("/", function(req, res) {
db.Article.find({})
.then(function(dbArticle) {
var articleArray = [];
for (var i=0; i < dbArticle.length; i++){
articleArray.push({headline: dbArticle[i].title, link: dbArticle[i].link, summary: dbArticle[i].summary, id: dbArticle[i]._id});
}
res.render("index", {article: articleArray});
})
.catch(function(err) {
// If an error occurs, send it back to the client
res.json(err);
});
});
// Route for grabbing a specific Article by id, populate it with it's note
app.get("/articles/:id", function(req, res) {
// route so it finds one article using the req.params.id,
// and run the populate method with "note",
// then responds with the article with the note included
db.Article.findById(req.params.id)
// Specify that we want to populate the retrieved libraries with any associated books
.populate("comment")
.then(function(dbArticle) {
console.log(dbArticle);
res.json(dbArticle);
})
.catch(function(err) {
// If an error occurs, send it back to the client
res.json(err);
});
});
// Route for saving/updating an Article's associated Note
app.post("/articles/:id", function(req, res) {
// TODO
// ====
// save the new note that gets posted to the Notes collection
// then find an article from the req.params.id
// and update it's "note" property with the _id of the new note
db.Comment.create(req.body)
.then(function(dbComment) {
// If a Book was created successfully, find one library (there's only one) and push the new Book's _id to the Library's `books` array
// { new: true } tells the query that we want it to return the updated Library -- it returns the original by default
// Since our mongoose query returns a promise, we can chain another `.then` which receives the result of the query
return db.Article.findOneAndUpdate({_id: req.params.id}, { $push: { comment: dbComment._id } }, { new: true });
})
.then(function(dbArticle) {
// If the Library was updated successfully, send it back to the client
res.json(dbArticle);
})
.catch(function(err) {
// If an error occurs, send it back to the client
res.json(err);
});
});
app.get("/api/articles/:id", function(req, res){
db.Article.findById(req.params.id)
.populate("comment")
.then(function(dbArticle) {
console.log(dbArticle);
res.json(dbArticle);
})
.catch(function(err) {
// If an error occurs, send it back to the client
res.json(err);
});
});
app.delete("/delete/:id", function(req, res){
db.Comment.findByIdAndRemove(req.params.id, function(err){
res.json(err);
})
})
// Start the server
app.listen(PORT, function() {
console.log("App running on port " + PORT + "!");
});
<file_sep># Two-Sense
A server-side application that scrapes the Wall Street Journal for news articels and allows users to comment on recent headlines.
## What does it do?
This app allows users to scape the web to display recent news article headlines and a brief summary. Users can click the headline to read the full article on the original site. Users can also click "View/Add Comments" to see comments other users have left, and/or add their own comments.
## How does it work?
This app uses cheerio to scrape the web site for news articles. It then stores the articles and the comments in a MongoDB database using Monggoose and express. Express-handlebars is used to display data on the page.
## Try it Out:
Click [here](https://polar-cove-40006.herokuapp.com/)
<file_sep>$(document).ready(function () {
console.log("ready");
$("#comment-div").hide();
$("#scrape").on("click", function () {
// console.log("scraping for new articles")
$.ajax({
method: "GET",
url: "/scrape"
}).then(function (data) {
console.log("scraped /n/n" + data)
})
location.reload();
});
$(".view-add-comments").on("click", function () {
var articleID = $(this).attr("data-id");
var articleTitle = $(this).attr("data-title");
console.log(articleID);
console.log(articleTitle);
$("#comment-div").show();
$("#comments").empty();
// var title = $("<h3>");
var title = $("#title");
title.text(articleTitle);
$("#comment-div").prepend(title);
$.ajax({
method: "GET",
url: "/api/articles/" + articleID
})
// With that done, add the note information to the page
.then(function (data) {
console.log(data);
var commentArray = data.comment;
if (commentArray) {
// for (var i=0; i<commentArray.length; i++) {
var userName = $("<h5>");
userName.text(commentArray.name + "'s Two Cents:");
var userComment = $("<p>");
userComment.text(commentArray.body);
var deleteBtn = $("<button>");
deleteBtn.text("Delete");
deleteBtn.addClass("btn btn-secondary");
deleteBtn.attr("id", "delete-btn");
deleteBtn.attr("type", "button");
deleteBtn.attr("data-id", commentArray._id);
$("#comments").append(userName);
$("#comments").append(userComment);
$("#comments").append(deleteBtn);
// }
}
else {
var noComment = $("<p>");
noComment.text("Be the first to add a comment");
$("#comments").append(noComment);
};
});
$(".submit-btn").on("click", function (event) {
event.preventDefault();
console.log($(".user-name").val());
console.log($("#usercomment").text());
var newComment = {
name: $(".user-name").val(),
body: $("#usercomment").val()
}
console.log(newComment);
console.log(articleID);
$.ajax({
method: "POST",
url: "/articles/" + articleID,
data: newComment
})
.then(function (data) {
console.log("added: " + data);
console.log(JSON.stringify(data));
});
$(".user-name").val("");
$("#usercomment").val("");
location.reload();
});
$("#comment-div").on("click", "#delete-btn", function () {
event.preventDefault();
console.log("fuck this!!!");
var commentID = $(this).attr("data-id");
console.log(commentID);
$.ajax({
method: "DELETE",
url: "/delete/" + commentID,
success: function(data) {
console.log("comment deleted")
},
error: function() {
console.log("error");
}
})
.then(function () {
location.reload();
});
});
})
}); | 6046ef59239f4ca805e4059e8dadba3de0e656d8 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | kimberlycase91/Two-Sense | 21f3edf0f7824eb8cbe4866e2a1d54d0812b9e97 | dd8bc35ded23e48b9efb3551ff290e3e3f7bd5fa |
refs/heads/master | <file_sep>from websocket import create_connection
# ws = create_connection("ws://forestwebsocket.herokuapp.com/test")
ws = create_connection("ws://127.0.0.1:8000/test")
# print("Sending 'Hello, World'...")
# ws.send("send task")
# print("Sent")
# print("Receiving...")
result = ws.recv()
print(result)
ws.close()
# import asyncio
# import websockets
# uri = "ws://127.0.0.1:8000/test"
# websockets.connect(uri)
# async def hello():
# uri = "ws://127.0.0.1:8000/test"
# async with websockets.connect(uri) as web:
# await web.send("send task")
# print(await web.recv())
# asyncio.get_event_loop().run_until_complete(hello())<file_sep>aioredis==1.3.1
asgiref==3.3.1
async-timeout==3.0.1
attrs==20.3.0
autobahn==21.3.1
Automat==20.2.0
cffi==1.14.5
channels-redis==3.2.0
constantly==15.1.0
cryptography==3.4.6
daphne==3.0.1
dj-database-url==0.5.0
Django==3.1.7
django-heroku==0.3.1
djangorestframework==3.12.2
gunicorn==20.0.4
hiredis==1.1.0
hyperlink==21.0.0
idna==3.1
incremental==21.3.0
msgpack==1.0.2
msgpack-python==0.5.6
psycopg2==2.8.6
pyasn1==0.4.8
pyasn1-modules==0.2.8
pycparser==2.20
pyOpenSSL==20.0.1
python-decouple==3.4
pytz==2021.1
service-identity==18.1.0
six==1.15.0
sqlparse==0.4.1
Twisted==21.2.0
txaio==21.2.1
websocket-client==0.58.0
websockets==8.1
whitenoise==5.2.0
zope.interface==5.2.0
<file_sep>from django.urls import path
from main import views
urlpatterns = [
path("", views.home, name="home"),
path('test_api', views.Test_api.as_view(), name='test_api'),
]<file_sep>from django.http import HttpResponse
from main import models
from rest_framework.views import APIView
from rest_framework.response import Response
import json
import datetime
# import routing
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
def home(request):
return HttpResponse("Hello, Django!")
class Test_api(APIView):
def post(self,request):
print("request accepted")
async_to_sync(get_channel_layer().group_send)(
"pratik",
{
'type': 'send_message',
'message': "I am Ravi"
}
)
return Response({"data":"Ravi"})<file_sep>from django.urls import re_path, path
from . import consumers
websocket_urlpatterns = [
# re_path(r'ws/chat/(?P<friendship_id>\w+)/$', consumers.ChatConsumer.as_asgi()),
path('test', consumers.Websocket.as_asgi(), name='test'),
]<file_sep>import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from channels.layers import get_channel_layer
class Websocket(WebsocketConsumer):
# def connect(self):
# print("connecting",self.channel_name)
# self.accept()
# def disconnect(self, close_code):
# print("disconnecting")
# pass
# def receive(self, text_data):
# print("rec",text_data)
# self.send(text_data=json.dumps({
# 'message': 123
# }))
# def __init__(self):
# self.room_group_name = "ravi"
# print("constructor")
# print(get_channel_layer())
def connect(self):
# Join room group
print("connecting")
async_to_sync(get_channel_layer().group_add)(
"pratik",
self.channel_name
)
self.accept()
def disconnect(self, close_code):
# Leave room group
async_to_sync(self.channel_layer.group_discard)(
"pratik",
self.channel_name
)
# Receive message from WebSocket
def receive(self, text_data):
print("recieving",text_data)
# text_data_json = json.loads(text_data)
# message = text_data_json
# Send message to room group
async_to_sync(self.channel_layer.group_send)(
"pratik",
{
'type': 'chat_message',
'message': text_data + " from ravi"
}
)
# # Receive message from room group
def chat_message(self, event):
print("chat message",event)
# message=event['message']
# Send message to WebSocket
# message["message"]+=" from Ravi"
self.send(text_data=event['message'])
def send_message(self,event):
print("Sending from server",event)
self.send(text_data=event['message'])<file_sep>"""
ASGI config for server project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
# import os
# from django.core.asgi import get_asgi_application
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings')
# application = get_asgi_application()
# import os
# from channels.auth import AuthMiddlewareStack
# from channels.routing import ProtocolTypeRouter, URLRouter
# from django.core.asgi import get_asgi_application
# import main.routing
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")
# application = ProtocolTypeRouter({
# "http": get_asgi_application(),
# "websocket": AuthMiddlewareStack(
# URLRouter(
# main.routing.websocket_urlpatterns
# )
# ),
# })
# import os
# from django.conf.urls import url
# from django.core.asgi import get_asgi_application
# import main.routing
# # Fetch Django ASGI application early to ensure AppRegistry is populated
# # before importing consumers and AuthMiddlewareStack that may import ORM
# # models.
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")
# django_asgi_app = get_asgi_application()
# from channels.auth import AuthMiddlewareStack
# from channels.routing import ProtocolTypeRouter, URLRouter
# from channels.layers import get_channel_layer
# channel_layer=get_channel_layer()
# application = ProtocolTypeRouter({
# # Django's ASGI application to handle traditional HTTP requests
# "http": django_asgi_app,
# # WebSocket chat handler
# "websocket": AuthMiddlewareStack(
# URLRouter(
# main.routing.websocket_urlpatterns
# )
# ),
# })
import os
import django
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")
django.setup()
application = get_default_application() | 779ba2123807ecf6e6376a71e92cfe3c3b8fd3de | [
"Python",
"Text"
] | 7 | Python | ravinalawade/forestweb-socket | 57f8d3b724189b63e3e81606b651ce62cec67763 | 53265ce6a426e0fa773aef8bcb8659437c6c185d |
refs/heads/master | <file_sep># uptimerobo
This is a Uptimerobo!
# Adding your url
- fork the repo
- add your url in `url.js`
- create a pull request
<file_sep>const axios = require("axios");
const urls = require("./url.js");
const uptimerobo = async () => {
setInterval(() => {
urls.forEach(url => {
axios.get(url).then(() => console.log("Pong at " + Date.now())).catch(() => {});
});
}, 60 * 1000);
};
uptimerobo();
<file_sep>const urls = [
"http://aurora-discord-bot-hehe.glitch.me/ping",
"http://snfdev.glitch.me",
"http://p74y.glitch.me",
"http://giveawayboat-discord.glitch.me",
"http://snowboats.glitch.me",
"http://elixirbot.glitch.me",
"http://bestest-bot.glitch.me",
"http://zyrouge-bot-list.glitch.me/ping",
"https://api.zyrouge.gq",
"https://uttermost-pinto-wheel.glitch.me"
];
module.exports = urls;
| 2eaeed7de11f05ad5de753073aed39366b2d6035 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | shadeoxide/uptimerobo | b04186e6ad9679ed88d2155972179bc6abcd8542 | cadc8107e22d5f8c7801b189ec4ad4519a415d7c |
refs/heads/main | <repo_name>Vincent9o9/ajax-ex-calendar<file_sep>/js/script.js
// Descrizione:
// Creiamo un calendario dinamico con le festività.
// Il calendario partirà da gennaio 2018 e si concluderà a dicembre 2018
// (unici dati disponibili sull’API).
// Milestone 1
// Creiamo il mese di Gennaio, e con la chiamata all'API inseriamo le festività.
// Milestone 2
// Diamo la possibilità di cambiare mese, gestendo il caso in cui l’API non possa
// ritornare festività.
// Link API: https://flynn.boolean.careers/exercises/api/holidays?year=2018&month=0
// "response": [
// {
// "name": "Capodanno",
// "date": "2018-01-01"
// },
// {
// "name": "Epifania",
// "date": "2018-01-06"
// }
// ]
$(document).ready(function() {
var dataCorrente = moment($("h1.month").attr("data-this-date"));
days(dataCorrente);
holidays(dataCorrente);
$("button#next").click(function() {
next(dataCorrente)
});
$("button#prev").click(function() {
prev(dataCorrente)
});
});
// ** FUNZIONI **
function days(data) {
$("ul.month-list").empty();
var daysMonth = data.daysInMonth();
var month = data.format("MMMM");
var year = data.format("YYYY");
$("h1.month").html(month + " " + year);
for (var i = 1; i <= daysMonth; i++) {
var source = $("#day-template").html();
var template = Handlebars.compile(source);
var context = {
day: addZero(i),
month: month,
completeDate: year + "-" + data.format("MM") + "-" + addZero(i),
};
var html = template(context);
$(".month-list").append(html);
};
};
function addZero(n) {
if (n < 10) {
return "0" + n;
}
return n;
};
function holidays(data){
$.ajax(
{
url: 'https://flynn.boolean.careers/exercises/api/holidays',
method: 'GET',
data:{
year: data.year(),
month: data.month()
},
success : function(risposta){
for (var i = 0; i < risposta.response.length; i++) {
var listItem = $('li[data-completa="'+ risposta.response[i].date + '"]');
listItem.addClass('holiday');
listItem.append('-' + risposta.response[i].name);
}
},
error: function (){
alert('errore')
}
}
);
};
function next(data) {
if (data.month() == 11) {
alert("Non puoi proseguire");
} else {
data.add(1, "months");
days(data);
holidays(data);
}
};
function prev(data) {
if (data.month() == 0) {
alert("Non puoi proseguire");
} else {
data.subtract(1, "months");
days(data);
holidays(data);
}
};
| 2691d5528631c600335ddea037c42dfbb75c21fb | [
"JavaScript"
] | 1 | JavaScript | Vincent9o9/ajax-ex-calendar | fa93addf13add5c34ed9bc26f17505aac507d838 | 5b24563535eebd0797c0a51b2ea1bf5d6de3f357 |
refs/heads/master | <file_sep>import os
import re
from datetime import datetime as dt
import pandas as pd
from scrapy.linkextractors import LinkExtractor
from scrapy.selector import Selector
from scrapy.spider import CrawlSpider, Rule
from housing.items import ScrapySmartShanghaiItem
def remove_spaces(str):
return " ".join(str.split()).encode('utf-8')
class HousingSpider(CrawlSpider):
name = 'ss_housing'
start_urls = ["http://www.smartshanghai.com/housing/apartments-rent/"]
allowed_domains = ["smartshanghai.com"]
file_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + "/output/listings.jl"
df = pd.read_json(file_path, lines=True)
# deny_list = ['(\/housing\/apartments\-rent\/%s)' % str(listing_id) for listing_id in df.listing_id]
# print deny_list
rules = [
Rule(
LinkExtractor(
allow='/housing/apartments-rent/(.+)',
# deny=deny_list,
restrict_css='.left'),
callback='parse_listing'),
Rule(
LinkExtractor(
allow='page=(\d+)',
restrict_css='.pagination'))
]
def parse_listing(self, response):
item = ScrapySmartShanghaiItem()
item['listing_id'] = re.match('[^0-9]*\/([0-9]*)', response.url).group(1)
heading = response.xpath('//div[@id="content-listing"]').xpath('.//div[@class="tupian"]//div[@class="wenzi"]')
item['author'] = heading.xpath('./a/text()').extract_first()
item['title'] = response.xpath('.//div[@class="mingzi"]/text()').extract_first()
item['view_count'] = response.xpath('//div[@class="qiyexinxi"]/ul/li/text()').re_first('([0-9]*)')
item['scrape_time'] = str(dt.utcnow())
publish_time = heading.xpath('./text()').re_first('([a-zA-Z]*\s{1,2}[0-9]{1,2}, [0-9]{4,}.*)')
if publish_time:
publish_time = re.sub(' +', ' ', publish_time)
item['publish_time'] = dt.strptime(publish_time, '%B %d, %Y, at %H:%M %p')
def grab_second_div(value, search_re=None, xpath=None):
for divpair in response.xpath('.//div[@class="xinxi"]/ul/li').extract():
if re.search(search_re, divpair):
newresponse = Selector(text=divpair)
item[value] = remove_spaces("".join(newresponse.xpath(xpath).extract()))
grab_second_div(value='metro', search_re='METRO:', xpath='//div[@class="wenzi station"]/text()')
grab_second_div(value='price', search_re='PRICE:', xpath='//div[@class="wenzi"]/text()')
grab_second_div(value='area', search_re='AREA:', xpath='//div[@class="wenzi"]/text()')
grab_second_div(value='rooms', search_re='ROOMS:', xpath='//div[@class="wenzi"]/text()')
grab_second_div(value='compound', search_re='COMPOUND:', xpath='//div[@class="wenzi"]/text()')
grab_second_div(value='size', search_re='SIZE:', xpath='//div[@class="wenzi"]/text()')
grab_second_div(value='floor', search_re='FLOOR:', xpath='//div[@class="wenzi"]/text()')
grab_second_div(value='area', search_re='AREA:', xpath='//div[@class="wenzi"]/text()')
grab_second_div(value='posted_type', search_re='TYPE:', xpath='//div[@class="wenzi"]/text()')
grab_second_div(value='metro', search_re='METRO:', xpath='//div[@class="wenzi"]/text()')
for divpair in response.xpath('.//div[@class="link"]').extract():
if re.search('Description', divpair):
newresponse = Selector(text=divpair)
item['description'] = "".join(newresponse.xpath('//div[@class="wenzi"]/text()').extract()).encode(
'utf-8'
)
for resp in response.xpath('//script'):
item['latitude'] = resp.re_first(r"[^//]var latitude = ([0-9\.]*)")
item['longitude'] = resp.re_first(r"[^//]var longitude = ([0-9\.]*)")
for a in response.xpath('.//div[@class="fast-navigation"]/ul/li[@class="silver"]/text()').extract():
key = a.lower().strip().replace('-', '_').replace(' ', '_')
item[key] = 0
for a in response.xpath('.//div[@class="fast-navigation"]/ul/li[@class="black"]/text()').extract():
key = a.lower().strip().replace('-', '_').replace(' ', '_')
item[key] = 1
yield item
<file_sep># -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
import os
from datetime import datetime
import pandas as pd
from scrapy.exceptions import DropItem
def myconverter(o):
if isinstance(o, datetime):
return o.__str__()
class ScrapySmartShanghaiPipeline(object):
def __init__(self):
self.file_path = os.path.dirname(os.path.dirname(__file__)) + "/output/listings.jl"
df = pd.read_json(self.file_path, lines=True)
if df.empty:
self.ids_seen=set()
else:
self.ids_seen = set(df.listing_id)
def open_spider(self, spider):
self.file = open(self.file_path, 'a')
def close_spider(self, spider):
self.file.close()
def process_item(self, item, spider):
if item['listing_id'] in self.ids_seen:
raise DropItem("Duplicate item found: %s" % item)
elif item['author'] is None:
raise DropItem("Null listing found: %s" % item)
else:
self.ids_seen.add(item['listing_id'])
if self.ids_seen:
line = "\n" + json.dumps(dict(item), default=myconverter)
else:
line = json.dumps(dict(item), default=myconverter)
self.file.write(line)
return item<file_sep># -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class ScrapySmartShanghaiItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
posted_type = scrapy.Field()
listing_id = scrapy.Field()
view_count = scrapy.Field()
scrape_time = scrapy.Field()
latitude = scrapy.Field()
longitude = scrapy.Field()
floor = scrapy.Field()
metro = scrapy.Field()
size = scrapy.Field()
author = scrapy.Field()
area = scrapy.Field()
compound = scrapy.Field()
publish_time = scrapy.Field()
description = scrapy.Field()
furnished = scrapy.Field()
rooms = scrapy.Field()
price = scrapy.Field()
title = scrapy.Field()
# Utilities
washing_machine = scrapy.Field()
parking = scrapy.Field()
tv = scrapy.Field()
central_aircon = scrapy.Field()
security = scrapy.Field()
balcony = scrapy.Field()
elevator = scrapy.Field()
playground = scrapy.Field()
oven = scrapy.Field()
dryer = scrapy.Field()
dvd_player = scrapy.Field()
health_club = scrapy.Field()
pool = scrapy.Field()
outdoor_space = scrapy.Field()
air_filter = scrapy.Field()
water_filter = scrapy.Field()
floor_heating = scrapy.Field()
wall_heating = scrapy.Field() | 4e78698e58b7fb63fa0a8655009d63ca09d647fe | [
"Python"
] | 3 | Python | tjspross/scrapy_smartshanghai | 3b1e8b6291346a45cea55abedf37dde3efa87961 | b2b015b3635a3e7c1fa5482b1f516a2187592d89 |
refs/heads/master | <repo_name>mercykinoti/Aptitude<file_sep>/app/controllers/company_controller.rb
class CompanyController < ApplicationController
def new
end
def create
@company = Company.new(params[:company])
@company.save
redirect_to @company
end
end
| 06f2567d295b23a407609a461eaec3b392ac5724 | [
"Ruby"
] | 1 | Ruby | mercykinoti/Aptitude | 64c4a137fbcdc540420680204eaa74a130508444 | e941a240b14c5c2693cb11ee6a8488498e4e696a |
refs/heads/master | <file_sep>from github import Github
import os
AUTH_TOKEN = os.environ["AUTH_TOKEN"]
g= Github(AUTH_TOKEN)
def change_protected_branch_settings():
for repo in g.get_user().get_repos():
branch = repo.get_branch("master")
branch.edit_protection(required_approving_review_count=2, enforce_admins=True)
print("Edited the branch protection rules for: " + repo.name)
def change_protected_branch_settings_test():
branch = g.get_repo("mynewexperiments/test123").get_branch("master")
branch.edit_protection(required_approving_review_count=2, enforce_admins=True)
<file_sep>appdirs==1.4.3
aspy.yaml==1.3.0
attrs==19.3.0
black==19.10b0
certifi==2019.11.28
cffi==1.13.2
cfgv==2.0.1
chardet==3.0.4
Click==7.0
cryptography==2.8
Deprecated==1.2.7
entrypoints==0.3
flake8==3.7.9
Flask==1.1.1
identify==1.4.9
idna==2.8
importlib-metadata==1.3.0
itsdangerous==1.1.0
Jinja2==2.10.3
jsonschema==3.2.0
MarkupSafe==1.1.1
mccabe==0.6.1
more-itertools==8.0.2
ngrok==0.0.1
nodeenv==1.3.4
# numpy==1.18.1
# openapi-spec-validator==0.2.8
packaging==20.0
# pandas==0.25.3
pathspec==0.7.0
pep8==1.7.1
pluggy==0.13.1
pre-commit==1.21.0
py==1.8.1
pycodestyle==2.5.0
pycparser==2.19
pyflakes==2.1.1
PyGithub==1.45
PyJWT==1.7.1
pyOpenSSL==19.1.0
pyparsing==2.4.6
pyrsistent==0.15.7
pytest==5.3.3
python-dateutil==2.8.1
pytz==2019.3
PyYAML==5.3
redis==3.3.11
regex==2020.1.8
requests==2.22.0
rq==1.2.0
simplekv==0.14.0
six==1.13.0
storefact==0.10.0
toml==0.10.0
toolz==0.10.0
typed-ast==1.4.1
uritools==3.0.0
urllib3==1.25.7
virtualenv==16.7.9
wcwidth==0.1.8
Werkzeug==0.16.0
wrapt==1.11.2
zipp==0.6.0
<file_sep>import argparse, json, requests, subprocess
import os
AUTH_TOKEN = os.environ["AUTH_TOKEN"]
def get_auth_token():
if AUTH_TOKEN is not None:
return AUTH_TOKEN
command = ' | '.join(('git credential fill <<< "host=github.com"',
'grep -o "password=\w\+"',
'cut -d= -f2'
))
return subprocess.check_output(command, shell=True).strip().decode('utf-8')
def make_api_url(*args):
return '/'.join(('https://api.github.com', 'repos', *args))
def make_api_headers():
APPLICATION_HEADER_VALUE='application/vnd.github.loki-preview+json'
return {
'Authorization': 'token {:s}'.format(get_auth_token()),
'Accept': APPLICATION_HEADER_VALUE,
}
def get_protection(target_repo, branch):
url = make_api_url(target_repo, 'branches', branch, 'protection')
return requests.get(url, headers=make_api_headers())
def set_protection(target_repo, branch, data=None):
url = make_api_url(target_repo, 'branches', branch, 'protection')
if data is None:
data = {
'required_status_checks': None,
'restrictions': {
'users': [],
'teams': [],
},
"required_status_checks": None,
"enforce_admins": None,
"required_pull_request_reviews": None,
"allow_force_pushes": True,
"allow_deletions": False,
}
return requests.put(url, headers=make_api_headers(), json=data)
def main():
parser = argparse.ArgumentParser(description = __doc__)
parser.add_argument(
'target_repo',
help='the target repository (specify as either org/repo or repo)'
)
parser.add_argument(
'target_branch',
help='the target branch'
)
parser.add_argument(
'action',
choices=['set', 'get', 'delete'],
help='action to perform on branch protections'
)
def do_and_print_json(fxn, *args):
print(
json.dumps(
fxn(*args).json(),
sort_keys=True,
indent=2
)
)
{
'get': lambda *args: do_and_print_json(get_protection, *args),
'set': lambda *args: do_and_print_json(set_protection, *args),
}[parser.parse_args().action](
parser.parse_args().target_repo,
parser.parse_args().target_branch
)
if __name__ == "__main__":
main()
<file_sep>import json
from flask import Flask
from flask import request, abort
import os
import hmac
import hashlib
GITHUB_SECRET = os.environ["AUTH_TOKEN"]
app = Flask(__name__, static_url_path='')
@app.route('/')
def api():
return "hello world"
@app.route("/health")
def health():
return (
"ok",
200,
{"Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-cache"},
)
@app.route('/github', methods=['POST'])
def listener():
"""
python - flask web application to listen to
github hooks
:return: json
"""
signature = request.headers.get("X-Hub-Signature")
if not signature or not signature.startswith("sha1="):
abort(400, "X-Hub-Signature required")
digest = hmac.new(GITHUB_SECRET.encode(),
request.data, hashlib.sha1).hexdigest()
if not hmac.compare_digest(signature, "sha1=" + digest):
abort(400, "Invalid signature")
if request.headers['Content-Type'] == 'application/json':
# url = os.path.join(os.path.dirname(__file__), "event_store")
event = json.dumps(request.json)
print(event)
return event
if __name__ == "__main__":
app.run(debug=True)
<file_sep>import json
import pytest
from src.dev.app import app
@pytest.fixture
def client(request):
test_client = app.test_client()
def teardown():
pass
request.addfinalizer(teardown)
return test_client
def post_json(client, url, json_dict):
return client.post(url, data=json.dumps(json_dict), content_type='application/json')
def json_of_response(response):
return json.loads(response.data.decode('utf8'))
def test_route(client):
response = client.get('/')
assert b'hello world' in response.data
def test_health(client):
response = client.get('/health')
assert b'ok' in response.data
<file_sep># Steps to run the web application
## Introduction
A simple web service using Python Flask that listens to **Webhook events** to know when a repository has been created.
For this example i have created a webhook event *Repository* .
## Create & configure a server
You will need to expose your local host with port:5000 to the internet. I used **ngrok** --> recommended by Github
(https://developer.github.com/webhooks/configuring/#using-ngrok)
ngrok would provide you a forwarded url --> use this as a **Payload Url** for the next section
## Create & configure Github webooks
To create a Repository webhook please follow the documentation below
(https://developer.github.com/webhooks/)
For this you would need the **Payload Url** created above.
## Test the application
- Create a Orgnaisation in **Github**
- Create a python3 Virtualenv
- pip install -r **requirements.txt**
- Run pytests --> py.test tests
- Start the python Flask application locally by executing the package **app.py**
- Create one or more repositories in the **org** with *Readme.md* as the first commit --> This would create a **Master branch**
Once the branch is created, Flask App would automatically trigger the **update-branch-protection** Github Api and apply
master branch protection on all **Repositories**
- Two branch protection packages are available
One that loops through all the branches and applies protection
Another by passing in the args --> set, add, del
## Tests
Unit tests are created to check the **route** & **health** of the Api
## Some References used
(https://github.com/BrinnerTechie/github-branch-protection-rules)
(https://stackoverflow.com/questions/51020398/github-api-enable-push-restrictions-for-branch)
## Next Steps or Improvements
- Build A CI pipeline
- Upgrade Github Rest Api 3 --> GraphQL API v4
- Add more tests(mock payload response) to improve code quality
- Create a workflow Automate
| badf1c3d2bba93a3e6711d80f567a42e90f9c39f | [
"Markdown",
"Python",
"Text"
] | 6 | Python | mynewexperiments/simple_webapp | 10c59a80e8f40fee94058e98e1a41a9f400b2b6a | f9afc035e060369cedab5404b7fa2cae190f2cd0 |
refs/heads/master | <file_sep>var height = 500;
var width = 675;
var padding = { "top": 50,
"right": 100,
"bottom": 0,
"left": 100 };
// creating svg canvas
var mainSelector = d3.select(".svg-container");
var scaleY = d3.scaleLinear()
.range([0, height - 4 * (padding.top)])
.nice(); // making scale end in round number
var scaleX = d3.scaleTime()
.range([0, width - padding.right - padding.left]);
var formatComma = d3.format(",");
d3.csv("./daca_approvals.csv", function(error, loadData) {
if (error) { throw error };
// parsing for number output
loadData.forEach(function(d){
d.date = parsingTime(d.date);
d.initial_intake = +d.initial_intake;
d.initial_approval = +d.initial_approval;
d.initial_cumulative = +d.initial_cumulative;
d.renewal_intake = +d.renewal_intake;
d.renewal_approval = +d.renewal_approval;
});
// var t = textures.lines()
// .orientation("7/8", "7/8")
// .size(10)
// .strokeWidth(.25)
// .stroke("#1F5869");
//
// svg.call(t);
scaleX.domain(d3.extent(loadData, function(d) { return d.date; }));
var dataIn = loadData.filter( function(d) { return d.data_origin == "uscis" });
var columnsNames = loadData.columns;
console.log(columnsNames);
var projection = loadData.filter( function(d) { return d.data_origin == "projection" });
for (var i = 8; i < columnsNames.length; i++) {
drawArea(dataIn, columnsNames[i], scaleX, scaleY, "#1F5869");
}
// drawing areas charts
// drawArea(projection, "initial_cumulative", scaleX, scaleY, t.url());
// drawArea(dataIn, "renewal_approval" , scaleX, scaleY, "#1F5869");
// drawLine(dataIn, "#1F5869" ,"1,0");
//drawing projection area chart
// drawArea(projection, "initial_cumulative", t.url())
// drawLine(projection, "#1F5869", "0.5,7");
// window.setTimeout(drawAnnotation, 1200);
//drawing circles on data points
// drawPlots(dataIn, "#282D48");
});
var parsingTime = d3.timeParse("%m/%d/%Y");
function drawAnnotation() {
const type = d3.annotationCalloutCircle
const annotations = [{
note: { label: "On Sep 5, Attorney General Jeff Sessions announced the Trump administration would stop receiving work permit applications immediately and cancel the program in six months.", title: "The end of DACA", wrap: 200},
// data: { date: "9/1/2017", initial_cumulative: 751659 },
x: 475, y: 118,
dy:0, dx: -100,
subject: { radius: 10, radiusPadding: 0 }
}]
// const parseTime = d3.timeParse("%b/%d/%Y")
// const timeFormat = d3.timeFormat("%d/%m/%Y")
const makeAnnotations = d3.annotation()
.type(type)
// accessors & accessorsInverse not needed
// if using x, y in annotations JSON
// .accessors({
// x: d => scaleX(parseTime(d.date)),
// y: d => scaleY(d.initial_cumulative)
// })
// .accessorsInverse({
// date: d => timeFormat(scaleX.invert(d.scaleX)),
// initial_cumulative: d => scaleY.invert(d.scaleY)
// })
.annotations(annotations)
d3.select("svg")
.append("g")
.attr("class", "annotation-group")
.call(makeAnnotations);
};
function drawArea(dataset, column, scalex, scaley, fill, i) {
var maxY = getMaxY(dataset, column);
scaleY.domain([maxY,0]).nice();
var svg = mainSelector.append("svg")
.attr("class", "svg-" + column + " charts" )
.attr("height", height)
.attr("width", width)
.append("g")
.attr("transform", "translate(" + padding.left + "," + 3 * padding.top + ")");
var initialArea = d3.area()
.x(0)
.y0(height - 200)
.y1(function(d) { return scaleY(d[column]) });
var area = d3.area()
.x(function(d) { return scaleX(d.date) })
.y0(height - 200)
.y1(function(d) { return scaleY(d[column]) });
var appendArea = svg.append("g")
.attr("class", "area-chart")
.append("path")
.data([dataset])
.attr("class", "area")
.attr("fill", fill)
.attr("opacity", .5)
.attr("d", initialArea)
.transition()
.duration(1000)
.ease(d3.easeCubic)
.attr("d", area);
// calling axis
xAxis(svg, scalex);
yAxis(svg, scaley);
// calling title, subtitle and axis labels
chartTitle(svg, column);
// chartSubtitle(svg);
// xLabel();
// yLabel(svg);
drawLine(svg, dataset, column, "#1F5869" ,"1,0");
drawLine(svg, dataset, column, "#1F5869", "0.5,7");
drawPlots(svg, dataset, column, fill);
};
function drawLine(container, dataset, column, stroke, dotted) {
var initialLine = d3.area()
.x(0)
.y0(height - 200)
.y1(function(d) { return scaleY(d[column]) });
var valueline = d3.line()
.x(function(d) { return scaleX(d.date) })
.y(function(d) { return scaleY(d[column]) });
var appendLine = container.append("g")
.attr("class", "line-chart")
.append("path")
.data([dataset])
.attr("class", "line")
.attr("fill", "none")
.attr("stroke", stroke)
.attr("stroke-width", 2.5)
.style("stroke-linecap", "round")
.style("stroke-dasharray", (dotted))
.attr("opacity", 1)
.attr("d", initialLine)
.transition()
.duration(1000)
.ease(d3.easeCubic)
.attr("d", valueline);
};
function drawPlots(container, dataset, column, fill) {
// drawing tooltip
var rects = container.append("g")
.attr("class", "rects")
var tooltips = container.append("g")
.attr("class", "text-labels")
rects.selectAll(".charts")
.data(dataset)
.enter()
.append("rect")
.attr("class", function(d) { return "c" + d.calendar_year + "-" + d.quarter } )
.attr("height", 30)
.attr("width", 65)
.attr("x", function(d) { return scaleX(d.date) + 3 })
.attr("y", function(d) { return scaleY(d[column]) - 30 })
.attr("fill", "#1F5869")
.attr("opacity", 0)
tooltips.selectAll(".charts")
.data(dataset)
.enter()
.append("text")
.attr("class", function(d) { return "c" + d.calendar_year + "-" + d.quarter } )
.attr("x", function(d) { return scaleX(d.date) + 8 })
.attr("y", function(d) { return scaleY(d[column]) - 10 })
.attr("fill", "white")
.attr("opacity", 0)
.html(function(d) { return formatComma(d[column]) })
container.append("g")
.attr("class", "plots")
.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("opacity", 0)
.attr("cy", function(d) { return scaleY(d[column]) })
.attr("fill", fill)
.attr("class", function(d) { return "c" + d.calendar_year + "-" + d.quarter } )
.attr("r", 5)
.on("mouseover", function(d) {
var selection = d3.select(this).attr("class");
container.selectAll("." + selection)
.attr("opacity", 1)
.attr("r", 10);
d3.selectAll(".charts")
.selectAll("." + selection)
.attr("opacity", 1)
.attr("r", 10);
})
.on("mouseout", function(d) {
var selection = d3.select(this).attr("class");
container.selectAll("." + selection)
.attr("opacity", 0)
.attr("r", 5);
d3.selectAll(".charts")
.selectAll("." + selection)
.attr("opacity", 0)
.attr("r", 5);
})
.attr("cx", 0)
.transition()
.duration(1000)
.ease(d3.easeSin)
.attr("cx", function(d) { return scaleX(d.date) });
};
function getMaxY(dataset,column) {
return d3.max(dataset, function(d) { return d[column] * 1.05 });
};
// defining functions to append axis
function xAxis(container, scale) {
container.append("g")
.attr("transform", "translate(0," + (height - 4 * (padding.top)) + ")" )
.attr("class", "xAxis")
.call(d3.axisBottom(scale));
};
function yAxis(container, scale) {
container.append("g")
.attr("transform", "translate(0,0)")
.attr("class", "yAxis")
.call(d3.axisLeft(scale));
};
// defining functions to append title, subtitle and labels to axis
function chartTitle(container, text) {
container.append("text")
.attr("x", 0)
.attr("y", -20)
.attr("class", "title")
.text(text);
};
function chartSubtitle(container) {
container.append("text")
.attr("x", 0)
.attr("y", -25)
.attr("class", "subtitle")
.text("");
};
// function xLabel() {
// svg.append("text")
// .attr("x", 300)
// .attr("y", 440)
// .attr("class", "label")
// .attr("text-anchor", "middle")
// .text("Total earnings, in USD");
// };
function yLabel(container) {
container.append("text")
.attr("transform", "rotate(270)")
.attr("x", -100)
.attr("y", -70)
.attr("class", "label")
.attr("text-anchor", "middle")
// .text("Cumulative approvals");
};
| fe513de089d7de09112fb8d7bc35b5ec7fe32a99 | [
"JavaScript"
] | 1 | JavaScript | VizTechFall2017/week7-fsorodrigues | d741513aafedead83402c5168a6fc313fe0bc99b | 8edb25912b829c46c9baf6458474e37f74c6d2b8 |
refs/heads/master | <repo_name>freewind-demos/junit-4-exception-handling-demo<file_sep>/src/test/java/demo/HelloTest.java
package demo;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.CoreMatchers.startsWith;
public class HelloTest {
@Rule
public ExpectedException expectedEx = ExpectedException.none();
@Test(expected = IllegalArgumentException.class)
public void shouldThrowIllegalArgumentException() {
throw new IllegalArgumentException("testing");
}
@Test
public void shouldThrowIllegalArgumentExceptionWithMessage() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage("testing");
throw new IllegalArgumentException("testing");
}
@Test
public void shouldThrowIllegalArgumentExceptionAndCheckMessagePattern() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage(startsWith("testing"));
throw new IllegalArgumentException("testing 23423!");
}
@Test
public void shouldThrowIllegalArgumentExceptionAndCheckMessageWithCustomPattern() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage(new BaseMatcher<String>() {
public boolean matches(Object item) {
String message = ((String) item);
return message.startsWith("testing ") && message.endsWith("!");
}
public void describeTo(Description description) {
}
});
throw new IllegalArgumentException("testing 23423!");
}
@Test
public void shouldThrowIllegalArgumentExceptionWithCause() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectCause(new BaseMatcher<NullPointerException>() {
public void describeTo(Description description) {
}
public boolean matches(Object item) {
if (item instanceof NullPointerException) {
NullPointerException cause = (NullPointerException) item;
return cause.getMessage().equals("testing-null");
} else {
return false;
}
}
});
throw new IllegalArgumentException("testing", new NullPointerException("testing-null"));
}
}
| 4f711446763ccd6a6ca5dc9adb4f49b42d9e1e7a | [
"Java"
] | 1 | Java | freewind-demos/junit-4-exception-handling-demo | 86115ea5d3fa3e3231862650d75fb0985160ac55 | 5b97ecdea3cb2940fe1c75a88d33995e5547099e |
refs/heads/master | <repo_name>anbanhuongtra/ColorTeting<file_sep>/README.md
# ColorTeting
Color Testing Puzzle Game
<file_sep>/game-chon-mau-master/game-chon-mau-master/GameChonMau/GameChonMau/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GameChonMau
{
public partial class Form1 : Form
{
int k; // đánh dấu
int point = 0; // điểm đạt được
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//SetColor();
RenderGrid();
}
private void button4_Click(object sender, EventArgs e)
{
if (k == 4) {
point++;
label1.Text = point.ToString();
SetColor();
}
}
public void SetColor()
{
Random p = new Random();
int x = p.Next(0, 255);
int y = p.Next(0, 255); // màu ngẫu nhiên
int z = p.Next(30, 255);
Random q = new Random();
k = q.Next(1,9); // ô ngẫu nhiên khác màu
if (k == 1)
{
button1.BackColor = Color.FromArgb(x, y, z - 30);
}
else button1.BackColor = Color.FromArgb(x, y, z);
if (k == 2)
{
button2.BackColor = Color.FromArgb(x, y, z - 30);
}
else button2.BackColor = Color.FromArgb(x, y, z);
if (k == 3)
{
button3.BackColor = Color.FromArgb(x, y, z - 30);
}
else button3.BackColor = Color.FromArgb(x, y, z);
if (k == 4)
{
button4.BackColor = Color.FromArgb(x, y, z - 30);
}
else button4.BackColor = Color.FromArgb(x, y, z);
if (k == 5)
{
button5.BackColor = Color.FromArgb(x, y, z - 30);
}
else button5.BackColor = Color.FromArgb(x, y, z);
if (k == 6)
{
button6.BackColor = Color.FromArgb(x, y, z - 30);
}
else button6.BackColor = Color.FromArgb(x, y, z);
if (k == 7)
{
button7.BackColor = Color.FromArgb(x, y, z - 30);
}
else button7.BackColor = Color.FromArgb(x, y, z);
if (k == 8)
{
button8.BackColor = Color.FromArgb(x, y, z - 30);
}
else button8.BackColor = Color.FromArgb(x, y, z);
if (k == 9)
{
button9.BackColor = Color.FromArgb(x, y, z - 30);
}
else button9.BackColor = Color.FromArgb(x, y, z);
}
public int GetGridLevel(int level)
{
if (level < 2) return 2;
if (level < 4) return 3;
if (level < 8) return 4;
if (level < 13) return 5;
if (level < 22) return 6;
if (level < 32) return 7;
if (level < 36) return 8;
if (level < 40) return 9;
if (level < 44) return 10;
if (level < 48) return 11;
return 12;
}
int level = 1;
int correct_tile = -1;
Random color_random = new Random();
Random tile_random = new Random();
public void RenderGrid()
{
int grid = GetGridLevel(level);
//set position of correct tile
int position = -1;
do
{
position = tile_random.Next(0, grid * grid -1);
} while (correct_tile == position);
//set color
var colordiff = getLevelColorDiff(level);
var r = color_random.Next(0, (255 - colordiff));
var g = color_random.Next(0, (255 - colordiff));
var b = color_random.Next(0, (255 - colordiff));
//render grid
for (int i = 0; i < grid * grid; i++)
{
Button tile = new Button();
tile.Width = (flowLayoutPanel1.Width / grid) - 10; // error at higher level
tile.Height = (flowLayoutPanel1.Height / grid) - 10; // error at higher level
tile.Tag = i;
if (i != position)
{
tile.BackColor = Color.FromArgb(255, r, g, b);
tile.Click += tile_Click_miss;
}
else
{
tile.BackColor = Color.FromArgb(255, r+colordiff, g+colordiff, b+colordiff);
tile.Click += tile_Click_correct;
}
flowLayoutPanel1.Controls.Add(tile);
}
}
private void button5_Click(object sender, EventArgs e)
{
if (k == 5)
{
point++;
label1.Text = point.ToString();
SetColor();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (k == 1)
{
point++;
label1.Text = point.ToString();
SetColor();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (k == 2)
{
point++;
label1.Text = point.ToString();
SetColor();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (k == 3)
{
point++;
label1.Text = point.ToString();
SetColor();
}
}
private void button6_Click(object sender, EventArgs e)
{
if (k == 6)
{
point++;
label1.Text = point.ToString();
SetColor();
}
}
private void button7_Click(object sender, EventArgs e)
{
if (k == 7)
{
point++;
label1.Text = point.ToString();
SetColor();
}
}
private void button8_Click(object sender, EventArgs e)
{
if (k == 8)
{
point++;
label1.Text = point.ToString();
SetColor();
}
}
private void button9_Click(object sender, EventArgs e)
{
if (k == 9)
{
point++;
label1.Text = point.ToString();
SetColor();
}
}
private void label1_Click(object sender, EventArgs e)
{
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e)
{
}
//tile click event
void tile_Click_correct(object sender, EventArgs e)
{
Button btn = sender as Button;
level++;
flowLayoutPanel1.Controls.Clear();
RenderGrid();
}
void tile_Click_miss(object sender, EventArgs e)
{
Button btn = sender as Button;
}
// set difficult level
int[] col = { 105, 75, 60, 45, 30, 20, 18, 16, 15, 15, 15, 14, 14, 14, 13, 13, 13, 12, 12, 12, 11, 11, 11, 10, 10, 9, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1, 1 };
public int getLevelColorDiff(int level)
{
if (level <= 58)
{
return col[level - 1];
}
return 1;
}
}
}
| 4ed49a782739281e83913b8a934f7772aa744968 | [
"Markdown",
"C#"
] | 2 | Markdown | anbanhuongtra/ColorTeting | 33f825a496c5b9a5455c47da692343ed3ea58afd | 04195ebfe9421cf5ff15c91cdebb3555e0db7ba5 |
refs/heads/main | <file_sep>$(function() {
'use strict';
$(".reserved-indicator").each(
function() {
var checkmarkImage = $(this);
checkmarkImage.popover({ trigger: 'hover focus' });
checkmarkImage.click(function() {
checkmarkImage.popover('show');
setTimeout(function() {
checkmarkImage.popover('destroy');
},
1000);
});
}
);
});
| 9b3e9df8c8d3b225336ed52b6706316c5ae36359 | [
"JavaScript"
] | 1 | JavaScript | LogiqsAgro/NuGetGallery | 3809cca376dd03904e2c2278872f2557eb528b49 | ea49a8f520bf861aaf63cb73a15cf81caa173b4c |
refs/heads/master | <file_sep>import { Component, OnDestroy, OnInit } from '@angular/core';
import { ChatService } from '../../services/chat.service';
import { FormControl, Validators } from '@angular/forms';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-group-chat',
templateUrl: './group-chat.component.html',
styleUrls: ['./group-chat.component.scss']
})
export class GroupChatComponent implements OnInit, OnDestroy {
private $unsubscribe: Subject<any> = new Subject<any>();
public newMessage = new FormControl('', [Validators.required]);
public messages: string[] = [];
constructor(private chatService: ChatService) {
}
ngOnInit() {
this.chatService
.subscribeToMessages()
.pipe(takeUntil(this.$unsubscribe))
.subscribe((message: any) => {
console.log('mmm', message);
this.messages.push(message.message);
console.log(this.messages);
});
}
ngOnDestroy(): void {
this.$unsubscribe.next();
this.$unsubscribe.complete();
}
sendMessage() {
this.chatService.sendMessage(this.newMessage.value).subscribe();
this.newMessage.reset();
console.log('------', this.messages);
}
}
<file_sep>import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
import { HttpClient } from "@angular/common/http";
@Injectable({
providedIn: 'root'
})
export class ChatService {
private url = 'http://localhost:8888';
private socket;
constructor(private http: HttpClient) {
this.socket = io(this.url);
}
public sendMessage(message) {
// this.socket.emit('new-message', message);
return this.http.post(`${this.url}/user/1/messages/3`, {message});
}
public subscribeToMessages = () => {
console.log(1);
return new Observable((observer: any) => {
console.log(2);
this.socket.on('new-message', (message) => {
console.log('socket', message);
observer.next(message);
console.log('getMessages work!!!');
});
});
}
// public sendMessage(message): Observable<any> {
// return
// }
}
| e0c5c2364e1e7b7d5535e36a415df7cc69a87900 | [
"TypeScript"
] | 2 | TypeScript | Luiza-Badikyan/webSocketFrontEnd | d7c405ee1b33ad64ea407cee2f743c5057d4efbf | 048faee0abfd448569c28681c4776b450721d933 |
refs/heads/master | <file_sep>from django.contrib import admin
from . models import Task
# Register your models here.
class TaskAdmin(admin.ModelAdmin):
list_display = ('title', 'description', 'author', 'created_date', 'duration', 'is_done')
list_select_related=('author', )
admin.site.register(Task, TaskAdmin)
<file_sep>from django import forms
from .models import Task
from django.contrib.auth.models import User
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ('title', 'description', 'duration')
widgets = {
'description' : forms.Textarea(attrs = {'cols' : 45 , 'rows' : 4}),
}
<file_sep># task_scheduler
Grid-Cloud spring 2018
https://imgur.com/a/uNvkgrE
# How to start work with app:
Was using PostgreSQL as db, so u have to install it to work with application.
-postgres=# CREATE DATABASE task_scheduler;
-postgres=# CREATE USER admin WITH password '<PASSWORD>';
-postgres=# GRANT ALL privileges ON DATABASE task_scheduler TO admin;
$ git clone https://github.com/Surprise34/task_scheduler.git
$ cd task_scheduler
$ source myvenv/bin/activate
$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver
<file_sep>from django.shortcuts import render, render_to_response, redirect
from .models import Task
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from datetime import timedelta
from django.utils import timezone
from .forms import TaskForm
from django.http import HttpResponse, Http404
from threading import Timer
# Create your views here.
def tasks_list(request):
if request.user.is_authenticated:
tasks_list = Task.objects.filter(author=request.user).order_by('created_date')
return render(
request, 'index.html', {
'tasks':tasks_list,
}
)
else:
return render(request, 'index.html')
@login_required
def task_detail(request , task_id):
try:
task = Task.objects.select_related('author').get(id=task_id)
except Task.DoesNotExist:
raise Http404
if request.user != task.author:
raise Http404
time_left = int((timezone.now()-task.created_date).total_seconds())
speed = int(task.duration.total_seconds()*10)
per = int(time_left/task.duration.total_seconds()*100)
return render(
request, 'task_detail.html',{
'task':task,
'speed':speed,
'per':per,
}
)
def task_execute(task_id):
task = Task.objects.get(id=task_id)
task.is_done=True
task.save()
@login_required
def task_create(request):
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
task = form.save(commit=False)
task.author = request.user
task.save()
timer = Timer(task.duration.total_seconds(),task_execute,args=(task.id,))
timer.start()
return redirect(tasks_list)
else:
form = TaskForm()
return render (
request, 'task_create.html', {
'form' : form,
}
)
<file_sep>from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^$', views.tasks_list, name='main_page'),
re_path(r'^task/detail/(?P<task_id>\d+)$',views.task_detail, name='task_detail'),
re_path(r'^task/create/', views.task_create, name='task_create'),
]
<file_sep>from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta
# Create your models here.
class Task(models.Model):
title = models.CharField(verbose_name='Заголовок', max_length=100)
description = models.CharField(verbose_name='Описание', max_length=200)
author = models.ForeignKey(
verbose_name = 'Пользователь',
to=User,
null=True,
on_delete = models.CASCADE
)
created_date = models.DateTimeField(verbose_name='Дата создания',default=timezone.now)
duration = models.DurationField(verbose_name='Продолжительность (в формате hh:mm:ss)',default=timedelta(seconds=30))
is_done=models.BooleanField(verbose_name='Статус',default=False)
class Meta:
ordering = ('title', 'author',)
verbose_name='Задача'
verbose_name_plural='Задачи'
def __str__(self):
return self.title
| 64a2befe18eaca839317e560c37baa5c3a366c78 | [
"Markdown",
"Python"
] | 6 | Python | Surprise34/task_scheduler | ee69ff20b6ed35fcb9fc0c8b2b32794aff1c596e | 83efa52e658ca92ff1def13639dca893ea89c282 |
refs/heads/master | <file_sep>chromedialer
============
A Google Chrome extension that provides BroadWorks telephony integration.
<file_sep>/*
Copyright 2013, BroadSoft, Inc.
Licensed under the Apache License,Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "ASIS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
importScripts('tinyxmlw3cdom.js', 'tinyxmlsax.js');
var LOG_PREFIX = 'xsi-events-api|';
var XML_HEADER = '<?xml version="1.0" encoding="UTF-8"?>';
var HEARTBEAT_INTERVAL = 15000;
// channel and subscription expiry in seconds, don't set
// this lower than 600
var EXPIRES = 3600;
var channelId = '';
var mainXhr = null;
var heartbeatIntervalId = null;
var state = 'disconnected';
var hostIndex = -1;
var channelSetId = 'broadworks4chromechannelset';
var applicationId = 'broadworks4chrome';
var hosts = [];
var credentials = '';
var username = '';
var parser = new DOMImplementation();
var EVENT_CLOSE = '</xsi:Event>';
var CHANNEL_CLOSE = '</Channel>';
var HEARTBEAT_CLOSE = '<ChannelHeartBeat xmlns="http://schema.broadsoft.com/xsi"/>';
var subscriptionIds = {};
var updateIntervalId = null;
// define endsWith method for String
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
self.addEventListener('message', function(e) {
switch (e.data.cmd) {
case 'init':
if (state == 'disconnected') {
log('intializing');
hosts = e.data.config.hosts;
username = e.data.config.username;
credentials = e.data.config.credentials;
}
break;
case 'start':
if (state == 'disconnected') {
log('starting');
connect();
}
break;
case 'stop':
log('stopping');
mainXhr.abort();
break;
}
}, false);
function connect() {
log('sending add channel request');
state = 'connecting';
hostIndex++;
if (hostIndex == hosts.length) {
hostIndex = 0;
}
mainXhr = new XMLHttpRequest();
var index = 0;
var responseBuffer = '';
var url = hosts[hostIndex]
+ '/com.broadsoft.async/com.broadsoft.xsi-events/v2.0/channel';
mainXhr.open('POST', url, true);
mainXhr.onreadystatechange = function() {
var chunk = mainXhr.responseText.substring(index,
mainXhr.responseText.length);
index = mainXhr.responseText.length;
log("Chunk is: " + chunk);
// Ensure there is at least one complete Channel Response, Event
// Response, or Heartbeat response in the responseText. Sometimes,
// responses are split across chunks
if (chunk.endsWith(EVENT_CLOSE) || chunk.endsWith(CHANNEL_CLOSE)
|| chunk.endsWith(HEARTBEAT_CLOSE)) {
// If anything is in the response buffer then add chunk to the
// buffer, set as response, and then clear the buffer
if (responseBuffer != '') {
responseBuffer += chunk;
response = responseBuffer;
responseBuffer = '';
} else {
response = chunk;
}
log("complete response is: " + response);
var tokens = response.split(XML_HEADER);
for ( var i = 0; i < tokens.length; i++) {
if (tokens[i] != '') {
process(tokens[i]);
}
}
}
// If no complete response then add the chunk to the buffer
else {
responseBuffer += chunk;
}
};
mainXhr.onloadend = function() {
log('sending disconnected message');
channelId = '';
clearInterval(heartbeatIntervalId);
heartbeatIntervalId = null;
clearInterval(updateIntervalId);
updateIntervalId = null;
state = 'disconnected';
// this is the only place that should send a disconnected message
sendMessage(state, this.status);
};
var request = XML_HEADER;
request = request + '<Channel xmlns="http://schema.broadsoft.com/xsi">';
request = request + '<channelSetId>' + channelSetId + '</channelSetId>';
request = request + '<priority>1</priority>';
request = request + '<weight>100</weight>';
request = request + '<expires>' + EXPIRES + '</expires>';
request = request + '<applicationId>broadworks4chrome</applicationId>';
request = request + '</Channel>';
mainXhr.setRequestHeader('Authorization', 'Basic ' + credentials);
mainXhr.send(request);
}
function process(chunk) {
log('received data: ' + chunk);
var xmlDoc = parser.loadXML(chunk).getDocumentElement();
if (chunk.indexOf('<Channel ') >= 0) {
channelId = xmlDoc.getElementsByTagName('channelId').item(0)
.getFirstChild().getNodeValue();
log('channelId: ' + channelId);
heartbeatIntervalId = setInterval(heartbeat, HEARTBEAT_INTERVAL);
status = 'connected';
addEventSubscription(username, "Standard Call");
addEventSubscription(username, "Do Not Disturb");
addEventSubscription(username, "Remote Office");
addEventSubscription(username, "Call Forwarding Always");
// start channel and subscription update timer 5 mins before they expire
if (updateIntervalId == null) {
updateIntervalId = setInterval(updateChannelAndEventSubscriptions,
(EXPIRES - 300) * 1000);
}
} else if (chunk.indexOf('<ChannelHeartBeat ') >= 0) {
} else if (chunk.indexOf('SubscriptionTerminatedEvent') >= 0) {
// don't handle these explicitly, just wait for the channel to terminate
// since we won't send a event response
} else if (chunk.indexOf('ChannelTerminatedEvent') >= 0) {
// nothing to do here, mainXhr will return after this and the disconnect
// message will be sent to background page
} else if (chunk.indexOf('<xsi:Event ') >= 0) {
var eventId = xmlDoc.getElementsByTagName('xsi:eventID').item(0)
.getFirstChild().getNodeValue();
sendEventResponse(eventId);
var eventType = xmlDoc.getElementsByTagName('xsi:eventData').item(0)
.getAttribute('xsi1:type').trim();
eventType = eventType.substring(4);// string off the prefix "xsi:" from
// the eventType
log('eventType: ' + eventType);
switch (eventType) {
case 'DoNotDisturbEvent':
case 'CallForwardingAlwaysEvent':
case 'RemoteOfficeEvent':
var active = xmlDoc.getElementsByTagName('xsi:active').item(0)
.getFirstChild().getNodeValue();
log('active: ' + active);
sendMessage(eventType, active);
break;
case 'CallSubscriptionEvent':
case 'CallOriginatingEvent':
case 'CallOriginatedEvent':
case 'CallReceivedEvent':
case 'CallAnsweredEvent':
case 'CallReleasedEvent':
case 'CallHeldEvent':
case 'CallRetrievedEvent':
case 'CallUpdatedEvent':
var calls = parseCalls(chunk);
sendMessage(eventType, calls);
break;
}
}
}
function heartbeat() {
// abort mainXhr on heart-beat errors
// we will use that to trigger disconnect messages
// error on all other requests are ignored, as failed event responses will
// eventually cause mainXhr to end
if (channelId != '') {
log('sending channel heartbeat');
var url = hosts[hostIndex] + '/com.broadsoft.xsi-events/v2.0/channel/'
+ channelId + '/heartbeat';
send('PUT', url, null, function(xhr) {
if (xhr.status != 200) {
log('aborting main xhr');
mainXhr.abort();
}
});
}
}
function send(type, url, data, responseHandler) {
log('sending ' + type + ' to ' + url);
var xhr = new XMLHttpRequest();
xhr.open(type, url, true);
if (responseHandler) {
xhr.onloadend = function() {
responseHandler(xhr);
};
}
xhr.setRequestHeader('Authorization', 'Basic ' + credentials);
xhr.send(data);
}
function sendMessage(type, value) {
self.postMessage({
type : type,
value : value
});
}
function log(message) {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}
if (hour.toString().length == 1) {
hour = '0' + hour;
}
if (minute.toString().length == 1) {
minute = '0' + minute;
}
if (second.toString().length == 1) {
second = '0' + second;
}
var timestamp = year + '/' + month + '/' + day + ' ' + hour + ':' + minute
+ ':' + second;
sendMessage('log', LOG_PREFIX + timestamp + '|' + message);
}
function parseCalls(xml) {
var calls = {};
var xmlDoc = parser.loadXML(xml).getDocumentElement();
var callNodes = xmlDoc.getElementsByTagName('xsi:call');
for ( var i = 0; i < callNodes.length; i++) {
var call = callNodes.item(i);
var callId = call.getElementsByTagName('xsi:callId').item(0)
.getFirstChild().getNodeValue();
var personality = call.getElementsByTagName('xsi:personality').item(0)
.getFirstChild().getNodeValue();
var state = call.getElementsByTagName('xsi:state').item(0)
.getFirstChild().getNodeValue();
var remotePartyElement = call.getElementsByTagName('xsi:remoteParty')
.item(0);
var nameElement = remotePartyElement.getElementsByTagName('xsi:name')
.item(0);
var name = "";
if (nameElement != null) {
name = nameElement.getFirstChild().getNodeValue();
}
var address = "";
var countryCode = "";
var addressElement = remotePartyElement
.getElementsByTagName('xsi:address');
if (addressElement != null) {
var addressNode = addressElement.item(0);
if (addressNode != null) {
address = addressNode.getFirstChild().getNodeValue();
if (addressNode.hasAttributes()) {
countryCode = addressNode.getAttribute('countryCode');
}
}
}
number = address.replace("tel:", "").replace("+" + countryCode,
"+" + countryCode + "-");
var startTime = call.getElementsByTagName('xsi:startTime').item(0)
.getFirstChild().getNodeValue();
var answerTime = null;
var answerTimeNode = call.getElementsByTagName('xsi:answerTime')
.item(0);
if (answerTimeNode) {
answerTime = answerTimeNode.getFirstChild().getNodeValue();
}
calls[callId] = {
personality : personality,
state : state,
name : name,
number : number,
countryCode : countryCode,
startTime : startTime,
answerTime : answerTime
};
}
return calls;
}
function addEventSubscription(targetId, event) {
var url = hosts[hostIndex] + "/com.broadsoft.xsi-events/v2.0/user/"
+ username;
var data = XML_HEADER;
data = data + "<Subscription xmlns=\"http://schema.broadsoft.com/xsi\">";
data = data + "<subscriberId>" + username + "</subscriberId>";
data = data + "<targetIdType>User</targetIdType>";
data = data + "<targetId>" + targetId + "</targetId>";
data = data + "<event>" + event + "</event>";
data = data + "<expires>" + EXPIRES + "</expires>";
data = data + "<channelSetId>" + channelSetId + "</channelSetId>";
data = data + "<applicationId>" + applicationId + "</applicationId>";
data = data + "</Subscription>";
send("POST", url, data, function(xhr) {
if (xhr.status == 200) {
var xmlDoc = parser.loadXML(xhr.responseText);
var subscriptionId = xmlDoc.getElementsByTagName('subscriptionId')
.item(0).getFirstChild().getNodeValue();
subscriptionIds[event] = subscriptionId;
}
});
}
function updateEventSubscription(subscriptionId) {
var url = hosts[hostIndex] + "/com.broadsoft.xsi-events/v2.0/subscription/"
+ subscriptionId;
var data = XML_HEADER;
data = data + "<Subscription xmlns=\"http://schema.broadsoft.com/xsi\">";
data = data + "<subscriptionId>" + subscriptionId + "</subscriptionId>";
data = data + "<expires>" + EXPIRES + "</expires>";
data = data + "</Subscription>";
send("PUT", url, data);
}
function sendEventResponse(eventId) {
var url = hosts[hostIndex]
+ "/com.broadsoft.xsi-events/v2.0/channel/eventresponse";
var data = XML_HEADER;
data = data + "<EventResponse xmlns=\"http://schema.broadsoft.com/xsi\">";
data = data + "<eventID>" + eventId + "</eventID>";
data = data + "<statusCode>200</statusCode>";
data = data + "<reason>OK</reason>";
data = data + "</EventResponse>";
send("POST", url, data);
}
function updateChannel() {
var url = hosts[hostIndex] + '/com.broadsoft.xsi-events/v2.0/channel/'
+ channelId + "/" + channelId;
var data = XML_HEADER;
data = data + '<Channel xmlns="http://schema.broadsoft.com/xsi">';
data = data + '<channelId>' + channelId + '</channelId>';
data = data + '<expires>' + EXPIRES + '</expires>';
data = data + '</Channel>';
send("PUT", url, data);
}
function updateChannelAndEventSubscriptions() {
if (channelId != '') {
updateChannel();
for ( var event in subscriptionIds) {
updateEventSubscription(subscriptionIds[event]);
}
}
}<file_sep>/*
Copyright 2013, BroadSoft, Inc.
Licensed under the Apache License,Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "ASIS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var XSIACTIONS = XSIACTIONS || {};
XSIACTIONS.API = (function() {
var MODULE = "xsiactions.js";
var host = "";
var username = "";
var password = "";
var context = "/com.broadsoft.xsi-actions";
var XML_HEADER = "<?xml version='1.0' encoding='UTF-8'?>";
function init(options) {
host = options.host;
username = options.username;
password = options.password;
if (options.context) {
context = options.context;
}
LOGGER.API.log(MODULE,"Xsi Actions initialized");
}
function getAuthorizationHeader() {
var header = "Basic " + $.base64.encode(username + ":" + password);
return header;
}
function sendXsiRequest(type, url, data) {
LOGGER.API.log(MODULE, "Request: " + type + " " + url);
if (data) {
LOGGER.API.log(MODULE, "Payload: ", data);
}
var response = null;
$.ajax({
beforeSend : function(request) {
request.setRequestHeader("Authorization", getAuthorizationHeader());
},
cache : false,
type : type,
url : url,
dataType : "xml",
data : data,
async : false,
success : function(doc) {
response = doc;
},
error : function(xhr, error) {
LOGGER.API.error(MODULE,xhr.responseText + " " + xhr.status + " " + error.message);
throw new Error("XSI Error status: " + xhr.status);
}
});
if (response) {
LOGGER.API.log(MODULE, "Response: ", response);
}
return response;
}
function getServices() {
var geturl = host + context + "/v2.0/user/" + username + "/services";
var response = sendXsiRequest("GET", geturl, null);
var services = new Array();
var x = 0;
$("service", response).each(function(i) {
services[x++] = $(this).find("name").text();
});
return services;
}
function getName() {
var geturl = host + context + "/v2.0/user/" + username + "/profile";
var response = sendXsiRequest("GET", geturl, null);
var name = $(response).find("firstName").text() + " " + $(response).find("lastName").text();
return name;
}
function getDoNotDisturb() {
var geturl = host + context + "/v2.0/user/" + username + "/services/donotdisturb";
var response = sendXsiRequest("GET", geturl, null);
var active = $(response).find("active").text();
return active == "true";
}
function setDoNotDisturb(dnd) {
var puturl = host + context + "/v2.0/user/" + username + "/services/donotdisturb";
var data = XML_HEADER + "<DoNotDisturb xmlns='http://schema.broadsoft.com/xsi'><active>" + dnd
+ "</active><ringSplash>false</ringSplash></DoNotDisturb>";
sendXsiRequest("PUT", puturl, data);
}
function getCallForwardAlways() {
var geturl = host + context + "/v2.0/user/" + username + "/services/callforwardingalways";
var response = sendXsiRequest("GET", geturl, null);
var active = $(response).find("active").text();
return active == "true";
}
function setCallForwardAlways(cfa) {
var puturl = host + context + "/v2.0/user/" + username + "/services/callforwardingalways";
var data = XML_HEADER + "<CallForwardingAlways xmlns='http://schema.broadsoft.com/xsi'><active>" + cfa + "</active></CallForwardingAlways >";
sendXsiRequest("PUT", puturl, data);
}
function getRemoteOffice() {
var geturl = host + context + "/v2.0/user/" + username + "/services/remoteoffice";
var response = sendXsiRequest("GET", geturl, null);
var active = $(response).find("active").text();
return active == "true";
}
function setRemoteOffice(ro) {
var puturl = host + context + "/v2.0/user/" + username + "/services/remoteoffice";
var data = XML_HEADER + "<RemoteOffice xmlns='http://schema.broadsoft.com/xsi'><active>" + ro + "</active></RemoteOffice>";
sendXsiRequest("PUT", puturl, data);
}
function call(destination) {
var posturl = host + context + "/v2.0/user/" + username + "/calls/new?address=" + encodeURIComponent(destination);
var response = sendXsiRequest("POST", posturl, null);
var callId = $(response).find("callId").text();
return callId;
}
function talk(callhalf) {
var puturl = host + context + "/v2.0/user/" + username + "/calls/" + callhalf + "/talk";
sendXsiRequest("PUT", puturl, null);
}
function transferToVoicemail(callhalf) {
var puturl = host + context + "/v2.0/user/" + username + "/calls/" + callhalf + "/vmtransfer";
sendXsiRequest("PUT", puturl, null);
}
function searchEnterpriseDirectory(data) {
var geturl = host + context + "/v2.0/user/" + username + "/directories/enterprise?";
var tokens = data.split(" ");
if (tokens.length == 1) {
geturl = geturl + "firstName=" + tokens[0] + "*/i&lastName=" + tokens[0] + "*/i&searchCriteriaModeOr=true";
} else if (tokens.length >= 2) {
geturl = geturl + "firstName=" + tokens[0] + "*/i&lastName=" + tokens[1] + "*/i";
}
var response = sendXsiRequest("GET", geturl, null);
return response;
}
function getCallLogs() {
LOGGER.API.log(MODULE,"get call logs user: " + username);
var geturl = host + context + "/v2.0/user/" + username + "/directories/calllogs";
var response = sendXsiRequest("GET", geturl, null);
return response;
}
function hangup(callhalf) {
var deleteurl = host + context + "/v2.0/user/" + username + "/calls/" + callhalf;
sendXsiRequest("DELETE", deleteurl, null);
}
function hold(callhalf) {
var puturl = host + context + "/v2.0/user/" + username + "/calls/" + callhalf + "/hold";
sendXsiRequest("PUT", puturl, null);
}
return {
init : init,
getServices : getServices,
getName : getName,
getDoNotDisturb : getDoNotDisturb,
setDoNotDisturb : setDoNotDisturb,
getCallForwardAlways : getCallForwardAlways,
setCallForwardAlways : setCallForwardAlways,
getRemoteOffice : getRemoteOffice,
setRemoteOffice : setRemoteOffice,
call : call,
talk : talk,
transferToVoicemail : transferToVoicemail,
searchEnterpriseDirectory : searchEnterpriseDirectory,
getCallLogs : getCallLogs,
hangup : hangup,
hold : hold
};
})();<file_sep>/*
Copyright 2013, BroadSoft, Inc.
Licensed under the Apache License,Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "ASIS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var MODULE = "dotabs.js";
// retrieve stored name
$("#name").text(localStorage["name"]);
function formatTimestamp(timestamp) {
var today = new Date();
var dt = new Date(timestamp);
if (today.getDay() == dt.getDay() && today.getMonth() == dt.getMonth()
&& today.getFullYear() == dt.getFullYear()) {
var hours = dt.getHours();
var minutes = dt.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
return hours + ":" + (minutes < 10 ? "0" + minutes : minutes) + " "
+ ampm;
}
return dt.getMonth() + "/" + dt.getDay() + "/" + dt.getFullYear();
}
// Event Listeners
// call history
$("#calllogentries").disableSelection();
$("#calllogentries").on("dblclick", "tr", function(e) {
e.preventDefault();
var number = $(this).attr("id").replace(/calllogentry.*_/g, "");
XSIACTIONS.API.call(number);
});
// dialer
$("#destination")
.autocomplete(
{
minLength : 2,
source : function(request, responseCallback) {
var suggestions = [];
var contacts = XSIACTIONS.API
.searchEnterpriseDirectory(request.term);
$(contacts).find("directoryDetails").each(
function() {
var name = $(this).find("firstName").text()
+ " "
+ $(this).find("lastName").text();
var number = $(this).find("number").text();
var mobile = $(this).find("mobile").text();
if (number != "") {
suggestions.push({
value : number,
label : name + " (work: " + number
+ ")"
});
}
if (mobile != "") {
suggestions.push({
value : mobile,
label : name + " (mobile: "
+ mobile + ")"
});
}
});
var url = "https://www.google.com/m8/feeds/contacts/default/full?v=3.0&max-results=50&q="
+ request.term;
authenticatedXhr(
'GET',
url,
function(error, status, response) {
$(response)
.find("entry")
.each(
function() {
var title = $(this)
.find("title")
.text();
if (title == "") {
title = "Unknown";
}
$(this)
.find(
"gd\\:phoneNumber")
.each(
function() {
var number = $(
this)
.text();
var type = $(
this)
.attr(
"rel")
.replace(
"http://schemas.google.com/g/2005#",
"");
suggestions
.push({
value : number,
label : title
+ " ("
+ type
+ ": "
+ number
+ ")"
});
});
});
console.log(suggestions);
responseCallback(suggestions);
});
},
autoFocus : true
});
$("#destination")
.keyup(
function(e) {
if (e.keyCode == 13) {
try {
var number = $("#destination").val();
var re = new RegExp();
re
.compile("((([2-9][0-8][0-9])|([\(][2-9][0-8][0-9][\)]))(.|-| )?([2-9][0-9]{2})(.|-| )?([0-9]{4}))");
var tokens = number.match(re);
LOGGER.API.log(MODULE, "number:" + number
+ " tokens:" + tokens);
if (tokens) {
XSIACTIONS.API.call(tokens[0]);
}
} catch (error) {
LOGGER.API.error(MODULE, error.message);
}
$("#destination").val("");
}
});
// signout
document.querySelector('#signout').addEventListener('click', function() {
signout(true);
});
// about
document.querySelector('#about_link_tabs').addEventListener('click',
showAboutBox);
// Click to dial checkbox
document.querySelector('#clicktodialbox').addEventListener('click', function() {
var clicktodial = $("#clicktodialbox").prop("checked");
localStorage["clicktodial"] = clicktodial;
});
// Notifications checkbox
document.querySelector('#notificationsbox').addEventListener('click',
function() {
var notifications = $("#notificationsbox").prop("checked");
localStorage["notifications"] = notifications;
});
// Text to speech checkbox
document.querySelector('#texttospeechbox').addEventListener('click',
function() {
var texttospeech = $("#texttospeechbox").prop("checked");
localStorage["texttospeech"] = texttospeech;
});
// Do Not disturb button
document.querySelector('#dndbutton').addEventListener('click', function() {
var dnd = localStorage["dnd"];
if (dnd != "unassigned") {
if (dnd == "true") {
dnd = "false";
} else {
dnd = "true";
}
try {
XSIACTIONS.API.setDoNotDisturb(dnd);
} catch (error) {
if (textToSpeechEnabled() == "true") {
chrome.tts.speak('An error occured saving your DND settings.');
LOGGER.API.error(MODULE, error.message);
}
}
}
});
// CFA button
document
.querySelector('#cfabutton')
.addEventListener(
'click',
function() {
var cfa = localStorage["cfa"];
if (cfa != "unassigned") {
if (cfa == "true") {
cfa = "false";
} else {
cfa = "true";
}
try {
XSIACTIONS.API.setCallForwardAlways(cfa);
} catch (error) {
if (textToSpeechEnabled() == "true") {
chrome.tts
.speak('An error occured saving your Call Forwarding Always settings.');
LOGGER.API.error(MODULE, error.message);
}
}
}
});
// Remote Office button
document
.querySelector('#robutton')
.addEventListener(
'click',
function() {
var ro = localStorage["ro"];
if (ro != "unassigned") {
if (ro == "true") {
ro = "false";
} else {
ro = "true";
}
try {
XSIACTIONS.API.setRemoteOffice(ro);
} catch (error) {
if (textToSpeechEnabled() == "true") {
chrome.tts
.speak('An error occured saving your Remote Office settings.');
LOGGER.API.error(MODULE, error.message);
}
}
}
});
// Signout. A manual signout means the user signed out themselves. In this case,
// clear out all info. If a force logout
// due to an authentication error or some other error, then retain some
// information.
function signout(manual) {
localStorage["password"] = "";
localStorage["name"] = "";
localStorage["cfa"] = "";
localStorage["ro"] = "";
localStorage["dnd"] = "";
localStorage["currentTab"] = "";
localStorage["connectionStatus"] = "signedOut";
if (manual) {
localStorage["url"] = "";
localStorage["username"] = "";
localStorage["clicktodial"] = "";
localStorage["notifications"] = "";
localStorage["texttospeech"] = "";
localStorage["errorMessage"] = "";
}
top.location.assign("options.html");
}
var services = {
dnd : {
buttonId : "#dndbutton",
activeImage : "images/dnd_active.png",
normalImage : "images/dnd_normal.png",
disabledImage : "images/dnd_disabled.png",
textToSpeech : "Do not disturb is "
},
ro : {
buttonId : "#robutton",
activeImage : "images/remoteoffice_active.png",
normalImage : "images/remoteoffice_normal.png",
disabledImage : "images/remoteoffice_disabled.png",
textToSpeech : "Remote office is "
},
cfa : {
buttonId : "#cfabutton",
activeImage : "images/callforward_active.png",
normalImage : "images/callforward_normal.png",
disabledImage : "images/callforward_disabled.png",
textToSpeech : "Call forward always is "
}
};
function setButtonState(service, value) {
if (value == "true") {
$(services[service].buttonId).removeAttr("disabled");
$(services[service].buttonId)
.attr("src", services[service].activeImage);
$(services[service].buttonId).css("background-color", "#F7A300");
} else if (value == "false") {
$(services[service].buttonId).removeAttr("disabled");
$(services[service].buttonId)
.attr("src", services[service].normalImage);
$(services[service].buttonId).css("background-color", "transparent");
} else {
$(services[service].buttonId).attr("disabled", "disabled");
$(services[service].buttonId).attr("src",
services[service].disabledImage);
$(services[service].buttonId).css("background-color", "transparent");
}
}
function announceServiceState(service, value) {
if (textToSpeechEnabled() == "true") {
if (value == "true") {
chrome.tts.speak(services[service].textToSpeech + "on");
} else if (value == "false") {
chrome.tts.speak(services[service].textToSpeech + "off");
} else {
chrome.tts.speak(services[service].textToSpeech + "unknown");
}
}
}
function restoreTabs() {
// restore Xsi-Actions
var xsiactions_options = {
host : localStorage["url"],
username : localStorage["username"],
password : localStorage["<PASSWORD>"],
};
XSIACTIONS.API.init(xsiactions_options);
try {
var name = XSIACTIONS.API.getName();
localStorage["name"] = name;
} catch (error) {
LOGGER.API.error(MODULE, error.message);
if (error.message.indexOf("401") != -1
|| error.message.indexOf("403") != -1) {
localStorage["errorMessage"] = "An authentication error occurred. Please login again.";
} else {
localStorage["errorMessage"] = "An error occurred. Please login again.";
}
signout(false);
return;
}
// create tabs
$("#tabs").tabs();
// add activate(select) event handler for tabs
$("#tabs")
.tabs(
{
activate : function(event, ui) {
if (ui.newPanel.attr("id") == "history") {
localStorage["currentTab"] = "history";
var callLogs = XSIACTIONS.API.getCallLogs();
var list = [];
$(callLogs)
.find("callLogsEntry")
.each(
function() {
var name = $(this).find(
"name").text();
var number = $(this).find(
"phoneNumber")
.text();
var time = $(this).find(
"time").text();
var type = $(this).parent()[0].nodeName;
list.push({
name : name,
number : number,
time : time,
type : type
});
});
list.sort(function(a, b) {
a = new Date(a.time);
b = new Date(b.time);
return b.getTime() - a.getTime();
});
$("#calllogentries").empty();
for ( var i = 0; i < list.length; i++) {
var row = "<tr id='calllogentry" + i + "_"
+ list[i].number + "'>";
row = row + "<td><p>" + list[i].name
+ "</p>" + list[i].number + "</td>";
row = row + "<td>"
+ formatTimestamp(list[i].time)
+ "</td>";
if (list[i].type == "placed") {
row = row
+ "<td><img src='images/history_outgoing_normal.png'/></td>";
} else if (list[i].type == "received") {
row = row
+ "<td><img src='images/history_incoming_normal.png'/></td>";
} else {
row = row
+ "<td><img src='images/history_missed_normal.png'/></td>";
}
$("#calllogentries").append(row);
}
} else if (ui.newPanel.attr("id") == "dialer") {
localStorage["currentTab"] = "dialer";
$('#destination').focus();
} else if (ui.newPanel.attr("id") == "preferences") {
localStorage["currentTab"] = "preferences";
}
}
});
// restore current tab
var currentTab = localStorage["currentTab"];
if (currentTab == "dialer") {
$("#tabs").tabs("option", "active", 0);
$('#destination').focus();
} else if (currentTab == "history") {
$("#tabs").tabs("option", "active", 1);
} else if (currentTab == "preferences") {
$("#tabs").tabs("option", "active", 2);
} else {
$("#tabs").tabs("option", "active", 0);
$('#destination').focus();
}
// restore service button states
setButtonState("dnd", localStorage["dnd"]);
setButtonState("ro", localStorage["ro"]);
setButtonState("cfa", localStorage["cfa"]);
var clicktodial = localStorage["clicktodial"];
if (clicktodial == "true") {
$("#clicktodialbox").prop('checked', true);
} else {
$("#clicktodialbox").prop('checked', false);
}
var notifications = localStorage["notifications"];
if (notifications == "true") {
$("#notificationsbox").prop('checked', true);
} else {
$("#notificationsbox").prop('checked', false);
}
var texttospeech = localStorage["texttospeech"];
if (texttospeech == "true") {
$("#texttospeechbox").prop('checked', true);
} else {
$("#texttospeechbox").prop('checked', false);
}
updateCalls();
$(window).bind(
"storage",
function(e) {
LOGGER.API.log(MODULE, "Event received with key: "
+ e.originalEvent.key);
if (e.originalEvent.key == "dnd" || e.originalEvent.key == "ro"
|| e.originalEvent.key == "cfa") {
setButtonState(e.originalEvent.key,
localStorage[e.originalEvent.key]);
announceServiceState(e.originalEvent.key,
e.originalEvent.newValue);
} else if (e.originalEvent.key == "calls") {
updateCalls();
} else if (e.originalEvent.key == "errorMessage") {
signout(false);
}
});
}
var callTimerId;
function updateCalls() {
$("#calls").empty();
window.clearInterval(callTimerId);
var calls = JSON.parse(localStorage["calls"]);
LOGGER.API.log(MODULE, calls);
for ( var callId in calls) {
var call = calls[callId];
var nameAndNumber = "<div class='nameAndNumber'>";
if (call.name == "") {
nameAndNumber += call.number;
} else {
nameAndNumber += call.name + " (" + call.number + ")";
}
nameAndNumber += "</div>";
var html = "<tr>";
switch (call.state) {
case "Alerting":
var callType = "Incoming Call";
if (call.personality != "Terminator") {
callType = "Outgoing Call";
}
html = html + "<td>" + nameAndNumber + "<div class='callDuration'>"
+ callType + "</div></td>";
html = html + "<td>";
if (call.personality == "Terminator") {
html = html + "<img id='answer_" + callId
+ "' src='images/answer.png' />";
}
html = html + "</td>";
html = html + "<td><img id='end_" + callId
+ "' src='images/decline.png' /></td>";
break;
case "Active":
html = html + "<td>" + nameAndNumber + "<div class='callDuration'>"
+ getCallDuration(call.answerTime) + "</div></td>";
html = html + "<td><img id='end_" + callId
+ "' src='images/hangup.png' /></td>";
html = html + "<td><img id='hold_" + callId
+ "' src='images/hold.png' /></td>";
break;
case "Held":
html = html + "<td>" + nameAndNumber + "<div class='callDuration'>"
+ getCallDuration(call.answerTime) + "</div></td>";
html = html + "<td><img id='end_" + callId
+ "' src='images/hangup.png' /></td>";
html = html + "<td><img id='answer_" + callId
+ "' src='images/hold_active.png' /></td>";
break;
}
html = html + "</tr>";
$("#calls").append(html);
}
$("#calls tbody tr td img").on("click", function(event) {
var tokens = $(this).attr("id").split("_");
callControl(tokens[0], tokens[1]);
});
callTimerId = window.setInterval(updateCallDurations, 1000);
}
function getCallDuration(answerTime) {
var delta = parseInt((new Date().getTime() - answerTime) / 1000);
var hh = parseInt(delta / 3600);
var mm = parseInt((delta - (hh * 3600)) / 60);
var ss = parseInt(delta - ((hh * 3600) + (mm * 60)));
var ret = hhmmssToString(hh, mm, ss);
return ret;
}
function hhmmssToString(hh, mm, ss) {
var ret = ss;
if (ss < 10) {
ret = "0" + ss;
}
if (mm < 10) {
ret = "0" + mm + ":" + ret;
} else {
ret = mm + ":" + ret;
}
if (hh > 0) {
ret = hh + ":" + ret;
}
return ret;
}
function updateCallDurations() {
$(".callDuration").each(function() {
var duration = $(this).text();
if (duration != "Incoming Call" && duration != "Outgoing Call") {
duration = incrementCallDuration(duration);
$(this).text(duration);
}
});
}
function textToSpeechEnabled() {
var texttospeech = localStorage["texttospeech"];
return texttospeech;
}
function showAboutBox() {
top.location.assign("about.html");
}
function callControl(action, callId) {
LOGGER.API.log(MODULE, action + " " + callId);
try {
switch (action) {
case "answer":
XSIACTIONS.API.talk(callId);
break;
case "hold":
XSIACTIONS.API.hold(callId);
break;
case "end":
XSIACTIONS.API.hangup(callId);
break;
default:
action = "unknown";
}
} catch (error) {
var calls = JSON.parse(localStorage["calls"]);
delete calls[callId];
localStorage["calls"] = JSON.stringify(calls);
if (textToSpeechEnabled() == "true") {
chrome.tts
.speak('Failed to perform ' + action + ' action on call.');
LOGGER.API.error(MODULE, error.message);
}
}
}
function incrementCallDuration(duration) {
var tokens = duration.split(":");
var hh = 0;
var mm = 0;
var ss = 0;
if (tokens.length == 3) {
hh = parseInt(tokens[0]);
mm = parseInt(tokens[1]);
ss = parseInt(tokens[2]);
} else {
mm = parseInt(tokens[0]);
ss = parseInt(tokens[1]);
}
ss++;
if (ss > 59) {
ss = 0;
mm++;
}
if (mm > 59) {
mm = 0;
hh++;
}
return hhmmssToString(hh, mm, ss);
}
document.addEventListener('DOMContentLoaded', restoreTabs);
| ea986beab52cb17acfc671c195f4fd3a074a2c97 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | sowderca/broadworks_ext | 485eb5fd5820a65117c26df775c2af3020fd3e3c | b18bc96aadda4a087b52d616b59f819c7e1a0fdf |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using FoodShop.App_Code;
namespace FoodShop.admin
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Login"] != null)
{
Response.Redirect("index.aspx");
}
}
protected int KTDangNhap()
{
string name = txtU.Text.Trim();
string pass = StringProc.MD5Hash(txtP.Text.Trim());
string sQuery = "SELECT COUNT(*) FROM Member WHERE username=@us and pass=@pass";
SqlParameter[] pars =
{
new SqlParameter("@us",SqlDbType.VarChar,50){Value=name},
new SqlParameter("@pass",SqlDbType.VarChar,255){Value=pass},
};
return DataProvider.executeScalar(sQuery, pars);
}
protected void btLogin_Click(object sender, EventArgs e)
{
if (KTDangNhap() > 0)
{
Session["Login"] = txtU.Text;
Response.Redirect("index.aspx");
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirectMe", "alert('Lỗi; Đăng nhập thất bại');", true);
}
}
protected void btCancel_Click(object sender, EventArgs e)
{
Response.Redirect("~/vegefoods/TrangChu.aspx");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FoodShop.App_Code;
using System.Data;
using System.Data.SqlClient;
namespace FoodShop.admin
{
public partial class a : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(@"Data Source=ADMIN\SQLEXPRESS;Initial Catalog=vegefoods;Integrated Security=True");
string sQuery = "";
sQuery = "Select * from Member";
//if (Session["allow"] == null)
//{
// Response.Redirect("Login.aspx");
//}
//Response.Write("Chao: " + Session["name"].ToString()); // xuất lời chào.
// Session["name"] = txtU.Text: giúp lấy lại biến user để khi qua trang admin bạn xuất lời chào.
//Session["allow"] = true: Xác định đã có biến này tồn tại sau khi đăng nhập thành công.
if (!IsPostBack)
{
if (Request["id"] != null)
{
sQuery = "select * from Member where username='" + Request["id"] + "'";
SqlDataAdapter lst = new SqlDataAdapter(sQuery, conn);
DataTable sp = new DataTable();
lst.Fill(sp);
exampleFirstName.Text = sp.Rows[0]["username"].ToString();
exampleInputPassword.Text = sp.Rows[0]["pass"].ToString();
exampleLastName.Text = sp.Rows[0]["name"].ToString();
exampleRepeatPhone.Text = sp.Rows[0]["phone"].ToString();
exampleInputEmail.Text = sp.Rows[0]["email"].ToString();
DropDownList_SelectStatus.SelectedValue = sp.Rows[0]["status"].ToString();
DropDownList_SelectRole.SelectedValue = sp.Rows[0]["role"].ToString();
btnAdd.Text = "Update";
}
SqlDataAdapter da = new SqlDataAdapter(sQuery, conn);
DataTable dt = new DataTable();
da.Fill(dt);
}
if (Request["del"] != null)
{
sQuery = "UPDATE [dbo].[Member] SET [status] = 0 WHERE username ='" + Request["del"].ToString() + "'";
if (DataProvider.executeNonQuery(sQuery))
{
lblModal.Text = "Xóa thành công";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
else
{
lblModal.Text = "Xóa thất bại";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (btnAdd.Text == "Thêm Member")
{
string sUserName = exampleFirstName.Text;
string sPass = <PASSWORD>;
string sName = exampleLastName.Text;
string sPhone = exampleRepeatPhone.Text;
string sMail = exampleInputEmail.Text;
int sStatus = Convert.ToInt32(DropDownList_SelectStatus.SelectedValue);
int sRole = Convert.ToInt32(DropDownList_SelectRole.SelectedValue);
Account acc = new Account(sUserName, sPass, sName, sPhone, sMail, sStatus, sRole);
if (acc.AddMember() == true)
{
lblModal.Text = "Thêm Thành Công" + " " + sUserName;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
else
{
lblModal.Text = "Thêm Member Thất Bại" + " " + sUserName;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
}
if (btnAdd.Text == "Update")
{
string sUserName = exampleFirstName.Text;
string sName = exampleLastName.Text;
string sPass = <PASSWORD>.Text;
string sPhone = exampleRepeatPhone.Text;
int sStatus = Convert.ToInt32(DropDownList_SelectStatus.SelectedValue);
int sRole = Convert.ToInt32(DropDownList_SelectRole.SelectedValue);
string sMail = exampleInputEmail.Text;
Account acc = new Account(sUserName, sPass, sName, sPhone, sMail, sStatus, sRole);
if (acc.UpdateMember() == true)
{
lblModal.Text = "Cập Nhật Thành Công" + " " + sUserName;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
else
{
lblModal.Text = "Cập Nhật Thất Bại" + " " + sUserName;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
}
}
protected void HuyButton_Click(object sender, EventArgs e)
{
exampleFirstName.Text = "";
exampleInputEmail.Text = "";
exampleInputPassword.Text = "";
exampleRepeatPassword.Text = "";
exampleLastName.Text = "";
exampleRepeatPhone.Text = "";
}
protected void btnSearch_Click(object sender, EventArgs e)
{
Response.Redirect("a.aspx?key=" + txtKey.Text);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace FoodShop.App_Code
{
public class order
{
private int _Order_id;
private string _Cus_name;
private string _Cus_phone;
private string _Cus_add;
private int _Quan;
private int _Sum;
private int _Status;
private DateTime _Modified;
private DateTime _Create;
private string _Cus_username;
public int Order_id { get => _Order_id; set => _Order_id = value; }
public string Cus_name { get => _Cus_name; set => _Cus_name = value; }
public string Cus_phone { get => _Cus_phone; set => _Cus_phone = value; }
public string Cus_add { get => _Cus_add; set => _Cus_add = value; }
public int Quan { get => _Quan; set => _Quan = value; }
public int Sum { get => _Sum; set => _Sum = value; }
public int Status { get => _Status; set => _Status = value; }
public DateTime Modified { get => _Modified; set => _Modified = value; }
public DateTime Create { get => _Create; set => _Create = value; }
public string Cus_username { get => _Cus_username; set => _Cus_username = value; }
public order(string name,string phone,string add,int quan,int sum,string cus_us,int id)
{
_Cus_name = name;
_Cus_phone = phone;
_Cus_add = add;
_Quan = quan;
_Sum = sum;
_Cus_username = cus_us;
_Order_id = id;
}
public bool Add()
{
string sQuery = "INSERT INTO [dbo].[Order]([cus_name],[cus_phone],[cus_add],[quan],[sum],[status],[modified],[created],[cus_username])VALUES(@name,@phone,@add,@quan,@sum,@status,GETDATE(),GETDATE(),@cus_us)";
SqlParameter[] pars =
{
new SqlParameter("@name",SqlDbType.NVarChar,100){Value=this.Cus_name},
new SqlParameter("@phone",SqlDbType.VarChar,50){Value=this.Cus_phone},
new SqlParameter("@add",SqlDbType.NVarChar,255){ Value=this.Cus_add},
new SqlParameter("@quan",SqlDbType.Int,4){Value=this.Quan},
new SqlParameter("@sum",SqlDbType.Int,4){Value=this.Sum},
new SqlParameter("@status",SqlDbType.Int,4){Value=this.Status},
new SqlParameter("@cus_us",SqlDbType.VarChar,50){Value=this.Cus_username}
};
return DataProvider.executeNonQuery(sQuery, pars);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace FoodShop.vegefoods
{
public partial class cart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Cart"] != null)
{
int total = 0;
DataTable dt = new DataTable();
dt = (DataTable)Session["cart"];
Repeater1.DataSource = dt;
Repeater1.DataBind();
for(int i=0;i<dt.Rows.Count;i++)
{
total += int.Parse(dt.Rows[i]["Total"].ToString());
}
lblSumTotal.Text = total.ToString();
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using FoodShop.App_Code;
namespace FoodShop.vegefoods
{
public partial class shop : System.Web.UI.Page
{
public static int sl = 1;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(@"Data Source=ADMIN\SQLEXPRESS;Initial Catalog=vegefoods;Integrated Security=True");
string sQuery = "";
sQuery = "Select * from Food where status=1";
if (Request["type"] != null)
{
sQuery = "Select * from Food where status=1 and type="+Request["type"].ToString();
}
DataTable dt = new DataTable();
dt = DataProvider.getDataTable(sQuery);
int so_item_1trang = 8;
int so_trang = dt.Rows.Count / so_item_1trang + (dt.Rows.Count % so_item_1trang == 0 ? 0 : 1);
int page = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
int from = (page - 1) * 8;
int to = page * 8 - 1;
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
if (i < from || i > to)
{
dt.Rows.RemoveAt(i);
}
}
Repeater2.DataSource = dt;
Repeater2.DataBind();
DataTable dtPage = new DataTable();
dtPage.Columns.Add("index");
dtPage.Columns.Add("active");
for (int i = 1; i <= so_trang; i++)
{
DataRow dr = dtPage.NewRow();
dr["index"] = i;
if ((Request["page"] == null && i == 1) || (Request["page"] != null && Convert.ToInt32(Request["page"]) == i))
dr["active"] = 1;
else
dr["active"] = 0;
dtPage.Rows.Add(dr);
}
Repeater3.DataSource = dtPage;
Repeater3.DataBind();
}
protected void Repeater2_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Add_to_cart")
{
HiddenField hf_id = (HiddenField)e.Item.FindControl("hf_id");
HiddenField hf_img = (HiddenField)e.Item.FindControl("hf_img");
HiddenField hf_name = (HiddenField)e.Item.FindControl("hf_name");
HiddenField hf_price = (HiddenField)e.Item.FindControl("hf_price");
HiddenField hf_unit = (HiddenField)e.Item.FindControl("hf_unit");
HiddenField hf_pricepromo = (HiddenField)e.Item.FindControl("hf_pricepromo");
DataTable dt = new DataTable();
if (Session["Cart"] == null)
{
dt.Columns.Add("ID");
dt.Columns.Add("Images");
dt.Columns.Add("Products Name");
dt.Columns.Add("Price");
dt.Columns.Add("PricePromo");
dt.Columns.Add("Unit");
dt.Columns.Add("Quantity");
dt.Columns.Add("Total");
}
else
{
dt = (DataTable)Session["Cart"];
}
int iRow = CheckExited(dt, hf_id.Value);
if (iRow != -1)
{
dt.Rows[iRow]["Quantity"] = Convert.ToInt32(dt.Rows[iRow]["Quantity"]) + sl;
dt.Rows[iRow]["Total"] = Convert.ToInt32(dt.Rows[iRow]["Total"]) * Convert.ToInt32(dt.Rows[iRow]["Quantity"]);
}
else
{
DataRow dr = dt.NewRow();
dr["ID"] = hf_id.Value;
dr["Images"] = hf_img.Value;
dr["Products Name"] = hf_name.Value;
dr["Price"] = hf_price.Value;
dr["Unit"] = hf_unit.Value;
dr["PricePromo"] = hf_pricepromo.Value;
dr["Quantity"] = sl;
dr["Total"] = hf_pricepromo.Value;
dt.Rows.Add(dr);
}
Session["Cart"] = dt;
}
}
private int CheckExited(DataTable dt, string id)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["ID"].ToString() == id)
{
return i;
}
}
return -1;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace FoodShop.App_Code
{
public class Account
{
private string _Username;
private string _Pass;
private string _Name;
private string _Phone;
private string _Email;
private int _Role;
private int _Status;
public string Username { get => _Username; set => _Username = value; }
public string Pass { get => _Pass; set => _Pass = value; }
public string Name { get => _Name; set => _Name = value; }
public string Phone { get => _Phone; set => _Phone = value; }
public int Role { get => _Role; set => _Role = value; }
public int Status { get => _Status; set => _Status = value; }
public string Email { get => _Email; set => _Email = value; }
public Account(string sUS, string sPass, string sName, string sPhone, string sEmail, int stt, int role)
{
_Username = sUS;
_Name = sName;
_Pass = sPass;
_Phone = sPhone;
_Email = sEmail;
_Status = stt;
_Role = role;
}
public bool AddMember()
{
string sQuery = "INSERT INTO [dbo].[Member]([username],[pass],[name],[phone],[email],[status],[role])VALUES(@username,@pass,@name,@phone,@email,@status,@role)";
SqlParameter[] pars =
{
new SqlParameter("@username",SqlDbType.VarChar,50){Value=this.Username},
new SqlParameter("@pass",SqlDbType.VarChar,255){ Value=(StringProc.MD5Hash(this.Pass))},
new SqlParameter("@name",SqlDbType.NVarChar,200){ Value=this.Name},
new SqlParameter("@phone",SqlDbType.VarChar,20){Value=this.Phone},
new SqlParameter("@email",SqlDbType.VarChar,255){Value=this.Email},
new SqlParameter("@role",SqlDbType.Int,4){Value=this.Role },
new SqlParameter("@status",SqlDbType.Int,4){Value=this.Status },
};
return DataProvider.executeNonQuery(sQuery, pars);
}
public bool UpdateMember()
{
string sQuery = "UPDATE [dbo].[Member] SET [pass]=@pass,[name]=@name,[email]=@email,[phone]=@phone,[status]=@stt,[role]=@role WHERE [username]=@username";
SqlParameter[] pars =
{
new SqlParameter("@username",SqlDbType.VarChar,50){ Value=this.Username},
new SqlParameter("@pass",SqlDbType.VarChar,255){ Value=(StringProc.MD5Hash(this.Pass))},
new SqlParameter("@name",SqlDbType.NVarChar,200){ Value=this.Name},
new SqlParameter("@phone",SqlDbType.VarChar,20){Value=this.Phone},
new SqlParameter("@email",SqlDbType.VarChar,255){Value=this.Email},
new SqlParameter("@role",SqlDbType.Int,4){Value=this.Role },
new SqlParameter("@stt",SqlDbType.Int,4){Value=this.Status },
};
return DataProvider.executeNonQuery(sQuery, pars);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using FoodShop.App_Code;
namespace FoodShop.vegefoods
{
public partial class checkout : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Cart"] != null)
{
int total = 0;
DataTable dt = new DataTable();
dt = (DataTable)Session["Cart"];
for (int i = 0; i < dt.Rows.Count; i++)
{
total += int.Parse(dt.Rows[i]["Total"].ToString());
}
lblSumTotal.Text = total.ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//if (Session["Cart"] != null)
//{
// DataTable dt = new DataTable();
// dt = (DataTable)Session["Cart"];
// SqlConnection con = new SqlConnection(@"Data Source=ADMIN\SQLEXPRESS;Initial Catalog=vegefoods;Integrated Security=True");
// con.Open();
// string squery = "INSERT INTO [dbo].[HD]([cus_name],[cus_add],[cus_receiver])VALUES('abc','123abc','n')";
// string cus_username = txt_FirtName.Text;
// string name = txt_LastName.Text;
// string phone = txt_phone.Text;
// string add = txt_add.Text;
// order a = new order(name,phone,add,)
// Account acc = new Account(sUserName, sPass, sName, sPhone, sMail, sStatus, sRole);
// if (acc.UpdateMember() == true)
// SqlCommand com = new SqlCommand(squery, con);
// com.ExecuteNonQuery();
// squery = "select @@indentity";
// com = new SqlCommand(squery, con);
// int id = Convert.ToInt32(com.ExecuteScalar().ToString());
// for (int i = 0; i < dt.Rows.Count; i++)
// {
// squery = "INSERT INTO [dbo].[CTHD]([id_hd],[id_sp],[price],[quan])VALUES(@id,@idsp,@price,@quan)";
// SqlParameter[] paras = new SqlParameter[4];
// paras[0] = new SqlParameter("@id", id);
// paras[1] = new SqlParameter("@idsp", dt.Rows[i]["id"]);
// paras[2] = new SqlParameter("@price", dt.Rows[i]["price"]);
// paras[3] = new SqlParameter("@quan", dt.Rows[i]["quan"]);
// com = new SqlCommand(squery, con);
// com.Parameters.AddRange(paras);
// com.ExecuteNonQuery();
// }
// con.Close();
// Session["cart"] = null;
// Response.Write("<script>alert('Dat hang thanh cong ');</script>");
//}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using FoodShop.App_Code;
using FoodShop.admin;
namespace FoodShop.admin
{
public partial class food : System.Web.UI.Page
{
public static int id;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=ADMIN\SQLEXPRESS;Initial Catalog=vegefoods;Integrated Security=True");
string sQuery = "";
sQuery = "Select * from Food";
if (Session["Login"] == null)
{
Response.Redirect("Login.aspx");
}
Response.Write("Chao: " + Session["Login"].ToString());
if (!IsPostBack)
{
if (Request["id"] != null)
{
sQuery = "select * from Food where id=" + Request["id"];
SqlDataAdapter lst = new SqlDataAdapter(sQuery, con);
DataTable sp = new DataTable();
lst.Fill(sp);
exampleFoodName.Text = sp.Rows[0]["name"].ToString();
exampleFoodDes.Text = sp.Rows[0]["description"].ToString();
exampleFoodPrice.Text = sp.Rows[0]["price"].ToString();
examplePricePromo.Text = sp.Rows[0]["price_promo"].ToString();
Image_Thumb.Visible = true;
Image_Thumb.ImageUrl = "~/img/" + sp.Rows[0]["img"].ToString();
Image1.Visible = true;
Image1.ImageUrl = "~/img/" + sp.Rows[0]["img"].ToString();
exampleUnit.Text = sp.Rows[0]["unit"].ToString();
examplePercent.Text = sp.Rows[0]["percent_promo"].ToString();
exampleRating.Text = sp.Rows[0]["rating"].ToString();
exampleSold.Text = sp.Rows[0]["sold"].ToString();
examplePoint.Text = sp.Rows[0]["point"].ToString();
DropDownList1.SelectedValue=sp.Rows[0]["type"].ToString();
DropDownList_SelectStatus.SelectedValue = sp.Rows[0]["status"].ToString();
exampleUsername.Text = sp.Rows[0]["username"].ToString();
exampleModifiled.Text = sp.Rows[0]["modified"].ToString();
id=Convert.ToInt32(sp.Rows[0]["id"].ToString());
btnAdd.Text = "Update";
}
SqlDataAdapter da = new SqlDataAdapter(sQuery, con);
DataTable dt = new DataTable();
da.Fill(dt);
}
if (Request["del"] != null)
{
sQuery = "UPDATE [dbo].[Food] SET [status] = 0 WHERE id ='" + Request["del"] + "'";
if (DataProvider.executeNonQuery(sQuery))
{
lbmodal.Text = "Xóa Thành Công";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
else
{
lbmodal.Text = "Xóa Thất Bại";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (btnAdd.Text == "Thêm Food")
{
string sName = exampleFoodName.Text;
string sDescription = exampleFoodDes.Text;
int sPrice = Convert.ToInt32(exampleFoodPrice.Text);
int sPrice_promo = Convert.ToInt32(examplePricePromo.Text);
string sThumb = FileUpload2.FileName;
string sImg = FileUpload1.FileName;
string sUnit = exampleUnit.Text;
int sPrecent_promo = Convert.ToInt32(examplePercent.Text);
int sRating = Convert.ToInt32(exampleRating.Text);
int sSold = Convert.ToInt32(exampleSold.Text);
int sPoint = Convert.ToInt32(examplePoint.Text);
int sType = Convert.ToInt32(DropDownList1.Text);
int stt = Convert.ToInt32(DropDownList_SelectStatus.Text);
string sUs = (string)Session["Login"];
Food food = new Food(sName, sDescription, sPrice, sPrice_promo, sThumb, sImg, sUnit, sPrecent_promo, sRating, sSold, sPoint, sType, stt, sUs,id);
if (food.AddFood() == true)
{
lbmodal.Text = "Thêm sản phẩm thành công";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
else
{
lbmodal.Text = "Thêm sản phẩm thất bại";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
}
if (btnAdd.Text == "Update")
{
string sName = exampleFoodName.Text;
string sDescription = exampleFoodDes.Text;
int sPrice = Convert.ToInt32(exampleFoodPrice.Text);
int sPrice_promo = Convert.ToInt32(examplePricePromo.Text);
string sThumb = FileUpload2.FileName;
string sImg = FileUpload1.FileName;
string sUnit = exampleUnit.Text;
int sPrecent_promo = Convert.ToInt32(examplePercent.Text);
int sRating = Convert.ToInt32(exampleRating.Text);
int sSold = Convert.ToInt32(exampleSold.Text);
int sPoint = Convert.ToInt32(examplePoint.Text);
int sType = Convert.ToInt32(DropDownList1.Text);
int stt = Convert.ToInt32(DropDownList_SelectStatus.Text);
string sUs = (string)Session["Login"];
Food food = new Food(sName, sDescription, sPrice, sPrice_promo, sThumb, sImg, sUnit, sPrecent_promo, sRating, sSold, sPoint, sType, stt, sUs,id);
if (food.UpdateFood() == true)
{
lbmodal.Text = "Cập nhật thành công";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
else
{
lbmodal.Text = "Cập nhật thất bại";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
}
}
//protected void btnHuy_Click(object sender, EventArgs e)
//{
// ex.Text = "";
// txtPos.Text = "";
// DropDownList_SelectStatus.SelectedValue = "Active";
//}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace FoodShop.App_Code
{
public class Food_type
{
private int _Type_id;
private string _Type_name;
private int _Type_post;
private string _Type_img;
private int _Status;
private string _Username;
private DateTime _Modified;
public string Type_name { get => _Type_name; set => _Type_name = value; }
public int Type_post { get => _Type_post; set => _Type_post = value; }
public string Type_img { get => _Type_img; set => _Type_img = value; }
public int Status { get => _Status; set => _Status = value; }
public string Username { get => _Username; set => _Username = value; }
public DateTime Modified { get => _Modified; set => _Modified = value; }
public int Type_id { get => _Type_id; set => _Type_id = value; }
public Food_type(string SName, int SPost, string SImg, int sStatus, string sUsername, int ID)
{
_Type_name = SName;
_Type_post = SPost;
_Type_img = SImg;
_Status = sStatus;
_Username = sUsername;
_Type_id = ID;
}
public bool AddFood()
{
string sQuery = "INSERT INTO [dbo].[food_type]([type_name],[type_pos],[type_img],[status],[username],[modified]) VALUES (@type_name,@type_pos,@type_img,@status,@username,GETDATE())";
SqlParameter[] pars =
{
new SqlParameter("@type_name",SqlDbType.NVarChar,50){Value=this.Type_name},
new SqlParameter("@type_pos",SqlDbType.Int,4){Value=this.Type_post},
new SqlParameter("@type_img",SqlDbType.VarChar,255){Value=this.Type_img},
new SqlParameter("@status",SqlDbType.Int,4){Value=this.Status},
new SqlParameter("@username",SqlDbType.VarChar,50){Value=this.Username}
};
return DataProvider.executeNonQuery(sQuery, pars);
}
public bool CapNhat()
{
string sQuery = "UPDATE [dbo].[food_type] SET [type_name] = @type_name, [type_pos] = @type_pos, [type_img] = @type_img, [status] = @status, [username] = @username,[modified] = GETDATE() WHERE [type_id] = @id ";
SqlParameter[] pars =
{
new SqlParameter("@type_name",SqlDbType.NVarChar,50){Value=this.Type_name},
new SqlParameter("@type_pos",SqlDbType.Int,4){Value=this.Type_post},
new SqlParameter("@type_img",SqlDbType.VarChar,255){Value=this.Type_img},
new SqlParameter("@status",SqlDbType.Int,4){Value=this.Status},
new SqlParameter("@username",SqlDbType.VarChar,50){Value=this.Username},
new SqlParameter("@id",SqlDbType.Int,4){Value=this.Type_id}
};
return DataProvider.executeNonQuery(sQuery, pars);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace FoodShop.App_Code
{
public class Food
{
private int _Id;
private string _Name;
private string _Desciption;
private int _Price;
private int _Price_promo;
private string _Thumb;
private string _Img;
private string _Unit;
private int _Precent_promo;
private int _Rating;
private int _Sold;
private int _Point;
private int _Type;
private int _Status;
private string _Username;
private DateTime _Modified;
public int Id { get => _Id; set => _Id = value; }
public string Name { get => _Name; set => _Name = value; }
public string Desciption { get => _Desciption; set => _Desciption = value; }
public string Thumb { get => _Thumb; set => _Thumb = value; }
public string Img { get => _Img; set => _Img = value; }
public string Unit { get => _Unit; set => _Unit = value; }
public int Rating { get => _Rating; set => _Rating = value; }
public int Sold { get => _Sold; set => _Sold = value; }
public int Type { get => _Type; set => _Type = value; }
public int Status { get => _Status; set => _Status = value; }
public string Username { get => _Username; set => _Username = value; }
public DateTime Modified { get => _Modified; set => _Modified = value; }
public int Price { get => _Price; set => _Price = value; }
public int Price_promo { get => _Price_promo; set => _Price_promo = value; }
public int Precent_promo { get => _Precent_promo; set => _Precent_promo = value; }
public int Point { get => _Point; set => _Point = value; }
public Food(string sName, string sDescription, int sPrice, int sPrice_promo, string sThumb, string sImg, string sUnit, int sPrecent_promo, int sRating, int sSold, int sPoint, int sType, int stt, string sUs,int Sid)
{
_Name = sName;
_Desciption = sDescription;
Price = sPrice;
Price_promo = sPrice_promo;
_Thumb = sThumb;
_Img = sImg;
_Unit = sUnit;
Precent_promo = sPrecent_promo;
_Rating = sRating;
_Sold = sSold;
Point = sPoint;
_Type = sType;
_Status = stt;
_Username = sUs;
_Id = Sid;
}
public bool AddFood()
{
string sQuery = "INSERT INTO [dbo].[Food]([name],[description],[price],[price_promo],[thumb],[img],[unit],[percent_promo],[rating],[sold],[point],[type],[status],[username],[modified])VALUES(@name,@description,@price,@price_promo,@thumb,@img,@unit,@percent_promo,@rating,@sold,@point,@type,@status,@username,GETDATE())";
SqlParameter[] pars =
{
new SqlParameter("@name",SqlDbType.NVarChar,50){Value=this.Name},
new SqlParameter("@description",SqlDbType.Text,255){Value=this.Desciption},
new SqlParameter("@price",SqlDbType.Int,4){ Value=this.Price},
new SqlParameter("@price_promo",SqlDbType.Int,4){Value=this.Price_promo},
new SqlParameter("@thumb",SqlDbType.VarChar,255){Value=this.Thumb},
new SqlParameter("@img",SqlDbType.VarChar,255){Value=this.Img},
new SqlParameter("@unit",SqlDbType.NVarChar,10){ Value=this.Unit},
new SqlParameter("@percent_promo",SqlDbType.Int,4){Value=this.Precent_promo},
new SqlParameter("@rating",SqlDbType.Int,4){Value=this.Rating},
new SqlParameter("@sold",SqlDbType.Int,4){Value=this.Sold},
new SqlParameter("@point",SqlDbType.Int,4){Value=this.Point},
new SqlParameter("@type",SqlDbType.Int,4){Value=this.Type},
new SqlParameter("@status",SqlDbType.Int,4){Value=this.Status},
new SqlParameter("@username",SqlDbType.VarChar,50){Value=this.Username}
};
return DataProvider.executeNonQuery(sQuery, pars);
}
public bool UpdateFood()
{
string sQuery = "UPDATE [dbo].[Food] SET [name] = @name ,[description] = @description ,[price]=@price,[price_promo]=@price_promo,[thumb]=@thumb,[img]=@img,[unit]=@unit,[percent_promo]=@percent_promo,[rating]=@rating,[sold]=@sold,[point]=@point,[type]=@type,[status]=@status,[username]=@username,[modified]=GETDATE() WHERE [id]=@id";
SqlParameter[] pars =
{
new SqlParameter("@name",SqlDbType.NVarChar,50){Value=this.Name},
new SqlParameter("@description",SqlDbType.Text,255){Value=this.Desciption},
new SqlParameter("@price",SqlDbType.Int,4){ Value=this.Price},
new SqlParameter("@price_promo",SqlDbType.Int,4){Value=this.Price_promo},
new SqlParameter("@thumb",SqlDbType.VarChar,255){Value=this.Thumb},
new SqlParameter("@img",SqlDbType.VarChar,255){Value=this.Img},
new SqlParameter("@unit",SqlDbType.NVarChar,10){ Value=this.Unit},
new SqlParameter("@percent_promo",SqlDbType.Int,4){Value=this.Precent_promo},
new SqlParameter("@rating",SqlDbType.Int,4){Value=this.Rating},
new SqlParameter("@sold",SqlDbType.Int,4){Value=this.Sold},
new SqlParameter("@point",SqlDbType.Int,4){Value=this.Point},
new SqlParameter("@type",SqlDbType.Int,4){Value=this.Type},
new SqlParameter("@status",SqlDbType.Int,4){Value=this.Status},
new SqlParameter("@id",SqlDbType.Int,4){Value=this.Id},
new SqlParameter("@username",SqlDbType.VarChar,50){Value=this.Username}
};
return DataProvider.executeNonQuery(sQuery, pars);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using FoodShop.App_Code;
namespace FoodShop.admin
{
public partial class Food_Type : System.Web.UI.Page
{
public static int id;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=ADMIN\SQLEXPRESS;Initial Catalog=vegefoods;Integrated Security=True");
string sQuery = "";
sQuery = "Select * from food_type";
if (Session["Login"] == null)
{
Response.Redirect("Login.aspx");
}
Response.Write("Chao: " + Session["Login"].ToString());
if (!IsPostBack)
{
if (Request["type_id"] != null)
{
sQuery = "select * from food_type where type_id='" + Request["type_id"] + "'";
SqlDataAdapter lst = new SqlDataAdapter(sQuery, con);
DataTable sp = new DataTable();
lst.Fill(sp);
txtName.Text = sp.Rows[0]["type_name"].ToString();
txtPos.Text = sp.Rows[0]["type_pos"].ToString();
DropDownList_SelectStatus.SelectedValue = sp.Rows[0]["status"].ToString();
id = Convert.ToInt32(sp.Rows[0]["type_id"].ToString());
btnAdd.Text = "Update";
FileUpload1.Visible = true;
}
SqlDataAdapter da = new SqlDataAdapter(sQuery, con);
DataTable dt = new DataTable();
da.Fill(dt);
}
if (Request["del"] != null)
{
sQuery = "UPDATE [dbo].[food_type] SET [status] = 0 WHERE type_id ='" + Request["del"] + "'";
if (DataProvider.executeNonQuery(sQuery))
{
lbmodal.Text = "Xóa Thành Công";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
else
{
lbmodal.Text = "Xóa Thất Bại";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (btnAdd.Text == "Thêm Food Type")
{
string sFoodName = txtName.Text;
int sPost = Convert.ToInt32(txtPos.Text);
string sFoodImage = FileUpload1.FileName;
string sUserName = (string)Session["Login"];
int sStatus = Convert.ToInt32(DropDownList_SelectStatus.SelectedValue);
Food_type food_type = new Food_type(sFoodName, sPost, sFoodImage, sStatus, sUserName, id);
if (food_type.AddFood() == true)
{
lbmodal.Text = "Thêm loại sản phẩm thành công";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
else
{
lbmodal.Text = "Thêm loại sản phẩm thất bại";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
}
if (btnAdd.Text == "Update")
{
string sFoodName = txtName.Text;
int sPost = Convert.ToInt32(txtPos.Text);
string sFoodImage = FileUpload1.FileName;
string sUserName = (string)Session["Login"];
int sStatus = Convert.ToInt32(DropDownList_SelectStatus.SelectedValue);
Food_type food_type = new Food_type(sFoodName, sPost, sFoodImage, sStatus, sUserName, id);
if (food_type.CapNhat() == true)
{
lbmodal.Text = "Cập nhật thành công";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
else
{
lbmodal.Text = "Cập nhật thất bại";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
}
}
protected void btnHuy_Click(object sender, EventArgs e)
{
txtName.Text = "";
txtPos.Text = "";
DropDownList_SelectStatus.SelectedValue = "Active";
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using FoodShop.App_Code;
namespace FoodShop.admin
{
public partial class lst_food : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=ADMIN\SQLEXPRESS;Initial Catalog=vegefoods;Integrated Security=True");
string sQuery = "";
sQuery = "Select * from Food";
if (Session["Login"] == null)
{
Response.Redirect("Login.aspx");
}
Response.Write("Chao: " + Session["Login"].ToString());
if (Request["del"] != null)
{
sQuery = "UPDATE [dbo].[Food] SET [status] = 0 WHERE id ='" + Request["del"] + "'";
if (DataProvider.executeNonQuery(sQuery))
{
lbmodal.Text = "Xóa Thành Công";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
else
{
lbmodal.Text = "Xóa Thất Bại";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
}
}
}
} | cadd2aad282e4b329e80410a6f46c77a1e4f8c86 | [
"C#"
] | 12 | C# | LeDuTuyetNhi/asp | b30d5770e6b259aa9eaba494e8ae918a1470b98c | 6a5b60c72a2371730c37b1cd6ef1767dcd468c2a |
refs/heads/master | <file_sep>#!/usr/bin/env python
import actionlib
import rospy
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from math import radians, degrees
from actionlib_msgs.msg import *
from geometry_msgs.msg import Point
from geometry_msgs.msg import Twist
from sound_play.libsoundplay import SoundClient
from topic_subscriber import compare_value
from topic_subscriber import findTxt
from topic_subscriber import result_TTS
from run_darknet import run_darknet
import os
from voice_count import play_audio
from test import rotate
rnum = 0
PI = 3.14159265358979323846;
class navi():
def __init__(self,message):
sc = SoundClient()
# declare the coordinates of interest
self.x1room = 3.661
self.y1room = 1.485
self.x2room = 5.751
self.y2room = -0.373
self.x3room = 1.133
self.y3room = -4.890
self.x4room = -1.102
self.y4room = -3.164
self.xHome = 0.08
self.yHome = 0.596
self.goalReached = False
# --- drive and search flow ---
# -----------------------------
# go first room
# compare value # if true, return home
# or, go second room
# compare value # if true, return home
# or, go third room
# compare value # if true, return home
# or, go forth room
# compare value
# return home
if( (message is 21) or (message is 22) or (message is 23) or (message is 24) or (message is 25) or (message is 26) or (message is 27) or (message is 28) ):
rospy.loginfo(message)
start_check = True
self.goalReached = self.moveToGoal(self.x1room, self.y1room,message)
rotate(300,True)
rotate(720,False)
rotate(720,True)
rotate(720,False)
rotate(720,True)
rnum = 1
while (start_check):
if compare_value(message): # image detect success
rospy.loginfo("go home")
self.goalReached = self.moveToGoal(self.xHome, self.yHome,message)
start_check = False
result_TTS(message,rnum)
elif rnum is 1 and compare_value(message) is False:
self.goalReached = self.moveToGoal(self.x4room, self.y4room,message)
rotate(300,True)
rotate(720,False)
rotate(720,True)
rotate(720,False)
rotate(720,True)
rnum = 4
if compare_value(message): # image detect success
rospy.loginfo("go home")
self.goalReached = self.moveToGoal(self.xHome, self.yHome,message)
start_check = False
result_TTS(message,rnum)
elif rnum is 4 and compare_value(message) is False:
goalReached = self.moveToGoal(self.x3room, self.y3room,message)
rotate(300,True)
rotate(720,False)
rotate(720,True)
rotate(720,False)
rotate(720,True)
rnum = 3
if compare_value(message): # image detect success
rospy.loginfo("go home")
self.goalReached = self.moveToGoal(self.xHome, self.yHome,message)
start_check = False
result_TTS(message,rnum)
elif rnum is 3 and compare_value(message) is False:
self.goalReached = self.moveToGoal(self.x2room, self.y2room,message)
rotate(300,True)
rotate(720,False)
rotate(720,True)
rotate(720,False)
rotate(720,True)
rnum = 2
if compare_value(message):
rospy.loginfo("go home")
self.goalReached = self.moveToGoal(self.xHome, self.yHome,message)
start_check = False
result_TTS(message,rnum)
elif rnum is 2 and compare_value(message) is False:
rospy.loginfo("go home")
self.goalReached = self.moveToGoal(self.xHome, self.yHome,message)
start_check = False
result_TTS(message,rnum)
elif(message is 11):
self.goalReached = self.moveToGoal(self.x1room, self.y1room,message)
rnum = 111
result_TTS(message,rnum)
elif(message is 12):
self.goalReached = self.moveToGoal(self.x1room, self.y1room,message)
rnum = 112
result_TTS(message,rnum)
elif(message is 13):
self.goalReached = self.moveToGoal(self.x1room, self.y1room,message)
rnum = 113
result_TTS(message,rnum)
elif(message is 14):
self.goalReached = self.moveToGoal(self.x1room, self.y1room,message)
rnum = 114
result_TTS(message,rnum)
else:
rospy.loginfo("fail to start .. plz reboot program")
rospy.loginfo("Quit program")
rospy.sleep()
def moveToGoal(self,xGoal,yGoal,message):
#define a client for to send goal requests to the move_base server through a SimpleActionClient
ac = actionlib.SimpleActionClient("move_base", MoveBaseAction)
#wait for the action server to come up
while(not ac.wait_for_server(rospy.Duration.from_sec(5.0))):
rospy.loginfo("Waiting for the move_base action server to come up")
goal = MoveBaseGoal()
#set up the frame parameters
goal.target_pose.header.frame_id = "map"
goal.target_pose.header.stamp = rospy.Time.now()
# moving towards the goal*/
goal.target_pose.pose.position = Point(xGoal,yGoal,0)
goal.target_pose.pose.orientation.x = 0.0
goal.target_pose.pose.orientation.y = 0.0
goal.target_pose.pose.orientation.z = 0.0
goal.target_pose.pose.orientation.w = 1.0
rospy.loginfo("Sending goal location ...")
ac.send_goal(goal)
ac.wait_for_result(rospy.Duration(60))
rospy.loginfo("testing..")
if(ac.get_state() == GoalStatus.SUCCEEDED):
rospy.loginfo("You have reached the destination")
return True
else:
rospy.loginfo("The robot failed to reach the destination")
return False
if __name__ == '__main__':
try:
rospy.init_node('navi', anonymous=False)
navi()
rospy.spin()
except rospy.ROSInterruptException:
rospy.loginfo("map_navigation node terminated.")
<file_sep>#!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
from voice_count import knust_voice
from voice_count import count
import voice_count
rospy.init_node('topic_publisher' ,anonymous=False)
pub = rospy.Publisher('voice',Int32,queue_size=1)
#voicerate = rospy.Rate(1)
knust_voice()
number = count()
#while not rospy.is_shutdown():
# pub.publish(number)
# voicerate.sleep()
pub.publish(number)
<file_sep>#!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
import actionlib
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from math import radians, degrees
from actionlib_msgs.msg import *
from geometry_msgs.msg import Point
from sound_play.libsoundplay import SoundClient
import voice_count
import navi
from voice_count import play_audio
def match_img(rst): # use in find specific room
if (rst == 'Man'):
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/man_done.wav')
elif (rst == 'Woman'):
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/woman_done.wav')
elif (rst == 'Apple'):
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/apple_done.wav')
elif (rst == 'Pear'):
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/pear_done.wav')
elif (rst == 'Chipmunk'):
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/chipmunk_done.wav')
elif (rst == 'Squirrel'):
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/squirrel_done.wav')
elif (rst == 'Maple Leaf'):
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/maple_done.wav')
elif (rst == 'Ginkgo Leaf'):
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/ginkgo_done.wav')
def match_rnum(rnum): # use in find specific image
if (rnum == 1):
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/1st_room_find.wav')
elif (rnum == 2):
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/2nd_room_find.wav')
elif (rnum == 3):
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/3rd_room_find.wav')
elif (rnum == 4):
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/4th_room_find.wav')
# in the end, speech the searched result
def result_TTS(msg,rnum): # man, woman, apple, pear, chipmunk, squirrel, maple, ginkgo
#rst = findTxt()
if (msg == 11): # 1st room
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/1st_room_done.wav')
#match_img(rst)
elif (msg == 12): # 2nd room
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/2nd_room_done.wav')
#match_img(rst)
elif (msg == 13): # 3rd room
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/3rd_room_done.wav')
#match_img(rst)
elif (msg == 14): # 4th room
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/4th_room_done.wav')
#match_img(rst)
elif (msg == 21): # found man
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/man_find.wav')
match_rnum(rnum)
elif (msg == 22): # found woman
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/woman_find.wav')
match_rnum(rnum)
elif (msg == 23): # found apple
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/apple_find.wav')
match_rnum(rnum)
elif (msg == 24): # found pear
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/pear_find.wav')
match_rnum(rnum)
elif (msg == 25): # found chipmunk
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/chipmunk_find.wav')
match_rnum(rnum)
elif (msg == 26): # found squirrel
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/squirrel_find.wav')
match_rnum(rnum)
elif (msg == 27): # found maple
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/maple_find.wav')
match_rnum(rnum)
elif (msg == 28): # found ginkgo
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/ginkgo_find.wav')
match_rnum(rnum)
else:
pass
def findTxt(msg): # find what should search image from detected image
count = {'Man': 0, 'Woman': 0, 'Apple': 0, 'Pear': 0, 'Maple Leaf': 0, 'Ginkgo Leaf': 0, 'Chipmunk': 0, 'Squirrel': 0 }
with open('/home/rastech/darknet/img_result.txt') as f:
lines = f.readlines()
for line in lines:
wrd = line.split(':', 1)[0]
if wrd == 'Man':
count['Man'] += 1
elif wrd == 'Woman':
count['Woman'] += 1
elif wrd == 'Apple':
count['Apple'] += 1
elif wrd == 'Pear':
count['Pear'] += 1
elif wrd == 'Maple Leaf':
count['Maple Leaf'] += 1
elif wrd == 'Ginkgo Leaf':
count['Ginkgo Leaf'] += 1
elif wrd == 'Chipmunk':
count['Chipmunk'] += 1
elif wrd == 'Squirrel':
count['Squirrel'] += 1
print('Man: ' + str(count.get('Man')))
print('Woman: ' + str(count.get('Woman')))
print('Apple: ' + str(count.get('Apple')))
print('Pear: ' + str(count.get('Pear')))
print('Maple Leaf: ' + str(count.get('Maple Leaf')))
print('Ginkgo Leaf: ' + str(count.get('Ginkgo Leaf')))
print('Chipmunk: ' + str(count.get('Chipmunk')))
print('Squirrel: ' + str(count.get('Squirrel')))
for completed_name , value in count.items(): # check value in list
if (value > 15) and ( completed_name == find_word(msg)):
return completed_name
# Room number flow
# 1. receive find 'apple' speech command
# 2. start navi, and detect room in order by room number
# 3. when first room detect is finished, compare 'find' value with 'detected' value
# 4. if value is True, retrun back home
def find_word(msg): # for compare with 'maxCount' value
global fwrd
if msg == 21:
fwrd = 'Man'
elif msg == 22:
fwrd = 'Woman'
elif msg == 23:
fwrd = 'Apple'
elif msg == 24:
fwrd = 'Pear'
elif msg == 25:
fwrd = 'Chipmunk'
elif msg == 26:
fwrd = 'Squirrel'
elif msg == 27:
fwrd = 'Maple Leaf'
elif msg == 28:
fwrd = 'Ginkgo Leaf'
else:
pass
return fwrd
def compare_value(msg): # execute when first room detect is finished
if findTxt(msg) == find_word(msg):
return True
else:
return False
def callback(msg):
global message
print(msg.data)
message = msg.data
try:
rospy.loginfo("You have reached the destination")
navi.navi(msg.data)
rospy.spin()
except rospy.ROSInterruptException:
rospy.loginfo("map_navigation node terminated.")
if __name__ == '__main__':
rospy.init_node('topic_subscriber',anonymous=False)
sub = rospy.Subscriber('voice',Int32,callback)
rospy.spin()
<file_sep># 2018 AISRC (AI Service Robot Competition)
#### 2018.10.13~11.17
#### 팀 구성 - 4인
***
<img src="https://github.com/bluein/Git-Test/blob/master/rmap.JPG" width=400 height=300/>
## 미션
- 주어진 경로로 이동하고 난 후에 각 방에 있었던 사진에 대한 설명
- ex) 4번방과 6번방에서 사진을 인식하고 난 후에 출발지점으로 와서 각 방의 사진을 설명하라 (당일에 방문하는 방의 수는 랜덤하게 결정)
***
## 세 가지 주요 기술
- Turtlebot을 이용한 Self Driving
- Deep Learning을 이용한 Real-Time Object Detection
- 음성 명령 및 결과 보고를 위한 STT & TTS
***
## 팀 내에서 맡은 부분
- 이미지 데이터 수집 및 전처리
- 이미지 학습 및 인식
- Main Program 설계 및 작성
***
## 개발 환경 및 API
Ubuntu 16.04 LTS
ROS Kinetic
Python (main program and other scripts)
Image Training & Detection: Darknet Framework & Yolo v3
STT: Google Speech API
TTS: Voice file Playing
Auto Driving: SLAM (get Map) & Navigation
***
## Flow Chart
<img src="https://github.com/bluein/Git-Test/blob/master/fc.JPG" width=300 height=400/>
***
## 1. Self Driving
#### SLAM 을 이용한 대회 경기장 Map 작성
<img src="https://github.com/bluein/Git-Test/blob/master/SLAM.png" width=350 height=300/>
## 2. Image Training
#### Training (8 Classes)
<img src="https://github.com/bluein/Git-Test/blob/master/img1.png" width=350 height=450/>
#### 단풍잎의 경우 더 많은 학습 과정
<img src="https://github.com/bluein/Git-Test/blob/master/img2.png" width=400 height=300/>
## 3. STT
<img src="https://github.com/bluein/Git-Test/blob/master/stt.png" width=300 height=150/>
## 4. TTS
<img src="https://github.com/bluein/Git-Test/blob/master/tts.JPG" width=400 height=300/>
## 결과
3위 수상
<file_sep># -*- coding: utf-8 -*-
#!/usr/bin/env python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Google Cloud Speech API sample application using the streaming API.
NOTE: This module requires the additional dependency `pyaudio`. To install
using pip:
pip install pyaudio
Example usage:
python transcribe_streaming_mic.py
"""
# [START speech_transcribe_streaming_mic]
from __future__ import division
import re
import sys
import subprocess
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
import pyaudio
from six.moves import queue
# Audio recording parameters
RATE = 16000
CHUNK = int(RATE / 10) # 100ms
class MicrophoneStream(object):
"""Opens a recording stream as a generator yielding the audio chunks."""
def __init__(self, rate, chunk):
self._rate = rate
self._chunk = chunk
# Create a thread-safe buffer of audio data
self._buff = queue.Queue()
self.closed = True
def __enter__(self):
self._audio_interface = pyaudio.PyAudio()
self._audio_stream = self._audio_interface.open(
format=pyaudio.paInt16,
# The API currently only supports 1-channel (mono) audio
# https://goo.gl/z757pE
channels=1, rate=self._rate,
input=True, frames_per_buffer=self._chunk,
# Run the audio stream asynchronously to fill the buffer object.
# This is necessary so that the input device's buffer doesn't
# overflow while the calling thread makes network requests, etc.
stream_callback=self._fill_buffer,
)
self.closed = False
return self
def __exit__(self, type, value, traceback):
self._audio_stream.stop_stream()
self._audio_stream.close()
self.closed = True
# Signal the generator to terminate so that the client's
# streaming_recognize method will not block the process termination.
self._buff.put(None)
self._audio_interface.terminate()
def _fill_buffer(self, in_data, frame_count, time_info, status_flags):
"""Continuously collect data from the audio stream, into the buffer."""
self._buff.put(in_data)
return None, pyaudio.paContinue
def generator(self):
while not self.closed:
# Use a blocking get() to ensure there's at least one chunk of
# data, and stop iteration if the chunk is None, indicating the
# end of the audio stream.
chunk = self._buff.get()
if chunk is None:
return
data = [chunk]
# Now consume whatever other data's still buffered.
while True:
try:
chunk = self._buff.get(block=False)
if chunk is None:
return
data.append(chunk)
except queue.Empty:
break
yield b''.join(data)
cmdLists = [
[u'그래','그럼 다녀오겠습니다',0],
[u'아니','다시 말씀해주시겠어요?',1],
[u'첫 번째 방 갔다 와','첫 번째 방으로 가면 되나요?',11],
[u'첫 번째 방 갔다','첫 번째 방으로 가면 되나요?',11],
[u'두 번째 방 갔다 와','두 번째 방으로 가면 되나요?',12],
[u'두 번째 방 갔다','두 번째 방으로 가면 되나요?',12],
[u'세 번째 방 갔다 와','세 번째 방으로 가면 되나요?',13],
[u'세 번째 방 갔다','세 번째 방으로 가면 되나요?',13],
[u'대만 지방 갔다 와','세 번째 방으로 가면 되나요?',13],
[u'대만 지방 갔다','세 번째 방으로 가면 되나요?',13],
[u'네 번째 방 갔다 와','네 번째 방으로 가면 되나요?',14],
[u'네 번째 방 갔다','네 번째 방으로 가면 되나요?',14],
[u'남자 사진 찾아 와','남자 사진을 찾아오면 되나요?',21],
[u'남자 사진 찾아','남자 사진을 찾아오면 되나요?',21],
[u'남자 사진 찾아 봐','남자 사진을 찾아오면 되나요?',21],
[u'명절 사진 찾아 와','남자 사진을 찾아오면 되나요?',21],
[u'여자 사진 찾아 와','여자 사진을 찾아오면 되나요?',22],
[u'여자 사진 찾아','여자 사진을 찾아오면 되나요?',22],
[u'여자 사진 찾아 봐','여자 사진을 찾아오면 되나요?',22],
[u'사과 사진 찾아 와','사과 사진을 찾아오면 되나요?',23],
[u'사과 사진 찾아','사과 사진을 찾아오면 되나요?',23],
[u'사과 사진 찾아 봐','사과 사진을 찾아오면 되나요?',23],
[u'배 사진 찾아 와','배 사진을 찾아오면 되나요?',24],
[u'배 사진 찾아','배 사진을 찾아오면 되나요?',24],
[u'배 사진 찾아 봐','배 사진을 찾아오면 되나요?',24],
[u'다람쥐 사진 찾아 와','다람쥐 사진을 찾아오면 되나요?',25],
[u'다람쥐 사진 찾아','다람쥐 사진을 찾아오면 되나요?',25],
[u'다람쥐 사진 찾아 봐','다람쥐 사진을 찾아오면 되나요?',25],
[u'청설모 사진 찾아 와','청설모 사진을 찾아오면 되나요?',26],
[u'청설모 사진 찾아','청설모 사진을 찾아오면 되나요?',26],
[u'청설모 사진 찾아 봐','청설모 사진을 찾아오면 되나요?',26],
[u'청솔모 사진 찾아 와','청설모 사진을 찾아오면 되나요?',26],
[u'청솔모 사진 찾아','청설모 사진을 찾아오면 되나요?',26],
[u'청솔모 사진 찾아 봐','청설모 사진을 찾아오면 되나요?',26],
[u'단풍잎 사진 찾아 와','단풍잎 사진을 찾아오면 되나요?',27],
[u'단풍잎 사진 찾아','단풍잎 사진을 찾아오면 되나요?',27],
[u'단풍잎 사진 찾아 봐','단풍잎 사진을 찾아오면 되나요?',27],
[u'단풍 사진 찾아 와','단풍잎 사진을 찾아오면 되나요?',27],
[u'단풍 사진 찾아','단풍잎 사진을 찾아오면 되나요?',27],
[u'단풍 사진 찾아 봐','단풍잎 사진을 찾아오면 되나요?',27],
[u'은행잎 사진 찾아 와','은행잎 사진을 찾아오면 되나요?',28],
[u'은행잎 사진 찾아','은행잎 사진을 찾아오면 되나요?',28],
[u'은행잎 사진 찾아 봐','은행잎 사진을 찾아오면 되나요?',28]
]
def CommandProc(stt):
cmd = stt.strip()
global num
if type(cmd) is unicode:
for cmdList in cmdLists:
if cmd == cmdList[0]:
print(cmdList[1])
if cmdList[2] == 0: # exit
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/exit.wav')
#print(num)
elif cmdList[2] == 1: # again
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/again.wav')
num = cmdList[2]
#print(num)
elif cmdList[2] == 11: # 1st room
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/1st_room.wav')
num = cmdList[2]
#print(num)
elif cmdList[2] == 12: # 2nd room
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/2nd_room.wav')
num = cmdList[2]
#print(num)
elif cmdList[2] == 13: # 3rd room
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/3rd_room.wav')
num = cmdList[2]
#print(num)
elif cmdList[2] == 14: # 4th room
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/4th_room.wav')
num = cmdList[2]
#print(num)
elif cmdList[2] == 21: # find man
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/find_man.wav')
num = cmdList[2]
#print(num)
elif cmdList[2] == 22: # find woman
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/find_woman.wav')
num = cmdList[2]
#print(num)
elif cmdList[2] == 23: # find apple
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/find_apple.wav')
num = cmdList[2]
#print(num)
elif cmdList[2] == 24: # find pear
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/find_pear.wav')
num = cmdList[2]
#print(num)
elif cmdList[2] == 25: # find asiatic chipmunk
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/find_chipmunk.wav')
num = cmdList[2]
#print(num)
elif cmdList[2] == 26: # find squirrel
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/find_squirrel.wav')
num = cmdList[2]
#print(num)
elif cmdList[2] == 27: # find maple leaf
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/find_maple.wav')
num = cmdList[2]
#print(num)
elif cmdList[2] == 28: # find ginkgo leaf
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/find_ginkgo.wav')
num = cmdList[2]
#print(num)
else:
num = cmdList[2]
#print(num)
return cmdList[2]
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/again.wav') # speech again
return 1
def listen_print_loop(responses):
"""Iterates through server responses and prints them.
The responses passed is a generator that will block until a response
is provided by the server.
Each response may contain multiple results, and each result may contain
multiple alternatives; for details, see https://goo.gl/tjCPAU. Here we
print only the transcription for the top alternative of the top result.
In this case, responses are provided for interim results as well. If the
response is an interim one, print a line feed at the end of it, to allow
the next result to overwrite it, until the response is a final one. For the
final one, print a newline to preserve the finalized transcription.
"""
num_chars_printed = 0
for response in responses:
if not response.results:
continue
# The `results` list is consecutive. For streaming, we only care about
# the first result being considered, since once it's `is_final`, it
# moves on to considering the next utterance.
result = response.results[0]
if not result.alternatives:
continue
# Display the transcription of the top alternative.
transcript = result.alternatives[0].transcript
# Display interim results, but with a carriage return at the end of the
# line, so subsequent lines will overwrite them.
#
# If the previous result was longer than this one, we need to print
# some extra spaces to overwrite the previous result
overwrite_chars = ' ' * (num_chars_printed - len(transcript))
if not result.is_final:
sys.stdout.write('Me : ')
sys.stdout.write(transcript + overwrite_chars + '\r')
sys.stdout.flush()
num_chars_printed = len(transcript)
else:
#### add ####
if CommandProc(transcript) == 0:
break;
"""
print(transcript + overwrite_chars)
# Exit recognition if any of the transcribed phrases could be
# one of our keywords.
if re.search(r'\b(exit|quit)\b', transcript, re.I):
print('Exiting..')
break
"""
#num_chars_printed = 0
def play_audio(filename):
print("Playing audio...")
subprocess.call(["aplay", filename])
def knust_voice():
# See http://g.co/cloud/speech/docs/languages
# for a list of supported languages.
language_code = 'en-US' # a BCP-47 language tag
language_code = 'ko-KR'
client = speech.SpeechClient()
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=RATE,
language_code=language_code)
streaming_config = types.StreamingRecognitionConfig(
config=config,
interim_results=True)
with MicrophoneStream(RATE, CHUNK) as stream:
audio_generator = stream.generator()
requests = (types.StreamingRecognizeRequest(audio_content=content)
for content in audio_generator)
responses = client.streaming_recognize(streaming_config, requests)
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/start.wav')
play_audio('/home/rastech/catkin_ws/src/voice/Sounds/help.wav')
# Now, put the transcription responses to use.
listen_print_loop(responses)
def count():
print("count num check")
print(num)
return num
def main():
# See http://g.co/cloud/speech/docs/languages
# for a list of supported languages.
language_code = 'en-US' # a BCP-47 language tag
language_code = 'ko-KR'
client = speech.SpeechClient()
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=RATE,
language_code=language_code)
streaming_config = types.StreamingRecognitionConfig(
config=config,
interim_results=True)
with MicrophoneStream(RATE, CHUNK) as stream:
audio_generator = stream.generator()
requests = (types.StreamingRecognizeRequest(audio_content=content)
for content in audio_generator)
responses = client.streaming_recognize(streaming_config, requests)
# Now, put the transcription responses to use.
listen_print_loop(responses)
if __name__ == '__main__':
main()
# [END speech_transcribe_streaming_mic]
| 2b3a8e3b200ca9e9edff3a4c227bd3721c1acc62 | [
"Markdown",
"Python"
] | 5 | Python | bluein/2018_AISRC-AI_Service_Robot_Competition | 02f2db556b851e22014bb40da66b91274f712436 | 06a1b8a96a79713468042b0bad3f26b0f2d19a50 |
refs/heads/master | <repo_name>ant-camp/link_shorten<file_sep>/spec/models/link_spec.rb
require 'rails_helper'
RSpec.describe Link, type: :model do
describe "database" do
it { should have_db_column(:original_url) }
it { should have_db_column(:shortened_url) }
it { should have_db_column(:expired).of_type(:boolean) }
it { should have_db_column(:hash_key) }
it { should have_db_index(:hash_key) }
it { should have_db_column(:clicks).of_type(:integer) }
end
describe "validation" do
it { should allow_value(Faker::Internet.url).for(:original_url) }
it { should_not allow_value(Faker::CryptoCoin.coin_name).for(:original_url) }
end
end
<file_sep>/spec/controllers/links_controller_spec.rb
require 'rails_helper'
RSpec.describe LinksController, type: :controller do
describe "Before action" do
it { should use_before_action(:set_link) }
end
describe 'POST #create' do
it "should create and shorten url and redirect" do
post :create, params: { link: { original_url: 'http://test.com'} }
expect(Link.last.original_url).to eq 'http://test.com'
expect(response.response_code).to eq 302
expect(response).to redirect_to("/links/#{Link.last.id}")
end
end
describe 'GET #forward_to_link' do
before do
allow_any_instance_of(Link).to receive(:click_counter).and_return(true)
end
context 'valid link' do
link = FactoryBot.create(:link, expired: false, original_url: 'http://google.com')
it "should redirect to the original url" do
get :forward_to_link, params: { hash_key: link.hash_key }
expect(response.response_code).to eq 301
expect(response).to redirect_to(link.original_url)
end
end
context 'expired link' do
link = FactoryBot.create(:link, expired: true, original_url: 'http://google.com')
it "should render 404 if the link is expired" do
get :forward_to_link, params: { hash_key: link.hash_key }
expect(response.response_code).to eq 404
end
end
end
describe 'GET #show' do
link = FactoryBot.create(:link, expired: true, original_url: 'http://google.com')
context 'Should render link/show' do
it "should show link" do
get :show, params: { id: link.id }
expect(response).to be_successful
end
end
end
end
<file_sep>/spec/controllers/admin/links_controller_spec.rb
require 'rails_helper'
#
RSpec.describe Admin::LinksController, type: :controller do
describe "Before action" do
it {should use_before_action(:set_link)}
end
describe 'GET #show' do
link = FactoryBot.create(:link, expired: true, original_url: 'http://google.com')
it "should show link" do
get :show, params: { id: link.id }
expect(response).to be_successful
end
end
end
<file_sep>/app/models/link.rb
class Link < ApplicationRecord
CACHE_SIZE = 50
URL_REGEX = /\A((http|https):\/\/)*[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?\z/ix
include Redis::Objects
before_validation :check_and_replace_url_protocal
validates :original_url, format: { with: URL_REGEX, message: 'Please provider a valid url.' }
before_create :short_url
before_create :create_hash_key
counter :redis_clicks
after_update :clear_cache
#Check if original_url has https or https
def check_and_replace_url_protocal
url = self.original_url.downcase
unless url.starts_with?("http://", "https://") && url.include?(".com")
self.original_url = "http://#{self.original_url}"
end
end
#Loop through generated hash_url until unique
def create_hash_key
loop do
self.hash_key = create_new_hash_key(self.original_url)
break unless Link.exists?(hash_key: hash_key)
end
end
#Redis fetch link by hash_key
def self.get_url!(hash_key)
Rails.cache.fetch(hash_key, expires_in: 1.day) do
Link.find_by(hash_key: hash_key)
end
end
#Redis update clicks if cache reached
def click_counter
redis_count = self.redis_clicks
redis_count.increment
clicks = redis_count.value
if clicks >= CACHE_SIZE
self.update_attribute(:clicks, clicks)
redis_count.clear
end
end
#Click count from db & redis counter
def actual_count
redis_count = self.redis_clicks.value
db_count = self.clicks || 0
redis_count + db_count
end
#Clear link cache
def clear_cache
Rails.cache.delete(self.hash_key)
end
private
#Generate short url by random hexidemical
def short_url
loop do
self.shortened_url = SecureRandom.hex(3)
break unless Link.exists?(shortened_url: shortened_url)
end
end
#Generate new hash_key
def create_new_hash_key(original_url)
salt = SecureRandom.hex(1)
self.hash_key = Digest::SHA1.hexdigest(salt + self.original_url)
end
end
<file_sep>/spec/rails_helper.rb
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = false
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
config.expect_with(:rspec) { |c| c.syntax = [:should, :expect] }
config.include FactoryBot::Syntax::Methods
config.before :all do
FactoryBot.reload
end
Capybara.register_driver :chrome do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome)
end
Capybara.register_driver :headless_chrome do |app|
capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
chromeOptions: { args: %w(headless disable-gpu window-size=1024,768) }
)
Capybara::Selenium::Driver.new app,
browser: :chrome,
desired_capabilities: capabilities
end
end
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
<file_sep>/spec/factories/links.rb
FactoryBot.define do
factory :link do
original_url { Faker::Internet.url }
shortened_url { Faker::Internet.slug }
expired { false }
clicks { 1 }
end
end
<file_sep>/README.md
# Getting Started
## Ruby 2.5.1 & Rails 5.2.2
## Run Locally
* `chruby ruby-2.5.1 or ruby package manager equivalent`
* `bundle install`
* `rake db:create db:migrate`
* `redis-server`
* `rails s`
# Running Tests
* `rspec`
<file_sep>/app/controllers/admin/links_controller.rb
class Admin::LinksController < ApplicationController
before_action :set_link, only: [:show, :expire_link]
def show
end
def expire_link
@link.update_attribute(:expired, true)
respond_to do |format|
format.js { render layout: false}
end
end
private
def set_link
@link = Link.find(params[:id])
end
end
<file_sep>/app/controllers/links_controller.rb
class LinksController < ApplicationController
before_action :set_link, only: [:show]
def new
@link = Link.new
end
def show
end
def create
@link = Link.new(link_params)
if @link.save
redirect_to @link, notice: "Link has been created and shortened."
else
redirect_to root_path, notice: "Not a valid url."
end
end
def forward_to_link
@link = Link.get_url!(params[:hash_key])
if @link.expired
render file: "#{Rails.root}/public/404.html", layout: false, status: 404
else
redirect_to @link.original_url, status: :moved_permanently
@link.click_counter
end
end
private
def set_link
@link = Link.find(params[:id])
end
def link_params
params.require(:link).permit(:original_url)
end
end
<file_sep>/app/helpers/links_helper.rb
module LinksHelper
def short_link_display(shortened_url)
#Wont work for Prod will need to refactor
#but for time being lets go with this
"http://localhost:3000/#{shortened_url}"
end
end
<file_sep>/spec/system/links_spec.rb
require 'rails_helper'
RSpec.describe 'Views', type: :system do
scenario 'visits root path' do
visit root_path
fill_in "Enter a url", with: "google.com"
click_on "Create Link"
expect(page).to have_content 'Link has been created and shortened.'
end
scenario "expiring a shortened URL" do
visit root_path
fill_in "Enter a url", with: "google.com"
click_on "Create Link"
find('a.admin').click
click_on "Expire"
end
scenario "creating with a invalid URL" do
visit root_path
fill_in "Enter a url", with: "google"
click_on "Create Link"
expect(page).to have_content "Not a valid url."
end
#
scenario "visiting a shortened URL" do
visit root_path
fill_in "Enter a url", with: "google.com"
click_on "Create Link"
find('a.admin').click
find('a.short').click
end
end
| e2208f1de0c27100fefcb9b202e9001a57ef0759 | [
"Markdown",
"Ruby"
] | 11 | Ruby | ant-camp/link_shorten | 3839cc14fe0e28bd6361f8611527dbc314395adb | 912829afe4a12f9e9d9b5cd1358d4af5e0e1977b |
refs/heads/master | <repo_name>bioidiap/bob.db.atvskeystroke<file_sep>/doc/index.rst
.. vim: set fileencoding=utf-8 :
.. _bob.db.atvskeystroke:
=========================
ATVS Keystroke Database
=========================
.. automodule:: bob.db.atvskeystroke
<file_sep>/bob/db/atvskeystroke/test.py
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
"""A few checks at the ATVS Keystroke database.
"""
import os, sys
import unittest
from .query import Database
class ATVSKeystrokeDatabaseTest(unittest.TestCase):
def test_clients(self):
db = Database()
assert len(db.groups()) == 1
assert len(db.clients()) == 126
assert len(db.clients(groups='eval')) == 63
assert len(db.clients(groups='Genuine')) == 63
assert len(db.clients(groups='Impostor')) == 63
assert len(db.models()) == 63
assert len(db.models(groups='eval')) == 63
assert len(db.models(groups='Genuine')) == 63
def test_objects(self):
db = Database()
assert len(db.objects()) == 1512
# A
assert len(db.objects(protocol='A')) == 1512
assert len(db.objects(protocol='A', groups='eval')) == 1512
assert len(db.objects(protocol='A', groups='eval', purposes='enrol')) == 378
assert len(db.objects(protocol='A', groups='eval', purposes='probe')) == 1134
assert len(db.objects(protocol='A', groups='eval', purposes='probe', classes='client')) == 378
assert len(db.objects(protocol='A', groups='eval', purposes='probe', classes='impostor')) == 756
assert len(db.objects(protocol='A', groups='eval', purposes='probe', model_ids=[1])) == 18
assert len(db.objects(protocol='A', groups='eval', purposes='probe', model_ids=[1], classes='client')) == 6
assert len(db.objects(protocol='A', groups='eval', purposes='probe', model_ids=[1], classes='impostor')) == 12
assert len(db.objects(protocol='A', groups='eval', purposes='probe', model_ids=[1,2])) == 36
assert len(db.objects(protocol='A', groups='eval', purposes='probe', model_ids=[1,2], classes='client')) == 12
assert len(db.objects(protocol='A', groups='eval', purposes='probe', model_ids=[1,2], classes='impostor')) == 24
def test_driver_api(self):
from bob.db.base.script.dbmanage import main
assert main('atvskeystroke dumplist --self-test'.split()) == 0
assert main('atvskeystroke checkfiles --self-test'.split()) == 0
assert main('atvskeystroke reverse Genuine_1_1 --self-test'.split()) == 0
assert main('atvskeystroke path 37 --self-test'.split()) == 0
| dc815413ec6718ad8790549127c19e85c16c8af1 | [
"Python",
"reStructuredText"
] | 2 | reStructuredText | bioidiap/bob.db.atvskeystroke | 5a828a921c0d2de625a30c858277656536a4259d | db4f597c9e9806a3ec9b1b4a4783926f1ece1156 |
refs/heads/master | <repo_name>ShivPatel9211/Java-Core-Project<file_sep>/Hospital Management/src/Doctor.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author spate
*/
public class Doctor extends javax.swing.JFrame {
/**
* Creates new form Patient
*/
Connection con;
PreparedStatement pst;
ResultSet rs;
public Doctor() {
initComponents();
}
int id;
String doc;
int newid;
String userName;
public Doctor(int id,String username,String doc) {
initComponents();
this.id=id;
this.doc=doc;
this.userName=username;
newid =id;
// JOptionPane.showMessageDialog(this,newid);
con=dbconnect.java_db();
AutoId();
DoctorTable();
}
public void AutoId()
{
try {
Statement s=con.createStatement();
rs=s.executeQuery("select MAX(doctorno) from Doctor");
rs.next();
rs.getString("MAX(doctorno)");
if( rs.getString("MAX(doctorno)")==null)
{
jLabel7.setText("DS001");
}
else
{
long id=Long.parseLong(rs.getString("MAX(doctorno)").substring(2,rs.getString("MAX(doctorno)").length()));
id++;
jLabel7.setText("DS"+String.format("%03d",id));
}
} catch (SQLException ex) {
Logger.getLogger(Patient.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void DoctorTable()
{
if(doc.equals("Doctor"))
{
try {
pst=con.prepareStatement("select *from Doctor where logedid=?");
pst.setInt(1,newid);
rs=pst.executeQuery();
ResultSetMetaData r=rs.getMetaData();
int c;
c=r.getColumnCount();
DefaultTableModel df=(DefaultTableModel)jTable1.getModel();
df.setRowCount(0);
while(rs.next())
{
Vector v= new Vector();
for(int i=1;i<=c;i++)
{
v.add(rs.getString("doctorno"));
v.add(rs.getString("doctorname"));
v.add(rs.getString("specialization"));
v.add(rs.getString("qualification"));
v.add(rs.getString("channelfee"));
v.add(rs.getString("phone"));
v.add(rs.getString("roam"));
v.add(rs.getString("logedid"));
}
df.addRow(v);
}
} catch (SQLException ex) {
Logger.getLogger(Patient.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if(doc.equals("Admin"))
{
try {
pst=con.prepareStatement("select *from Doctor");
rs=pst.executeQuery();
ResultSetMetaData r=rs.getMetaData();
int c;
c=r.getColumnCount();
DefaultTableModel df=(DefaultTableModel)jTable1.getModel();
df.setRowCount(0);
while(rs.next())
{
Vector v= new Vector();
for(int i=1;i<=c;i++)
{
v.add(rs.getString("doctorno"));
v.add(rs.getString("doctorname"));
v.add(rs.getString("specialization"));
v.add(rs.getString("qualification"));
v.add(rs.getString("channelfee"));
v.add(rs.getString("phone"));
v.add(rs.getString("roam"));
v.add(rs.getString("logedid"));
}
df.addRow(v);
}
} catch (SQLException ex) {
Logger.getLogger(Patient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jTextField5 = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jSpinner1 = new javax.swing.JSpinner();
jTextField1 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jTextField3 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(null);
jTextField5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jPanel1.add(jTextField5);
jTextField5.setBounds(160, 560, 240, 40);
jLabel8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel8.setText("Channel Fee");
jPanel1.add(jLabel8);
jLabel8.setBounds(10, 510, 150, 22);
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel9.setText("Phone No.");
jPanel1.add(jLabel9);
jLabel9.setBounds(10, 560, 130, 22);
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel10.setText("Room No.");
jPanel1.add(jLabel10);
jLabel10.setBounds(10, 610, 130, 22);
jSpinner1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jPanel1.add(jSpinner1);
jSpinner1.setBounds(170, 612, 110, 30);
jTextField1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jPanel1.add(jTextField1);
jTextField1.setBounds(160, 440, 240, 40);
jTextField4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jPanel1.add(jTextField4);
jTextField4.setBounds(160, 500, 240, 40);
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jPanel1.add(jLabel7);
jLabel7.setBounds(160, 250, 190, 30);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Doctor No", "Doctor Name", "Specialization", "Qualification", "Channel Fee", "Phone No", "Room No"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane2.setViewportView(jTable1);
jPanel1.add(jScrollPane2);
jScrollPane2.setBounds(440, 270, 850, 350);
jTextField2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jPanel1.add(jTextField2);
jTextField2.setBounds(160, 320, 240, 40);
jButton1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/male-user-add (1).png"))); // NOI18N
jButton1.setText("Add");
jButton1.setIconTextGap(10);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1);
jButton1.setBounds(20, 720, 140, 50);
jButton2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/icons8-update-64.png"))); // NOI18N
jButton2.setText("Update");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jPanel1.add(jButton2);
jButton2.setBounds(170, 720, 180, 50);
jButton3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/icons8-delete-bin-64.png"))); // NOI18N
jButton3.setText("Delete");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jPanel1.add(jButton3);
jButton3.setBounds(360, 720, 180, 50);
jButton4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/back.png"))); // NOI18N
jButton4.setText("Back");
jButton4.setIconTextGap(10);
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jPanel1.add(jButton4);
jButton4.setBounds(550, 720, 160, 50);
jTextField3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jPanel1.add(jTextField3);
jTextField3.setBounds(160, 380, 240, 40);
jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 60)); // NOI18N
jLabel2.setForeground(new java.awt.Color(204, 255, 204));
jLabel2.setText("Doctor Registation");
jPanel1.add(jLabel2);
jLabel2.setBounds(0, 0, 550, 160);
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel3.setText("Doctor No.");
jPanel1.add(jLabel3);
jLabel3.setBounds(10, 240, 290, 40);
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel4.setText("Specialization");
jPanel1.add(jLabel4);
jLabel4.setBounds(10, 370, 290, 40);
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel5.setText("<NAME>");
jPanel1.add(jLabel5);
jLabel5.setBounds(10, 310, 290, 40);
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel6.setText("Qualification");
jPanel1.add(jLabel6);
jLabel6.setBounds(10, 430, 290, 40);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/sick-patient-sitting-bed-hospital-81419684.jpg"))); // NOI18N
jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel1MouseClicked(evt);
}
});
jPanel1.add(jLabel1);
jLabel1.setBounds(0, 0, 1370, 820);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 1292, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 819, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
//add
String id,name,special,qualification,room,channelfee;
String phone;
id=jLabel7.getText();
name=jTextField2.getText();
special=jTextField3.getText();
qualification=jTextField1.getText();
channelfee=jTextField4.getText();
phone=jTextField5.getText();
room=jSpinner1.getValue().toString();
try {
pst=con.prepareStatement("insert into Doctor(doctorno,doctorname,specialization,qualification,channelfee,phone,roam,logedid )values(?,?,?,?,?,?,?,?)");
pst.setString(1, id);
pst.setString(2, name);
pst.setString(3,special);
pst.setString(4,qualification);
pst.setString(5,channelfee);
pst.setString(6,phone);
pst.setString(7,room);
pst.setInt(8,newid);
pst.executeUpdate();
JOptionPane.showMessageDialog(this, "Doctor is inserted");
AutoId();
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jSpinner1.setValue(0);
jTextField2.requestFocus();
DoctorTable();
} catch (Exception e) {
JOptionPane.showMessageDialog(this,e.getMessage());
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
// TODO add your handling code here:
//Mouse Clicked
DefaultTableModel d1= (DefaultTableModel)jTable1.getModel();
int index = jTable1.getSelectedRow();
jLabel7.setText(d1.getValueAt(index,0).toString());
jTextField1.setText(d1.getValueAt(index,1).toString());
jTextField2.setText(d1.getValueAt(index,2).toString());
jTextField3.setText(d1.getValueAt(index,3).toString());
jTextField4.setText(d1.getValueAt(index,4).toString());
jTextField5.setText(d1.getValueAt(index,5).toString());
jSpinner1.setValue(Integer.parseInt(d1.getValueAt(index,6).toString()));
jButton1.setEnabled(false);
}//GEN-LAST:event_jTable1MouseClicked
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
///Update
String id,name,special,qualification,room,channelfee;
String phone;
id=jLabel7.getText();
name=jTextField2.getText();
special=jTextField3.getText();
qualification=jTextField1.getText();
channelfee=jTextField4.getText();
phone=jTextField5.getText();
room=jSpinner1.getValue().toString();
try {
pst=con.prepareStatement("update Doctor set doctorname=?,specialization=?,qualification=?,channelfee=?,phone=?,roam=? where doctorno=?");
pst.setString(1, name);
pst.setString(2,special);
pst.setString(3,qualification);
pst.setString(4,channelfee);
pst.setString(5,phone);
pst.setString(6,room);
pst.setString(7,id);
pst.executeUpdate();
JOptionPane.showMessageDialog(this, "Doctor is Upedated");
AutoId();
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jSpinner1.setValue(0);
jTextField2.requestFocus();
DoctorTable();
jButton1.setVisible(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(this,e.getMessage());
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
//delete
String id;
id=jLabel7.getText();
try {
pst=con.prepareStatement("delete from Doctor where doctorno=?");
pst.setString(1,id);
pst.executeUpdate();
JOptionPane.showMessageDialog(this, "Doctor information is deleted");
AutoId();
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jSpinner1.setValue(0);
jTextField2.requestFocus();
DoctorTable();
jButton1.setVisible(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(this,e.getMessage());
}
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
//Exit
new Home(id,userName,doc).setVisible(true);
this.dispose();
}//GEN-LAST:event_jButton4ActionPerformed
private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked
// TODO add your handling code here:
//outside click
AutoId();
jTextField2.setText("");
jTextField3.setText("");
jTextField1.setText("");
jTextField4.setText("");
jTextField5.setText("");
jSpinner1.setValue(0);
jTextField2.requestFocus();
DoctorTable();
jButton1.setEnabled(true);
}//GEN-LAST:event_jLabel1MouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Patient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Patient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Patient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Patient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Patient().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSpinner jSpinner1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
// End of variables declaration//GEN-END:variables
}
<file_sep>/Hospital Management/src/saleReport.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author spate
*/
public class saleReport extends javax.swing.JFrame {
/**
* Creates new form saleReport
*/
Connection con;
PreparedStatement pst;
ResultSet rs;
public saleReport() {
initComponents();
con = dbconnect.java_db();
salesTable();
}
int id;
String userName;
String userType;
public saleReport(int id,String username,String usertype) {
initComponents();
this.id=id;
this.userName=username;
this.userType=usertype;
con = dbconnect.java_db();
salesTable();
}
public void salesTable() {
try {
pst = con.prepareStatement("select * from sales");
rs = pst.executeQuery();
ResultSetMetaData r = rs.getMetaData();
int c;
c = r.getColumnCount();
DefaultTableModel df = (DefaultTableModel) jTable1.getModel();
df.setRowCount(0);
while (rs.next()) {
Vector v = new Vector();
for (int i = 1; i <= c; i++) {
v.add(rs.getString(1));
v.add(rs.getString(2));
v.add(rs.getString(3));
v.add(rs.getString(4));
v.add(rs.getString(5));
}
df.addRow(v);
}
} catch (SQLException ex) {
Logger.getLogger(Patient.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(null);
jButton1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/back.png"))); // NOI18N
jButton1.setText("Close");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1);
jButton1.setBounds(970, 690, 210, 80);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Date", "Total", "Paid", "Balance"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
jPanel1.add(jScrollPane1);
jScrollPane1.setBounds(70, 200, 1000, 440);
jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 60)); // NOI18N
jLabel2.setForeground(new java.awt.Color(240, 240, 240));
jLabel2.setText("Sales Report");
jPanel1.add(jLabel2);
jLabel2.setBounds(160, -20, 730, 220);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/80433269-abstract-blur-background-of-goods-crate-on-metal-shelf-aisle-in-superstore-or-moderntrade-inventory-.jpg"))); // NOI18N
jPanel1.add(jLabel1);
jLabel1.setBounds(0, 0, 1250, 830);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
setSize(new java.awt.Dimension(1266, 870));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// back
new Home(id,userName,userType).setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(saleReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(saleReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(saleReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(saleReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new saleReport().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
<file_sep>/WebApplication2/build/generated/src/org/apache/jsp/Signup_jsp.java
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class Signup_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html>\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
out.write(" <title>JSP Page</title>\n");
out.write(" \n");
out.write(" \n");
out.write(" <!-- Compiled and minified CSS -->\n");
out.write(" <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css\">\n");
out.write("\n");
out.write(" <!-- Compiled and minified JavaScript -->\n");
out.write(" <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js\"></script>\n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" </head>\n");
out.write(" <body bgcolor=\"green\"style=\"text-align: center;\">\n");
out.write(" <div class=\"container\">\n");
out.write(" <div class=\"row\">\n");
out.write(" <div class=\"col m6 offset-m3\" >\n");
out.write(" <div class=\"card\">\n");
out.write(" <div style=\"background: url(img/imgev.jpg);background-size: cover; background-attachment: fixed \"class=\"card-content\">\n");
out.write(" <h3 style=\"margin: 10px; padding:10px 10px 10px 10px; \">Register Here!!!</h3>\n");
out.write(" <div class=\"form\"style=\"text-align: center;\" id=\"myform\">\n");
out.write(" <form action=\"Register\" method=\"post\">\n");
out.write(" <input type=\"text\" name=\"username\" placeholder=\"Enter user's name\">\n");
out.write(" <input type=\"password\" name=\"password\" placeholder=\"Enter user's password\">\n");
out.write(" <input type=\"email\" name=\"email\" placeholder=\"Enter user's email\">\n");
out.write(" <input type=\"text\" name=\"phone\" placeholder=\"Enter user's Phone number\">\n");
out.write(" <button type=\"submit\" class=\" btn \" > Submit</button>\n");
out.write(" \n");
out.write(" </div>\n");
out.write(" <div class=\"lodder \" style=\"text-align: center;display: none\" >\n");
out.write(" <div class=\"preloader-wrapper big active\">\n");
out.write(" <div class=\"spinner-layer spinner-blue\">\n");
out.write(" <div class=\"circle-clipper left\">\n");
out.write(" <div class=\"circle\"></div>\n");
out.write(" </div><div class=\"gap-patch\">\n");
out.write(" <div class=\"circle\"></div>\n");
out.write(" </div><div class=\"circle-clipper right\">\n");
out.write(" <div class=\"circle\"></div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" <h5>Please wait..</h5>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" \n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" <script\n");
out.write(" src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\"\n");
out.write(" integrity=\"<KEY>\n");
out.write(" crossorigin=\"anonymous\"></script>\n");
out.write(" <script >\n");
out.write(" $(document).ready(function(){\n");
out.write(" console.log(\"page is ready..\")\n");
out.write(" $(\"#myform\").on('submit', function (event){\n");
out.write(" event.preventDefault();\n");
out.write(" var f= $(this).serialize();\n");
out.write(" console.log(f);\n");
out.write(" // $.ajax({\n");
out.write(" // url:\"Register\",\n");
out.write(" // data:f,\n");
out.write(" // type:'POST',\n");
out.write(" // success: function (data, textStatus, jqXHR) {\n");
out.write(" // console.log(data);\n");
out.write(" // console.log(\"success...\")\n");
out.write(" // },\n");
out.write(" // error: function (jqXHR, textStatus, errorThrown) {\n");
out.write(" // console.log(data);\n");
out.write(" // console.log(\"error...\")\n");
out.write(" },\n");
out.write(" })\n");
out.write(" })\n");
out.write(" })\n");
out.write(" </script>\n");
out.write(" </body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| 887cb0b1690cdd6bc14bd470f4541ec99c3671c6 | [
"Java"
] | 3 | Java | ShivPatel9211/Java-Core-Project | 257edc06df6fd2ddb0b69392f76601dad1718f28 | 6303bacf70e05d1e1ab779a1afe017bd6333c707 |
refs/heads/master | <repo_name>Darmody/yoga-layout-wasm<file_sep>/README.md
# yoga-layout-wasm
> yoga-layout webassembly module, for browser and node. fallback to asm.js in non-webassembly environment
## Get Start
```
$ npm i yoga-layout-wasm --save
```
``` javascript
import Yoga from 'yoga-layout-wasm'
function test (yoga) {
const Node = yoga.Node
const root = Node.create();
root.setWidth(500);
root.setHeight(300);
root.setJustifyContent(yoga.JUSTIFY_CENTER);
const node1 = Node.create();
node1.setWidth(100);
node1.setHeight(100);
const node2 = Node.create();
node2.setWidth(100);
node2.setHeight(100);
root.insertChild(node1, 0);
root.insertChild(node2, 1);
root.calculateLayout(500, 300, yoga.DIRECTION_LTR);
console.log(root.getComputedLayout());
// {left: 0, top: 0, width: 500, height: 300}
console.log(node1.getComputedLayout());
// {left: 150, top: 0, width: 100, height: 100}
console.log(node2.getComputedLayout());
// {left: 250, top: 0, width: 100, height: 100}
}
const wasmFilePath = 'node_modules/yoga-layout-wasm/dist/yoga.wasm'
Yoga.init(wasmFilePath).then(test)
```
### Single `asm.js` module
``` javascript
// *.js
import Yoga from 'yoga-layout-wasm/asm'
Yoga.init().then(yoga => {
// ... test()
})
```
### Webpack and Auto Fallback
``` javascript
// ... webpack.config.js
module.exports = {
// ... other config
module: {
// ... other module
rules: [
// ...other rules
{
test: /\.(wasm)$/,
type: 'javascript/auto',
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[md5:hash:base64:6].[ext]',
},
},
],
}
],
},
resolve: {
// ...
alias: { // required in browser
path: false,
fs: false
}
}
};
// ...
```
``` javascript
// *.js
typeof WebAssembly === 'undefined' ?
import('yoga-layout-wasm/asm')
.then(mod => mod.default.init())
.then(test) :
import('yoga-layout-wasm')
.then(mod => mod.default.init(require('yoga-layout-wasm/dist/yoga.wasm')))
.then(test);
```
## Examples
```
$ npm run example:node
$ npm run example:html
$ npm run example:node:asm
```<file_sep>/asm.d.ts
import Yoga from "yoga-layout";
export {
YogaNode,
YogaConfig,
YogaAlign,
YogaDirection,
YogaDisplay,
YogaEdge,
YogaFlexDirection,
YogaExperimentalFeature,
YogaFlexWrap,
YogaJustifyContent,
YogaOverflow,
YogaPositionType,
YogaUnit,
YogaMeasureMode,
} from "yoga-layout"
export type YogaStatic = typeof Yoga
export type YogaWasm = {
init(): Promise<YogaWasm>
} & YogaStatic
const mod: YogaWasm
export default mod<file_sep>/bindings/Layout.hh
#pragma once
struct Layout {
double left;
double right;
double top;
double bottom;
double width;
double height;
};
| a174552c5f70c41fdffcbb21d7a7713db53d4ba7 | [
"Markdown",
"C",
"TypeScript"
] | 3 | Markdown | Darmody/yoga-layout-wasm | 2e21a81c97eaa7004920e2289c7cdd89f4768799 | 433b7451c8b57fafe02e4dffe5d939f6f0ed670d |
refs/heads/main | <repo_name>rohith017/sporty-shoes<file_sep>/java/org/simplilearn/fsd/p3/ui/controller/CategoryController.java
package org.yokekhei.fsd.p3.ui.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.yokekhei.fsd.p3.dto.Category;
import org.yokekhei.fsd.p3.service.AdminService;
import org.yokekhei.fsd.p3.service.SportyShoesServiceException;
import org.yokekhei.fsd.p3.ui.View;
@Controller
public class CategoryController {
@Autowired
private AdminService service;
@GetMapping("/admin/category")
public String categoryList(Model model,
HttpServletRequest request) throws SportyShoesServiceException {
model.addAttribute("category", new Category());
List<Category> categoryList = service.getAllCategories();
request.getSession(false).setAttribute("categoryList", categoryList);
return View.V_ADMIN_CATEGORY_LIST;
}
@PostMapping("/admin/category")
public String categoryForm(@RequestParam(name = "action") String action,
@Valid @ModelAttribute("category") Category category,
BindingResult result,
ModelMap modelMap,
HttpServletRequest request) throws SportyShoesServiceException {
HttpSession session = request.getSession(false);
if (!isValidAction(action) || result.hasErrors()) {
modelMap.addAttribute("category", new Category());
if (result.hasErrors()) {
session.setAttribute("alert", result.getAllErrors().get(0).getDefaultMessage());
} else {
session.setAttribute("alert", "Category action not supported");
}
return View.V_ADMIN_CATEGORY_LIST;
}
if (action.equals("add")) {
service.addCategory(category);
} else if (action.equals("update")) {
service.updateCategory(category);
} else if (action.equals("delete")) {
service.deleteCategory(category.getId());
}
return "redirect:/" + View.C_ADMIN_CATEGORY;
}
@ExceptionHandler(SportyShoesServiceException.class)
public String handlerException(SportyShoesServiceException exception,
Model model,
HttpServletRequest request) {
model.addAttribute("category", new Category());
request.getSession(false).setAttribute("alert", exception.getMessage());
return View.V_ADMIN_CATEGORY_LIST;
}
private boolean isValidAction(String action) {
return action != null &&
(action.equals("add") ||
action.equals("update") ||
action.equals("delete"));
}
}
<file_sep>/java/org/simplilearn/fsd/p3/dao/CategoryDao.java
package org.yokekhei.fsd.p3.dao;
import java.util.List;
import org.yokekhei.fsd.p3.dto.Category;
public interface CategoryDao {
List<Category> getAllCategories() throws SportyShoesDaoException;
Category getCategory(Long id) throws SportyShoesDaoException;
Category save(Category category) throws SportyShoesDaoException;
void remove(Long id) throws SportyShoesDaoException;
}
<file_sep>/java/org/simplilearn/fsd/p3/dao/jpa/ProductMapper.java
package org.yokekhei.fsd.p3.dao.jpa;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
@Mapper
public interface ProductMapper {
@Mapping(target = "picture", ignore = true)
org.yokekhei.fsd.p3.entity.Product toEntity(org.yokekhei.fsd.p3.dto.Product dto);
@Mapping(target = "categoryId", ignore = true)
@Mapping(target = "imageFile", ignore = true)
org.yokekhei.fsd.p3.dto.Product toDto(org.yokekhei.fsd.p3.entity.Product entity);
}
<file_sep>/java/org/simplilearn/fsd/p3/dao/PurchaseDao.java
package org.yokekhei.fsd.p3.dao;
import java.time.LocalDateTime;
import java.util.List;
import org.yokekhei.fsd.p3.dto.Category;
import org.yokekhei.fsd.p3.dto.Purchase;
public interface PurchaseDao {
List<Purchase> getAllPurchasesCreatedBetween(LocalDateTime start, LocalDateTime end)
throws SportyShoesDaoException;
List<Purchase> getPurchasesByCategory(Category category) throws SportyShoesDaoException;
Purchase getPurchase(Long id) throws SportyShoesDaoException;
}
<file_sep>/java/org/simplilearn/fsd/p3/service/UserService.java
package org.yokekhei.fsd.p3.service;
import java.util.List;
import org.yokekhei.fsd.p3.dto.Category;
import org.yokekhei.fsd.p3.dto.Payment;
import org.yokekhei.fsd.p3.dto.Product;
import org.yokekhei.fsd.p3.dto.User;
public interface UserService {
User login(String email, String password) throws SportyShoesServiceException;
User register(User user) throws SportyShoesServiceException;
List<Category> getAllCategories() throws SportyShoesServiceException;
List<Product> getProductsByCategory(Long categoryId) throws SportyShoesServiceException;
byte[] getProductPicture(Long productId) throws SportyShoesServiceException;
Product getProduct(Long productId) throws SportyShoesServiceException;
Payment pay(Payment payment) throws SportyShoesServiceException;
Payment getPayment(Long paymentId) throws SportyShoesServiceException;
}
<file_sep>/java/org/simplilearn/fsd/p3/dao/jpa/PurchaseRepository.java
package org.yokekhei.fsd.p3.dao.jpa;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.yokekhei.fsd.p3.entity.Purchase;
import org.yokekhei.fsd.p3.entity.PurchaseItem;
public interface PurchaseRepository extends JpaRepository<Purchase, Long> {
List<Purchase> findAllByCreatedDateTimeBetween(
LocalDateTime createdDateTimeStart,
LocalDateTime createdDateTimeEnd);
List<Purchase> findDistinctByItemsIn(List<PurchaseItem> items);
}
<file_sep>/resources/data.sql
USE SportyShoes;
delete from users;
insert into users (user_email, user_password, user_role)
values ('<EMAIL>', '<PASSWORD>', 'A');
delete from categories;
insert into categories(category_id, category_name, category_desc)
values (1, 'Lifestyle', 'Lifestyles of men & women');
delete from products;
insert into products(product_id, product_category, product_name, product_short_desc, product_long_desc, product_price)
values(1, 1, 'Nike Air Force 1 NDESTRUKT', 'Men''s Shoe,1 Colour', 'Put it through the ringer and still show up looking good. The Nike Air Force 1 NDESTRUKT re-imagines the b-ball icon with a tough, street-ready touch. Forged with TecTuff™ and durable rubber accents on the toe, heel and sides, it mixes action-sport style with everyday function.', 619);<file_sep>/java/org/simplilearn/fsd/p3/dao/jpa/CategoryDaoImpl.java
package org.simplilearn.fsd.p3.dao.jpa;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.yokekhei.fsd.p3.dao.CategoryDao;
import org.yokekhei.fsd.p3.dao.SportyShoesDaoException;
import org.yokekhei.fsd.p3.dto.Category;
@Repository
@Qualifier("jpa")
public class CategoryDaoImpl implements CategoryDao {
@Resource
private CategoryRepository repository;
@Resource
private CategoryMapper mapper;
@Override
public List<Category> getAllCategories() throws SportyShoesDaoException {
List<Category> categories = null;
try {
categories = repository.findAll()
.stream()
.map(entity -> mapper.toDto(entity))
.collect(Collectors.toList());
} catch (Exception e) {
throw new SportyShoesDaoException(e.getMessage());
}
return categories;
}
@Override
public Category getCategory(Long id) throws SportyShoesDaoException {
Category category = null;
try {
category = repository.findById(id)
.map(entity -> mapper.toDto(entity))
.orElse(null);
} catch (Exception e) {
throw new SportyShoesDaoException(e.getMessage());
}
return category;
}
@Override
@Transactional
public Category save(Category category) throws SportyShoesDaoException {
Category savedCategory = null;
try {
savedCategory = mapper.toDto(repository.save(mapper.toEntity(category)));
} catch (Exception e) {
throw new SportyShoesDaoException(e.getMessage());
}
return savedCategory;
}
@Override
@Transactional
public void remove(Long id) throws SportyShoesDaoException {
try {
repository.deleteById(id);
} catch (Exception e) {
throw new SportyShoesDaoException(e.getMessage());
}
}
}
<file_sep>/java/org/simplilearn/fsd/p3/service/AdminServiceImpl.java
package org.simplilearn.fsd.p3.service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.yokekhei.fsd.p3.Common;
import org.yokekhei.fsd.p3.dao.CategoryDao;
import org.yokekhei.fsd.p3.dao.ProductDao;
import org.yokekhei.fsd.p3.dao.PurchaseDao;
import org.yokekhei.fsd.p3.dao.UserDao;
import org.yokekhei.fsd.p3.dto.Category;
import org.yokekhei.fsd.p3.dto.Product;
import org.yokekhei.fsd.p3.dto.Purchase;
import org.yokekhei.fsd.p3.dto.User;
@Service
public class AdminServiceImpl implements AdminService {
@Resource
@Qualifier("jpa")
private UserDao userDao;
@Resource
@Qualifier("jpa")
private CategoryDao categoryDao;
@Resource
@Qualifier("jpa")
private ProductDao productDao;
@Resource
@Qualifier("jpa")
private PurchaseDao purchaseDao;
@Override
public User login(String email, String password) throws SportyShoesServiceException {
User user = null;
try {
user = userDao.getUser(email, password);
if (user == null) {
throw new SportyShoesServiceException("Invalid credentials");
} else if (!user.getRole().equals(Common.ROLE_ADMIN)) {
throw new SportyShoesServiceException("Insufficient administrator privileges");
} else if (!user.getEnabled()) {
throw new SportyShoesServiceException("Administrator permission is disabled");
}
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
return user;
}
@Override
public User changePassword(User user, String newPassword) throws SportyShoesServiceException {
User savedUser = null;
try {
user.setPassword(<PASSWORD>);
savedUser = userDao.update(user);
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
return savedUser;
}
@Override
public List<User> getAllUsers() throws SportyShoesServiceException {
List<User> users = null;
try {
users = userDao.getAllUsers();
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
return users;
}
@Override
public List<User> getUsersWithUserRole() throws SportyShoesServiceException {
List<User> users = null;
try {
users = userDao.getUsersWithUserRole();
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
return users;
}
@Override
public List<User> getAllUsersWithUserRoleCreatedBetween(LocalDateTime start, LocalDateTime end)
throws SportyShoesServiceException {
List<User> users = null;
try {
users = userDao.getAllUsersCreatedBetween(start, end)
.stream()
.filter(user -> user.getRole().equals(Common.ROLE_USER))
.collect(Collectors.toList());
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
return users;
}
@Override
public List<User> getUsersByFirstName(String firstName) throws SportyShoesServiceException {
List<User> users = null;
try {
users = userDao.getUsersByFirstName(firstName)
.stream()
.filter(user -> user.getRole().equals(Common.ROLE_USER))
.collect(Collectors.toList());
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
return users;
}
@Override
public List<Category> getAllCategories() throws SportyShoesServiceException {
List<Category> categories = null;
try {
categories = categoryDao.getAllCategories();
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
return categories;
}
@Override
public void addCategory(Category data) throws SportyShoesServiceException {
try {
categoryDao.save(data);
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
}
@Override
public void updateCategory(Category data) throws SportyShoesServiceException {
try {
categoryDao.save(data);
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
}
@Override
public void deleteCategory(Long id) throws SportyShoesServiceException {
try {
categoryDao.remove(id);
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
}
@Override
public List<Product> getAllProducts() throws SportyShoesServiceException {
List<Product> products = null;
try {
products = productDao.getAllProducts();
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
return products;
}
@Override
public void addProduct(Product data) throws SportyShoesServiceException {
try {
if (data.getCategory() == null) {
data.setCategory(categoryDao.getCategory(data.getCategoryId()));
}
productDao.save(data);
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
}
@Override
public void updateProduct(Product data) throws SportyShoesServiceException {
try {
if (data.getCategory() == null) {
data.setCategory(categoryDao.getCategory(data.getCategoryId()));
}
productDao.update(data);
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
}
@Override
public void deleteProduct(Long id) throws SportyShoesServiceException {
try {
productDao.remove(id);
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
}
@Override
public List<Purchase> getAllPurchasesCreatedBetween(LocalDateTime start, LocalDateTime end)
throws SportyShoesServiceException {
List<Purchase> purchases = null;
try {
purchases = purchaseDao.getAllPurchasesCreatedBetween(start, end);
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
return purchases;
}
@Override
public List<Purchase> getPurchasesByCategory(Long categoryId) throws SportyShoesServiceException {
List<Purchase> purchases = null;
try {
Category category = categoryDao.getCategory(categoryId);
if (category == null) {
throw new SportyShoesServiceException("Invalid category chosen to query purchases");
}
purchases = purchaseDao.getPurchasesByCategory(category);
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
return purchases;
}
@Override
public Purchase getPurchase(Long id) throws SportyShoesServiceException {
Purchase purchase = null;
try {
purchase = purchaseDao.getPurchase(id);
} catch (Exception e) {
throw new SportyShoesServiceException(e.getMessage());
}
return purchase;
}
}
<file_sep>/java/org/simplilearn/fsd/p3/ui/controller/CatalogProductController.java
package org.yokekhei.fsd.p3.ui.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.yokekhei.fsd.p3.dto.BagItem;
import org.yokekhei.fsd.p3.dto.Product;
import org.yokekhei.fsd.p3.service.SportyShoesServiceException;
import org.yokekhei.fsd.p3.service.UserService;
import org.yokekhei.fsd.p3.ui.View;
@Controller
public class CatalogProductController {
@Autowired
UserService service;
@GetMapping("/catalog/product")
public String catalogProduct(@RequestParam(name = "id") Long productId,
HttpServletRequest request,
Model model) throws SportyShoesServiceException {
Product product = service.getProduct(productId);
model.addAttribute("product", product);
model.addAttribute("bagItem", new BagItem());
return View.V_USER_PRODUCT;
}
@GetMapping("/catalog/product/image")
public void showImage(@RequestParam("productId") Long productId,
HttpServletRequest request,
HttpServletResponse response) throws SportyShoesServiceException {
try {
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
byte[] picture = service.getProductPicture(productId);
if (picture == null) {
Resource resource = new ClassPathResource(View.DEFAULT_CATALOG_PRODUCT_IMAGE);
picture = IOUtils.toByteArray(resource.getInputStream());
}
response.getOutputStream().write(picture);
response.getOutputStream().close();
} catch (IOException e) {
throw new SportyShoesServiceException(e.getMessage());
}
}
@ExceptionHandler(SportyShoesServiceException.class)
public String handlerException(SportyShoesServiceException exception,
HttpServletRequest request) {
request.getSession(false).setAttribute("alert", exception.getMessage());
return "redirect:/" + View.C_USER_CATALOG;
}
}
<file_sep>/java/org/simplilearn/fsd/p3/dao/jpa/PaymentRepository.java
package org.yokekhei.fsd.p3.dao.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import org.yokekhei.fsd.p3.entity.Payment;
public interface PaymentRepository extends JpaRepository<Payment, Long> {
}
<file_sep>/resources/schema.sql
DROP DATABASE IF EXISTS SportyShoes;
CREATE DATABASE SportyShoes;
USE SportyShoes;
DROP USER IF EXISTS 'sportyshoes_user'@'localhost';
CREATE USER 'sportyshoes_user'@'localhost' IDENTIFIED BY '<PASSWORD>';
GRANT ALL PRIVILEGES ON * . * TO 'sportyshoes_user'@'localhost';
FLUSH PRIVILEGES;
DROP TABLE IF EXISTS Users;
CREATE TABLE Users (
user_email VARCHAR(255) NOT NULL,
user_password VARCHAR(255) NOT NULL,
user_fname VARCHAR(255),
user_lname VARCHAR(255),
user_dob DATE,
user_gender CHAR(1),
user_role CHAR(1) NOT NULL,
user_enabled BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_email)
) ENGINE=INNODB;
DROP TABLE IF EXISTS Categories;
CREATE TABLE Categories (
category_id BIGINT NOT NULL AUTO_INCREMENT,
category_name VARCHAR(255) NOT NULL,
category_desc VARCHAR(255) NOT NULL,
PRIMARY KEY (category_id)
) ENGINE=INNODB;
DROP TABLE IF EXISTS Products;
CREATE TABLE Products (
product_id BIGINT NOT NULL AUTO_INCREMENT,
product_category BIGINT NOT NULL,
product_name VARCHAR(255) NOT NULL,
product_short_desc VARCHAR(255) NOT NULL,
product_long_desc VARCHAR(1024) NOT NULL,
product_price DECIMAL(18, 5) NOT NULL,
product_picture BLOB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (product_id),
CONSTRAINT fk_products_category FOREIGN KEY (product_category) REFERENCES Categories(category_id)
) ENGINE=INNODB;
DROP TABLE IF EXISTS PurchaseItems;
CREATE TABLE PurchaseItems (
pitem_id BIGINT NOT NULL AUTO_INCREMENT,
pitem_product BIGINT NOT NULL,
pitem_quantity INT NOT NULL,
pitem_price DECIMAL(18, 5) NOT NULL,
PRIMARY KEY (pitem_id),
CONSTRAINT fk_purchaseitems_product FOREIGN KEY (pitem_product) REFERENCES Products(product_id)
) ENGINE=INNODB;
DROP TABLE IF EXISTS Purchases;
CREATE TABLE Purchases (
purchase_id BIGINT NOT NULL AUTO_INCREMENT,
purchase_user VARCHAR(255) NOT NULL,
purchase_price DECIMAL(18, 5) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (purchase_id),
CONSTRAINT fk_purchases_user FOREIGN KEY (purchase_user) REFERENCES Users(user_email)
) ENGINE=INNODB;
DROP TABLE IF EXISTS PurchaseDetails;
CREATE TABLE PurchaseDetails (
purchase_id BIGINT NOT NULL,
pitem_id BIGINT NOT NULL,
CONSTRAINT fk_purchases FOREIGN KEY (purchase_id) REFERENCES Purchases(purchase_id),
CONSTRAINT fk_purchaseitems FOREIGN KEY (pitem_id) REFERENCES PurchaseItems(pitem_id)
) ENGINE=INNODB;
DROP TABLE IF EXISTS Payment;
CREATE TABLE Payment (
payment_id BIGINT NOT NULL AUTO_INCREMENT,
purchase_id BIGINT NOT NULL,
payor_name VARCHAR(100) NOT NULL,
total_paid DECIMAL(18, 5) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (payment_id),
CONSTRAINT fk_payment_purchase FOREIGN KEY (purchase_id) REFERENCES Purchases(purchase_id)
) ENGINE=INNODB; | a30d4a3d08ccf576996157023dbad9a640b424ff | [
"Java",
"SQL"
] | 12 | Java | rohith017/sporty-shoes | 9ec55ed2de60c53c522c2b71e0c3558cfdaf64cb | 08b38e51dbe8725036ee1a523fe18868426ef6aa |
refs/heads/master | <file_sep>package com.mvn.marvinmao.argumentResolver;
import com.mvn.marvinmao.annotation.MarvinRequestParam;
import com.mvn.marvinmao.annotation.MarvinService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@MarvinService("requestParamArgumentResolver")
//解析声明注解为RequestParam, 获取注解的值
public class RequestParamArgumentResolver implements ArgumentResolver {
//判断传进来的参数是否为EnjoyRequestParam
public boolean support(Class<?> type, int paramIndex, Method method) {
Annotation[][] an = method.getParameterAnnotations();
Annotation[] paramAns = an[paramIndex];
for (Annotation paramAn : paramAns) {
//判断传进的paramAn.getClass()是不是 MarvinRequestParam 类型
if (MarvinRequestParam.class.isAssignableFrom(paramAn.getClass())) {
return true;
}
}
return false;
}
//参数解析,并获取注解的值
public Object argumentResolver(HttpServletRequest request,
HttpServletResponse response, Class<?> type, int paramIndex,
Method method) {
Annotation[][] an = method.getParameterAnnotations();
Annotation[] paramAns = an[paramIndex];
for (Annotation paramAn : paramAns) {
if (MarvinRequestParam.class.isAssignableFrom(paramAn.getClass())) {
MarvinRequestParam rp = (MarvinRequestParam) paramAn;
String value = rp.value();
return request.getParameter(value);
}
}
return null;
}
}
| f2d31344c0c4ddd1c7e072d4ec47821daba570d1 | [
"Java"
] | 1 | Java | marvinmao/springmvc | a4148fa6190046d6c6bb03858691ca4bd83eb7c4 | f4a4cb4fffd41e121254fe0e74fb05e8cda590ac |
refs/heads/master | <file_sep>
$(document).ready(function () {
// VARIABLES
var searchBtn, searchForm, searchClose, hamBtn, hamMenu, hamClose;
searchBtn = document.querySelector('#search-nav');
searchForm = document.querySelector('#search-form');
searchClose = document.querySelector('#search-close');
hamBtn = document.querySelector('#ham-btn');
hamBtn2 = document.querySelector('#ham-btn-2');
hamMenu = document.querySelector('#ham-menu');
hamClose = document.querySelector('#ham-close')
//CLICK BTN
hamBtn.addEventListener('click', function() {
if (hamMenu.classList.contains('ham-deactive')) {
hamMenu.classList.remove('ham-deactive');
hamMenu.classList.add('ham-active');
}
})
hamBtn2.addEventListener('click', function() {
if (hamMenu.classList.contains('ham-deactive')) {
hamMenu.classList.remove('ham-deactive');
hamMenu.classList.add('ham-active');
}
})
hamClose.addEventListener('click', function() {
if (hamMenu.classList.contains('ham-active')) {
hamMenu.classList.remove('ham-active');
hamMenu.classList.add('ham-deactive');
}
})
searchBtn.addEventListener('click', function() {
if (searchForm.classList.contains('search-form-deactive')) {
searchForm.classList.remove('search-form-deactive');
searchForm.classList.add('search-form-active');
}
})
searchClose.addEventListener('click', function() {
if (searchForm.classList.contains('search-form-active')) {
searchForm.classList.remove('search-form-active');
searchForm.classList.add('search-form-deactive');
}
})
});<file_sep>from flask import Flask, render_template
from app import app
@app.route("/")
def home():
return render_template('home.html')
@app.route("/az/cards/debet")
def debetcard():
return render_template('debet.html')
@app.route("/az/cards/kredit")
def creditcard():
return render_template('credit.html')
@app.route("/az/cards/other")
def othercard():
return render_template('more.html')
# @app.route('/students/<int:stu_index>')
# def student_list(stu_index):
# student_Uni = list(
# filter(lambda student: student['Id'] == stu_index, students_info))[0]
# return render_template('studentlist.html', studentAPI=student_Uni)
# @app.route("/students/")
# def students():
# return render_template('students.html', student_list=students_info)
# @app.route("/contact/")
# def contact():
# form = ContactForm()
# return render_template('contact.html',form=form)<file_sep>from flask import Flask
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:1234@127.0.0.1:3306/Unibank_Cards'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# from extensions import *
# from models import *
# from controller import *
if __name__ == '__main__':
# app.init_app(db)
# app.init_app(migrate)
app.run(debug=True)
| 3f7e024e0996d2a9b5170846d5ed06e21ac22521 | [
"JavaScript",
"Python"
] | 3 | JavaScript | koki014/Mars_unibank | b720099866a49adbac5882308d6dc507a5bae8b1 | 27ec2462a4d818b987fafd098993af8ef4cc9cb9 |
refs/heads/master | <repo_name>Labiri/NazcaBot.github.io<file_sep>/static/js/main.js
// -------------------------------------
// Mobile menu
// -------------------------------------
var mobileToggle = document.getElementById('mobile-toggle')
mobileToggle.addEventListener("click", function() {
document.body.classList.toggle('open')
})
document.querySelectorAll('header .nav-links a').forEach(function(a) {
a.addEventListener("click", function() {
document.body.classList.remove('open')
})
})
// -------------------------------------
// FAQ accordion
// -------------------------------------
var faqItem = document.querySelectorAll('#faq .q')
faqItem.forEach(function(i) {
i.addEventListener('click', function(e) {
let li = e.target.closest('li')
if (li.classList.length) {
li.classList.remove("active")
e.target.querySelector('.fa-plus').style.display = "block"
e.target.querySelector('.fa-minus').style.display = "none"
} else {
li.classList.add("active")
e.target.querySelector('.fa-plus').style.display = "none"
e.target.querySelector('.fa-minus').style.display = "block"
}
})
})
// -------------------------------------
// Init Waitlist
// -------------------------------------
document.addEventListener("DOMContentLoaded", function(event) {
window.waitlisted.start({domain: "nazca.app.waitlisted.co"})
});
| dc9d60811bf0fafe1bde8aa882eaacaf9b289101 | [
"JavaScript"
] | 1 | JavaScript | Labiri/NazcaBot.github.io | 810425e8140acb0b478edbda832201a494922e81 | 3ee5c949f77a3acb863776d2f116b353fda4a88d |
refs/heads/master | <repo_name>easinyo/Ecommerce-Book-Store<file_sep>/bookstore.sql
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE IF NOT EXISTS `cart` (
`Customer` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`Product` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`Quantity` int(5) NOT NULL,
PRIMARY KEY (`Customer`,`Product`),
KEY `Product` (`Product`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `cart` (`Customer`, `Product`, `Quantity`) VALUES
('hello', 'ENT-12', 1),
('sebastien', 'ACA-6', 1),
('emmanuel', 'NEW-4', 5),
('brahim', 'ENT-1', 3);
CREATE TABLE IF NOT EXISTS `products` (
`PID` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`Title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`Author` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`MRP` float NOT NULL,
`Price` float NOT NULL,
`Discount` int(11) DEFAULT NULL,
`Available` int(11) NOT NULL,
`Publisher` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`Edition` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
`Category` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`Description` text COLLATE utf8_unicode_ci,
`Language` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`page` int(5) DEFAULT NULL,
`weight` int(4) DEFAULT '500',
PRIMARY KEY (`PID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `products` (`PID`, `Title`, `Author`, `MRP`, `Price`, `Discount`, `Available`, `Publisher`, `Edition`, `Category`, `Description`, `Language`, `page`, `weight`) VALUES
('ACA-1', 'Code complete 2', '<NAME>', 225, 200, 30, 12, 'G.K Publication', '2', 'Academic and Professional', '', 'English', 456, 500),
('ACA-2', 'Intermediate PYTHON Programming', '<NAME>', 339, 233, 5, 11, 'Wiley India', '1', 'Academic and Professional', 'Python is called the "Super-heroic Framework" by The Code Project. It''s an open source client side framework maintained by Google that greatly simplifies frontend development, making it easy and fun to write complex web apps. The online documentation and existing books on the subject lack simple explanations of some of the more advanced concepts, and how they work together. As a result, many developers get used to the basic concepts of AngularJS fairly quickly, but struggle when it comes to building more complex (real world) applications. ', 'English', 396, 500),
('ACA-3', 'WEB Scraping with Python 2', '<NAME>', 204, 101, 20, 20, 'Chapman and Hall/CRC', '1', 'Academic and Professional', 'Builfing Web app with python.', 'English', 240, 500);
INSERT INTO `products` (`PID`, `Title`, `Author`, `MRP`, `Price`, `Discount`, `Available`, `Publisher`, `Edition`, `Category`, `Description`, `Language`, `page`, `weight`) VALUES
('CHILD-1', 'JUST STUPID', '<NAME>', 50, 45, 05, 12, 'KID Books International', '1', 'Children and Teens', '', 'English', 220, 500),
('CHILD-2', 'The Unteachables', 'KID BOOKS', 299, 194, 34, 12, 'Penguin Books', '1', 'Children and Teens', '', 'English', 224, 500),
('CHILD-3', 'WOULD YOU RATHER', 'RIDDLELAND', 30, 30, 0, 4, 'KID Books International', '1', 'Children and Teens', '', 'English', 236, 500),
('CHILD-4', 'NOTORIOUS', '<NAME>', 40, 24, 47, 6, 'KID Books International', '1', 'Children and Teens', '', 'English', 220, 500);
INSERT INTO `products` (`PID`, `Title`, `Author`, `MRP`, `Price`, `Discount`, `Available`, `Publisher`, `Edition`, `Category`, `Description`, `Language`, `page`, `weight`) VALUES
('LIT-1', 'UNESCO and the fate of the literary', '<NAME>', 59, 25, 49, 12, 'Random House', '1', 'Literature and Fiction', '', 'English', 320, 500),
('LIT-2', 'Music from a Speeding Train', '<NAME>', 57, 57, 0, 5, 'Litterature Books', '1', 'Literature and Fiction', NULL, 'English', 248, 500),
('LIT-3', 'Phono Poetics', '<NAME>', 99, 50, 50, 13, 'The making of Early Literary Recordings', '2', 'Literature and Fiction', NULL, 'English', 228, 500);
INSERT INTO `products` (`PID`, `Title`, `Author`, `MRP`, `Price`, `Discount`, `Available`, `Publisher`, `Edition`, `Category`, `Description`, `Language`, `page`, `weight`) VALUES
('SPO-1', 'Moneyball: The Art of Winning an Unfair Game', '<NAME>', 15, 10, 33.33, 111, '<NAME>', '1', 'Sports', 'Moneyball: The Art of Winning an Unfair Game is a book by <NAME>, published in 2003, about the Oakland Athletics baseball team and its general manager <NAME>. Its focus is the teams analytical, evidence-based, sabermetric approach to assembling a competitive baseball team despite Oaklands small budget.', 'English', 288, 350),
('SPO-2', 'Open', '<NAME>', 20, 10, 50, 60, '<NAME>', '1', 'Sports', 'Far more than a superb memoir about the highest levels of professional tennis, Open is the engrossing story of a remarkable life.
<NAME> had his life mapped out for him before he left the crib. Groomed to be a tennis champion by his moody and demanding father, by the age of twenty-two Agassi had won the first of his eight grand slams and achieved wealth, celebrity, and the game’s highest honors. But as he reveals in this searching autobiography, off the court he was often unhappy and confused, unfulfilled by his great achievements in a sport he had come to resent. Agassi writes candidly about his early success and his uncomfortable relationship with fame, his marriage to <NAME>, his growing interest in philanthropy, and—described in haunting, point-by-point detail—the highs and lows of his celebrated career.', 'English', 255, 400),
('SPO-3', 'The Game', '<NAME>', 15, 12, 25, 23, 'Wiley', '1', 'Sports', 'The Game is a book written by former ice hockey goaltender <NAME>. Published in 1983, the book is a non-fiction account of the 1978-79 Montreal Canadiens, detailing the life of a professional hockey player.', 'English', 308, 500),
('SPO-4', 'The Illustrated History of Football: Hall of Fame', '<NAME>', 25, 20, 25, 11, 'Wiley', '1', 'Sports', '‘A fresh look at the beautiful game’ - NMEWelcome back to the inimitable work of illustrator <NAME>.Most football fans can only dream of pulling on the shirt of their favourite team and running out in front of thousands of adoring fans. Pitch invaders aside, few of us get to experience that adrenalin rush.', 'English', 402, 670);
CREATE TABLE IF NOT EXISTS `users` (
`UserName` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
`Password` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`UserName`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `users` (`UserName`, `Password`) VALUES
('sebastien', '<PASSWORD>'),
('emmanuel', '<PASSWORD>'),
('hello', 'hello'),
('brahim', '<PASSWORD>');<file_sep>/README.md
## Team (Contributors)
| Name | Email |Student ID |
|------------------------|---------------------|-------------|
| <NAME> | <EMAIL> |8879715 |
| <NAME> | <EMAIL> |8890676 |
| <NAME> | <EMAIL> |6978470 |
# Project - BookStore website
* A book store website to sell the pdf and hardcopies best seller and new coming books.
* The website will allow the user to browse for books, add them to chart and check out.
------------------
# Color Palette
## Primary Colors
We will be using these colors as our primary one through the whole website. With Black or white test.

## Complemenary Colors
We will be using those colors as our secondary color palette

# Fonts and Type scale
| scale category| font | size | case |
|---------------|---------|--------|-----------|
| H1 | Light | 96 | Sentence |
| H2 | Light | 60 | Sentence |
| H3 | Regular | 48 | Sentence |
| H4 | Regular | 34 | Sentence |
| H5 | Medium | 24 | Sentence |
| H6 | Regular | 20 | Sentence |
| body | Regular | 16 | Sentence |
| p | Regular | 16 | Sentence |
| button | Medium | 14 | All caps |
Main font type used is: **Arial**
# Features
* Login as an existing user.

* Sign up as a new user.

* Display list of book.

* Browse per categorie.

* Search feature for books ( per title or per author ).

* Display Book info


* Sort books by price or discount.

* Add to chart.

* Check out.

------------------
# Color Palette
## Primary Colors
We will be using these colors as our primary one through the whole website. With Black or white test.

## Complemenary Colors
We will be using those colors as our secondary color palette

# Fonts and Type scale
| scale category| font | size | case |
|---------------|---------|--------|-----------|
| H1 | Light | 96 | Sentence |
| H2 | Light | 60 | Sentence |
| H3 | Regular | 48 | Sentence |
| H4 | Regular | 34 | Sentence |
| H5 | Medium | 24 | Sentence |
| H6 | Regular | 20 | Sentence |
| body | Regular | 16 | Sentence |
| p | Regular | 16 | Sentence |
| button | Medium | 14 | All caps |
Main font type used is: **Arial**
## Used technologies:
- HTML5
- CSS3
- Javascript
- PHP
- SQL
- PHP Unit
## Development Environment Setup Guide
----------------------------------------
Please follow those instruction to set up your local work environment. (To be added)
## Database Schema
----------------------------------------

### Setup:
Please follow those instruction to set up your local machine.
1. Download xampp: https://www.apachefriends.org/download.html
2. Find and open ```php.ini``` in xampp file. For mac : Open your XAMPP application and ```press start``` on the ```general``` tab. After that go into the ```Volumes``` tab, and click ```mount```. Once it is mounted navigate click the ```explore``` button and it will open you the ```lampp``` folder, where all your application/apache related files are located.
3. Add those lines to the end in your ```php.ini```.
- For mac: ```extension=pgsql.so```
- For windows: ```extension=php_pdo_pgsql.dll``` and ```extension=php_pgsql.dll```
5. Pull this repository to your machine and make sure to locate at xampp/htdocs
6. For mac: from the ```lampp``` folder navigate to ```etc``` > ```extra``` > ```httpd-xampp.conf```. Open this file and in the section ```Since xampp 1.4.3``` change the ```Require admin``` to ```Require all granted```
7. Open in your browser ```http://localhost:8080/phpmyadmin/``` and click ```New``` at the left Navigator to create a new database. (```name= DatabaseName```, ```uft code= utf8_unicode_ci```) <br />
8. once ```DatabaseName``` created, navigate to your project location, usually on ```c:\xampp\htdocs\BookStore``` and import ```bookstore.sql```
9. Then ignore the error that shows up After clicking ```Go```.
### Deployement Script: Running the Web Application
1. Open xampp and go to manage servers and start ```Apache``` and ```MySQL``` web server.
2. Open ```dbconnect.php``` and modify it.
3. To find where is your ```localhost/password```, please follow step
- Step 1:
- Locate phpMyAdmin installation path.
- Step 2:
- Open phpMyAdmin>config.inc.php in your favourite text editor.
- Step 3:
- $cfg['Servers'][$i]['auth_type'] = 'config';
- $cfg['Servers'][$i]['user'] = 'root';
- $cfg['Servers'][$i]['password'] = '';
- $cfg['Servers'][$i]['extension'] = 'mysqli';
- $cfg['Servers'][$i]['AllowNoPassword'] = true;
- $cfg['Lang'] = '';
4. navigate to http://localhost/BookStore/ and you are all set :D
N.B: if you created a new folder named ```example``` to pull the repository to it, make sure to add the name of the folder in your URL (e.g: http://localhost/example/BookStore/)
## Setting-up the testing environment
Unit tesiting: For the unit testing we used [Composer](https://getcomposer.org/) (v1.9.3) and [PHPUnit](https://phpunit.de/) (v9.0)
### Composer
Installing composer on windows/osx is different and you can find extra information on how to install it here: https://getcomposer.org/doc/00-intro.md
Theses commands will install composer globally on your machine, and can be used by any of your project.
1. For mac, type in terminal: ```curl -sS https://getcomposer.org/installer | php```
2. rename it to composer for ease of use: ```mv composer.phar /usr/local/in/composer```
3. ```composer init```
### PHPUnit
1. ```composer require phpunit/phpunit```
To run the tests in the ```tests``` folder, run ```./vendor/bin/phpunit tests``` from inside your project.
<file_sep>/dbconnect.php
<?php
define('DB_HOST', '127.0.0.1');
define('DB_NAME', 'DatabaseName');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysqli_select_db($con,DB_NAME) or die("Failed to connect to MySQL: " . mysql_error());
?>
| 35df8f2a9765f7431a4228ad653e7edc534cf9bd | [
"Markdown",
"SQL",
"PHP"
] | 3 | SQL | easinyo/Ecommerce-Book-Store | 5d8b8c5ca1affbb149662f83e7c97d23de3c231d | e0764b2d1e13c9c11e789458fd5c1b78c9b6d831 |
refs/heads/master | <repo_name>neal-shah/SpringRdbcExample<file_sep>/startPostgres.sh
docker run --name myDatabase -p 5432:5432 -e POSTGRES_PASSWORD=<PASSWORD> postgres
| 8ee9106e4a46afb65e898a37a8f3995dd089ddeb | [
"Shell"
] | 1 | Shell | neal-shah/SpringRdbcExample | 76e69df8c47327f12b436981ef4da89dfac9b9c2 | 3de423855fe274ec41f083da87dcd8e81b608dd2 |
refs/heads/master | <repo_name>Ransinghsatyajitray/Knowdege-ka-Pitara<file_sep>/Purrr Concepts.R
# Iteration is a powerful way to make the computer do the work for you. It can also be an area of coding
# where it is easy to make lots of typos and simple mistakes. The purrr package helps simplify iteration
# so you can focus on the next step, instead of finding typos.
install.packages("repurrrsive")
# The power of iteration
map(object, functions)
# # Initialize list
# all_files <- list()
#
# # For loop to read files into a list
# for(i in seq_along(files)){
# all_files[[i]] <- read_csv(file = files[[i]])
# }
#
# # Output size of list object
# length(all_files)
# # Load purrr library
# library(purrr)
#
# # Use map to iterate
# all_files_purrr <- map(files,readr::read_csv)
#
# # Output size of list object
# length(all_files_purrr)
# Load repurrrsive package, to get access to the wesanderson dataset
library(repurrrsive)
# Load wesanderson dataset
data(wesanderson)
# Get structure of first element in wesanderson
str(wesanderson[[1]])
# Get structure of GrandBudapest element in wesanderson
str(wesanderson$GrandBudapest)
# Third element of the first wesanderson vector
wesanderson[[1]][3]
# Fourth element of the GrandBudapest wesanderson vector
wesanderson$GrandBudapest[4]
# Subset the first element of the sw_films data
sw_films[[1]]
# Subset the first element of the sw_films data, the title column
sw_films[[1]]$title
# Many flavors of map():
#map_dbl -> vector
# Map over wesanderson, and determine the length of each element
map(wesanderson, ~length(.x))
# Create a dataframe that has the number of colors from each movie, using map_dbl(). The dbl means a double or a number that can have a decimal.
# Create a numcolors column and fill with length of each wesanderson element
data.frame(numcolors = map_dbl(wesanderson, ~length(.x)))
# pipe inside map.----
map(mtcars,~.x %>% sum() %>% log())
# List of sites north, east, and west
sites <- list("north","east","west")
# Create a list of dataframes, each with a years, a, and b column
list_of_df <- map(sites,
~data.frame(sites = .x,
a = rnorm(mean = 5, n = 200, sd = (5/2)),
b = rnorm(mean = 200, n = 200, sd = 15)))
list_of_df
# Map over the models to look at the relationship of a vs b
list_of_df %>%
map(~ lm(a ~ b, data = .)) %>%
map(summary)
# map2 and pmap
# List of 1, 2 and 3
means <- list(1,2,3)
# Create sites list
sites <- list("north","west","east")
# Map over two arguments: sites and means
list_of_files_map2 <- map2(sites, means, ~data.frame(sites = .x,
a = rnorm(mean = .y, n = 200, sd = (5/2))))
list_of_files_map2
# # Create a master list, a list of lists
# pmapinputs <- list(sites = sites, means = means, sigma = sigma,
# means2 = means2, sigma2 = sigma2)
#
# # Map over the master list
# list_of_files_pmap <- pmap(pmapinputs,
# function(sites, means, sigma, means2, sigma2)
# data.frame(sites = sites,
# a = rnorm(mean = means, n = 200, sd = sigma),
# b = rnorm(mean = means2, n = 200, sd = sigma2)))
#
# list_of_files_pmap
# safely: to check where in the list the error is occuring.
# eg. map(safely(function(x),x*10,otherwise=NA_real_))
# possibly: dont show the error.
# walk:
# Load the gap_split data
data(gap_split)
# Map over the first 10 elements of gap_split
plots <- map2(gap_split[1:10],
names(gap_split[1:10]),
~ ggplot(.x, aes(year, lifeExp)) +
geom_line() +
labs(title = .y))
# Object name, then function name
walk(plots, print)
mtcars %>% map_df(~.x %>% log() %>% sin())
# XXXXXXXXXXXXXXXXXXXXXX more practice needed XXXXXXXXXXXXXXXXXXXXXXXXXXx
# need to revise again
<file_sep>/All about Visualization in R Old Sheet.R
setwd("C:\\Users\\<NAME>\\Desktop\\Practice Projects R\\Predicting Emp Attrition R Project Kindle Book\\All about Visualization in R")
data("diamonds")
str(diamonds)
#Simple Graph g1----
ggplot(diamonds,aes(x=carat,y=price))+geom_point()
#Result: Here we get black and white graph
#Character Changed to factor g2----
ggplot(diamonds,aes(x=factor(clarity),y=price))+geom_point()
#Result: Here we get an overplotted black and white graph, oppertunity of using jittering here. The x axis
#written as factor(clarity) is annoying
#Simple Graph with color g3----
ggplot(diamonds,aes(x=carat,y=price,color=color))+geom_point()
#Result: Here we get colored graph with the points being colored(aesthetic) as per their color(variable)
#g3 Graph with color aesthetic written in geom_point g4----
ggplot(diamonds,aes(x=carat,y=price))+geom_point(aes(color=color))
#this is same as ggplot(diamonds,aes(x=carat,y=price,color=color))+geom_point()
# Graph with size element g5----
ggplot(diamonds,aes(x=carat,y=price,size=x))+geom_point()
# this produces graph with size of the point depending on the x
#Alpha included g6----
ggplot(diamonds,aes(x=carat,y=price,color=clarity))+geom_point(alpha=0.4)
#this produces graph with providing some transperency to the points
#With smoothing line along with point g7----
ggplot(diamonds,aes(x=carat,y=price))+geom_point(alpha=0.6)+
geom_smooth(method='lm',col='red',se=F)
#this produces graph scatter plot with a smoothing line
#With coord_fixed: A fixed scale coordinate system forces a specified ratio between the physical
#representation of a data unit on the axes. The default ratio=1, ensure that one unit on the x-axis
#is same length as one unit on the y axis.
#coord_fixed (ratio=1) (x/y) ie. x unit in x axis to y unit in y axis to g8
ggplot(diamonds,aes(x=carat,y=price))+geom_point(alpha=0.4)+coord_fixed()
#As the x axis is very smaller than y axis scale, thus our graph is very weird
#1000 unit in y axis is 1 unit in x axis=> ratio=x/y (1/1000)= 0.001 g9
ggplot(diamonds,aes(x=table,y=price))+geom_point(alpha=0.4)+coord_fixed(ratio=.001)
#Over plotting is a problem here as seen
#we are log transforming the y axis scale_y_log10 g10
ggplot(diamonds,aes(x=table,y=price))+geom_point(alpha=0.4)+scale_y_log10()
# To change the range of a continuous axis, the functions xlim() and ylim() can be used we
#limit the graph to 80 in x axis and 10000 in y axis g11
ggplot(diamonds,aes(x=table,y=price))+geom_point(alpha=0.4)+scale_y_log10()+xlim(0,80)+ylim(0,10000)
# this is same as g11 as g12 (ax ylim is overwriting on the scale_y_log10)
ggplot(diamonds,aes(x=table,y=price))+geom_point(alpha=0.4)+xlim(0,80)+ylim(0,10000)
# the function expand_limits() can be used to :quickly set the intercept of x and y axes at (0,0)
# change the limits of x and y axes g13
ggplot(diamonds,aes(x=table,y=price))+geom_point(alpha=0.4)+expand_limits(x=c(0,80),y=c(0,10000))
#This is same as g11
# It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.
#
# The simplified formats of the functions are :
#
# scale_x_continuous(name, breaks, labels, limits, trans)
# scale_y_continuous(name, breaks, labels, limits, trans) g14
ggplot(diamonds,aes(x=table,y=price))+geom_point(alpha=0.4)+
scale_x_continuous(name="Axis for Table",breaks=c(5,10,30,80),limits=c(0,80))
#Here we did 3 things in 1 go, we named the Axis, pointed out where we want the breaks in the axis to show up
#and set the limit 0 min and 80 max
#scale_x_sqrt(), scale_y_sqrt() : for sqrt transformation g15
ggplot(diamonds,aes(x=table,y=price))+geom_point(alpha=0.4)+scale_y_sqrt()
#like like scale_y_log10() we did sqrt transformation of y axis
#The transforming the scale dont have physical effect on the data point like scale_y_sqrt dont
#square root the y axis elements, it simply transform the axis scaling showing data only in the
#specific ranges as specified in the scaling and exclude other
#Axis tick marks can be set to show exponents. The scales package is required to
#access break formatting functions g16
library(scales)
ggplot(diamonds,aes(x=table,y=price))+geom_point(alpha=0.4)+
scale_y_continuous(trans=log2_trans(),breaks=trans_breaks("log2",function(x)2^x),labels= trans_format("log2",math_format(2^.x)))
#for running trans_breaks and trans_format we use scales packages
#any exponential thing comes under logvalue_trans() and the function to write the trans_breaks is like above
#Note that many transformation functions are available using the scales package : log10_trans(),
#sqrt_trans(), etc. Use help(trans_new) for a full list.
#Smoothing line by geom smooth
#methods: auto- smoothing method choosen based on the size of largest group
#loess- used for less than 1000 obs
#gam- >1000 obs
#lm- linear model g17
ggplot(diamonds,aes(x=x,y=y))+geom_point(alpha=0.2)+
geom_smooth(aes(color=clarity),se=FALSE)
#Interesting thing to node that except x and y aesthetic other aesthetics can also go in inside geoms
#We can also see even if we dont specify the method R automatically took smoothing method to be
# gam as the number of observations >1000
#Multiple smoothing lines all serving different purpose g18
ggplot(mtcars,aes(x=wt,y=mpg,col=factor(cyl)))+geom_point()+geom_smooth(method="lm",se=FALSE)+
geom_smooth(aes(group=1),method="lm",se=F,linetype=2)
#Overplotting where jittering is required g19
ggplot(diamonds,aes(y=carat,x=clarity,color=cut))+geom_point(position="jitter")
#this is same as g20
ggplot(diamonds,aes(y=carat,x=clarity,color=cut))+geom_jitter()
str(diamonds)
#the following are the elements of the aesthetics
#x,y,color,size,alpha,linewidth,fill,labels,shape,linetype
#Shape 21 goes in the geom_point (donot mention it in aesthetics) and not in ggplot
#When shape 21 is used the size goes in geom_point too g21
ggplot(diamonds,aes(x=x,y=y,color=color,alpha=0.3))+geom_point(shape=21,size=4)
str(mtcars)
#use of text in graphs, we use geom_text() g22
ggplot(mtcars,aes(x=wt,y=mpg,label=cyl,color=vs))+geom_text(size=3)
#The labeled variable is shown g23
ggplot(mtcars,aes(x=wt,y=mpg,label=cyl,color=factor(vs)))+geom_text(size=3)
#Jittering with jitter width g24
ggplot(mtcars,aes(x=factor(cyl),y=mpg,col=factor(gear),alpha=0.5))+
geom_point(position=position_jitter(0.1))
#or
ggplot(mtcars,aes(x=factor(cyl),y=mpg,col=factor(gear),alpha=0.5))+
geom_jitter(width=0.1)
#Faceting facet_grid y | ~ x - g25
ggplot(mtcars,aes(x=mpg,y=cyl,col=as.factor(vs)))+
geom_point()+facet_grid(am~gear)
#Problem here is by just looking at the figure we cant say which one is am and which one is gear
#g26
ggplot(mtcars,aes(x=mpg,y=cyl,col=as.factor(vs)))+geom_point()+facet_grid(am~.)
#g27
ggplot(mtcars,aes(x=mpg,y=cyl,col=as.factor(vs)))+geom_point()+facet_grid(.~gear)
#Problem with g25,g26,g27 is it is difficult to identify what does the facet parameters refer to
# the concept of ggplot divides a plot into three different fundamental
# parts: plot = data + Aesthetics + geometry.
#geom_histogram, the fill should be place in geom g28
ggplot(mtcars,aes(x=wt))+geom_histogram(alpha=0.4,fill="blue")
#density plot g29
ggplot(mtcars,aes(x=wt))+geom_density(fill="blue",alpha=0.4)
#A subset of mtcars data is used by the layer geom_line(). The line is colored
#according to the values of the continuous variable cyl. g30
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_point() + # to draw points
geom_line(data = head(mtcars), color = "red")
#Use of pipe inside geom g31
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_point() + # to draw points
geom_line(data = mtcars%>%filter(vs==1), color = "red")
#Use of pipe inside geom g32
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_point() + # to draw points
geom_line(data = mtcars%>%filter(vs==1), color = "red")+
geom_line(data = mtcars%>%filter(vs==0), color = "green")
# For one continuous variable:
# - geom_area() for area plot
# - geom_density() for density plot
# - geom_dotplot() for dot plot
# - geom_freqpoly() for frequency polygon
# - geom_histogram() for histogram plot
# - stat_ecdf() for empirical cumulative density function
# - stat_qq() for quantile - quantile plot
#geom_area require both x and y aesthetics g33
ggplot(mtcars,aes(x=drat,y=hp))+geom_area()
#frequency polygon, the thing we plot using the geom_histogram we could plot the same
#using frequency ploygon g34
ggplot(mtcars,aes(x=drat))+geom_freqpoly()
#fill and color dont work in geom_freqpoly
#We can color the area under the frequency ploygon by using below g35
ggplot(mtcars,aes(x=drat))+geom_area(stat="bin",color= "black", fill="#00AFBB")
#stat="bin is must otherwise r will throw an error
#through the ..internal_parameter.. we get the density plot by controlling the
#y axis g36
ggplot(mtcars,aes(x=drat))+geom_histogram(aes(y=..density..))
#Bar plot vs area plot
ggplot(mtcars,aes(x=drat))+geom_bar(stat="bin") #bar plot g37
ggplot(mtcars,aes(x=drat))+geom_area(stat="bin") #area plot g38
#Density plot g39
ggplot(mtcars,aes(x=drat))+geom_density(color="black",fill="gray")+
geom_vline(aes(xintercept=mean(drat),color="#FC4E07", linetype="dashed"))
#What should be in aesthetics: basically all x , y of any form which are accessed directly from the data (be it directly or be it indirectly like mean sd operation on them)
#Change colors by groups g40
ggplot(mtcars,aes(x=drat))+geom_density(aes(color=factor(cyl)))
#g41
ggplot(mtcars,aes(x=drat))+geom_density(aes(fill=factor(cyl)),alpha=0.4)
#An example where different dataframe used for plotting graph (Vimp) g42
ggplot(mtcars,aes(x=drat))+geom_density(aes(color=factor(cyl),alpha=0.4))+
geom_vline(data=diamonds,aes(xintercept=mean(x),color=cut),linetype="dashed")
#Although the above graph is confusing but it serve our pupose to show multiple dataframe could be used
#How to know the formula of colors used in R
#Basic Histo, increasing no of bins, change line color and fill color, overlaod histo, dodge (interleaved),
#histo with density,
#qqplot
# geom_point() for scatter plot
# . geom_smooth() for adding smoothed line such as regression line
# . geom_quantile() for adding quantile lines
# . geom_rug() for adding a marginal rug
# . geom_jitter() for avoiding overplotting
# . geom_text() for adding textual annotations
#Histogram with density plot g43
ggplot(mtcars,aes(x=drat))+geom_histogram(aes(y=..density..), colour="black", fill="white") +
geom_density(alpha=0.2, fill = "#FF6666")
#frequency ploygon (normal data count) & density plot (normal data %cummulative)
#g44
ggplot(mtcars,aes(x=drat))+geom_histogram(aes(y=..density.., color = factor(am), fill = factor(am)),
alpha=0.5)+
geom_density(aes(color = factor(am)), size = 1)
#ECDF (Empirical Cumulative Density Function) reports for any given number the
#percent of individuals
ggplot(mtcars,aes(x=drat))+stat_ecdf(geom="point") #g45
ggplot(mtcars,aes(x=drat))+stat_ecdf(geom="step") #g46
#bar: fill, dodge, stack
ggplot(mtcars,aes(x=cyl,fill=am))+geom_bar() #g47
ggplot(mtcars,aes(x=cyl,fill=factor(am)))+geom_bar(position="stack") #g48
ggplot(mtcars,aes(x=cyl,fill=factor(am)))+geom_bar(position="fill") #g49
ggplot(mtcars,aes(x=cyl,fill=factor(am)))+geom_bar(position="dodge") #g50
ggplot(mtcars,aes(x=cyl,fill=factor(am)))+geom_bar(position=position_dodge(width=0.2)) #g51
ggplot(mtcars,aes(x=cyl,fill=factor(am)))+geom_bar(position="dodge",width=.2)
#Scatter plots: Continuous X and Y
b <- ggplot(mtcars, aes(x = wt, y = mpg))
b+geom_point() #g52
b+geom_smooth() #g53
b+geom_quantile() #g54
#Smoothing line g55
b+geom_smooth(method="auto", se=TRUE, fullrange=FALSE, level=0.95)
#Add quantile lines from a quantile regression g56
ggplot(mpg, aes(cty, hwy)) +
geom_point() + geom_quantile() +
theme_minimal()
#Add marginal rugs using faithful data g57
data(faithful)
ggplot(faithful, aes(x = eruptions, y = waiting)) +
geom_point() + geom_rug()
#g58
b + geom_point(aes(color = factor(cyl))) +
geom_rug(aes(color = factor(cyl)))
#Rug are lines attached to the axis, they provide more(additional) insight in to data of how data is distributed
#Textual annotations (use of row names) g59
b + geom_text(aes(label = rownames(mtcars)),
size = 3)
#2d density plot g60
c <- ggplot(diamonds, aes(carat, price))
c + geom_density_2d()
#Scatter plots with 2d density estimation g61
sp <- ggplot(faithful, aes(x = eruptions, y = waiting))
sp + geom_point(color = "#00AFBB") +
geom_density_2d(color = "#E7B800")
data("ToothGrowth")
e <- ggplot(ToothGrowth, aes(x = factor(dose), y = len))
#Check where fun.data and fun.args are used
#when we are using summary of certain aesthetic in stat_summary we use fun.y(or fun.x) depending on which axis factor
#we are doing the analysis g62
e + geom_jitter(position = position_jitter(0.2)) +
stat_summary(fun.y = mean, geom = "point",
shape = 18, size = 3, color = "red")
#stat_summary fun.data and fun.args g63
#The function stat_summary() can be used to add mean/median points
e + geom_jitter(position = position_jitter(0.2))+
stat_summary(fun.data="mean_sdl", fun.args = list(mult=1),
geom="pointrange", color = "red")
#here in stat summary since we are not only using y data mean alone we are using std with 1 standard deviation
#mult=1
#g64
e + geom_jitter(position = position_jitter(0.2))+
stat_summary(fun.data="mean_sdl", fun.args = list(mult=3),
geom="pointrange", color = "red")
# Change manually point colors using the functions :
# . scale_color_manual(): to use custom colors
# . scale_color_brewer(): to use color palettes from RColorBrewer package
# . scale_color_grey(): to use grey color palettes
e3 <- e + geom_jitter(aes(color = factor(dose)), position = position_jitter(0.2)) +
theme_minimal()
e3 + scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9")) #g65
e3 + scale_color_brewer(palette="Dark2") #g66
#Bar Chart
f <- ggplot(mtcars, aes(x = factor(cyl), y = wt))
# Change fill color manually: custom color
f + geom_bar(aes(fill = factor(am)), stat="identity") +
scale_fill_manual(values = c("#999999", "#E69F00")) #g67
# Add labels to a dodged bar plot :
# ggplot(data=df2, aes(x=dose, y=len, fill=supp)) +
# geom_bar(stat="identity", position = position_dodge())+
# geom_text(aes(label = len), vjust = 1.6, color = "white",
# position = position_dodge(0.9), size = 3.5)
# Possible layers include:
# . geom_crossbar() for hollow bar with middle indicated by horizontal line
# . geom_errorbar() for error bars
# . geom_errorbarh() for horizontal error bars
# . geom_linerange() for drawing an interval represented by a vertical line
# . geom_pointrange() for creating an interval represented by a vertical line,
# with a point in the middle.
# Horizontal error bar
#The arguments xmin and xmax are used for horizontal error bars.
# ggplot(mtcars, aes(x = factor(cyl), y = wt ,
# xmin = wt-sd, xmax = wt+sd))
#Pie Charts
#The function coord_polar() is used to produce a pie chart, which is just a stacked
#bar chart in polar coordinates.
df <- data.frame(
group = c("Male", "Female", "Child"),
value = c(25, 25, 50))
#default plot
ggplot(df, aes(x="", y = value, fill=group)) +
geom_bar(width = 1, stat = "identity") + coord_polar("y", start=0) #g68
ggplot(df, aes(x="", y = value, fill=group)) +
geom_bar(width = 1, stat = "identity") + coord_polar("y", start=0) +
scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9")) #g69
#Check out how to plot pei chart in R
count.data <- data.frame(
class = c("1st", "2nd", "3rd", "Crew"),
n = c(325, 285, 706, 885),
prop = c(14.8, 12.9, 32.1, 40.2)
)
mycols <- c("#0073C2FF", "#EFC000FF", "#868686FF", "#CD534CFF")
ggplot(count.data, aes(x = "", y = prop, fill = class)) +
geom_bar(width = 1, stat = "identity", color = "white")+
coord_polar("y", start = 0) #Very simple pie chart g70
#cumsum ie cummulative sum plays a very vital role in pie chart with label
count.data<-count.data %>%
arrange(desc(class)) %>%
mutate(cum_sum = cumsum(prop),lab.ypos = cumsum(prop) - 0.5*prop)
#this step lab.ypos = cumsum(prop) - 0.5*prop is very vital in plotting the graph
ggplot(count.data, aes(x = "", y = prop, fill = class)) +
geom_bar(width = 1, stat = "identity", color = "white") +
coord_polar("y", start = 0)+
geom_text(aes(y = lab.ypos, label = prop), color = "white") #g71
#Theme is taken as void while considering pie chart
#Add text annotations : The package scales is used to format the labels in percent
ggplot(count.data, aes(x = "", y = prop, fill = class)) +
geom_bar(width = 1, stat = "identity", color = "white") +
coord_polar("y", start = 0)+
geom_text(aes(y = lab.ypos, label = prop), color = "white")+
theme_void() #g72
#We go with pie chart ony after we have compiled our entire data
#Donut Chart
ggplot(count.data, aes(x = 2, y = prop, fill = class)) +
geom_bar(stat = "identity", color = "white") +
coord_polar(theta = "y", start = 0)+
geom_text(aes(y = lab.ypos, label = prop), color = "white")+
scale_fill_manual(values = mycols) +
theme_void()+
xlim(0.5, 2.5) #g73
## Simple Pie Chart
slices <- c(10, 12,4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pie(slices, labels = lbls, main="Pie Chart of Countries") #g74
pct <- round(slices/sum(slices)*100)
lbls <- paste(lbls, pct) # add percents to labels
lbls <- paste(lbls,"%",sep="") # ad % to labels
pie(slices,labels = lbls, col=rainbow(length(lbls)),
main="Pie Chart of Countries") #g75
#pie(numerical data, catagorical data for labels, heading)
ggplot(count.data, aes(x = 2, y = prop, fill = class)) +
geom_bar(stat = "identity", color = "white") +
coord_polar(theta = "y", start = 0)+
geom_text(aes(y = lab.ypos, label = paste(prop,"%")), color = "white")+
theme_void() #g76
#All columns except am
group_by_am<-9
my_names_am<-(1:11)[-group_by_am] #vector of all numbers from 1 to 11 except
#Dropping levels
#When we have a catagorical variable withy many levels which are not all present in each sub group og another
#,it may be desirable to drop the unused levels.
str(diamonds)
d<-ggplot(diamonds,aes(x=x,y=y,col=factor(cut)))+geom_point()
#faceting as per clarity
d+facet_grid(clarity~.) #g77
#Speifying scale argument to free up rows
d+facet_grid(clarity~.,scale="free_y") #scale="free_y" removes the data which are very low beonging to perticular
#combination of catagory g78
d+facet_grid(clarity~.,space="free_y")# y axis scale are clearly visible g79
d+facet_grid(clarity~.,space="free_y",scale="free_y") #g80
#theme
diamonds%>%ggplot(aes(X=color,y=price))+
geom_boxplot(outlier.colour = "red",outlier.shape = 2,outlier.size = 1,alpha=0.2)+
geom_hline(yintercept = c(5000,10000,13500),linetype="dashed",color="steelblue")+
facet_grid(~clarity,scale="free_x",space="free_y")+
theme_grey()+ #text in the x axis
theme(axis.text.x=element_text(angle=45,size=5))+ #the faceting creates grey section which are called strip
theme(strip.text.x=element_text(angle=90,size=7))+ggtitle("Pricing of diamonds")+
theme(plot.title=element_text(hjust=0.5))+
theme(axis.text.y=element_text(angle=90)) #g81
#Accumulating multiple graphs in a single page
d1<-diamonds%>%ggplot(aes(X=color,y=price))+
geom_boxplot(outlier.colour = "red",outlier.shape = 2,outlier.size = 1,alpha=0.2)+
geom_hline(yintercept = c(5000,10000,13500),linetype="dashed",color="steelblue")+
facet_grid(~clarity,scale="free_x",space="free_y")+
theme_grey()+ #text in the x axis
theme(axis.text.x=element_text(angle=45,size=5))+ #the faceting creates grey section which are called strip
theme(strip.text.x=element_text(angle=90,size=7))+ggtitle("Pricing of diamonds")+
theme(plot.title=element_text(hjust=0.5))+
theme(axis.text.y=element_text(angle=90))
d2<-d+facet_grid(clarity~.,space="free_y")
d3<-ggplot(count.data, aes(x = 2, y = prop, fill = class)) +
geom_bar(stat = "identity", color = "white") +
coord_polar(theta = "y", start = 0)+
geom_text(aes(y = lab.ypos, label = paste(prop,"%")), color = "white")+
theme_void()
d4<-f + geom_bar(aes(fill = factor(am)), stat="identity") +
scale_fill_manual(values = c("#999999", "#E69F00"))
d5<-ggplot(faithful, aes(x = eruptions, y = waiting)) +
geom_point() + geom_rug()
d6<-ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_point() + # to draw points
geom_line(data = mtcars%>%filter(vs==1), color = "red")
library(cowplot)
plot_grid(d1,d2,d3,d4,d5,d6,nrow=2,ncol=3,labels=c("d1","d2","d3","d4","d5","d6"),hjust=1) #g82
#More Practice needed on theme layer and color coding
library(RColorBrewer)
ggplot(diamonds,aes(cut,fill=color))+
geom_bar(position="dodge")
#It is simpler to use color schemes that have been designed by other people==========
ggplot(diamonds,aes(cut,fill=color))+
geom_bar(position="dodge")+
scale_fill_brewer() #g83
#This color scheme better suits to continuous rather than the categorical data
#check out all brewer present
display.brewer.all()
ggplot(diamonds,aes(cut,fill=color))+
geom_bar(position="dodge")+
scale_fill_brewer(palette="Pastel1") #g84
ggplot(diamonds,aes(cut,fill=color))+
geom_bar(position="dodge")+
scale_fill_brewer(palette="Paired") #g85
ggplot(diamonds,aes(cut,fill=color))+
geom_bar(position="dodge")+
scale_fill_brewer(palette="Accent") #g86
#Control chart in R
# Load the qcc package
library(qcc)
# Step 1
# The first step is loading the qcc package and sample data.It can be seen from the data that there are total 200 observations of diameter
# of Piston rings- 40 samples with 5 reading/observation each.
data(pistonrings)
head(pistonrings)
# Step 2
# Before creating control charts, we need to create qcc object from the data, which can be done by calling qcc function.
diameter<-qcc.groups(pistonrings$diameter,pistonrings$sample)
# Step 3
# Now, we consider first 40 samples as training data.
# R chart (plotting range of all groups) and X-bar chart
# (plotting averages of all groups) can be created as follows:
obj <- qcc(diameter[1:40,], type="R") #g87
obj <- qcc(diameter[1:40,], type="xbar") #g88
#Let's see what happen if I change the nsigma to 2.
obj <- qcc(diameter[1:30,], type="xbar",nsigmas = 2) #g89
#' The data, from sample published by <NAME>
my.xmr.raw <- c(5045,4350,4350,3975,4290,4430,4485,4285,3980,3925,3645,3760,3300,3685,3463,5200)
#' Create the individuals chart and qcc object
my.xmr.x <- qcc(my.xmr.raw, type = "xbar.one", plot = TRUE,data.name="Water") #g90
my.xmr.x <- qcc(my.xmr.raw, type = "xbar.one", plot = TRUE,title="Individual Chart") #g91
#' Create the moving range chart and qcc object. qcc takes a two-column matrix
#' that is used to calculate the moving range.
my.xmr.raw.r <- matrix(cbind(my.xmr.raw[1:length(my.xmr.raw)-1], my.xmr.raw[2:length(my.xmr.raw)]), ncol=2)
my.xmr.mr <- qcc(my.xmr.raw.r, type="R", plot = TRUE)
mean(my.xmr.raw)
sd(my.xmr.raw)
help(qcc)
#Have an idea on how Individual Chart Sddev is calculated. Checkout the histogram too
#Idea is to use qcc in map +group+ungroup and create objects for i chart and then put them in
#cow plot for analysis
<file_sep>/Correspondance Analysis.R
# Correspondence Analysis is an extension of Principal Component Analysis suited to explore the relationship among
# qualitative variables (categorical variables)
library(FactoMineR)
library(factoextra)
data("housetasks")
# The data for the CA should be in a correspondence table
library(gplots)
# Convert the data as a table:
dt <- as.table(as.matrix(housetasks))
# Ballonplot:
balloonplot(t(dt),main="housetasks",xlab="",ylab="",label=FALSE,show.margins = FALSE)
chisq <- chisq.test(housetasks)
res.ca <- CA(housetasks,graph = FALSE)
eig.val <- get_eigenvalue(res.ca)
fviz_screeplot(res.ca,addlabels=TRUE,ylim=c(0,50))
fviz_ca_biplot(res.ca) # rows in blue and columns in red
<file_sep>/Predicting Employee Attrition_stacking.R
# Process: trainControl > algorithm list > set.seed > caretList to check accuracy of different models > modelCor > caretStack for different methods
setwd("C:\\Users\\DELL PC\\Desktop\\Practice Projects R\\Predicting Emp Attrition R Project Kindle Book")
library(readr)
library(dplyr)
library(caret)
library(caretEnsemble)
mydata <- read_csv("Raw_data_Emp_Att.csv")
mydata <- mydata %>% select(-EmployeeNumber,-EmployeeCount,-Over18, -StandardHours)
# In stacking we build multiple models with various ML Algorithms. Each algorithm possesses a unique
# way of learning the characteristics of data and final stacked model indirectly incorporates all the
# unique ways of learning. Stacking gets the combined power of several ML Algorithms through getting
# the final prediction by means of voting or averaging as we do in other types of ensembles.
control<-trainControl(method="repeatedcv",number=10, repeats = 10,savePredictions = TRUE,classProbs = TRUE)
#Declaring the ML Algorithm to use in stacking:
algorithmList<- c("C5.0","knn","svmRadial")
#Setting the seed to ensure reproducibility of results,
set.seed(1000)
#Creating Stacking Model,
models <- caretList(Attrition~., data=mydata, trControl=control, methodList=algorithmList)
# Obtaining the stacking model result and printing them
results <- resamples(models)
summary(results)
# Identifying the correlation between the results
modelCor(results)
# We can see from the correlation table results that none of the individual ML algorithms
# predictions are highly correlated. Very high correlated result means that the algorithms
# have produced very similar predictions. Combining the very similar prediction may not
# really yield significant benefit compared with what one would avail from accepting the
# individual prediction.
# Setting up the cross validation control parameters for stacking the predictions from individual ML algorithms
stackControl <- trainControl(method="cv", number=10, savePredictions = TRUE, classProbs=TRUE)
# Stacking the predictions of individual ML algorithms using generalized linear model
stack.glm <- caretStack(models,method="glm",trControl=stackControl)
# printing the stacked final results
print(stack.glm)
# Stacking the predictions of individual ML algorithms using random Forest
stack.rf <- caretStack(models,method="rf",trControl=stackControl)
# Printing the summary of rf based on stacking
print(stack.rf)
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXxx OUTPUT xxxxxxxxxxxxxxxxxxxxxxxxx
# > setwd("C:\\Users\\DELL PC\\Desktop\\Practice Projects R\Predicting Emp Attrition R Project Kindle Book")
# Error: '\P' is an unrecognized escape in character string starting ""C:\\Users\\DELL PC\\Desktop\\Practice Projects R\P"
# > setwd("C:\\Users\\DELL PC\\Desktop\\Practice Projects R\\Predicting Emp Attrition R Project Kindle Book")
# > mydata <- mydata %>% select(-EmployeeNumber,-EmployeeCount,-Over18, -StandardHours)
# Error in mydata %>% select(-EmployeeNumber, -EmployeeCount, -Over18, -StandardHours) :
# could not find function "%>%"
# > library(readr)
# Warning message:
# package 'readr' was built under R version 3.5.3
# > library(dplyr)
#
# Attaching package: 'dplyr'
#
# The following objects are masked from 'package:stats':
#
# filter, lag
#
# The following objects are masked from 'package:base':
#
# intersect, setdiff, setequal, union
#
# > library(caret)
# Loading required package: lattice
# Loading required package: ggplot2
# Warning messages:
# 1: package 'caret' was built under R version 3.5.3
# 2: package 'ggplot2' was built under R version 3.5.3
# > mydata <- read_csv("Raw_data_Emp_Att.csv")
# Parsed with column specification:
# cols(
# .default = col_double(),
# Attrition = col_character(),
# BusinessTravel = col_character(),
# Department = col_character(),
# EducationField = col_character(),
# Gender = col_character(),
# JobRole = col_character(),
# MaritalStatus = col_character(),
# Over18 = col_character(),
# OverTime = col_character()
# )
# See spec(...) for full column specifications.
# > mydata <- mydata %>% select(-EmployeeNumber,-EmployeeCount,-Over18, -StandardHours)
# > install.packages("caretEnsemble")
# Installing package into 'C:/Users/DELL PC/Documents/R/win-library/3.5'
# (as 'lib' is unspecified)
# also installing the dependency 'pbapply'
#
# trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.5/pbapply_1.4-2.zip'
# Content type 'application/zip' length 69488 bytes (67 KB)
# downloaded 67 KB
#
# trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.5/caretEnsemble_2.0.1.zip'
# Content type 'application/zip' length 1738358 bytes (1.7 MB)
# downloaded 1.7 MB
#
# package 'pbapply' successfully unpacked and MD5 sums checked
# package 'caretEnsemble' successfully unpacked and MD5 sums checked
#
# The downloaded binary packages are in
# C:\Users\DELL PC\AppData\Local\Temp\RtmpgxNBNl\downloaded_packages
# > control<-trainControl(method="repeatedcv",number=10, repeats = 10)
# > #Declaring the ML Algorithm to use in stacking:
# > algorithmList <- c("C5.0","nb","glm","knn","svmRadial")
# > #Setting the seed to ensure reproducibility of results,
# > set.seed(1000)
# > mydata <- read_csv("Raw_data_Emp_Att.csv")
# Parsed with column specification:
# cols(
# .default = col_double(),
# Attrition = col_character(),
# BusinessTravel = col_character(),
# Department = col_character(),
# EducationField = col_character(),
# Gender = col_character(),
# JobRole = col_character(),
# MaritalStatus = col_character(),
# Over18 = col_character(),
# OverTime = col_character()
# )
# See spec(...) for full column specifications.
# > #Setting the seed to ensure reproducibility of results,
# > set.seed(1000)
# > #Creating Stacking Model,
# > models <- caretList(Attrition~.,data=mydata,trControl=control, methodList=algorithmList)
# Error in caretList(Attrition ~ ., data = mydata, trControl = control, :
# could not find function "caretList"
# > library(caretEnsemble)
#
# Attaching package: 'caretEnsemble'
#
# The following object is masked from 'package:ggplot2':
#
# autoplot
#
# Warning message:
# package 'caretEnsemble' was built under R version 3.5.3
# > #Creating Stacking Model,
# > models <- caretList(Attrition~.,data=mydata,trControl=control, methodList=algorithmList)
# Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
# contrasts can be applied only to factors with 2 or more levels
# In addition: Warning messages:
# 1: In trControlCheck(x = trControl, y = target) :
# trControl$savePredictions not 'all' or 'final'. Setting to 'final' so we can ensemble the models.
# 2: In trControlCheck(x = trControl, y = target) :
# indexes not defined in trControl. Attempting to set them ourselves, so each model in the ensemble will have the same resampling indexes.
# > # Obtaining the stacking model result and printing them
# > results <- resamples(models)
# Error in resamples(models) : object 'models' not found
# > View(mydata)
# > #Creating Stacking Model,
# > models <- caretList(Attrition~.,data=mydata,trControl=control, methodList=algorithmList)
# Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
# contrasts can be applied only to factors with 2 or more levels
# In addition: Warning messages:
# 1: In trControlCheck(x = trControl, y = target) :
# trControl$savePredictions not 'all' or 'final'. Setting to 'final' so we can ensemble the models.
# 2: In trControlCheck(x = trControl, y = target) :
# indexes not defined in trControl. Attempting to set them ourselves, so each model in the ensemble will have the same resampling indexes.
# > #Creating Stacking Model,
# > models <- caretList(Attrition~., data=mydata, trControl=control, methodList=algorithmList)
# Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
# contrasts can be applied only to factors with 2 or more levels
# In addition: Warning messages:
# 1: In trControlCheck(x = trControl, y = target) :
# trControl$savePredictions not 'all' or 'final'. Setting to 'final' so we can ensemble the models.
# 2: In trControlCheck(x = trControl, y = target) :
# indexes not defined in trControl. Attempting to set them ourselves, so each model in the ensemble will have the same resampling indexes.
# > control<-trainControl(method="repeatedcv",number=10, repeats = 10,savePredictions = TRUE,classProbs = TRUE)
# > #Creating Stacking Model,
# > models <- caretList(Attrition~., data=mydata, trControl=control, methodList=algorithmList)
# Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
# contrasts can be applied only to factors with 2 or more levels
# In addition: Warning messages:
# 1: In trControlCheck(x = trControl, y = target) :
# x$savePredictions == TRUE is depreciated. Setting to 'final' instead.
# 2: In trControlCheck(x = trControl, y = target) :
# indexes not defined in trControl. Attempting to set them ourselves, so each model in the ensemble will have the same resampling indexes.
# > #Declaring the ML Algorithm to use in stacking:
# > algorithmList<- c("C5.0","nb","glm","knn","svmRadial")
# > #Creating Stacking Model,
# > models <- caretList(Attrition~., data=mydata, trControl=control, methodList=algorithmList)
# Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
# contrasts can be applied only to factors with 2 or more levels
# In addition: Warning messages:
# 1: In trControlCheck(x = trControl, y = target) :
# x$savePredictions == TRUE is depreciated. Setting to 'final' instead.
# 2: In trControlCheck(x = trControl, y = target) :
# indexes not defined in trControl. Attempting to set them ourselves, so each model in the ensemble will have the same resampling indexes.
# > mydata <- mydata %>% select(-EmployeeNumber,-EmployeeCount,-Over18, -StandardHours)
# > #Creating Stacking Model,
# > models <- caretList(Attrition~., data=mydata, trControl=control, methodList=algorithmList)
# Error in { :
# task 1 failed - "Not all variable names used in object found in newdata"
# In addition: There were 50 or more warnings (use warnings() to see the first 50)
# > View(mydata)
# > names(mydata)
# [1] "Age" "Attrition" "BusinessTravel"
# [4] "DailyRate" "Department" "DistanceFromHome"
# [7] "Education" "EducationField" "EnvironmentSatisfaction"
# [10] "Gender" "HourlyRate" "JobInvolvement"
# [13] "JobLevel" "JobRole" "JobSatisfaction"
# [16] "MaritalStatus" "MonthlyIncome" "MonthlyRate"
# [19] "NumCompaniesWorked" "OverTime" "PercentSalaryHike"
# [22] "PerformanceRating" "RelationshipSatisfaction" "StockOptionLevel"
# [25] "TotalWorkingYears" "TrainingTimesLastYear" "WorkLifeBalance"
# [28] "YearsAtCompany" "YearsInCurrentRole" "YearsSinceLastPromotion"
# [31] "YearsWithCurrManager"
# > #Creating Stacking Model,
# > models <- caretList(Attrition~., data=mydata, trControl=control, methodList=algorithmList)
#
# Warning messages:
# 1: In trControlCheck(x = trControl, y = target) :
# x$savePredictions == TRUE is depreciated. Setting to 'final' instead.
# 2: In trControlCheck(x = trControl, y = target) :
# indexes not defined in trControl. Attempting to set them ourselves, so each model in the ensemble will have the same resampling indexes.
# > #Declaring the ML Algorithm to use in stacking:
# > algorithmList<- c("C5.0","knn","svmRadial")
# > #Creating Stacking Model,
# > models <- caretList(Attrition~., data=mydata, trControl=control, methodList=algorithmList)
# There were 30 warnings (use warnings() to see them)
# > # Obtaining the stacking model result and printing them
# > results <- resamples(models)
# > summary(results)
#
# Call:
# summary.resamples(object = results)
#
# Models: C5.0, knn, svmRadial
# Number of resamples: 100
#
# Accuracy
# Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
# C5.0 0.8013699 0.8549611 0.8639456 0.8651628 0.8835616 0.9256757 0
# knn 0.7972973 0.8299320 0.8367347 0.8370902 0.8435374 0.8698630 0
# svmRadial 0.8424658 0.8581081 0.8775510 0.8773423 0.8911565 0.9251701 0
#
# Kappa
# Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
# C5.0 0.07278020 0.31008554 0.37402609 0.3801010 0.4566182 0.6900228 0
# knn -0.04892966 0.03939894 0.05637734 0.0764370 0.1160784 0.2618414 0
# svmRadial 0.19900498 0.36394481 0.43939394 0.4413922 0.5213675 0.6896949 0
#
# > # Identifying the correlation between the results
# > modelCor(results)
# C5.0 knn svmRadial
# C5.0 1.00000000 -0.05749405 0.4288936
# knn -0.05749405 1.00000000 -0.0805878
# svmRadial 0.42889357 -0.08058780 1.0000000
# > stackControl <- trainControl(method="repeatedCV",number=10,repeats=10,savePredictions = TRUE, classProbs=TRUE)
# Warning message:
# `repeats` has no meaning for this resampling method.
# > stackControl <- trainControl(method="repeatedCV", number=10, repeats=10,savePredictions = TRUE, classProbs=TRUE)
# Warning message:
# `repeats` has no meaning for this resampling method.
# > stackControl <- trainControl(method="cv", number=10, savePredictions = TRUE, classProbs=TRUE)
# > # Stacking the predictions of individual ML algorithms using generalized linear model
# > stack.glm <- caretStack(models,method="glm",trControl=stackControl)
# > # printing the stacked final results
# > print(stack.glm)
# A glm ensemble of 3 base models: C5.0, knn, svmRadial
#
# Ensemble results:
# Generalized Linear Model
#
# 14700 samples
# 3 predictor
# 2 classes: 'No', 'Yes'
#
# No pre-processing
# Resampling: Cross-Validated (10 fold)
# Summary of sample sizes: 13230, 13230, 13230, 13230, 13230, 13230, ...
# Resampling results:
#
# Accuracy Kappa
# 0.8784354 0.4493652
#
# > # Stacking the predictions of individual ML algorithms using random Forest
# > stack.rf <- caretStack(models,method="rf",trControl=stackControl)
# note: only 2 unique complexity parameters in default grid. Truncating the grid to 2 .
#
# > # Printing the summary of rf based on stacking
# > print(stack.rf)
# A rf ensemble of 3 base models: C5.0, knn, svmRadial
#
# Ensemble results:
# Random Forest
#
# 14700 samples
# 3 predictor
# 2 classes: 'No', 'Yes'
#
# No pre-processing
# Resampling: Cross-Validated (10 fold)
# Summary of sample sizes: 13230, 13230, 13230, 13230, 13230, 13230, ...
# Resampling results across tuning parameters:
#
# mtry Accuracy Kappa
# 2 0.8748980 0.4646706
# 3 0.8712245 0.4505075
#
# Accuracy was used to select the optimal model using the largest value.
# The final value used for the model was mtry = 2.
# > <file_sep>/Predicting Employee Attrition_xgboost.R
setwd("C:/Users/<NAME>/Desktop/Practice Projects R/Predicting Emp Attrition R Project Kindle Book")
library(readr)
library(dplyr)
library(caret)
mydata <- read_csv("Raw_data_Emp_Att.csv")
names(getModelInfo())
set.seed(1202)
mydata <- mydata %>% select(-EmployeeNumber,-EmployeeCount,-Over18, -StandardHours)
# setting up crossvalidation
crossvalidation <- trainControl(method="cv",number=10)
# If the parameters values are not known then its values should be taken as multiple of 10.
# setting the hyper parameters.
# 1. eta is the learning rate (taking care of gradient feature in it) it value should be low like 0.01, 0.1, 0.2, 0.3
# 2. colsample_bytree it has a range of (0,1],it is the subsample ratio of column when constructing each tree
# 3. max_depth is the maximum depth of trees,
# 4. nrounds=100. it control the maximum number of iterations. it is linked with learning rate
# 5. gamma is the complexity parameter. Gamma values around 20 are extremely high and should be used only when you are using high depth
# gamma is dependent on the data and the other hyperparameters
# 6. min_child_weight is If the tree partition step results in a leaf node with the sum of
# instance weight less than min_child_weight, then the building process will give up
# further partitioning. In linear regression task, this simply corresponds to minimum
# number of instances needed to be in each node. The larger min_child_weight is, the more
# conservative the algorithm will be.
parameters_grid <- expand.grid(eta=0.1, colsample_bytree=c(0.5,0.7), max_depth=c(3,6,8), nrounds=100,
gamma=1, min_child_weight=2, subsample=0.5)
model_xgboost <- train(Attrition~., data=mydata, trControl=crossvalidation, method="xgbTree",tuneGrid=parameters_grid)
model_xgboost
prediction <- predict(model_xgboost,mydata)
confusionMatrix(as.factor(mydata$Attrition),prediction)
saveRDS(model_xgboost,"xgboost_model.rds")
<file_sep>/Writing Function in R.R
setwd("C:\\Users\\<NAME>\\Desktop\\Practice Projects R\\Predicting Emp Attrition R Project Kindle Book\\Writing Function and Functional Programming with purrr")
data(iris)
# Arguments----
args(median)
# function (x, na.rm = FALSE, ...)
# NULL
median(iris$Sepal.Length,na.rm=TRUE)
args(rank)
# function (x, na.last = TRUE, ties.method = c("average", "first",
# "last", "random", "max", "min"))
# NULL
# 1st place: the largest positive value in iris$Sepal.Length is the smallest ("most negative") value in -iris$Sepal.Length.
rank(-iris$Sepal.Length, na.last = "keep", ties.method = "min")
# Converting Scripts to function:----
library(readr)
library(lubridate)
library(dplyr)
data_1990 <- read_csv("data_from_1990.csv") %>% filter(a<0) %>% mutate(c=a+b)
data_1991 <- read_csv("data_from_1991.csv") %>% filter(a<0) %>% mutate(c=a+b)
data_1992 <- read_csv("data_from_1992.csv") %>% filter(a<0) %>% mutate(c=a+b)
# Step1: Donot Run
data_year <- function(file_csv){ # argument is anything that changes between multiple rewrites
data_1990 <- read_csv("data_from_1990.csv") %>% filter(a<0) %>% mutate(c=a+b)
}
# Step2: Donot Run
data_year <- function(file_csv){
data_1990 <- read_csv(file_csv) %>% filter(a<0) %>% mutate(c=a+b)
}
# Step3:
data_year <- function(file_csv){
read_csv(file_csv) %>% filter(a<0) %>% mutate(c=a+b) # no need to assign the last value so assignment is removed
}
# example:
data_1993 <- data_year("data_from_1993.csv")
data_1994 <- data_year("data_from_1994.csv")
# The Process:
# 1. Make a template
# 2. Paste in the script
# 3. Choose the arguments
# 4. Replace specific values with argument names
# 5. Make specific varaible name more general
# 6. Remove a final assignment
# Update the function to return n_flips coin tosses
toss_coin <- function(n_flips) {
coin_sides <- c("head", "tail")
sample(coin_sides, n_flips, replace = TRUE) # sample argument takes what to chose from randomly, how many times to choose, with or without replace
}
# Generate 10 coin tosses
toss_coin(10)
# Update the function so heads have probability p_head
toss_coin <- function(n_flips, p_head) {
coin_sides <- c("head", "tail")
# Define a vector of weights
weights <- c(p_head, 1 - p_head)
# Modify the sampling to be weighted
sample(coin_sides, n_flips, replace = TRUE, prob = weights) #prob is also an argument in sample
}
# Generate 10 coin tosses
toss_coin(10, p_head = 0.8)
# function are like verbs (eg. select, arrange, mutate)----
# Error (VIMP)
mtcars %>% lm(mpg~.) #this will throw an error as pipe operator demands first argument of preceding function to be data
# No error as we corrected the error, now %>% can respond
run_regression <- function(data,formula){
lm(formula,data) #follow the function code of lm
}
run_regression(mtcars,mpg~.)
# or
mtcars %>% run_regression(mpg~.)
# Regression predicted values column adding----
run_reg_poisson <- function(data,formula){
glm(formula,data,family = poisson ) #checkout what family mean and how they are given what they are given
}
model_reg <- mtcars %>% run_reg_poisson(mpg~.)
mtcars %>% mutate(predicted_value=predict(model_reg,type = "response"))
#or
mtcars %>% mutate(predicted_value=predict(mtcars %>%
run_reg_poisson(mpg~.),type = "response"))
# Default Argument mention it in function argument----
# Cutting a vector by quantile: (Converting a numerical variable to categorical variable is called cutting)
?cut
# cut(x, breaks, labels = NULL, #NULL -> (]
# include.lowest = FALSE, right = TRUE, dig.lab = 3,
# ordered_result = FALSE, ...)
# (a,b) = a<x<b
# [a,b) = a<=x<b
cut_by_quantile <- function(x, n, na.rm, labels, interval_type) {
probs <- seq(0, 1, length.out = n + 1) # partitioning the probability
qtiles <- quantile(x, probs, na.rm = na.rm, names = FALSE)
right <- switch(interval_type, "(lo, hi]" = TRUE, "[lo, hi)" = FALSE)
cut(x, qtiles, labels = labels, right = right, include.lowest = TRUE)
}
cut_by_quantile(mtcars$mpg,n=4,na.rm=TRUE,labels=c("a1","a2","a3","a4"),interval_type = TRUE)
# [1] a3 a3 a3 a3 a2 a2 a1 a4 a3 a2 a2 a2 a2 a1 a1 a1 a1 a4 a4 a4 a3 a2 a1 a1 a2 a4 a4 a4 a2
# [30] a3 a1 a3
# Levels: a1 a2 a3 a4
# To minimise the line of code while execute the function we can use default values and values to choose from
# Set the categories for interval_type to "(lo, hi]" and "[lo, hi)"
cut_by_quantile_1 <- function(data_input, n = 5, na.rm = FALSE, labels = NULL,
interval_type = c("(lo, hi]", "[lo, hi)")) {
# Match the interval_type argument
interval_type <- match.arg(interval_type) # interesting
probs <- seq(0, 1, length.out = n + 1)
qtiles <- quantile(data_input, probs, na.rm = na.rm, names = FALSE)
right <- switch(interval_type, "(lo, hi]" = TRUE, "[lo, hi)" = FALSE)
cut(data_input, qtiles, labels = labels, right = right, include.lowest = TRUE)
}
cut_by_quantile_1(mtcars$mpg)
# Passing arguments between function:----
# can use pipe operator
# Challenge:
# 1. handling missing value
# use of elipses ... argument (this mean accept any other argument in to the function and
# pass it into the function that require it)
get_reciprocal <- function(x,na.rm=TRUE){
1/x
}
# Custom function inside another function
calc_harmonic_mean <- function(x, na.rm = FALSE) {
x %>%
get_reciprocal() %>%
mean(na.rm = na.rm)
}
mtcars %>% group_by(gear) %>%
summarise(Reciprocal_of_mean_mpg=calc_harmonic_mean(mpg,na.rm = TRUE))
mtcars$mpg
# elipses ...
# Swap na.rm arg for ... in signature and body
calc_harmonic_mean1 <- function(x, ...) {
x %>%
get_reciprocal() %>%
mean(...) %>%
get_reciprocal()
}
mtcars %>% group_by(gear) %>% summarise(Calc_hm=calc_harmonic_mean1(mpg,na.rm=TRUE))
# Checking Argument (providing error message) ----
# if the creater made mistake it is called bug
calc_with_error_msg <- function(data,na.rm=FALSE){
if(!is.numeric(data)){
stop("data is not of numeric class, it is of",class(data)," type.") # or warning
}else{data %>% log() %>% mean(na.rm=na.rm)
}
}
iris %>% group_by(Cutting_Var=cut(Sepal.Length,breaks = seq(min(Sepal.Length,na.rm=TRUE),max(Sepal.Length,na.rm=TRUE),by=1))) %>%
summarise(Mean_value=calc_with_error_msg(Species))
# This is assertion:
# Error: Problem with `summarise()` input `Mean_value`.
# x data is not of numeric class, it is offactor type.
# i Input `Mean_value` is `calc_with_error_msg(Species)`.
# i The error occured in group 1: Cutting_Var = "(4.3,5.3]".
# Run `rlang::last_error()` to see where the error occurred.
iris %>% group_by(Cutting_Var=cut(Sepal.Length,breaks = seq(min(Sepal.Length,na.rm=TRUE),max(Sepal.Length,na.rm=TRUE),by=1))) %>%
summarise(Mean_value=calc_with_error_msg(Sepal.Width))
library(assertive)
# Return Value and Scope:----
# Return value from a function----
# It is the last value when the body come to end
# But some times it is required to return early (this done using if and return statement inside it)
A <- c(1,2,3,4,5,6,7,NA)
B <- c(1,2,3,4,5,6,7)
simple_sum <- function(x){
if(anyNA(x)){
return(NA)
}else{
total <- 0
for(any_value in x){
total <- total+any_value}
total # or return(total)
}
}
simple_sum(B)
# With respect to scoping one good thing to remember is father cant know whats inside child but child can see whats inside father
# Returning invisibly (nothing gets printed in the console, good for graphs in which we need to make plots in Plots section)----
# When the main purpose of a function is to generate output, like drawing a plot or
# printing something in the console, you may not want a return value to be printed as
# well. In that case, the value should be invisibly returned.
pipeable_plot <- function(data, formula) {
# Call plot() with the formula interface
plot(formula, data)
# Invisibly return the input dataset
invisible(data)
}
# Nothing in console, everything in Plots
mtcars %>% pipeable_plot(mpg ~ gear)
# Returning multiple values from functions (we can do this by keeping variables in list ----
R.version.string
session <- function(){
list(
r_version=R.version.string,
operating_sys=Sys.info()[c("sysname","release")],
loaded_pkgs=loadedNamespaces()
)
}
session()
# Multiassignment operator with zeallot package (Similar to Python unpacking variables)
library(zeallot)
# we assign the variables inside c() the list outputs
c(Ransingh, Satyajit, Ray) %<-% session() # At a time we created 3 variable
attributes(iris$Species)
attributes(iris)
# dplyr has dataframe has input and dataframe as output----
# broom package : 1. glance -> degree of freedom, AIC, BIC etc
# 2. tidy -> p value
# 3. augment -> residuals
# broom package----
library(broom)
# We have created run_reg_poisson earlier
model_reg <- mtcars %>% run_reg_poisson(mpg~.)
groom_model <- function(model) {
list(
dof = glance(model),
coefficients_pvalue = tidy(model),
observations_residuals = augment(model)
)
}
# Call groom_model on model, assigning to 3 variables
c(mdl, cff, obs) %<-% groom_model(model_reg)
mdl
cff
obs
# Check if glance, tidy and augment also work on other models too?----
# Environment----
# childs are also called environment
<file_sep>/Predicting Employee Attrition_bagging.R
# Bagging involves creating multiple different models from a single dataset. It is important to understand
# an important statistical technique called bootstrapping in order to get an understnading of bagging
# Bootsraping involves multiple random subsets of a dataet being created. It is possible that the same data
# sample gets picked up in multiple subsets and this is termed as bootstap with replacement
# In bagging the actual training dataset is split into multiple bags through sampling with replacement
# asssuming thate we ended up with n bags when an ML algorithm is applied on each of these bags, we obtain
# we n different models. Each model is focused on one bag. When it comes to making predictions on new
# unseen data, each of these n models makes independent predictions on the data. A final prediction
# is arrived at by combining the predictions of the observations of all the n models.
#Classification -> voting
#Regression -> average
# Bagging is very effective to handle the high sensitivity to data changes.
# caret library provides a framework to implement bagging with any stand alone ML algorithm.
# ldaBag, plsBag, nbBag, treeBag,
setwd("C:/Users/DELL PC/Desktop/Practice Projects R/Predicting Emp Attrition R Project Kindle Book")
library(readr)
library(dplyr)
mydata <- read_csv("Raw_data_Emp_Att.csv")
mydata <- mydata %>% select(-EmployeeNumber,-EmployeeCount,-Over18, -StandardHours)
# setting up crossvalidation
crossvalidation <- trainControl(method="repeatedcv",number=10,repeats = 10)
set.seed(1200)
# bagging model
model.bagg <- train(Attrition~.,data=mydata,method="treebag",B=10,trControl=crossvalidation,importance=TRUE)
# prediction:
prediction <- predict(model.bagg,mydata)
# ConfusionMatrix:
confusionMatrix(as.factor(mydata$Attrition),prediction)
# saving the model
saveRDS(model.bagg,"treebagg.rds")
# loading the model
treebag <- readRDS("treebagg.rds")
# the accuracy got from the printing model directly is that of model developed on training data
# confusionMatrix accuracy is that model predicted value to the test values
# model accuracy is calculated on training data, but overfitting and underfitting is checked using the
# test data
<file_sep>/Principal Component Analysis and Clustering.R
# For PCA, following packages are used, FactoMineR, ade4, stats, cs, MASS and ExPosition
# FactoMineR > Performs PCA, MCA(Multiple Correspondence Analysis), FAMD(Factor Analysis of Mixed Data), MFA(Multiple Factor Analysis), HCPC (Hierarchical Clustering on Principal Components)
# > Provides the coordinates, the quality of representation and contribution of individual observation and varibles.
# > Predicts the result for supplimentary individual and variables.
# factoextra > produces ggplot2 based elegant data
# > simplifies cluster analysis and visualization
# Load FactoMineR----
library(FactoMineR)
library(factoextra)
# function of factorextra:----
# 1. Visualize PC method outputs (fviz_*)
# 2. Extracting data from PC method outputs (get_*)
# The amount of Variance retained by each principal components is measured by eigen value.
# PCA Method is useful when the variables within the dataset are highly correlated.
# Correlation represent the redundancy in the data. Due to this redundancy, PCA can be used to reduce
# the original variables into a smaller number of new variables explaining most of the variance in the
# original variables.
# The Main Purpose of PCA----
# 1. Identify hidden pattern in the data
# 2. Reduce the dimentionlaity and noise in the data
# 3. Identify the correlated variables.
data("decathlon2")
# Note that only some of these individuals and the variables will be used to perform the principal
# component analysis. The coordinates of the remaining individuals and the variables and variables on
# the factor map will be predicted after the PCA.
# Active Individual and Supplimentary Individual
decathlon2.active <- decathlon2[1:23,1:10]
# Data Standardization:----
# In the principal component analysis, variables are often scaled (standardized). This is particularly
# recommended when variables are measured in different scales otherwise the PCA outputs obtained will be
# severely affected.
# The PCA function in FactoMineR standardizes the data automatically during the PCA.
res.pca <- PCA(decathlon2.active,graph=TRUE) #ncp argument in it helps in determining the number of dimentions kept in final results.
print(res.pca)
# **Results for the Principal Component Analysis (PCA)**
# The analysis was performed on 23 individuals, described by 10 variables
# *The results are available in the following objects:
#
# name description
# 1 "$eig" "eigenvalues"
# 2 "$var" "results for the variables"
# 3 "$var$coord" "coord. for the variables"
# 4 "$var$cor" "correlations variables - dimensions"
# 5 "$var$cos2" "cos2 for the variables"
# 6 "$var$contrib" "contributions of the variables"
# 7 "$ind" "results for the individuals"
# 8 "$ind$coord" "coord. for the individuals"
# 9 "$ind$cos2" "cos2 for the individuals"
# 10 "$ind$contrib" "contributions of the individuals"
# 11 "$call" "summary statistics"
# 12 "$call$centre" "mean of the variables"
# 13 "$call$ecart.type" "standard error of the variables"
# 14 "$call$row.w" "weights for the individuals"
# 15 "$call$col.w" "weights for the variables"
res.pca$ind$coord
# Visualization:----
eig.val <- get_eigenvalue(res.pca)
eig.val
# Eigenvalues can be used to determine the number of principal components to retain after PCA.
# eigen value>1 indicates that the PCs account for more variance than accounted by one of the original
# variable in the standardized data. This is commonly used as a cutoff point for which PCs are retained.
# Unfortunately there is no well accepted objective way to decide how many principal components are enough.
# This will depend on the specific field of application and the specific data set.
# Scree Plot: to find contribution of each eigen vector to the variance explained in model
fviz_eig(res.pca,addlabels = TRUE,ylim=c(0,50))
# This function provides a list of matrices containing all the results for the active variables
var <- get_pca_var(res.pca) # This can also be got using PCA result and $ in it
var$coord # coefficient of the coordinates
var$cor # same as coord
var$contrib # % contribution of variables to the principal components
# Correlation Circle: correlation between the variables and the PCs----
fviz_pca_var(res.pca,col.var = "black")
# Positively correlated are in same quandrant
# Negatively are in opposite quadrant
# The correlation between the variables and the principal component can be found by the following machanism
# using the Cos2 component of var
library(corrplot)
corrplot(var$cos2,is.corr=FALSE)
# A high cos2(correlation of variable with PCs) indicate a good representation quality of the variable on principal components.
# The closer the vraiable is to the circle of correlations, the better the representation and
# variables that are closes to center of plot are less important for first component
# cos2 is square cosine
# color by cos2 values: quality on the factor map
fviz_pca_var(res.pca,col.var = "cos2",gradient.cols=c("#00AFBB","#E7B800","#FC4E07"),
repel = TRUE # Avoid text overlapping
)
# Variables that are correlated with PC1 and PC2 are the msot important in explaining the variablity
# in the dataset
# Vraibles that donot correlated with any PC might be removed to simplify overall analysis.
# Contribution of variables to PC1:
fviz_contrib(res.pca,choice="var",axes=1,top=10) #PC1
fviz_contrib(res.pca,choice="var",axes=2,top=10) #PC2
fviz_contrib(res.pca,choice="var",axes=1:2,top=10) #Total contribution to PC1 and PC2
# The total contribution for a given variable is calculated by,
# contrib= [(C1*Eig1)+(C2*Eig2)/(Eig1+Eig2)]
# Eig1, Eig2: eigen values are amount of variation retained by each PC.
# C1,C2: contribution of variables on PC1 and PC2
# It is also possible to change the color of the variables by group defined by variables
# factor grouping
# Process for showing the PC plot by coloring the variable grouping
# for grouping variables we use kmeans clustering
# Create a grouping variables using the kmeans
# Create 3 groups of variables (centers=3)
set.seed(123)
res.km <- kmeans(var$coord,centers=3,nstart=25)
grp <- as.factor(res.km$cluster)
#Color variables by group
fviz_pca_var(res.pca,col.var= grp, palette= c("#0073C2FF","#EFC000FF","#868686FF"),legend.title="Cluster")
# Dimention Description:
res.desc <- dimdesc(res.pca,axes=c(1,2),proba = 0.05)
# Desciption of dimention 1
res.desc$Dim.1
# Desciption of dimention 2
res.desc$Dim.2
# fviz_pca_var(res.pca,col.var= grp, palette= c("#0073C2FF","#EFC000FF","#868686FF"),legend.title="Cluster")
# this represent the variables but we can also see individual observations too
# We are establishing how closely each observation (row) is related to the principal components
fviz_pca_ind(res.pca,col.ind="cos2",gradient.cols=c("#00AFBB","#E7B800","#FC4E07"),repel = TRUE)
# Contribution of individual observation to PC1 and PC2.
fviz_contrib(res.pca,choice="ind",axes=1:2)
data("iris")
iris.pca <- PCA(iris[,-5],graph = FALSE)
fviz_pca_ind(iris.pca,col.ind=iris$Species,palette=c("#00AFBB","#EFB800","#FC4E07"),addEllipses = TRUE,legend.title="Groups")
fviz_pca_ind(iris.pca,geom.ind="point",col.ind=iris$Species,palette=c("#00AFBB","#EFB800","#FC4E07"),addEllipses = TRUE,legend.title="Groups")
# Biplot----
fviz_pca_biplot(res.pca,repel = TRUE,col.var = "#2E9FDF",col.ind = "#696969")
fviz_pca_biplot(iris.pca,
# Individual
geom.ind = "point",fill.ind = iris$Species,
col.ind = "black",pointshape=21,pointsize=2,palette = "jco",addEllipses = TRUE,
# Variable
alpha.var="contrib",
col.var = "contrib",
gradient.cols = "RdYlBu",
legend.title=list(fill="Species",color="Contrib",alpha="Contrib"))
<file_sep>/Functional Programming with purrr in R.R
setwd("C:\\Users\\<NAME>\\Desktop\\Practice Projects R\\Predicting Emp Attrition R Project Kindle Book\\Writing Function and Functional Programming with purrr")
#__________________________________PURRR_______________________________________________
#Lists can be difficult to both understand and manipulate, but they can pack a ton of information and are very powerful.
library(purrr)
# Using for loop----
#empty list that takes inputs from content within for loop
list_to_fill <- list()
for(i in seq_along(mtcars)){
list_to_fill[[i]] <- mean(mtcars[[i]])
}
list_to_fill
# using map
map(mtcars,mean) # This gives the same result
# _______________________________Index subsetting if list___________________________________
mtcars[1]
mtcars[[1]] #this gives list
mtcars[[1]][1]
library(dplyr)
map_df(mtcars,mean) %>% pivot_longer(cols=1:11,names_to = "Variables",values_to = "Mean")
df_rows <- data.frame(names=names(mtcars),rows=NA)
for(i in seq_along(mtcars)){
df_rows[i,'rows'] <- mean(mtcars[[i]])
}
df_rows
# map outputs a list
map_df(mtcars,~mean(.x)/sd(.x))
library(repurrrsive)
data("sw_films")
# sw_films is a list of dataframes
sw_films %>% set_names(map_chr(sw_films,"title"))
map_chr(sw_films,"title")
sw_films[[1]]$episode_id
# pipes with map.----
map_df(mtcars,~.x %>% sum() %>% log())
map_df(mtcars,~.x %>% sum(.) %>% log(.)) #always keep . within the function and always start with ~.x
map_df(mtcars,~mean(.)/sd(.))
map_df(mtcars,~.x %>% mean(.)/sd(.))
# creating list df----
sites <- list("north","east","west")
list_of_df <- map(sites,
~data.frame(sites = .x,
a = rnorm(mean = 5, n = 200, sd = (5/2)),
b = rnorm(mean = 200, n = 200, sd = 15)))
# Multiple linear equation on go----
list_of_df %>%
map(~.x %>% lm(a~b,data=.)) %>%
map(summary)
# getting specific output from regression model
library(broom)
list_of_df %>%
map(~.x %>% lm(a~b,data=.)) %>%
map(~.x %>% glance(.))
list_of_df %>%
map(~.x %>% lm(a~b,data=.)) %>%
map(~.x %>% tidy(.))
list_of_df %>%
map(~.x %>% lm(a~b,data=.)) %>%
map(~.x %>% augment(.))
# map2 when different input data are stored in 2 different list----
# List of 1, 2 and 3
means <- list(1,2,3)
# Create sites list
sites <- list("north","west","east")
# Map over two arguments: sites and means
list_of_files_map2 <- map2(sites, means, ~data.frame(sites = .x,
a = rnorm(mean = .y, n = 200, sd = (5/2))))
# # pmap when different input data are stored in more than 2 different list----
sites <- list("a","b","c","d")
means <- list(1,2,3,4)
sigma <- list(.1,.2,.3,.4)
means2 <- list(10,20,30,40)
sigma2 <- list(1,2,3,4)
# Create a master list, a list of lists
pmapinputs <- list(sites = sites, means = means, sigma = sigma,
means2 = means2, sigma2 = sigma2)
# Map over the master list
list_of_files_pmap <- pmap(pmapinputs,
function(sites, means, sigma, means2, sigma2)
data.frame(sites = sites,
a = rnorm(mean = means, n = 200, sd = sigma),
b = rnorm(mean = means2, n = 200, sd = sigma2)))
list_of_files_pmap
# safely----
list_of_df %>%
map(safely(function(x)lm(a~b,data=x)))
<file_sep>/Predicting Employee Attrition_boosting.R
# A weak learner is an algorithm that performs relatively poorly generally, the accuracy obtained with
# weak learners is just above chance. It is often if not always observed that the weak learners are computationally
# simple. Decison stumps or 1R algorithms are some example of weak learners.
# Boosting converts weak learners into strong learners.
# A boosting model is a sequence of models learned on subset of data similar to that of the bagging ensemble
# technique. The difference is in creation of subset of data.
# Unlike bagging all the subsets of data used for model training are not created prior to the start of the training
# Rather boosting builds a first model with an ML algo that does prediction on the entire dataset. Now there
# are some missclassified instances that are subsets and used by the second model. The second model
# only learns from this misclassified set of data curated from the first model's output.
# The second model's misclassified instance become input to the third model. The process of building model
# is repeated until the stopping criteria is met.
# The final prediction for an observation in the unseen datset is arrived by averaging or voting
# the prediction from all the models.
# GBM, AdaBoost, XGBoost, LightGBM
setwd("C:/Users/DELL PC/Desktop/Practice Projects R/Predicting Emp Attrition R Project Kindle Book")
library(readr)
library(dplyr)
library(caret)
mydata <- read_csv("Raw_data_Emp_Att.csv")
names(getModelInfo())
mydata <- mydata %>% select(-EmployeeNumber,-EmployeeCount,-Over18, -StandardHours)
# setting up crossvalidation
crossvalidation <- trainControl(method="repeatedcv",number=10,repeats = 10)
set.seed(1201)
# Converting the target variables and other categorical variable to numeric as the gbm model expect
# all numeric fields in the dataset
library(recipes)
my_data_updated <- recipe(Attrition~., data=mydata) %>%
step_dummy(all_nominal()) %>%
prep() %>% bake(new_data=mydata)
fit_control <- trainControl(method="cv",number=10)
tuneGrid <- expand.grid(n.trees=c(5,50,500),shrinkage=c(0.01,0.02),interaction.depth=c(1,2,3),n.minobsinnode=c(1,2,3))
model_gbm <- train(Attrition~., data=mydata, method="gbm",distribution="bernoulli",tuneGrid=tuneGrid,trcontrol=fit_control)
<file_sep>/Dplyr Concepts.R
###########################################################################
###########################################################################
### Companion code for book: DPLYR ###
### Author: <NAME> ###
### Open source ###
### ###
###########################################################################
###########################################################################
getwd()
setwd("C:/Users/DELL PC/Desktop/Practice Projects R/Predicting Emp Attrition R Project Kindle Book") #this will vary; change to fit your hard drive/subdirectory of choice
# rm(list = ls()) # clear the workspace
# BOOK REFERENCE: 001 -----------------------------------------------------
#install.packages("tidyverse") #uncomment the "install" code if
#you have never installed the tidyverse package. Then recomment.
# install.packages("tidyverse") #run installs one time only
# install.packages("lubridate")
# install.packages("stringr")
# install.packages("formattable") #this is optional. Merely improves
#the appearance of output
library(tidyverse) #load all of them into memory prior to running code
library(lubridate)
library(stringr)
library(formattable) # again, optional head function can be used here
# ----------------------------------------------------------------------------
library(tidyverse)
data("iris")
data("USArrests")
options(warn=0)
# BOOK REFERENCE: 002 -----------------------------------------------------
# Filter
# note to self -- use snagit to format the tables, with shadow
data("mtcars")
#select only cars with six cylinders
six.cyl.only <- filter(mtcars, cyl == 6)
# show first few records of the new dataframe
head(six.cyl.only)
#--------------------------------------------------------------------------------
# BOOK REFERENCE: 003 -----------------------------------------------------
six.cylinders.and.110.horse.power <- filter(mtcars, cyl == 6, hp == 110)
# show first few records of the new dataframe
formattable(six.cylinders.and.110.horse.power)
#-----------------------------------------------------------------------
# BOOK REFERENCE: 004 -----------------------------------------------------
data("ChickWeight")
#formattable(ChickWeight) #before
chick.subset <- filter(ChickWeight, Time < 6, weight > 50)
#formattable(chick.subset) #after
# ---------------------------------------------------------------------
# BOOK REFERENCE: 005 -----------------------------------------------------
gear.eq.4.or.more.than.8 <- filter(mtcars, gear == 4|cyl > 6) #OR
# formattable(gear.eq.4.or.more.than.8)
#filter based on smallest engine displacement
smallest.engine.displacement <- filter(mtcars, disp == min(disp))
#formattable(smallest.engine.displacement)
# ----------------------------------------------------------------------
# BOOK REFERENCE: 006 -----------------------------------------------------
data("airquality")
formattable(airquality)
no.missing.ozone = filter(airquality, !is.na(Ozone))
formattable(no.missing.ozone)
airquality.no.na = filter(airquality, complete.cases(airquality)) #we can use na.omit too
formattable(airquality.no.na)
# ------------------------------------------------------------------------
# BOOK REFERENCE: 007 -----------------------------------------------------
data("iris")
#before
table(iris$Species) #counts of species in the dataset
iris.two.species <- filter(iris, Species %in% c("setosa", "virginica"))
#after
table(iris.two.species$Species)
# another way to demonstrate that the filter worked
nrow(iris); nrow(iris.two.species)
# BOOK REFERENCE: 007B -----------------------------------------------------
data("airquality")
formattable(airquality)
airqual.3.columns = filter(airquality, Ozone > 29)[,1:3] #only rows with Ozone more than 29; include only first three columns
formattable(airqual.3.columns)
# --------------------------------------------------------------------------
# BOOK REFERENCE: 008 -----------------------------------------------------
nrow(mtcars)
mtcars.more.than.200 <- filter_all(mtcars, any_vars(. > 200)) #anyting, anywhere, more than 200
nrow(mtcars.more.than.200)
formattable(mtcars.more.than.200)
mtcars.even.starts.with.h <- filter_at(mtcars, vars(starts_with("h")), any_vars((. %% 2) == 0))
formattable(mtcars.even.starts.with.h)
nrow(mtcars.even.starts.with.h)
# ------------------------------------------------------------------------
# BOOK REFERENCE: 009 -----------------------------------------------------
table(mtcars$gear)
more.frequent.no.of.gears <- mtcars %>%
group_by(gear) %>%
filter(n() > 10)
table(more.frequent.no.of.gears$gear)
#additional criteria can be added to the filter
more.frequent.no.of.gears.and.low.horsepower <- mtcars %>%
group_by(gear) %>%
filter(n() > 10, hp < 105)
table(more.frequent.no.of.gears.and.low.horsepower$gear)
# -----------------------------------------------------------------
# BOOK REFERENCE: 010 & 011 -----------------------------------------------------
msleep <- ggplot2::msleep #loads the msleep dataframe from the package ggplot2
formattable(msleep)
msleep.over.5 <- msleep %>%
select(name, sleep_total:sleep_rem, brainwt:bodywt) %>%
filter_at(vars(contains("sleep")), all_vars(.>5))
formattable(msleep.over.5)
msleep <- ggplot2::msleep #loads the msleep dataframe from the package ggplot2
formattable(msleep[,1:4])
animal.name.sequence <- arrange(msleep, vore, order)
formattable(animal.name.sequence[,1:4])
animal.name.sequence.desc <- arrange(msleep, vore, desc(order))
formattable(animal.name.sequence.desc[,1:4])
# ---------------------------------------------------------------------------------
# BOOK REFERENCE: 012 -----------------------------------------------------
#rename - rename one or more columns in a dataset
names(iris) #iris is a built-in dataset
renamed.iris <- rename(iris, width.of.petals = Petal.Width, various.plants.and.animals = Species)
names(renamed.iris)
#----------------------------------------------------------------------------
# BOOK REFERENCE: 013 -----------------------------------------------------
#Mutate
data("ChickWeight")
formattable(ChickWeight[1:2,] ) #first two rows
Chickweight.with.log <- mutate(ChickWeight, log.of.weight = log10(weight))
formattable(Chickweight.with.log[1:2,]) #first two rows, with new field added
# ----------------------------------------------------------------------------
#put a 99 in front of the Diet number
ChickWeight[1:3,]
Chickweight.w.99 <- mutate(ChickWeight, new.diet.no = paste("99", Diet, sep = ""))
Chickweight.w.99[1:3,]
#Ifelse logic for mutate
data("airquality")
airquality[1:3,]
airquality.w.text <- mutate(airquality, very.high.wind = ifelse(Wind > 17,"Yes","No")) %>%
arrange(desc(very.high.wind))
airquality.w.text[1:4,]
# BOOK REFERENCE: 014 -----------------------------------------------------
msleep <- ggplot2::msleep #loads the msleep dataframe from the package ggplot2
names(msleep)
msleep.with.square.roots <- mutate_all(msleep[,6:11], funs("square root" = sqrt( . )))
names(msleep.with.square.roots)
formattable(msleep.with.square.roots)
msleep.with.square.roots[1:2,] #show first two rows of new dataframe
names(msleep.with.square.roots)
msleep.with.square.roots[1:2,]
# -----------------------------------------------------------------------------
# funs used when more than 1 columns. vars and funs go hand in hand
# # install.packages("stargazer")
# library(stargazer)
# # stargazer(mtcars, type = 'text', out = 'out.txt')
#
# stargazer(msleep.with.square.roots, type = "text", out = "out.txt")
mydata4 = mutate_at(mydata2, vars(Sepal.Length,Sepal.Width), funs(Rank=min_rank(desc(.))))
ls("package:datasets")
# BOOK REFERENCE: 015 -----------------------------------------------------
data("Titanic")
Titanic <- as.data.frame(Titanic)
formattable(Titanic)
titanic.with.ranks <- mutate_at(Titanic, vars(Class,Age,Survived),
funs(Rank = min_rank(desc(.))))
formattable(titanic.with.ranks)
msleep <- ggplot2::msleep #loads the msleep dataframe from the package ggplot2
#the package stringr is used below; it is automatically loaded with the library(tidyverse) command
# str_detect looks for the occurence of a designated string, anywhere in the field listed
class(msleep$sleep_total) # class function shows that the sleep_total variable is numeric
sleep.changed.variables <- msleep %>% mutate_if( (str_detect(colnames(.), "sleep")), as.character)
class(sleep.changed.variables$sleep_total) #class function now shows sleep_total variable is character
# ---------------------------------------------------------------------------
# BOOK REFERENCE: 016 -----------------------------------------------------
#create toy dataframe
fruit <- c("apple","pear","orange","grape", "orange","orange")
x <- c(1,2,4,9,4,6)
y <- c(22,3,4,55,15,9)
z <- c(3,1,4,10,12,8)
df <- data.frame(fruit,x,y,z)
formattable(df)
df.show.single.dup <- mutate(df, duplicate.indicator = duplicated(x))
formattable(df.show.single.dup) #note that although there are three instances of orange, only the second and third instances are flagged as TRUE duplicates
# ------------------------------------------------------------------------------------------------------------------------
# BOOK REFERENCE: 017 -----------------------------------------------------
#drop variables
#create toy dataframe
fruit <- c("apple","pear","orange","grape", "orange","orange")
x <- c(1,2,4,9,4,6)
y <- c(22,3,4,55,15,9)
z <- c(3,1,4,10,12,8)
df <- data.frame(fruit,x,y,z)
df <- mutate(df, z = NULL)
formattable(df)
# -----------------------------------------------------
# BOOK REFERENCE: 018 -----------------------------------------------------
# mutate guidelines
library(nycflights13) #not recommended but works
mutate(flights,
gain = arr_delay - dep_delay,
hours = air_time / 60,
gain_per_hour = gain / hours,
gain_per_minute = 60 * gain_per_hour)
library(nycflights13) #recommended
newfield.flights <- flights %>%
mutate(gain = arr_delay - dep_delay,
hours = air_time / 60) %>%
mutate(gain_per_hour = gain / hours) %>%
mutate(gain_per_minute = 60 * gain_per_hour)
newfield.flights[1:6,c(1:2,20:23)] #show selected columns for first six rows, including the newly created ones
# ---------------------------------------------------------------------------------------------
# BOOK REFERENCE: 019 -----------------------------------------------------
#transmute
#keep only variables created
#create toy dataframe
fruit <- c("apple","pear","orange","grape", "orange","orange")
x <- c(1,2,4,9,4,6)
y <- c(22,3,4,55,15,9)
z <- c(3,1,4,10,12,8)
df <- data.frame(fruit,x,y,z)
df
df <- transmute(df, new.variable = x + y + z)
#row "apple" =1 + 22 + 3 = 26
#row "pear" = 2 + 3 + 1 = 6 and so on
df
# -------------------------------------------------------
# BOOK REFERENCE: 020 -----------------------------------------------------
#create toy dataframe
fruit <- c("apple","pear","orange","grape", "orange","orange")
x <- c(1,2,4,9,4,6)
y <- c(22,3,4,55,15,9)
z <- c(3,1,4,10,12,8)
df <- data.frame(fruit,x,y,z) #before select
df
new.df.no.fruit <- select(df, -fruit) #put a minus sign in front of any #variable(s) to be dropped
new.df.no.fruit #after select
#------------------------------------------------------------
# BOOK REFERENCE: 021 -----------------------------------------------------
data("mtcars")
names(mtcars) #the names command lists column names in the dataframe
mtcars.no.col.names.start.with.d <- select(mtcars, -starts_with("d"))
names(mtcars.no.col.names.start.with.d) #show starting column names
mtcars.no.col.names.ends.with <- select(mtcars, - ends_with("t")) #drop drat and wt
names(mtcars.no.col.names.ends.with) #show column names after the select
# --------------------------------------------------------------------------
# BOOK REFERENCE: 022 -----------------------------------------------------
fruit <- c("apple","pear","orange","grape", "orange","orange")
x <- c(1,2,4,9,4,6)
y <- c(22,3,4,55,15,9)
z <- c(3,1,4,10,12,8)
df <- data.frame(fruit,x,y,z)
df
#to move column "z" to the extreme left (first column);
# sometimes it is more convenient to have frequently used columns on the left
df.new <- select(df,z, everything()) #the keyword "everything()" means that all remaining columns should be retained
df.new
# BOOK REFERENCE: 023 -----------------------------------------------------
#data on top 3 states by household income and other measures
# sources: US Census, New York Times and Wikipedia
state <- c("Maryland", "Alaska", "New Jersey")
income <- c(76067,74444,73702)
median.us <- c(61372,61372,61372)
life.expectancy <- c(78.8,78.3,80.3)
m.some.number <- c(33,11,44)
top.3.states <- data.frame(state, income, median.us, life.expectancy, m.some.number)
top.3.states #before
m.variables <- c(var1 = "median.us", var2 = "m.some.number")
only.m <- select(top.3.states, !!m.variables)
only.m #after
# --------------------------------------------------------------------
# BOOK REFERENCE: 024 -----------------------------------------------------
#select all
#applies a function to columns
top.3.states #before - column names are not capitalized
#capitalize column names, using the "toupper" function
new.top.3.states <- select_all(top.3.states, toupper)
new.top.3.states #after function "toupper" applied
# --------------------------------------------------------
# BOOK REFERENCE: 025 -----------------------------------------------------
state <- c("Maryland", "Alaska", "New Jersey")
income <- c(76067,74444,73702)
median.us <- c(61372,61372,61372)
life.expectancy <- c(78.8,78.3,80.3)
m.some.number <- c(33,11,44)
top.3.states <- data.frame(state, income, median.us, life.expectancy, m.some.number)
top.3.states #display dataframe values
pull.first.column <- pull(top.3.states,1) #get only first column, the state
pull.first.column #show contents of first column (in this case, the state)
# use a negative to pull a column from the right. -1 = rightmost column
pull.last.column <- pull(top.3.states,-1) #get only last column, m.some.number
pull.last.column #show contents of last column
# ------------------------------------------------------------
# BOOK REFERENCE: 026 -----------------------------------------------------
nrow(mtcars) #number of rows in original data frame
mtcars.more.than.200 <- filter_all(mtcars, any_vars(. > 200))
#anyting, anywhere, more than 200
nrow(mtcars.more.than.200)
#shows that only 16 rows met the criteria
#---------------------------------------------------
# BOOK REFERENCE: 027 -----------------------------------------------------
#select specified columns plus any column without a "p"
names(mtcars) #column names of mtcars dataframe
cars.with.no.p <- select(mtcars, mpg, everything(), -contains("p"))
names(cars.with.no.p) #names of dataframe columns after select statement
#No column name with a "p" anywhere is included in the new dataframe
# ---------------------------------------------------------------------------
# BOOK REFERENCE: 028 -----------------------------------------------------
#select using wildcard type matching
names(mtcars) #column names of built-in mtcars dataframe
#column name(s) selected contain the characters "pg" or "gea"
subset.mtcars <- select(mtcars,
matches("pg|gea"))
names(subset.mtcars)
# --------------------------------------------------------------------
# BOOK REFERENCE: 029 -----------------------------------------------------
# column -> pull, row -> slice
#slice
msleep <- ggplot2::msleep #loads the msleep dataframe from the package ggplot2
nrow(msleep) #initially 83 rows
msleep.only.first.6 <- slice(msleep, 1:6) #you do not have to know how many columns exist in the data frame. n() = total # of rows
nrow(msleep.only.first.6) #now only six rows - the first six rows of the dataframe
msleep.20.rows <- msleep %>%
slice(20:39)
nrow(msleep.20.rows)
#you can show the difference between the original and sliced data frame (or tibble) as follows:
nrow(msleep) - nrow(msleep.20.rows)
# ---------------------------------------------------------------------------------
# BOOK REFERENCE: 030 -----------------------------------------------------
#Left join: match both files using key (by = "key"); keep all records on left dataframe
# for any matching records on the right dataframe, add data to a new column to create
# the output dataframe
us.state.areas <- as.data.frame(cbind(state.abb, state.area))
us.state.areas[1:3,]
us.state.abbreviation.and.name <- as.data.frame(cbind(state.abb, state.name))
us.state.abbreviation.and.name[1:3,]
#match by state abbreviation using left join
#for illustration purposes, alter the abbreviation for Alabama; you will see a warning message
us.state.abbreviation.and.name[1,1] <- "Intentional Mismatch"
us.state.with.abbreviation.and.name.and.area <- left_join(us.state.areas, us.state.abbreviation.and.name,
by = "state.abb")
us.state.with.abbreviation.and.name.and.area[1:3,]
# BOOK REFERENCE: 031 -----------------------------------------------------
#inner join
#create first dataframe
names <- c("Sally","Tom","Frieda","Alfonzo")
team.scores <- c(3,5,2,7)
team.league <- c("alpha","beta","gamma", "omicron")
team.info <- data.frame(names, team.scores, team.league)
#create second dataframe
names = c("Sally","Tom", "Bill", "Alfonzo")
school.grades <- c("A","B","C","B")
school.info <- data.frame(names, school.grades)
school.and.team <- inner_join(team.info, school.info, by = "names")
school.and.team
#data appears on the school.and.team dataframe only when names match exactly
# BOOK REFERENCE: 032 -----------------------------------------------------
#antijoin - keeps all values from X with no match in y
# useful, for example, in a quality control review
# an individual in a firm's payroll table should have a match on
# a corresponding Human Resources table. Mismatch is an error
#create first dataframe
names <- c("Sally","Tom","Frieda","Alfonzo")
team.scores <- c(3,5,2,7)
team.league <- c("alpha","beta","gamma", "omicron")
team.info <- data.frame(names, team.scores, team.league)
team.info
#create second dataframe
names <- c("Sally","Tom", "Bill", "Alfonzo")
school.grades <- c("A","B","C","B")
school.info <- data.frame(names, school.grades)
school.info
team.info.but.no.grades <- anti_join(team.info, school.info, by = "names")
team.info.but.no.grades
# BOOK REFERENCE: 033 -----------------------------------------------------
#fulljoin - keeps all values from X and Y; puts NAs
# where appropriate
#create first dataframe
names = c("Sally","Tom","Frieda","Alfonzo")
team.scores = c(3,5,2,7)
team.league = c("alpha","beta","gamma", "omicron")
team.info = data.frame(names, team.scores, team.league)
#create second dataframe
names = c("Sally","Tom", "Bill", "Alfonzo")
school.grades = c("A","B","C","B")
school.info = data.frame(names, school.grades)
team.info.and.or.grades <- full_join(team.info, school.info, by = "names")
team.info.and.or.grades
# BOOK REFERENCE: 034 -----------------------------------------------------
#mutate_if
#eliminate factors
names = c("Sally","Tom","Frieda","Alfonzo")
team.scores = c(3,5,2,7)
team.league = c("alpha","beta","gamma", "omicron")
team.info = data.frame(names, team.scores, team.league)
str(team.info) #shows factors
team.info.no.factors <- mutate_if(team.info, is.factor, as.character)
str(team.info.no.factors)
# any NA in a numeric field is replaced by zero
df <- data.frame(
alpha = c(22, 1, NA),
almond = c(0, 5, 10),
grape = c(0, 2, 2),
apple = c(NA, 5, 10))
df
df.fix.alpha <- df %>% mutate_if(is.numeric, coalesce, ... = 0)
df.fix.alpha
new.df <- df %>% mutate_if((~max(.)==10 & str_detect(names(.), "al")), as.character)
new.df
x <- sample(c(1:5, NA, NA, NA))
coalesce(x, 44L)
# BOOK REFERENCE: 035 -----------------------------------------------------
#Right join:
# return all rows from y, and all columns from x and y. Rows in y with no match in x
# will have NA values in the new columns. If there are multiple matches between x and y,
# all combinations of the matches are returned.
us.state.areas <- as.data.frame(cbind(state.abb, state.area))
us.state.areas[1:3,]
us.state.abbreviation.and.name <- as.data.frame(cbind(state.abb, state.name))
us.state.abbreviation.and.name[1:3,]
#match by state abbreviation using left join
#for illustration purposes, alter the abbreviation for Alabama; you will see a warning message
us.state.abbreviation.and.name[1,1] <- "Intentional Mismatch"
us.state.with.abbreviation.and.name.and.area <- right_join(us.state.areas, us.state.abbreviation.and.name,
by = "state.abb")
us.state.with.abbreviation.and.name.and.area[1:3,]
# --------------------------------------------------------------------------------
# SOMETHING ELSE?????
#filter out any vore name with an "a" or a "c" anywhere in the name
# ! is the not equal symbol in R. str_detect is part of the stringr package
# which is automatically loaded using library(tidyverse)
msleep <- ggplot2::msleep #loads the msleep dataframe from the package ggplot2
table(msleep$vore)
msleep.no.c.or.a <- filter(msleep, !str_detect(vore, paste(c("c","a"), collapse = "|")))
table(msleep.no.c.or.a$vore)
head(msleep.no.c.or.a)
#mutate: add a field indicating whether a particular value in a column occurs more than once
# in this case, the column is conservation
msleep.with.dup.indicator <- mutate(msleep, duplicate.indicator = duplicated(conservation))
formattable(msleep.with.dup.indicator[1:6,]) #note new field, duplicate.indicator to the right. Logical True or False
msleep.with.dup.indicator2 <- mutate(msleep, duplicate.indicator = duplicated(conservation, genus)) %>%
arrange(conservation,genus)
formattable(msleep.with.dup.indicator2) #both conversation and genus have to be duplicated for the duplicate.indicator to be set to TRUE
# book reference: 036 -----------------------------------------------------
test <- c(3,11,6,88)
first(test)
last(test)
nth(test,2) #get second number
# -----------------------------------------------------------------------
# book reference: 037 -----------------------------------------------------
# RANKING
y <- c(100,4,12,6,8,3)
rank1 <-row_number(y)
rank1 #shows the vector index numbers corresponding to each rank
# [1] 6 2 5 3 4 1
y[rank1[1]] #lowest rank; in this case, rank1[1] points to y[6] which is 3 (lowest)
y[rank1[6]] #highest ranking number, in this case the first number, 100
#minimum rank
rank2 <- min_rank(y) #in this specific case (for y), gives same results as row_number
rank2
#dense rank
rank3 <- dense_rank(y)
rank3
#percent rank
rank4 <- percent_rank(y) #1st element of y is in the 100 percentile, 2nd element of y is in the 2 percentile
# the last element of y is in the 0 percentile
rank4
#cumulative distribution function. It shows the proportion of all values
# less than or equal to the current rank
rank5 <- cume_dist(y)
rank5
#breaks the input vector into n buckets
rank6 = ntile(y, 3) #in this case, choose 3 buckets
rank6
#note: the base R quantile function also has an easy to read output
test.vector <- c(2,22,33,44,77,89,99)
quantile(test.vector, prob = seq(0,1,length = 11),type = 5)
# -----------------------------------------------------------------------------------------------------
# book reference: 038 -----------------------------------------------------
#sampling
data("ChickWeight")
my.sample <- sample_n(ChickWeight, 5) #randomly sample 5 rows out of ChickWeight's 578 entries
my.sample
set.seed(833) #change this number each time you want the random function to produce the same results; otherwise, it will change from time to time
my.sample <- sample_n(ChickWeight, 10, replace = TRUE) #sampling with replacement = TRUE means that you could get the same row or element more than once
# whether to use True or False depends on your purpose. If you are investigating manufacturing defects, you might want to use replace = FALSE
# since you don't want to waste your time investigating the same defect again
my.sample
# in some cases sampling needs to be biased towards some higher impact data element. For example, if you are verifying the accuracy of invoices
# you may want to weight large dollar amounts more than smaller amounts. As a result you are more likely to get a high value invoice than one with a low dollar amount
#in this example, cars with more cylinders are more likely to be selected as part of the sample
my.sample <- sample_n(mtcars, 12, weight = cyl)
my.sample[,1:5]
x <-sample_frac(ChickWeight, 0.02) #sample 2% of the dataframe rows
x
by_hair_color <- starwars %>% group_by(hair_color)
my.sample <- sample_frac(by_hair_color, .07, replace = TRUE) #sample 7% with replacement
my.sample[,1:5]
# ----------------------------------------------------------------------------------
# Book reference: 039 -----------------------------------------------------
# tally & count
row.kount.only <- ChickWeight %>% tally() #provides only a count (578)
row.kount.only
diet.kount <- ChickWeight %>% count(Diet) #includes both group_by and tally. Convenient
diet.kount
# starwars example adapted from the DPLYR documentation (https://cran.r-project.org/web/packages/dplyr/dplyr.pdf)
# show only species that have a single member
# add_count is useful for groupwise filtering
single.species.kount <- starwars %>%
add_count(species) %>%
filter(n == 1)
single.species.kount[,1:6]
#-----------------------------------------------------------------------------------------------
# book reference: 040 -----------------------------------------------------
data(mtcars)
names(mtcars)
mtcars <- rename(mtcars, spam_mpg = mpg)
names(mtcars)
#-------------------------------------------------------------------------
# book reference: 041 -----------------------------------------------------
# not used
#-------------------------------------------------------------------------
# book reference: 042 -----------------------------------------------------
#case_when
#source:https://dplyr.tidyverse.org/reference/case_when.html
# case_when is particularly useful inside mutate when you want to
# create a new variable that relies on a complex combination of existing
# variables
new.starwars <- starwars %>%
select(name:mass, gender, species) %>%
mutate(
type = case_when(
height > 200 | mass > 200 ~ "large",
species == "Droid" ~ "robot",
TRUE ~ "other"
)
)
new.starwars
#--------------------------------------------------------------------------
# book reference: 043 -----------------------------------------------------
row1 <- c("a","b","c","d","e","f","column.to.be.changed")
row2 <- c(1,1,1,6,6,1,2)
row3 <- c(3,4,4,6,4,4,4)
row4 <- c(4,6,25,5,5,2,9)
row5 <- c(5,3,6,3,3,6,2)
df <- as.data.frame(rbind(row2,row3,row4,row5))
names(df) <- row1
df #original
new.df <-df %>%
mutate(column.to.be.changed = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~
2, a == 0 | a == 1 | a == 4 | a == 3 | c == 4 ~ 3,
TRUE ~ NA_real_))
#this is a series of "OR" conditions
#if any of them are true, then the last column (column.to.be.changed) will be
#either a 2 or a 3
new.df #modified
#----------------------------------------------------------------------
# book reference 044 ------------------------------------------------------
#Gathering
state <- c("Maryland", "Alaska", "New Jersey")
income <- c(76067,74444,73702)
median.us <- c(61372,61372,61372)
life.expectancy <- c(78.8,78.3,80.3)
teen.birth.rate.2015 <- c(17,29.3,12.1) #per 1,000 women (www.cdc.gov)
teen.birth.rate.2007 <- c(34.3,42.9,24.9)
teen.birth.rate.1991 <- c(54.1, 66, 41.3)
top.3.states <- data.frame(state, income, median.us, life.expectancy,
teen.birth.rate.2015, teen.birth.rate.2007, teen.birth.rate.1991)
names(top.3.states) <- c("state", "income", "median.us", "life.expectancy","2015","2007","1991")
top.3.states #before
# to put all three years in one column, use gather
new.top.3.states <- top.3.states %>%
gather("2015", "2007", "1991", key = "year", value = "cases")
new.top.3.states
#--------------------------------------------------------------------------
# book reference: 045 -----------------------------------------------------
# spread
df_1 <- data_frame(Type = c("TypeA", "TypeA", "TypeB", "TypeB"),
Answer = c("Yes", "No", NA, "No"),
n = 1:4)
df_1 #before
df_2 <- df_1 %>%
filter(!is.na(Answer)) %>%
spread(key=Answer, value=n)
df_2 #after
#-------------------------------------------------------------------
# Book reference: 046 -----------------------------------------------------
# separate
state <- c("Maryland", "Alaska", "New Jersey")
income <- c(76067,74444,73702)
median.us <- c(61372,61372,61372)
life.expectancy <- c(78.8,78.3,80.3)
teen.birth <- c("17//34.3//54.1", "29.0//42.9//66.0", "12.1//24.9//41.3")
#teen.birth as a column has three data elements per row, separated by a special
# character ("//")
top.3.states <- data.frame(state, income, median.us, life.expectancy,
teen.birth)
top.3.states #before: years 2015, 2007, and 1991 are combined in one column, "teen.birth"
top.3.states.separated.years <- top.3.states %>%
separate(teen.birth, into = c("2015", "2007","1991"), sep = "//")
top.3.states.separated.years #after
# --------------------------------------------------------------------------------
<file_sep>/All about visualization in R.R
# Visualization Centric Packages
library(ggplot2)
library(dplyr)
library(DataExplorer)
library(patchwork)
library(gganimate)
library(gapminder)
library(gifski)
setwd("C:\\Users\\DELL PC\\Desktop\\All about Visualization in R")
data("gapminder")
# Basic histogram with ggplot2----
# dataset:
data <- data.frame(value=rnorm(100))
# basic histogram
p <- ggplot(data, aes(x=value)) +
geom_histogram()
p
# Load dataset from github
data1 <- read.table("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/1_OneNum.csv", header=TRUE)
# plot
p1 <- data1 %>%
filter( price<300 ) %>%
ggplot( aes(x=price)) +
geom_histogram( binwidth=3, fill="#69b3a2", color="#e9ecef", alpha=0.9) +
ggtitle("Bin size = 3") +
theme_ipsum() +
theme(
plot.title = element_text(size=15)
)
p1
# Mirror density chart with ggplot2----
# Dummy data
data3 <- data.frame(
var1 = rnorm(1000),
var2 = rnorm(1000, mean=2)
)
# Chart
p3 <- ggplot(data3, aes(x=x) ) +
# Top
geom_density( aes(x = var1, y = ..density..), fill="#69b3a2" ) +
geom_label( aes(x=4.5, y=0.25, label="variable1"), color="#69b3a2") +
# Bottom
geom_density( aes(x = var2, y = -..density..), fill= "#404080") +
geom_label( aes(x=4.5, y=-0.25, label="variable2"), color="#404080") +
theme_ipsum() +
xlab("value of x")
p3
# Histogram with several groups - ggplot2----
# Build dataset with different distributions
data4 <- data.frame(
type = c( rep("variable 1", 1000), rep("variable 2", 1000) ),
value = c( rnorm(1000), rnorm(1000, mean=4) )
)
# Represent it
p4 <- data4 %>%
ggplot( aes(x=value, fill=type)) +
geom_histogram( color="#e9ecef", alpha=0.6, position = 'identity') +
scale_fill_manual(values=c("#69b3a2", "#404080")) +
theme_ipsum() +
labs(fill="")
p4
# Using small multiple
library(viridis)
library(forcats)
# Animation:----
# Get data:
# Charge libraries:
# library(ggplot2)
# library(gganimate)
# library(gifski)
# Make a ggplot, but add frame=year: one image per year
animate_1 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent)) +
geom_point() +
scale_x_log10() +
theme_bw() +
# gganimate specific bits:
labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
transition_time(year) + # time variables used for transition
ease_aes('linear')
# Save at gif:
animate(animate_1, duration = 5, fps = 20, width =500, height =500, renderer = gifski_renderer())
anim_save("output.gif")
# Make a ggplot, but add frame=year: one image per year
animate_2 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
geom_point(alpha = 0.7, show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
scale_x_log10() +
facet_wrap(~continent) +
labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
transition_time(year) +
ease_aes('linear')
# Save at gif:
animate(animate_2, duration = 5, fps = 20, width =500, height =500, renderer = gifski_renderer())
anim_save("output2.gif")
# Progressive line chart rendering
library(babynames)
library(hrbrthemes)
# Keep only 3 names
don <- babynames %>%
filter(name %in% c("Ashley", "Patricia", "Helen")) %>%
filter(sex=="F")
# Plot
annimate_3 <- don %>%
ggplot( aes(x=year, y=n, group=name, color=name)) +
geom_line() +
geom_point() +
scale_color_discrete() +
ggtitle("Popularity of American names in the previous 30 years") +
theme_ipsum() +
ylab("Number of babies born") +
transition_reveal(year)
animate(annimate_3, duration = 5, fps = 20, width =500, height =500, renderer = gifski_renderer())
anim_save("output1.gif")
<file_sep>/Predicting Employee Attrition_knn.R
# Averaging, majority vote, weighted average,
# consolidated learning
# multiple model + multiple subset of data
# snergy
setwd("C:\\Users\\DELL PC\\Desktop\\Practice Projects R\\Predicting Emp Attrition R Project Kindle Book")
library(rsample)
data("attrition")
library(dplyr)
library(ggplot2)
str(attrition)
mydata <- attrition
table(mydata$Attrition)
# Out of 1470 observations in the dataset, we have 1233 samples that are non attrition and 237 attrition cases.
# Clearly we are dealing with class imbalance dataset.
# considering only the numeric variables in dataset.
numeric_mydata <- select_if(mydata,is.numeric)
# converting the target variable "yes" or "no" values into numeric
# it defaults to 1 and 2 however converting it into 0 and 1 to be consistent
numeric_attrition <- as.numeric(mydata$Attrition)-1
# Creating a new dataframe with numeric columns and numeric target
numeric_mydata <- cbind(numeric_mydata,numeric_attrition)
# loading the corrplot library for conducting the correlation analysis
library(corrplot)
# Creating the correlation plot
M <- cor(numeric_mydata)
corrplot(M,method = "circle")
# High correlation between the independent variables indicates the existance of redundant features
# This is called multicolliearlity
# If we were to fit a regression model, then
# 1. removing the redundant features
# 2. apply PCA or
# 3. partial least square regression
# A. Overtime Vs Attrition:
l <- ggplot(mydata, aes(OverTime,fill=Attrition))
l <- l + geom_histogram(stat="count")
# Finding out what proportion of people working overtime get attrited, mean is applied on as.numeric(mydata$Attrition)-1
tapply(as.numeric(mydata$Attrition)-1, mydata$OverTime, mean)
print(l)
# B. MaritalStatus Vs Attrition:
l1 <- ggplot(mydata, aes(MaritalStatus,fill=Attrition))
l1 <- l1 + geom_histogram(stat="count")
# Finding out what proportion of MaritalStatus get attrited, mean is applied on as.numeric(mydata$Attrition)-1
tapply(as.numeric(mydata$Attrition)-1, mydata$MaritalStatus, mean)
print(l1)
# JobRole Vs Attrition:
l2 <- ggplot(mydata, aes(JobRole,fill=Attrition))
l2 <- l2 + geom_histogram(stat="count")
# Finding out what proportion of MaritalStatus get attrited, mean is applied on as.numeric(mydata$Attrition)-1
tapply(as.numeric(mydata$Attrition)-1, mydata$JobRole, mean)
print(l2)
# Gender Vs Attrition:
l3 <- ggplot(mydata, aes(Gender,fill=Attrition))
l3 <- l3 + geom_histogram(stat="count")
# Finding out what proportion of MaritalStatus get attrited, mean is applied on as.numeric(mydata$Attrition)-1
tapply(as.numeric(mydata$Attrition)-1, mydata$Gender, mean)
print(l3)
# EducationField Vs Attrition:
l4 <- ggplot(mydata, aes(EducationField,fill=Attrition))
l4 <- l4 + geom_histogram(stat="count")
# Finding out what proportion of MaritalStatus get attrited, mean is applied on as.numeric(mydata$Attrition)-1
tapply(as.numeric(mydata$Attrition)-1, mydata$EducationField, mean)
print(l4)
# Department Vs Attrition:
l5 <- ggplot(mydata, aes(Department,fill=Attrition))
l5 <- l5 + geom_histogram(stat="count")
# Finding out what proportion of MaritalStatus get attrited, mean is applied on as.numeric(mydata$Attrition)-1
tapply(as.numeric(mydata$Attrition)-1, mydata$Department, mean)
print(l5)
# BusinessTravel Vs Attrition:
l6 <- ggplot(mydata, aes(BusinessTravel,fill=Attrition))
l6 <- l6 + geom_histogram(stat="count")
library(patchwork)
(l1+l2+l3)/(l4+l5+l6)
# Finding out what proportion of MaritalStatus get attrited, mean is applied on as.numeric(mydata$Attrition)-1
tapply(as.numeric(mydata$Attrition)-1, mydata$BusinessTravel, mean)
print(l6)
# jitter plot:
ggplot(mydata, aes(OverTime, Age))+
facet_grid(.~MaritalStatus)+geom_jitter(aes(color=Attrition),alpha=0.5)+
ggtitle("x=OverTime, y=Age, z=MaritalStatus")+
theme_light()
# For imbalance datasets, Kappa or precision & recall or AUC of ROC are the appropriate metrics to use
library(caret)
# Removing the non-discriminatory features (as identified during EDA) from the dataset
library(readr)
mydata <- read_csv("Raw_data_Emp_Att.csv")
mydata <- mydata %>% select(-EmployeeNumber,-Over18,-EmployeeCount,-StandardHours)
# Setting the seed prior to model building to ensures reproducibility of the results obtained
set.seed(1000)
# Setting the train control parameters specifying gold standard 10 fold cross validation repeated 10 times
fitControl <- trainControl(method = "repeatedcv",number = 10,repeats = 10)
#knn model
# We pass the train control parameters and specify that knn algorithm need to be used to build the model
# we specify 20 as parameter which means the train command will search through 20 different random k values
# and finally retain the model that produces the best performance measurement.
knn_model <- train(Attrition~., data=mydata, trControl=fitControl, method="knn", tuneLength=20)
predicted_values <- predict(knn_model,mydata)
confusionMatrix(as.factor(mydata$Attrition),predicted_values)
# save the model to the disk
saveRDS(knn_model,"knn_model.rds")
# load the model
loaded_knn <- readRDS("knn_model.rds")
final_prediction <- predict(loaded_knn,mydata)
confusionMatrix(as.factor(mydata$Attrition),final_prediction)
<file_sep>/Predicting Employee Attrition_randomForest.R
setwd("C:/Users/<NAME>/Desktop/Practice Projects R/Predicting Emp Attrition R Project Kindle Book")
library(readr)
library(dplyr)
library(caret)
mydata <- read_csv("Raw_data_Emp_Att.csv")
names(getModelInfo())
mydata <- mydata %>% select(-EmployeeNumber,-EmployeeCount,-Over18, -StandardHours)
# setting up crossvalidation
crossvalidation <- trainControl(method="cv",number=10)
set.seed(1201)
tuneGrid <- expand.grid(mtry=c(5,7,10))
model_rf <- train(Attrition~.,data=mydata,trControl=crossvalidation,method="rf",tuneGrid=tuneGrid)
saveRDS(model_rf,"rf_model.rds")
| f0fcf9a3895494e32b264ade3c061cd0468b150d | [
"R"
] | 14 | R | Ransinghsatyajitray/Knowdege-ka-Pitara | d438a5404e0b6f50c815d6b67a6bcbbd4c62cf66 | 5a31b989e2f67b8aa58eb61210bc94d6b1e26518 |
refs/heads/master | <file_sep>import cPickle as pickle
from utils.inverted import InvertedIndex
from vptest import VPTree, jaccard, fingerprint
from flask import Flask, request
app = Flask(__name__)
app.debug = True
########## LOAD DATA STRUCTURES ##########
inverted = pickle.load(open("../data/org-inverted.pk", "rb" ))
searchtree = pickle.load(open("../data/org-vptree.pk", "rb" ))
########## ROUTES ##########
@app.route("/")
def index():
qs = str(request.args.get('qs'))
return str(inverted.search(qs))
#return str(searchtree.search(fingerprint(qs), 0.25))
########## MAIN ##########
if __name__ == "__main__":
app.run()<file_sep>import re, string
PUNCTUATION = re.compile('[%s]' % re.escape(string.punctuation))
def shingle(word, n):
'''
More on shingling here: http://blog.mafr.de/2011/01/06/near-duplicate-detection/
'''
return set([word[i:i + n] for i in range(len(word) - n + 1)])
def jaccard(a, b):
'''
Jaccard similarity between two sets.
Explanation here: http://en.wikipedia.org/wiki/Jaccard_index
'''
x = shingle(a, 3)
y = shingle(b, 3)
return 1.0 - (float(len(x & y) + 1) / float(len(x | y) + 1)) # Smoothing
def fingerprint(word, n=7):
return '%s' % ''.join(sorted(set(
list(PUNCTUATION.sub('', word.strip()).lower())[:n])
))
<file_sep>import operator
from collections import defaultdict
class InvertedIndex(object):
def __init__(self):
self.index = {}
def insert(self, tokens):
k, v = tokens
if not self.index.has_key(k):
self.index[k] = defaultdict(int)
self.index[k][v] += 1
return
def search(self, string):
return dict(self.index[string]) if self.index.has_key(string) else None
def search_top_n(self, string, n):
return sorted(self.search(string).iteritems(), key=operator.itemgetter(1), reverse=True)[:n] \
if self.index.has_key(string) else None<file_sep>pacstd
======
PAC Standard: An experiment in cleaning up dirty company names using metric trees.
WORK IN PROGRESS!
<file_sep>import re, collections
class SpellingModel(object):
def __init__(self):
self.model = collections.defaultdict(lambda: 1) # And-one smoothing
def train(self, features):
'''
Basically counts words.
'''
for f in features:
self.model[f] += 1
return
#P(c) = The number of times each variant appears in either the unstandardized or standardized field
#P(w|c) = 1 if there is a standardized name match; metric distance to closest match otherwise? Test that.
# Edit distance isn't going to work here because of massive variations in company spelling. "AT&T vs. TECHNICIAN/ATT"
# Need to use something like a metric tree instead to find candidate matches. Further, need something like
# a VP-tree to do continuous value search with Jaccard.
# Use a substring or ngram error model? What's the probability that they mean "<NAME>" if the input
# string contains "Covington" and so forth.
# Aggregate four models: Straight-up match + Norvig spellcheck based on prob. models + ngram/substr probs + acronym model
# One at a time. If not X certain after all those, hit up Yahoo. | d3edf6084a4820fbc4edd782968948fc6e11d997 | [
"Markdown",
"Python"
] | 5 | Python | pombredanne/pacstd | f1bd9a1f87fadff570fbf8ca6a37b74780cb622d | c186fd4d663808d052d1b89b7bb22a32205300b7 |
refs/heads/master | <file_sep># Lunar-Phase-Calculator-Swift-4
A simple function for the calculation of current lunar phase
<file_sep>//
// LunarPhaseCal.swift
// Lunar phase calculator
//
// Created by <NAME> on 1/2/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
class LunarPhaseCal {
private init() {}
static func moonPhaseNum() -> Double{
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let year = Double(components.year!)
let month = Double(components.month!)
let day = Double(components.day!)
let a = Int((year/100).rounded())
let b = Int(a/4)
let c = 2-a+b
let e = Int((365.25 * (Double(year)+4716)).rounded())
let f = Int((30.6001 * (Double(month)+1)).rounded())
let firstPart = c+Int(day)
let secondPart = e+f
let thirdPart: Double = Double(firstPart + secondPart)
let jd = thirdPart-1524.5
let daysSinceNewMoon = jd - 2451549.5
let newMoons: Double = daysSinceNewMoon/29.53
let daysIntoCycle = newMoons.truncatingRemainder(dividingBy: 1)
var current = Double(daysIntoCycle * 29.53).rounded(toPosition: 2)
if current > 2.1 {
current = current - 2.0
}
return current
}
}
extension Double {
func rounded(toPosition number:Int) -> Double {
let dividedBy = pow(10.0, Double(number))
let roundsTo = (self * dividedBy).rounded() / dividedBy
return roundsTo
}
}
| 6062f27680151c94acb70aac1b6afa9af97a0b35 | [
"Markdown",
"Swift"
] | 2 | Markdown | DavidPerezP124/Lunar-Phase-Calculator-Swift-4 | c20b437800ab1f81e9e2491cab1112c9eb1f81a3 | df2055d7dbd72eb423caed0daf2b35be8f56a880 |
refs/heads/master | <repo_name>ekyna/dockerized-rsyncd<file_sep>/build/entrypoint.sh
#!/bin/bash
set -e
if [[ "$1" == 'ssh-allow' ]]
then
sed -i \
-e 's/^PermitRootLogin prohibit-password/PermitRootLogin yes/g' \
/etc/ssh/sshd_config
supervisorctl -c /etc/supervisor.conf restart ssh
exit $?
elif [[ "$1" == 'ssh-deny' ]]
then
sed -i \
-e 's/^PermitRootLogin yes/PermitRootLogin prohibit-password/g' \
/etc/ssh/sshd_config
supervisorctl -c /etc/supervisor.conf restart ssh
exit $?
elif [[ "$1" == '/usr/bin/supervisord' ]]
then
if [[ -n ${TZ} ]] && [[ -f /usr/share/zoneinfo/${TZ} ]]
then
ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime
echo ${TZ} > /etc/timezone
fi
if [[ ! -e /data/mirror ]]
then
mkdir -p /data/mirror
fi
if [[ ! -e /data/full ]]
then
mkdir -p /data/full
fi
chown -R ${USER_ID}:${GROUP_ID} /data
eval "echo \"$(cat /etc/rsyncd.conf.tpl)\"" > /etc/rsyncd.conf
for f in /entrypoint.d/*
do
case "$f" in
*.sh) echo "$0: running $f"; . "$f" ;;
*) echo "$0: ignoring $f" ;;
esac
done
fi
exec "$@"
<file_sep>/build/Dockerfile
FROM alpine
MAINTAINER <NAME> <<EMAIL>>
COPY rsyncd.conf.tpl /etc/rsyncd.conf.tpl
COPY supervisord.conf /etc/supervisor.conf
COPY entrypoint.sh /
RUN apk --update add \
bash \
tzdata \
rsync \
openssh \
supervisor \
&& rm -rf /var/cache/apk/* \
&& mkdir /var/run/sshd \
&& mkdir -p /var/log/supervisor \
&& sed -i \
-e 's/^UsePAM yes/#UsePAM yes/g' \
-e 's/^#PermitRootLogin prohibit-password/PermitRootLogin prohibit-password/g' \
-e 's/^PasswordAuthentication yes/PasswordAuthentication no/g' \
-e 's/^#UseDNS yes/UseDNS no/g' \
/etc/ssh/sshd_config \
&& /usr/bin/ssh-keygen -A \
&& echo "root:root" | chpasswd \
&& chmod +x /entrypoint.sh \
&& mkdir -p /entrypoint.d
EXPOSE 22
EXPOSE 873
# Default environment variables
ENV TZ="Europe/Paris" \
LANG="C.UTF-8"
ENTRYPOINT [ "/entrypoint.sh" ]
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor.conf"]
<file_sep>/manage.sh
#!/bin/bash
cd "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [[ ! -f './.env' ]]
then
printf "\e[31mEnv file not found\e[0m\n"
exit 1;
fi
source ./.env
if [[ -z ${COMPOSE_PROJECT_NAME+x} ]]; then printf "\e[31mThe 'COMPOSE_PROJECT_NAME' variable is not defined.\e[0m\n"; exit 1; fi
if [[ -z ${READ_ONLY+x} ]]; then printf "\e[31mThe 'READ_ONLY' variable is not defined.\e[0m\n"; exit 1; fi
if [[ -z ${CHROOT+x} ]]; then printf "\e[31mThe 'CHROOT' variable is not defined.\e[0m\n"; exit 1; fi
if [[ -z ${HOSTS_ALLOW+x} ]]; then printf "\e[31mThe 'HOSTS_ALLOW' variable is not defined.\e[0m\n"; exit 1; fi
if [[ -z ${USER_ID+x} ]]; then printf "\e[31mThe 'USER_ID' variable is not defined.\e[0m\n"; exit 1; fi
if [[ -z ${GROUP_ID+x} ]]; then printf "\e[31mThe 'GROUP_ID' variable is not defined.\e[0m\n"; exit 1; fi
if [[ -z ${RSYNC_PORT+x} ]]; then printf "\e[31mThe 'RSYNC_PORT' variable is not defined.\e[0m\n"; exit 1; fi
if [[ -z ${SSH_PORT+x} ]]; then printf "\e[31mThe 'SSH_PORT' variable is not defined.\e[0m\n"; exit 1; fi
LOG_PATH="./log/docker.log"
echo "" > ${LOG_PATH}
Title() {
printf "\n\e[1;46m ----- $1 ----- \e[0m\n"
}
Success() {
printf "\e[32m$1\e[0m\n"
}
Error() {
printf "\e[31m$1\e[0m\n"
}
Warning() {
printf "\e[31;43m$1\e[0m\n"
}
Comment() {
printf "\e[36m$1\e[0m\n"
}
Help() {
printf "\e[2m$1\e[0m\n"
}
Ln() {
printf "\n"
}
DoneOrError() {
if [[ $1 -eq 0 ]]
then
Success 'done'
else
Error 'error'
exit 1
fi
}
Confirm () {
Ln
choice=""
while [[ "$choice" != "n" ]] && [[ "$choice" != "y" ]]
do
printf "Do you want to continue ? (N/Y)"
read choice
choice=$(echo ${choice} | tr '[:upper:]' '[:lower:]')
done
if [[ "$choice" = "n" ]]; then
Warning "Abort by user"
exit 0
fi
Ln
}
VolumeExists() {
if [[ "$(docker volume ls --format '{{.Name}}' | grep $1\$)" ]]
then
return 0
fi
return 1
}
VolumeCreate() {
printf "Creating volume \e[1;33m$1\e[0m ... "
if ! VolumeExists $1
then
docker volume create --name $1 >> ${LOG_PATH} 2>&1
if [[ $? -eq 0 ]]
then
Success "created"
else
Error "error"
exit 1
fi
else
Comment "exists"
fi
}
VolumeRemove() {
printf "Removing volume \e[1;33m$1\e[0m ... "
if VolumeExists $1
then
docker volume rm $1 >> ${LOG_PATH} 2>&1
if [[ $? -eq 0 ]]
then
Success "removed"
else
Error "error"
exit 1
fi
else
Comment "unknown"
fi
}
IsUpAndRunning() {
if [[ "$(docker ps --format '{{.Names}}' | grep ${COMPOSE_PROJECT_NAME}_$1\$)" ]]
then
return 0
fi
return 1
}
ComposeUp() {
printf "Composing \e[1;33mUp\e[0m ... "
docker-compose -f compose.yml up -d --build >> ${LOG_PATH} 2>&1
DoneOrError $?
}
ComposeDown() {
printf "Composing \e[1;33mDown\e[0m ... "
docker-compose -f compose.yml down -v --remove-orphans >> ${LOG_PATH} 2>&1
DoneOrError $?
}
CreateVolumes() {
VolumeCreate "${COMPOSE_PROJECT_NAME}_ssh"
VolumeCreate "${COMPOSE_PROJECT_NAME}_data"
}
RemoveVolumes() {
VolumeRemove "${COMPOSE_PROJECT_NAME}_ssh"
VolumeRemove "${COMPOSE_PROJECT_NAME}_data"
}
case $1 in
# -------------- UP --------------
up)
CreateVolumes
ComposeUp
;;
# ------------- DOWN -------------
down)
ComposeDown
;;
# ------------- DOWN -------------
clear)
Title "Clearing stack"
Confirm
ComposeDown
RemoveVolumes
;;
# ------------- DOWN -------------
ssh)
if [[ $2 == 'allow' ]]
then
printf "Allowing \e[1;33mssh password\e[0m ... "
export MSYS_NO_PATHCONV=1 && \
docker exec ${COMPOSE_PROJECT_NAME}_rsync bash -c \
"/entrypoint.sh ssh-allow" >> ${LOG_PATH} 2>&1
elif [[ $2 == 'deny' ]]
then
printf "Denying \e[1;33mssh password\e[0m ... "
export MSYS_NO_PATHCONV=1 && \
docker exec ${COMPOSE_PROJECT_NAME}_rsync bash -c \
"/entrypoint.sh ssh-deny" >> ${LOG_PATH} 2>&1
else
Help "Usage: ./manage.sh ssh [allow|deny]"
exit 1
fi
DoneOrError $?
;;
# ------------- HELP -------------
*)
Help "Usage: ./manage.sh [action] [options]
\e[0mup\e[2m Create network and volumes and start containers.
\e[0mdown\e[2m Stop containers."
;;
esac
| f0aa58a1ec1eeabab3f23ccef6e95574792274cb | [
"Dockerfile",
"Shell"
] | 3 | Shell | ekyna/dockerized-rsyncd | 97270d61a6b492ab68dd13dfcb9b3e31172ef801 | b7fcea564742f019ec2fd6b0c332b304ccaf3a09 |
refs/heads/master | <repo_name>Confalone/data-structures-and-algorithms<file_sep>/breadth-first-traversal/README.md
# Breadth-first Traversal
#### Traverse through a binary tree using breadth-first, printing every nodes value.
[]
## Challenge
* Write a function called breadthFirstTraversal which takes a Binary Tree as its unique input. Without utilizing any of the built-in methods available to your language, traverse the input tree using a Breadth-first approach; print every visited node’s value.
## Solution
<file_sep>/arrays/README.md
# data-structures-and-algorithms
# Reverse an Array
Given a set of numbers return the same set in reverse order.
## Challenge
Challenge was to handle an array of numbers and return the array in reverse order.
## Solution

<file_sep>/fifo_animal_shelter/README.md
# First-in, First out Animal Shelter.
Is an animal shelter that operates using a first in first out basis. This shelter only holds dogs and cats.
## Challenge
* `enqueue(animal)`: adds animal to the shelter `animal` can only be a dog or cat object
* `dequeue(pref)`: returns longest waiting dog or cat depending on what is asked for
## Solution
<file_sep>/fizz-buzz-tree/fizz-buzz-tree.test.js
'use strict';
const BinaryTree = require('../trees/lib/binary-tree');
const Node = require('../trees/lib/binary-tree');
const fizzBuzzTree = require('./fizzbuzztree');
let treeToTest = () => {
const one = new Node(1);
const two = new Node(2);
const three = new Node(3);
const four = new Node(4);
const five = new Node(5);
const six = new Node(6);
const seven = new Node(7);
const eight = new Node(8);
const nine = new Node(9);
const tree = new BinaryTree(one);
one.left = two;
one.right = three;
two.right = four;
three.right = five;
two.left = six;
four.right = seven;
four.left = eight;
five.left = nine;
return tree;
};
describe('fizzbuzztree', () => {
it('should return "Fizz" for values divisible by 3 ', () => {
let tree = treeToTest();
fizzBuzzTree(tree);
expect(tree.root.right.root).toBe(3);
});
});
<file_sep>/11_kth_from_end/__test__/11_kth_from_end.test.js
'use strict';
const LinkedList = require('./11_kth_from_end');
it('ll_kth_from_end(): should remove a chosen element from the ll', () => {
let list = new LinkedList();
list.append(6);
list.append(7);
list.append(8);
list.remove(1);
expect(list.head.value).toEqual(6);
expect(list.head.next.value).toEqual(8);
});
it('ll_kth_from_end: should throw an error if the offset value is larger than length of ll', () => {
let list = new LinkedList();
list.append(6);
list.append(7);
list.append(8);
expect(() => {
list.remove(10);
}).toThrow();
});
it('ll_kth_from_end(): should throw an error if the offset value is not a number', () => {
let list = new LinkedList();
list.append(6);
list.append(7);
list.append(8);
expect(() => {
list.remove('tyler');
}).toThrow();
});<file_sep>/multi-bracket-validation/README.md
# Multi-bracket Validation.
Returns TRUE or FALSE depending on if brackets match.
## Challenge
Using a function called MultiBracketValidation(input) take in a string and return a boolean TRUE or FALSE based on if they match. 3 types of brackets. round(), square[], curly{}.
## Solution
<file_sep>/find-maximum-value-binary-tree/README.md
[]
# find maximum value binary tree
The goal of this WB is to take in a binary tree and return the maximum value stored in the tree. The values stored in the Binary Tree will be numeric.
## Challenge
Take in a binary tree and return the maximum value stored in the tree. The values stored in the Binary Tree will be numeric.
## Solution
<file_sep>/ll_merge/README.md
# Merge two Linked Lists
This code takes in 2 linked lists. It returns one linked list that combines the 2 given linked lists, making every other node a number from each list.
## Challenge
<!-- Description of the challenge -->
## Solution
<file_sep>/arrays/array-shift/README.md
# Insert and shift middle index of array
Short summary or background information
took an array and an input; than took the input and put it in middle of the array
## Challenge
Description of the challenge
using no built in JS methods take an array and an input and change the array so the input is in the middle of the new array
## Solution
Embedded whiteboard image
<file_sep>/arrays/array-reverse.js
'use strict';
function reversed(array) {
let backwards = [];
for (let i = array.length - 1; i >= 0; i--) {
backwards.push(array[i]);
}
console.log(backwards);
return backwards;
}
reversed([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]);<file_sep>/fizz-buzz-tree/README.md
# FizzBuzz Tree
This takes in a tree and returns the tree replacing multiples of 3 with the word "fizz" and multiples of 5 with the word "buzz".
## Challenge
* Write a function called FizzBuzzTree which takes a tree as an argument.
* Without utilizing any of the built-in methods available to your language, determine weather or not the value of each node is divisible by 3, 5 or both, and change the value of each of the nodes respectively. Return the tree with it’s news values.
## Solution
<file_sep>/ll_insertions/__test__/ll_insertions.test.js
'use strict';
const LinkedList = require('../lib/ll_insertions');
describe('Linked list', () => {
it ('append: should append a node to the end of a linked-list.', () =>{
let list = new LinkedList();
list.append(4);
list.append(5);
list.append(6);
expect(list.head.value).toEqual(4);
expect(list.head.next.value).toEqual(5);
expect(list.head.next.next.value).toEqual(6);
expect(list.head.next.next.next).toEqual(null);
});
it('append: should throw an error if no value is given', () => {
let list = new LinkedList();
expect(() => {
list.append();
}).toThrow();
});
it('append: if linked list is empty, value should replace the head value', () => {
let list = new LinkedList();
list.append(9);
expect(list.head.value).toEqual(9);
});
it('insertBefore: node value passed in should replace value of the head node', () => {
let list = new LinkedList();
list.append(4);
list.insertBefore(3);
expect(list.head.value).toEqual(3);
expect(list.head.next.value).toEqual(4);
});
it('insertBefore: node should be prepended with a longer linked list', () => {
let list = new LinkedList();
list.append(4);
list.append(3);
list.append(2);
list.insertBefore(1);
expect(list.head.value).toEqual(1);
expect(list.head.next.value).toEqual(4);
});
it('insertBefore: should throw an error if no value is given', () => {
let list = new LinkedList();
expect(() => {
list.insertBefore();
}).toThrow();
});
it ('insertAfter: should append a node to the end of a linked-list.', () =>{
let list = new LinkedList();
list.append(4);
list.append(5);
list.insertAfter(6);
expect(list.head.value).toEqual(4);
expect(list.head.next.value).toEqual(5);
expect(list.head.next.next.value).toEqual(6);
expect(list.head.next.next.next).toEqual(null);
});
it('insertAfter: should throw an error if no value is given', () => {
let list = new LinkedList();
expect(() => {
list.insertAfter();
}).toThrow();
});
});<file_sep>/11_kth_from_end/README.md
[](https://travis-ci.com/Confalone/data-structures-and-algorithms)
# kth from the end of a Linked List
The goal of this WB is to write a linked list class which takes a number as a parameter and returns the node that is from the end of the linked list.
## Challenge
We are to write a method for the Linked List class which takes a number, k, as a parameter. Return the node that is k from the end of the linked list. you have access to tbhe node class and all the properties on the Linked List class as well as the methods created in previous challenges.
## Solution
<file_sep>/ll_insertions/README.md
[](https://travis-ci.com/Confalone/data-structures-and-algorithms)
## Linked List Insertions
###The goal of this WB is to manipulate a linked-list.
## Challenge
###Write the following methods for the Linked List class:
####.append(value)
####.insertBefore()
####.insertAfter()
## Solution
<file_sep>/linked-lists/README.md
[](https://travis-ci.com/Confalone/data-structures-and-algorithms)
# Linked List Data Structure - Big O
## Instructions
In order to use this app you must first: initialize npm, install jest, install travis.yml, install npm test. Enjoy and please let me know if I need to put more detailed instructions.
## Modules
* `append(value)` -
### Append takes a value adds the value onto the end of an list, and returns the new list. It has an O(n) because the length of the list can vary making the amount of time it takes to run vary.
```
append(value) { // BIG O -> O(n)
if(!value) {
throw 'Must provide a value';
}
let node = new Node(value);
if(!(this.head)) {
this.head = node;
return this;
}
let current = this.head;
while(current.next) {
current = current.next;
}
current.next = node;
return this;
}
```
* `prepend(value)`
### Prepend takes a value and adds it on the front of the list. It has an O(1) because it just needs to find the first element in the linked list.
```
prepend(value) { // BIG O -> O(1)
if(!value) {
throw 'Must provide a value';
}
let node = new Node(value);
node.next = this.head;
this.head = node;
}
```
* `reverse()`
### Reverse returns a new list that is in backwards order to the original list.
```
reverse() { // BIG O -> O(n)
let current = this.head;
let next = null;
let previous = null;
while(current) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
this.head = previous;
return this;
}
```
* `remove(offset)`
### remove(offset) takes an element off of a list and returns the new list.
```
remove(offset) { // BIG O(n)
let current = this.head;
let counter = 0;
let next = current.next;
let previous = null;
if(typeof offset !== 'number') throw 'offset must be a number';
while(counter !== offset) {
if(!current.next) throw 'the offset value must be smaller than the length of the Linked List ';
previous = current;
current = current.next;
next = current.next;
counter++;
}
if(this.head === current) {
this.head.next = null;
this.head = next;
} else {
current.next = null;
previous.next = next;
}
return this;
}
```
* `serialize()`
### Serialize converts an object to string form. Than returns the new serilaized string.
```
serialize() { // BIG O(n)
let arrayOfNodes = [];
let current = this.head;
while(current) {
arrayOfNodes.push(current.value);
current = current.next;
}
if(arrayOfNodes.length === 0) throw 'linked list is empty';
return JSON.stringify(arrayOfNodes);
}
```
* `deserialize()`
### Desrialize takes in a serilaized string and converts it to an object. Than returns the new object.
```
deserialize(string) { // BIG O(n)
if(!string) throw 'we need a string';
let data = JSON.parse(string);
for(let i = 0; i < data.length; i++) {
this.append(data[i]);
}
return this;
}
}
```<file_sep>/array_binary_search/README.md
<a href:="https://travis-ci.com/Confalone/data-structures-and-algorithms.svg?branch=master">
# Binary Search
find the key in an array and return the index the key is located in.
## Challenge
create javaScript code that takes in an array and a key than finds the key and returns the index the key is located in said array
## Solution
loop through an array; find key. figure out what part of array the key falls. return that index
## Challenge
using a key find the index it is placed in the array
## Solution

<file_sep>/trees/README.md
[](https://travis-ci.com/Confalone/data-structures-and-algorithms)
# Tree Data Structure
#### Author: <NAME>
## Data Structure: Binary Search Tree
#### Instructions:
How to make your BST:
```
let bst = new BST();
bst.insert(9);
bst.insert(16);
bst.insert(4);
bst.insert(10);
bst.insert(2);
```
### `insert` method:
Insert methods allows a number value to be inserted into the BST. An error will be thrown if input is a value other than a number.
ex:
```
expect(bst.root.value).toEqual(9);
expect(bst.root.right.value).toEqual(16);
expect(bst.root.right.left.value).toEqual(10);
expect(bst.root.left.value).toEqual(4);
expect(bst.root.left.left.value).toEqual(2);
```
### `find` method:
Find method searches the BST for a number value and returns said number value. An error will be thrown if input is a value other than a number.
ex:
```
expect(bst.find(9).value).toEqual(9);
expect(bst.find(16).value).toEqual(16);
expect(bst.find(4).value).toEqual(4);
expect(bst.find(10).value).toEqual(10);
expect(bst.find(2).value).toEqual(2);
```
### `serialize` method
Serialize converts an object to string form. Than returns the new serilaized string.
```
serialize() { // BIG O(n)
let arrayOfNodes = [];
let current = this.head;
while(current) {
arrayOfNodes.push(current.value);
current = current.next;
}
if(arrayOfNodes.length === 0) throw 'linked list is empty';
return JSON.stringify(arrayOfNodes);
}
```
### `deserialize` method
Desrialize takes in a serilaized string and converts it to an object. Than returns the new object.
```
deserialize(string) { // BIG O(n)
if(!string) throw 'we need a string';
let data = JSON.parse(string);
for(let i = 0; i < data.length; i++) {
this.append(data[i]);
}
return this;
}
}
```
License: MIT<file_sep>/trees/lib/binary-search-tree.js
'use strict';
const Node = require('./node');
module.exports = class BinarySearchTree {
constructor(root = null) {
this.root = root;
}
insert(value) { // BIG O = O(n) n = height of tree
if (typeof value != 'number') {
throw new TypeError('Value must be a number');
}
const node = this.root;
if (!node) {
this.root = new Node(value);
return;
}
let _insert = (node) => { // BIG O = O(n) n = height of tree
if (node.value === value) {
throw new TypeError('Value already exists');
}
if (value < node.value) {
if (node.left === null) {
node.left = new Node(value);
return;
} else if (node.left !== null) {
return _insert(node.left);
}
} else if (value >= node.value) {
if (node.right === null) {
node.right = new Node(value);
return;
} else if (node.right !== null) {
return _insert(node.right);
}
} else {
return null;
}
};
_insert(node);
}
_find(node, value) { // BIG O = O(n) n = height of the tree
if (!node) {
return null;
} else if (node.value === value) {
return node;
} else if (node.value < value) {
return this._find(node.right, value);
} else if (node.value > value) {
return this._find(node.left, value);
}
}
find(value) { // BIG O = O(n) n = height of the tree
return this._find(this.root, value);
}
serialize() { // BIG O(n) = height of the tree
let arrayOfNodes = [];
let current = this.head;
while(current) {
arrayOfNodes.push(current.value);
current = current.next;
}
if(arrayOfNodes.length === 0) throw 'BST is empty';
return JSON.stringify(arrayOfNodes);
}
deserialize(string) { // BIG O(n) = height of the tree
if(!string) throw 'we need a string';
let data = JSON.parse(string);
for(let i = 0; i < data.length; i++) {
this.append(data[i]);
}
return this;
}
};
<file_sep>/ll_detect_loop/README.md
# Identify a Circular Reference
Reverse LL. If head node has .next of null than its not a linked-list. False. If it is pointing to another element in the linked-list than it is a circular refence.
## Challenge
Utilize the Single-responsibility priniciple to determine if a Linked list has a circular shape or not. Return boolean False or True. Write three test assertions for each method. Ensure your tests are passing before you submit your solution.
## Solution
<file_sep>/linked-lists/__tests__/linked-list.test.js
'use strict';
const LinkedList = require('../lib/linked-list');
describe('Linked list', () => {
it ('append: should append a node to the end of a linked-list.', () =>{
let list = new LinkedList();
list.append(4);
list.append(5);
list.append(6);
expect(list.head.value).toEqual(4);
expect(list.head.next.value).toEqual(5);
expect(list.head.next.next.value).toEqual(6);
expect(list.head.next.next.next).toEqual(null);
});
it('append: should throw an error if no value is given', () => {
let list = new LinkedList();
expect(() => {
list.append();
}).toThrow();
});
it('append: if linked list is empty, value should replace the head value', () => {
let list = new LinkedList();
list.append(9);
expect(list.head.value).toEqual(9);
});
it('prepend: node value passed in should replace value of the head node', () => {
let list = new LinkedList();
list.append(4);
list.prepend(3);
expect(list.head.value).toEqual(3);
expect(list.head.next.value).toEqual(4);
});
it('prepend: node should be prepended with a longer linked list', () => {
let list = new LinkedList();
list.append(4);
list.append(3);
list.append(2);
list.prepend(1);
expect(list.head.value).toEqual(1);
expect(list.head.next.value).toEqual(4);
});
it('prepend: should throw an error if no value is given', () => {
let list = new LinkedList();
expect(() => {
list.prepend();
}).toThrow();
});
it('reverse: should return a reversed order of a list', () => {
let list = new LinkedList();
list.append(4);
list.append(3);
list.append(2);
list.reverse();
expect(list.head.value).toEqual(2);
expect(list.head.next.value).toEqual(3);
expect(list.head.next.next.value).toEqual(4);
expect(list.head.next.next.next).toBeNull();
});
it('reverse: if linked list has one value, it should return the same ll', () => {
let list = new LinkedList();
list.append(1);
list.reverse();
expect(list.head.value).toEqual(1);
expect(list.head.next).toBeNull();
});
it('remove(offset): should remove a chosen element from the ll', () => {
let list = new LinkedList();
list.append(6);
list.append(7);
list.append(8);
list.remove(1);
expect(list.head.value).toEqual(6);
expect(list.head.next.value).toEqual(8);
});
it('remove(offset): should throw an error if the offset value is larger than length of ll', () => {
let list = new LinkedList();
list.append(6);
list.append(7);
list.append(8);
expect(() => {
list.remove(10);
}).toThrow();
});
it('remove(offset): should throw an error if the offset value is not a number', () => {
let list = new LinkedList();
list.append(6);
list.append(7);
list.append(8);
expect(() => {
list.remove('tyler');
}).toThrow();
});
it('serialize: should convert an object to string form', () => {
let list = new LinkedList();
list.append(6);
list.append(7);
list.append(8);
let serialized = list.serialize();
expect(serialized).toEqual('[6,7,8]');
});
it('serialize: should throw an error if linked list is empty', () => {
let list = new LinkedList();
expect(() => {
list.serialize();
}).toThrow();
});
it('deserialize: should throw an error if a string is not provided', () => {
let list = new LinkedList();
expect(() => {
list.deserialize();
}).toThrow();
});
it('deserialize: should take a serialized string and convert it to an object', () => {
let list = new LinkedList();
list.append(6);
list.append(7);
list.append(8);
let serialized = list.serialize();
let secondList = new LinkedList();
secondList.deserialize(serialized);
expect(secondList).toEqual(list);
});
});<file_sep>/queue_with_stacks/README.md
# Implement a Queue using two Stacks.
####implement 2 methods
1. enqueue(value) which takes a value and using first in first out places it on the front of a stack
2. dequeue() using first in first out extract from the stack
## Challenge
Create a method that allows you to add on to the front of a stack & create another method that allows you to take something out of the stack.
## Solution
<file_sep>/array_adjacent_product/README.md
# Largest product of 2 adjacent values in a 2D array
take in a 2D array of numbers, multiply evvery number by its neighbor and return the largest product of adjacent neighbors
## Challenge
take in a 2D array, and return the largest adjacent values product
## Solution
<file_sep>/towers_of_Hanoi/README.md
# Towers of Hanoi
You are given 3 towers and an unkown number of disks. The disks are stacked with smallest on top in size order on the left tower. The disks must all be moved to the right tower, but a larger disk can never be placed on a smaller disk.
## Challenge
You must take the top smallest disk from the left colum and place it in the middle column. Thank you take the next disk from the left tower to the 3rd tower bypassing tower 2 where the smallest is. now u take the smallest from tower 2 to tower 3. now you take the third disk and place it in the second tower that is empty. smallest disk goes to tower 1.
## Solution
<file_sep>/queue_with_stacks/lib/queue_with_stacks.js
'use strict';
module.exports = class Queue {
makingStack() {
this.enqueueStack = [];
this.dequeueStack = [];
console.log('?', this.makingStack());
};
enqueue(val) {
this.enqueueStack.push(val);
return this.enqueueStack;
}
dequeue() {
this.dequeueStack.push(A);
this.dequeueStack.push(B);
this.dequeueStack.pop();
}<file_sep>/trees/test/binary-tree.test.js
'use strict';
const BinaryTree = require('../lib/binary-tree');
const Node = require('../lib/node');
describe('inOrder() of BinaryTree', () => {
it('Testing that inOrder() returns a string.', () => {
const t = new Node('T');
const y = new Node('Y');
const l = new Node('L');
const e = new Node('E');
const r = new Node('R');
const c = new Node('C');
const o = new Node('O');
const tree = new BinaryTree(t);
t.left = y;
t.right = l;
y.left = e;
y.right = r;
l.left = c;
l.right = o;
let value = tree.inOrder();
expect(typeof(value)).toBe('string');
});
it('expecting to receive the correct node values returned in order', () => {
const t = new Node('T');
const y = new Node('Y');
const l = new Node('L');
const e = new Node('E');
const r = new Node('R');
const c = new Node('C');
const o = new Node('O');
const tree = new BinaryTree(e);
e.left = y;
e.right = c;
y.left = t;
y.right = l;
c.left = r;
c.right = o;
let value = tree.inOrder();
expect(value).toBe('T,Y,L,E,R,C,O');
});
it('expects value to be undefined', () => {
const t = new Node('T');
const y = new Node('Y');
const l = new Node('L');
const e = new Node('E');
const r = new Node('R');
const c = new Node('C');
const o = new Node('O');
const tree = new BinaryTree(e);
e.left = y;
e.right = c;
y.left = t;
y.right = l;
c.left = r;
c.right = o;
let value = tree.inOrder();
expect(value).toBeDefined();
});
});<file_sep>/array_binary_search/__test__/array_binary_search.test.js
'use strict';
let BinarySearch = require('../array_binary_search.js');
describe('BinarySearch', () => {
it(' will find index of array at second place', () => {
expect(BinarySearch.BinarySearch([1, 2, 4, 5], 4)).toEqual(2);
});
it(' will find index of array', () => {
expect(BinarySearch.BinarySearch([1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12], 4)).toEqual(3);
});
it(' will return -1 is the key is not the array', () => {
expect(BinarySearch.BinarySearch([4,8,23,42], 16)).toEqual(-1);
});
}); | 22ffb1031598618ced6499c4920cdc4e31a93a29 | [
"Markdown",
"JavaScript"
] | 26 | Markdown | Confalone/data-structures-and-algorithms | f6d75f1ac08128de001060e5b446ef1076a335e4 | 0cbb0778c2b6da6659ba063e412820fd7deed337 |
refs/heads/master | <file_sep>local function add()
pcall(require, "cvar3")
if cvar3 or debug.getregistry().ConVar.SetValue then -- hack
local function SetConVar(cvar,val)
local cv = GetConVar(cvar)
if cv then
cv:SetValue(val)
else return false end
end
local function StripFlags(cvar,val)
cv:SetFlags(bit.band(cvar:GetFlags(), bit.bnot(val, 0)))
end
aowl.AddCommand("cvar", function(ply, _, cvar, val)
if not cvar or not val then return false, "invalid input" end
if SetConVar(cvar, val:Trim()) == false then return false, "convar does not exist" end
end, "developers")
aowl.AddCommand("stripflags", function(ply, _, cvar)
if not cvar then return false, "invalid input" end
local cv = GetConVar(cvar)
if not cv then return false, "convar does not exist" end
StripFlags(cvar, FCVAR_CHEAT)
end, "developers")
end
pcall(require, "sourcenetinfo")
if sourcenetinfo then
aowl.AddCommand("stoppackets",function(ply,_,who_r,time)
time = tonumber(time or "") or 5
time = math.ceil(time)
local who = easylua.FindEntity(who_r)
if not who then return false, aowl.TargetNotFound(who_r) end
timer.Create("ddos_" .. ply:UniqueID(), 0.001, time * 100, function()
if IsValid(who) then
who:GetNetChannel():Reset()
who:GetNetChannel():Transmit(false)
end
end)
timer.Simple(time, function()
if IsValid(who) then
who:GetNetChannel():Transmit(true)
end
end)
end, "developers")
end
end
if aowl then
add()
else
hook.Add("AowlInitialized","aowljunk",add)
end
<file_sep>AddCSLuaFile()
DoorSystem = {}
if SERVER then
DoorSystem.Interface = {}
local def = {}
for i = 0, 9, 1 do
def[i] = false
end
function DoorSystem:CleanInterface(sid)
local interface = self.Interface[sid]
if not (interface and interface.ents) then return false end
for k, v in next, interface.ents do
if not (v.ent and IsValid(v.ent)) then table.remove(self.Interface[sid].ents, k) end
end
return true
end
function DoorSystem:CreateDoor(ent, ply, channel)
if not (ent and not ent:IsWorld() and not ent:IsPlayer() and ply and ply:IsPlayer() and channel and isnumber(channel) and channel <= 10 and channel >= 0) then return false end -- Stop buggering
local sid = ply:SteamID()
if not self.Interface[sid] then self.Interface[sid] = {chan = def, ents = {}} end
self:CleanInterface(sid)
table.insert(self.Interface[sid].ents, {ent = ent, channel = channel})
ent:CallOnRemove("Door", function(s) DoorSystem:RemoveDoor(s) end)
undo.Create("Door")
undo.AddFunction(function(t, e) DoorSystem:RemoveDoor(e) end, ent)
undo.SetPlayer(ply)
undo.SetCustomUndoText("Undone Door Creation")
undo.Finish()
return true
end
function DoorSystem:RemoveDoor(ent)
print(self, ent)
if not (ent and not ent:IsWorld() and not ent:IsPlayer()) then return false end
self:CleanInterface(sid)
local interface = self.Interface
local found = false
for sid, v in next, interface do
for i, t in next, v.ents do
if t.ent == ent then
self:Fade(ent, false)
table.remove(self.Interface[sid].ents, i)
found = true
end
end
end
return found
end
function DoorSystem:CreateKeypad(trace, ply, channel, password)
return true
end
local _R = debug.getregistry()
function DoorSystem:Fade(ent, state)
if not (ent and not ent:IsWorld() and not ent:IsPlayer() and state ~= nil) then return false end
if state and not ent.IsFaded then
ent.fadeBackup = {["SetMaterial"] = ent:GetMaterial() or ""}
ent:SetCollisionGroup(COLLISION_GROUP_DEBRIS)
ent:SetMaterial("models/shadertest/shader3")
elseif not state and ent.IsFaded then
ent:SetMaterial("")
local t = _R.Entity
if ent.fadeBackup and t then
for k, v in next,ent.fadeBackup do
if t[k] then t[k](ent, istable(v) and unpack(v) or v) end
end
end
ent:SetCollisionGroup(COLLISION_GROUP_NONE)
else
return false
end
ent.IsFaded = state
return true
end
function DoorSystem:Toggle(ply, channel)
if not (ply and ply:IsPlayer() and channel and isnumber(channel) and channel <= 10 and channel >= 0) then return false end
local sid = ply:SteamID()
if not (self.Interface[sid] and self.Interface[sid].ents and #self.Interface[sid].ents > 0) then return false end
self:CleanInterface(sid)
local s = self.Interface[sid].chan[channel] -- State of channel
s = not s
self.Interface[sid].chan[channel] = s
for i, v in next, self.Interface[sid].ents do
local c = v.channel
if c ~= channel then continue end
local e = v.ent
DoorSystem:Fade(e, s)
end
return true
end
end
<file_sep>noclip_whitelist = noclip_whitelist or {
}
hook.Add("PlayerNoClip", "noclip_whitelist", function(p)
if noclip_whitelist[p:SteamID()] then
return true
end
end)
if SERVER then
util.AddNetworkString("noclip_whitelist")
local function send(ply)
net.Start("noclip_whitelist")
net.WriteTable(noclip_whitelist)
if ply then net.Send(ply) else net.Broadcast() end
end
local function whitelist(sid)
noclip_whitelist[sid] = true
send()
end
local function remove(sid)
noclip_whitelist[sid] = nil
send()
end
hook.Add("PlayerInitialSpawn", "noclip_whitelist", send)
if aowl then
aowl.AddCommand({"nc", "ncwhite", "whitelistnc"}, function(ply, line, target)
local ent = easylua.FindEntity(target)
if ent:IsPlayer() then whitelist(ent:SteamID()) end
end, "moderators")
aowl.AddCommand({"removenc", "ncremove"}, function(ply, line, target)
local ent = easylua.FindEntity(target)
if ent:IsPlayer() then remove(ent:SteamID()) end
end, "moderators")
end
else
net.Receive("noclip_whitelist", function()
noclip_whitelist = net.ReadTable()
end)
end
<file_sep>hook.Add("PhysgunPickup", "parent_fix", function(p, e)
if e:GetParent():IsValid() then return false end
end)
<file_sep>lifesupport = {} -- fucking local variables, are you serious
-- This exposes internal LS stuff to global table
lifesupport.Temp_Min = 0
lifesupport.FairTemp_Min = 283
lifesupport.FairTemp_Max = 308
lifesupport.Temp_Max = 546
lifesupport.environment = {}
lifesupport.environment.o2 = 0
lifesupport.environment.temperature = 0
lifesupport.suit = {}
lifesupport.suit.o2 = 0
lifesupport.suit.coolant = 0
lifesupport.suit.energy = 0
hook.Add("InitPostEntity", "lifesupport_override", function()
local function LS_umsg_hook1(um)
lifesupport.environment.o2 = um:ReadFloat()
lifesupport.suit.o2 = um:ReadShort()
lifesupport.environment.temperature = um:ReadShort()
lifesupport.suit.coolant = um:ReadShort()
lifesupport.suit.energy = um:ReadShort()
end
usermessage.Hook("LS_umsg1", LS_umsg_hook1)
local function LS_umsg_hook2(um)
lifesupport.suit.o2 = um:ReadShort()
end
usermessage.Hook("LS_umsg2", LS_umsg_hook2)
local ScH = ScrH()
local MidW = ScrW() / 2
local huds = {}
--Hud 1
local hud1 = {}
hud1.ScH = ScH;
hud1.MidW = MidW;
hud1.Left = hud1.MidW - 80 --70
hud1.Left2 = hud1.MidW - 90 --80
hud1.Right = hud1.MidW + 80 --70
hud1.H1 = hud1.ScH / 8
hud1.H2 = hud1.ScH - hud1.H1
hud1.H3 = hud1.H1 - 5
hud1.TH = { hud1.H2 + 5, hud1.H2 + 20, hud1.H2 + 35, hud1.H2 + 50 }
hud1.Font = "LS3HudHeader"
huds[1] = hud1
hud1 = nil
--Hud2
local hud2 = {}
hud2.ScH = ScH;
hud2.MidW = MidW;
hud2.Width = 224
hud2.Height = 128
hud2.Bottom = hud2.ScH - 32
hud2.Top = hud2.Bottom - hud2.Height
hud2.HalfWidth = math.Round(hud2.Width/2)
hud2.Left = hud2.MidW - hud2.HalfWidth
hud2.Rounding = 8
hud2.Top2 = hud2.ScH + 8
hud2.Font = "LS3HudHeader"
hud2.Font2 = "LS3HudSubtitle"
hud2.Font3 = "LS3HudSubSubtitle"
huds[2] = hud2
hud2 = nil
local colors = {}
colors.White = Color(225,225,225,255)
colors.Black = Color(0,0,0,100)
colors.Cold = Color(0,225,255,255)
colors.Hot = Color(225,0,0,255)
colors.Warn = Color(255,165,0,255)
colors.Grey = Color(150, 150, 150, 255)
colors.Green = Color(0, 225, 0, 255);
local MaxAmounts = 4000
local MaxAmountsDivide = MaxAmounts/100
local Display_temperature = GetConVar("LS_Display_Temperature")
local Display_hud = GetConVar("LS_Display_HUD")
local function lifesupport_HUDPaint()
if GetConVarString('cl_hudversion') == "" then
local ls_sb_mode = false;
if CAF.GetAddon("Spacebuild") and CAF.GetAddon("Spacebuild").GetStatus() then
ls_sb_mode = true;
end
local ply = LocalPlayer()
if not ply or not ply:Alive() or (IsValid(ply:GetActiveWeapon()) and ply:GetActiveWeapon():GetClass():match("camera")) then return end
local hud_to_use = Display_hud:GetInt()
if hud_to_use ~= 0 then
if not ls_sb_mode then
if ply:WaterLevel() > 2 then
local Air = lifesupport.suit.o2 / MaxAmountsDivide
local valcol = colors.White
if Air < 4 then valcol = colors.Warn end
local hud = huds[1]
local air_time_left = math.floor(lifesupport.suit.o2 / 5)
draw.RoundedBox( 8, hud.Left2 , hud.H2, 180, 20, colors.Black)
draw.DrawText( CAF.GetLangVar("Air")..":", hud.Font, hud.Left, hud.H2 + 5, colors.White, 0 )
draw.DrawText( tostring(Air).."% ("..tostring(air_time_left).."s)", hud.Font, hud.Right,hud.H2 + 5, valcol, 2 )
end
else
if ply:WaterLevel() > 2 or
lifesupport.environment.o2 < 5 or
(lifesupport.environment.temperature > 0 and not (lifesupport.environment.temperature >= lifesupport.FairTemp_Min and lifesupport.environment.temperature <= lifesupport.FairTemp_Max)) or
(ply.LSHudOn and ply.LSHudOn == true) then
if hud_to_use == 2 then
local hud = huds[2]
--[[
Draw Left Side
]]
draw.RoundedBox( hud.Rounding, hud.Left , hud.Top, hud.HalfWidth, hud.Height, colors.Black)
surface.SetFont( hud.Font )
local width, height = surface.GetTextSize(CAF.GetLangVar("Suit"))
if width == nil or height == nil then return end
local top = hud.Top
draw.DrawText( CAF.GetLangVar("Suit"), hud.Font, hud.Left + 64 - math.floor(width/2) , top , colors.White, 0 )
top = top + 16
--Oxygen
--top = top + 2
draw.DrawText( CAF.GetLangVar("Air"), hud.Font2, hud.Left + 16, top , colors.White, 0 )
top = top + 16 --18
local Air = lifesupport.suit.o2 / MaxAmountsDivide
top = top + 4
draw.RoundedBox( 0, hud.Left + 16 , top , 8, 10, colors.Hot) -- 0 -> 10
draw.RoundedBox( 0, hud.Left + 24 , top , 12, 10, colors.Warn) -- 10 -> 25
draw.RoundedBox( 0, hud.Left + 36 , top , 60, 10, colors.Green) -- 25 -> 100
surface.SetFont( hud.Font3 )
local air_text = tostring(Air).."%"
width, height = surface.GetTextSize(air_text)
draw.DrawText( air_text, hud.Font3, hud.Left + 16 + 40 - math.floor(width/2) , top , colors.White, 0 ) -- top +6
-- =((8 + 12 + 60)/2)
if Air > 100 then
Air = 100
end
local air_pos = hud.Left + 16 + math.Round(Air * 0.8) --1.6
draw.RoundedBox( 0, air_pos , top -2, 1, 10, colors.Grey)
draw.RoundedBox( 2, air_pos - 3 , top - 4, 6, 6, colors.Grey)
top = top + 8
draw.RoundedBox( 2, air_pos - 3 , top, 6, 6, colors.Grey)
top = top + 4
--Energy
--top = top + 2
draw.DrawText( CAF.GetLangVar("Energy"), hud.Font2, hud.Left + 16, top , colors.White, 0 )
top = top + 16
local Energy = lifesupport.suit.energy / MaxAmountsDivide
top = top + 4
draw.RoundedBox( 0, hud.Left + 16 , top , 8, 10, colors.Hot) -- 0 -> 10
draw.RoundedBox( 0, hud.Left + 24 , top , 12, 10, colors.Warn) -- 10 -> 25
draw.RoundedBox( 0, hud.Left + 36 , top , 60, 10, colors.Green) -- 25 -> 100
surface.SetFont( hud.Font3 )
local energy_text = tostring(Energy).."%"
width, height = surface.GetTextSize(energy_text)
draw.DrawText( energy_text, hud.Font3, hud.Left + 16 + 40 - math.floor(width/2) , top , colors.White, 0 )
if Energy > 100 then
Energy = 100
end
local energy_pos = hud.Left + 16 + math.Round(Energy * 0.8)
draw.RoundedBox( 0, energy_pos , top , 1, 10, colors.Grey)
draw.RoundedBox( 2, energy_pos - 3 , top - 4, 6, 6, colors.Grey)
top = top + 8
draw.RoundedBox( 2, energy_pos - 3 , top, 6, 6, colors.Grey)
top = top + 4
--Coolant
--top = top + 2
draw.DrawText( CAF.GetLangVar("Coolant"), hud.Font2, hud.Left + 16, top , colors.White, 0 )
top = top + 16
local Coolant = lifesupport.suit.coolant / MaxAmountsDivide
top = top + 4
draw.RoundedBox( 0, hud.Left + 16 , top , 33, 10, colors.Hot) -- 0 -> 10
draw.RoundedBox( 0, hud.Left + 24 , top , 12, 10, colors.Warn) -- 10 -> 25
draw.RoundedBox( 0, hud.Left + 36 , top , 60, 10, colors.Green) -- 25 -> 100
surface.SetFont( hud.Font3 )
local coolant_text = tostring(Coolant).."%"
width, height = surface.GetTextSize(coolant_text)
draw.DrawText( coolant_text, hud.Font3, hud.Left + 16 + 40 - math.floor(width/2) , top , colors.White, 0 )
if Coolant > 100 then
Coolant = 100
end
local coolant_pos = hud.Left + 16 + math.Round(Coolant * 0.8)
draw.RoundedBox( 0, coolant_pos , top , 1, 10, colors.Grey)
draw.RoundedBox( 2, coolant_pos - 3 , top - 4, 6, 6, colors.Grey)
top = top + 8
draw.RoundedBox( 2, coolant_pos - 3 , top, 6, 6, colors.Grey)
top = top + 4
--[[
Draw Right Side
]]
top = hud.Top
draw.RoundedBox( hud.Rounding, hud.Left + hud.HalfWidth , hud.Top, hud.HalfWidth, hud.Height, colors.Black)
surface.SetFont( hud.Font )
width, height = surface.GetTextSize(CAF.GetLangVar("Environment"))
draw.DrawText( CAF.GetLangVar("Environment"), hud.Font, hud.Left + hud.HalfWidth + 64 - math.floor(width/2), top , colors.White, 0 )
top = top + 16
--Temperature
--top = top + 2
draw.DrawText( CAF.GetLangVar("Temperature"), hud.Font2, hud.Left + hud.HalfWidth + 16, top , colors.White, 0 )
top = top + 16 --18
top = top + 4
draw.RoundedBox( 0, hud.Left + hud.HalfWidth + 16 , top , 32, 10, colors.Cold) -- 0 -> 273
draw.RoundedBox( 0, hud.Left + hud.HalfWidth + 16 + 32 , top , 3, 10, colors.Warn) -- 273 -> 283
draw.RoundedBox( 0, hud.Left + hud.HalfWidth + 16 + 32 + 3 , top , 6, 10, colors.Green) -- 283 -> 308
draw.RoundedBox( 0, hud.Left + hud.HalfWidth + 16 + 32 + 3 + 6 , top , 3, 10, colors.Warn) -- 308 ->318
draw.RoundedBox( 0, hud.Left + hud.HalfWidth + 16 + 32 + 3 + 6 + 3 , top , 20, 10, colors.Hot) -- 318 ->546
surface.SetFont( hud.Font3 )
--local air_text = tostring(Air).."%"
--width, height = surface.GetTextSize(air_text)
--draw.DrawText( air_text, hud.Font3, hud.Left + hud.HalfWidth + 16 + 40 - math.floor(width/2) , top , colors.White, 0 ) -- top +6
-- =((8 + 12 + 60)/2)
local temp = lifesupport.environment.temperature
temp = temp - 136.5
if temp > 444.6 then
temp = 444.6
elseif temp < 0 then
temp = 0
end
local temp2 = (temp / 273) * 100
local temp_pos = hud.Left + hud.HalfWidth + 16 + math.Round(temp2 * 0.8) --1.6
draw.RoundedBox( 0, temp_pos , top -2, 1, 10, colors.Grey)
draw.RoundedBox( 2, temp_pos - 3 , top - 4, 6, 6, colors.Grey)
top = top + 8
draw.RoundedBox( 2, temp_pos - 3 , top, 6, 6, colors.Grey)
top = top + 4
--Pressure
--top = top + 2
draw.DrawText( CAF.GetLangVar("Pressure"), hud.Font2, hud.Left + hud.HalfWidth + 16, top , colors.White, 0 )
top = top + 16
local Energy = lifesupport.suit.energy / MaxAmountsDivide
top = top + 4
draw.RoundedBox( 0, hud.Left + 16 + hud.HalfWidth , top , 8, 10, colors.Hot) -- 0 -> 10
draw.RoundedBox( 0, hud.Left + 24 + hud.HalfWidth , top , 12, 10, colors.Warn) -- 10 -> 25
draw.RoundedBox( 0, hud.Left + 36 + hud.HalfWidth , top , 60, 10, colors.Green) -- 25 -> 100
surface.SetFont( hud.Font3 )
local energy_text = tostring(Energy).."%"
width, height = surface.GetTextSize(energy_text)
draw.DrawText( energy_text, hud.Font3, hud.Left + hud.HalfWidth + 16 + 40 - math.floor(width/2) , top , colors.White, 0 )
if Energy > 100 then
Energy = 100
end
local energy_pos = hud.Left + hud.HalfWidth + 16 + math.Round(Energy * 0.8)
draw.RoundedBox( 0, energy_pos , top , 1, 10, colors.Grey)
draw.RoundedBox( 2, energy_pos - 3 , top - 4, 6, 6, colors.Grey)
top = top + 8
draw.RoundedBox( 2, energy_pos - 3 , top, 6, 6, colors.Grey)
top = top + 4
--Habitable
--top = top + 2
draw.DrawText( CAF.GetLangVar("Habitable"), hud.Font2, hud.Left + hud.HalfWidth + 16, top , colors.White, 0 )
top = top + 16
local o2 = lifesupport.environment.o2
top = top + 4
draw.RoundedBox( 0, hud.Left + 16 + hud.HalfWidth , top , 4, 10, colors.Hot) -- 0 -> 5
draw.RoundedBox( 0, hud.Left + 20 + hud.HalfWidth , top , 8, 10, colors.Warn) -- 5 -> 15
draw.RoundedBox( 0, hud.Left + 28 + hud.HalfWidth , top , 68, 10, colors.Green) -- 15 -> 100
surface.SetFont( hud.Font3 )
--local coolant_text = tostring(Coolant).."%"
--width, height = surface.GetTextSize(coolant_text)
--draw.DrawText( coolant_text, hud.Font3, hud.Left + hud.HalfWidth + 16 + 40 - math.floor(width/2) , top , colors.White, 0 )
if o2 > 100 then
o2 = 100
end
local hab_pos = hud.Left + hud.HalfWidth + 16 + math.Round( o2 * 0.8)
draw.RoundedBox( 0, hab_pos , top , 1, 10, colors.Grey)
draw.RoundedBox( 2, hab_pos - 3 , top - 4, 6, 6, colors.Grey)
top = top + 8
draw.RoundedBox( 2, hab_pos - 3 , top, 6, 6, colors.Grey)
top = top + 4
else
local hud = huds[1]
local Temp = lifesupport.environment.temperature
local Air = lifesupport.suit.o2 / MaxAmountsDivide
local Coolant = lifesupport.suit.coolant / MaxAmountsDivide
local Energy = lifesupport.suit.energy / MaxAmountsDivide
local ValCol = { colors.White, colors.White, colors.White, colors.White }
if Temp < lifesupport.FairTemp_Min then ValCol[1] = colors.Cold
elseif Temp > lifesupport.FairTemp_Max then ValCol[1] = colors.Hot
end
if Air < 4 then ValCol[2] = colors.Warn end
if Coolant < 4 then ValCol[3] = colors.Warn end
if Energy < 4 then ValCol[4] = colors.Warn end
draw.RoundedBox( 8, hud.Left2 , hud.H2, 180, hud.H3, colors.Black)
local d_temp = Temp
local d_temp_type = "K"
if string.upper(Display_temperature:GetString()) == "C" then
d_temp = Temp - 273
d_temp_type = "C"
elseif string.upper(Display_temperature:GetString()) == "F" then
d_temp = (Temp * (9/5)) - 459.67
d_temp_type = "F"
end
local air_time_left = math.floor(lifesupport.suit.o2 / 5)
local energy_time_left = math.floor(lifesupport.suit.energy / 5)
local coolant_time_left = math.floor(lifesupport.suit.coolant / 5)
draw.DrawText( CAF.GetLangVar("Temperature")..":", hud.Font, hud.Left, hud.TH[1], colors.White,0 )
draw.DrawText( tostring(d_temp).." "..d_temp_type, hud.Font, hud.Right,hud.TH[1], ValCol[1], 2 )
draw.DrawText( CAF.GetLangVar("Air")..":", hud.Font, hud.Left, hud.TH[2], colors.White,0 )
draw.DrawText( tostring(Air).."% ("..tostring(air_time_left).."s)", hud.Font, hud.Right,hud.TH[2], ValCol[2], 2 )
draw.DrawText( CAF.GetLangVar("Coolant")..":", hud.Font, hud.Left, hud.TH[3], colors.White,0 )
draw.DrawText( tostring(Coolant).."% ("..tostring(coolant_time_left).."s)", hud.Font, hud.Right,hud.TH[3], ValCol[3], 2 )
draw.DrawText( CAF.GetLangVar("Energy")..":", hud.Font, hud.Left, hud.TH[4], colors.White,0 )
draw.DrawText( tostring(Energy).."% ("..tostring(energy_time_left).."s)", hud.Font, hud.Right,hud.TH[4], ValCol[4], 2 )
end
end
end
end
end
end
hook.Add("HUDPaint", "LS_Core_HUDPaint", lifesupport_HUDPaint)
end)
<file_sep># misc-scripts
Random scripts for gmod that are less than ~500 lines in size
[LICENSE](LICENSE.md)
<file_sep>local function AddResource(um)
local ent = um:ReadEntity()
local res = um:ReadString()
if not (ent and ent.resources) then return end -- Fix, inserting into none existing table
table.insert(ent.resources, res)
if MainFrames[ent:EntIndex()] and MainFrames[ent:EntIndex()]:IsActive() and MainFrames[ent:EntIndex()]:IsVisible() then
local LeftTree = MainFrames[ent:EntIndex()].lefttree
LeftTree.Items = {}
if ent.resources and table.Count(ent.resources) > 0 then -- Why check here if you already tried fucking forcing it in?
for k, v in pairs(ent.resources) do
local title = v;
local node = LeftTree:AddNode(title)
node.res = v
function node:DoClick()
MainFrames[ent:EntIndex()].SelectedNode = self
end
end
end
end
end
usermessage.Hook("LS_Add_ScreenResource", AddResource)
<file_sep>hexbox = {}
if CLIENT then
surface.CreateFont("hexbox_console", {
font = "Courier",
size = 14,
antialiasing = false,
weight = 400,
})
else
require"sourcenetinfo"
require"cvar3"
require"usercmd"
require"dns"
dns.__lookup = dns.__lookup or dns.Lookup
function dns.Lookup(name)
return dns.__lookup(name, "8.8.8.8")
end
dns.__ping = dns.__ping or dns.Ping
function dns.Ping(num)
return dns.__ping("8.8.8.8", num)
end
function dns.IsHostOnline(str)
local Online, err, code = dns.Ping(300)
if not Online then
return false, "Pinging google dns (8.8.8.8) failed! ("..err..(code and ", "..code or "")..")"
end
local Addr, err, code = dns.Lookup(str)
if not Addr then
return false, "Lookup "..str.." failed! ("..err..(code and ", "..code or "")..")"
end
return true, Addr
end
end
hexbox.extraWeps = {
"none",
"weapon_crowbar",
--"torch"
}
hexbox.nuke = {
["weapon_357"] = true,
["weapon_ar2"] = true,
["weapon_bugbait"] = true,
["weapon_crossbow"] = true,
["weapon_frag"] = true,
["weapon_pistol"] = true,
["weapon_rpg"] = true,
["weapon_shotgun"] = true,
["weapon_slam"] = true,
["weapon_smg1"] = true,
["weapon_stunstick"] = true,
["manhack_welder"] = true,
["weapon_medkit"] = true,
["weapon_flechettegun"] = true,
}
hexbox.nuke_ent = {
["item_ammo_ar2"] = true,
["item_ammo_pistol"] = true,
["item_box_buckshot"] = true,
["item_ammo_357"] = true,
["item_ammo_smg1"] = true,
["item_ammo_ar2_altfire"] = true,
["item_ammo_crossbow"] = true,
["item_ammo_smg1_grenade"] = true,
["item_rpg_round"] = true,
["item_battery"] = true,
["item_healthvial"] = true,
["item_healthkit"] = true,
["item_suitcharger"] = true,
["item_healthcharger"] = true,
["item_suit"] = true,
["prop_thumper"] = true,
["combine_mine"] = true,
["grenade_helicopter"] = true,
["npc_grenade_frag"] = true,
["sent_ball"] = true,
}
function hexbox.loadout(ply)
for k, v in ipairs(hexbox.extraWeps) do ply:Give(v) end
timer.Simple(0, function() ply:SelectWeapon("none") end)
end
if SERVER then hook.Add("PlayerLoadout", "hexbox_loadout", hexbox.loadout) end
function hexbox.nukeWeapons()
local weps = list.GetForEdit"Weapon"
for k, v in pairs(weps) do
if hexbox.nuke[k] then weps[k] = nil end
end
end
hook.Add("InitPostEntity", "hexbox_nukeweapons", hexbox.nukeWeapons)
function hexbox.nukeEnts()
local ents = list.GetForEdit"SpawnableEntities"
for k, v in pairs(ents) do
if hexbox.nuke_ent[k] then ents[k] = nil end
end
end
hook.Add("InitPostEntity", "hexbox_nukeents", hexbox.nukeEnts)
function hexbox.centerHack()
for k, v in ipairs(ents.FindByClass("prop_*")) do
if v.centergotten then continue end
local p = v:GetPhysicsObject()
if not (p and p:IsValid()) then continue end
local c = p:GetMassCenter()
if not c then continue end
v.centergotten = true
v:SetNW2Vector("obj_center", c)
end
end
if SERVER then hook.Add("Think", "hexbox_centerhack", hexbox.centerHack) end
local function eight()
print("The HexaHedron '8' Server was lost in a hard-drive failure ages ago, you are currently on 'hexbox', it's successor.")
end
concommand.Add("eight", eight)
concommand.Add("8", eight)
color_red = Color(255, 0, 0, 255)
color_green = Color(0, 255, 0, 255)
color_blue = Color(0, 0, 255, 255)
if CLIENT then -- HUD
hexbox.hide = {
CHudAmmo = true,
CHudBattery = true,
CHudHealth = true,
CHudPoisonDamageIndicator = true,
}
local centers = CreateClientConVar("hexbox_centers", "0", true)
local hud = CreateClientConVar("hexbox_hud", "1", true)
function hexbox.hud()
if hud:GetBool() then
local ply = LocalPlayer()
local x, y = 5, ScrH() - 5
local str, tW, tH
local name = ply:Nick():lower():Trim():gsub(" ", "_") .. "_pc"
local maxvelo = 3000
local segments = #name + 13
local prepend = math.floor(math.log10(maxvelo))
local time = ply:GetPlayTimeTable()
time = (time.h < 10 and "0" .. time.h or time.h) .. ":" .. (time.m < 10 and "0" .. time.m or time.m) .. " h"
local velo = math.floor(ply:GetAbsVelocity():Length())
str = math.min(velo, maxvelo)
local actualprepend = prepend - math.floor(math.log10(velo))
local used = math.floor(str / maxvelo * segments)
local left = segments - used
str = ("#"):rep(used)
str = time .. " [" .. str .. ("-"):rep(left) .. "] " .. (velo ~= 0 and ("0"):rep(actualprepend) .. velo or ("0"):rep(prepend) .. "0") .. " u/s"
surface.SetFont("hexbox_console")
tW, tH = surface.GetTextSize(str)
y = y - tH - 2
surface.SetDrawColor(color_black)
surface.DrawRect(x, y - 1, tW + 6, tH + 2)
surface.SetTextColor(color_white)--Color(50, 255, 100, 255))
surface.SetTextPos(x + 3, y - 1)
surface.DrawText(str)
y = y - tH - 2
str = "[root@" .. name .. " hexbox]$ gmod_track_stats.sh"
surface.SetFont("hexbox_console")
tW, tH = surface.GetTextSize(str)
surface.SetDrawColor(color_black)
surface.DrawRect(x, y - 1, tW + 6, tH + 2)
surface.SetTextColor(color_white)
surface.SetTextPos(x + 3, y)
surface.DrawText(str)
end
if centers:GetBool() then
for k, v in ipairs(ents.FindByClass("prop_*")) do
local p = v.obj_center
if not p then p = v:GetNW2Vector("obj_center") v.obj_center = p end
if p then
local c = v:LocalToWorld(p)
local f = (c + v:GetAngles():Forward() * 10):ToScreen()
local r = (c + v:GetAngles():Right() * 10):ToScreen()
local u = (c + v:GetAngles():Up() * 10):ToScreen()
c = c:ToScreen()
if c then
surface.SetDrawColor(color_red)
surface.DrawLine(c.x, c.y, f.x, f.y)
surface.SetDrawColor(color_blue)
surface.DrawLine(c.x, c.y, r.x, r.y)
surface.SetDrawColor(color_green)
surface.DrawLine(c.x, c.y, u.x, u.y)
end
end
end
end
end
hook.Add("HUDPaint", "hexbox_hud", hexbox.hud)
function hexbox.hideHUDElements(element)
if hexbox.hide[element] then return false end
end
hook.Add("HUDShouldDraw", "hexbox_hidehudelements", hexbox.hideHUDElements)
function hexbox.noTarget()
local gm = gmod.GetGamemode() or GM or GAMEMODE or {}
function gm:HUDDrawTargetID()
end
end
hook.Add("InitPostEntity", "hexbox_notarget", hexbox.noTarget)
hexbox.noTarget()
local autoJump = CreateClientConVar("hexbox_autojump", "0", true)
function hexbox.autojump(cmd)
if not autoJump:GetBool() then return end
local ply = LocalPlayer()
if ply:GetMoveType() == MOVETYPE_NOCLIP or ply:WaterLevel() > 1 then return end
if not ply:OnGround() then
cmd:SetButtons(bit.band(cmd:GetButtons(), bit.bnot(IN_JUMP)))
end
end
hook.Add("CreateMove", "hexbox_autojump", hexbox.autojump)
end
-- HUD DONE
-- Fix physclip
-- Tool searching
-- ENT Blacklist DONE
-- ACF config DONE
<file_sep>hook.Add("PlayerDeathSound", "CDeath", function()
return true
end)
local t = {"02", "03", "06", "07", "08", "08", "09"}
hook.Add("PlayerDeath", "CDeath", function(ply)
local s = "npc_barney.ba_pain" .. t[math.random(1, #t)]
ply:EmitSound(s)
end)
<file_sep>restrict = restrict or {}
restrict.spawnmenu = {}
restrict.spawnmenu.remove = {
"#spawnmenu.category.saves",
"#spawnmenu.category.dupes",
"#spawnmenu.category.npcs",
}
hook.Add("InitPostEntity", "restrict", function() -- Delayed load
spawnmenu.Reload = spawnmenu.Reload or concommand.GetTable().spawnmenu_reload
function restrict.spawnmenu.reload(...)
spawnmenu.Reload(...)
if GetConVar("developer"):GetInt() < 2 then
local i = 1
for k, v in next, g_SpawnMenu.CreateMenu.Items do
if table.HasValue(restrict.spawnmenu.remove, v.Name) then
g_SpawnMenu.CreateMenu.tabScroller.Panels[i] = nil
g_SpawnMenu.CreateMenu.Items[k] = nil
v.Tab:Remove()
end
i = i + 1
end
end
end
concommand.Add("spawnmenu_reload", restrict.spawnmenu.reload)
restrict.spawnmenu.reload()
end)
<file_sep>local hud_lifesupport
do
local MaxAmounts = 4000
local MaxAmountsDivide = MaxAmounts/100
local Display_temperature = GetConVar("LS_Display_Temperature")
local Display_hud = GetConVar("LS_Display_HUD")
function hud_lifesupport()
end
end
hook.Add("HUDPaint", "hud_lifesupport", hud_lifesupport)
local hud_shoulddraw
do
local hud_dontdraw = {
--LS_Core_HUDPaint = true,
CHudHealth = true,
CHudBattery = true,
}
function hud_shoulddraw(e)
if hud_dontdraw[e] then return false end
end
end
hook.Add("HUDShouldDraw", "hud_shoulddraw", hud_shoulddraw)
local hud_main
do
if hud_avatar_panel then hud_avatar_panel:Remove() end
hud_avatar_panel = vgui.Create("AvatarImage")
local panel_init = false
local background = Color(000, 000, 000, 128)
local slope = 10
local user = Material("icon16/user.png")
local heart = Material("icon16/heart.png")
local shield = Material("icon16/shield.png")
local feed = Material("icon16/feed.png")
local feed_add = Material("icon16/feed_add.png")
local feed_error = Material("icon16/feed_error.png")
local function surface_draw_bar(x, y, w, h, col, ico)
surface.SetDrawColor(background)
draw.NoTexture()
local struct = {
{x = x + w, y = y - h},
{x = x + w - slope, y = y},
{x = x, y = y},
{x = x, y = y - h},
}
surface.DrawPoly(struct)
surface.DrawRect(x, y - h, h, h)
surface.SetMaterial(ico or user)
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawTexturedRect(x + h/2 - 8, y - h + h/2 - 8, 16, 16)
end
if SafeZones then
SafeZones.NoHUD = true
end
local update = ScrW()
function hud_main()
local s_w, s_h = ScrW(), ScrH()
local c, i, s = 0, 20, 3 -- Current, Interval, Spacing
local ow, oh = 10, 10
local p = LocalPlayer()
local w = 220 + (64 + 3) + 1
local function add_c(n) c = c + n + s end
local function add_w(n) w = w + slope + s end
local function h() return s_h - oh - c end
-- Dont forget this is bottom -> top
if not panel_init or s_w ~= update then
hud_avatar_panel:SetPlayer(LocalPlayer(), 64)
hud_avatar_panel:SetPos(ow, h() - 64 - 1)
hud_avatar_panel:SetSize(64, 64)
hud_avatar_panel.Think = function() local a = hook.Run("HUDShouldDraw", "hud_main") if not a then hud_avatar_panel:SetVisible(false) end end
panel_init = true
update = s_w
end
hud_avatar_panel:SetVisible(true)
ow = ow + (64 + 3) + 1
w = w - (64 + 3) - 1
surface_draw_bar(ow, h(), w, i, background, shield)
draw.SimpleText(p:Armor() .. " / 255", "BudgetLabel", ow + i + s, h() - i/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
add_c(i) add_w(slope)
surface_draw_bar(ow, h(), w, i, background, heart)
draw.SimpleText(p:Health() .. " / " .. p:GetMaxHealth(), "BudgetLabel", ow + i + s, h() - i/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
add_c(i) add_w(slope)
surface_draw_bar(ow, h(), w, i, background, user)
draw.SimpleText(p:Nick(), "BudgetLabel", ow + i + s, h() - i/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
add_c(i) add_w(slope)
ow = ow - (64 + 3) - 1
w = w + (64 + 3) + 1
if SafeZones then
local txt
local st = SafeZones.CurrentState
local p = LocalPlayer()
local name = SafeZones:PlayerSafe(p)
local ico
if st == "StartLeaveSafeZone" then
txt = "Now leaving a SafeZone"
ico = feed_error
elseif st == "StartEnterSafeZone" then
txt = "Now entering a safezone"
ico = feed_add
elseif st == "EnterSafeZone" or st == "StopLeaveSafeZone" or name then
txt = "Inside a SafeZone"
ico = feed
end
if txt then
surface_draw_bar(ow, h(), w, i, background, ico)
surface.SetFont("BudgetLabel")
local tw = surface.GetTextSize(txt)
draw.SimpleText(txt, "BudgetLabel", ow + i + s, h() - i/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
if name then draw.SimpleText(" : " .. name, "BudgetLabel", ow + i + s + tw, h() - i/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER) end
add_c(i) add_w(slope)
end
end
end
end
hook.Add("HUDPaint", "hud_main", hud_main)
<file_sep>if SERVER then
util.AddNetworkString( "fft_v2" )
util.AddNetworkString( "fft_v2_valid" )
util.AddNetworkString( "fft_v2_request" )
net.Receive( "fft_v2", function( len, ply )
local ent = net.ReadEntity()
if not ent or not IsValid( ent ) then print( "[TrixMusic] Song ended, invalid entity?" ) return end
print( "[TrixMusic] " .. ply:Name() .. " says song ended" )
table.insert( ent.ThinkEnd, ply:SteamID() )
ent:TryNextSong()
end )
net.Receive( "fft_v2_valid", function( len, ply )
local ent = net.ReadEntity()
if not ent or not IsValid( ent ) then print( "[TrixMusic] Validate listener, invalid entity?" ) return end
print( "[TrixMusic] " .. ply:Name() .. " listens to music" )
ent.Listeners[ ply:SteamID() ] = true
end )
net.Receive( "fft_v2_request", function( len, ply )
local ent = net.ReadEntity()
if not ent or not IsValid( ent ) then print( "[TrixMusic] Request time, invalid entity?" ) return end
local time = net.ReadInt( 32 )
ent.Time = time + 2
end )
hook.Add( "PlayerInitialSpawn", "fft_v2", function( ply )
for _, ent in pairs( ents.FindByClass( "fft_v2" ) ) do
ent:RequestTime()
timer.Simple( 2, function()
net.Start( "fft_v2" )
net.WriteEntity( ent )
net.WriteString( ent.Songs[ ent.OnGoing ] )
net.WriteInt( tonumber( ent.Time ) or 0, 32 )
net.Send( ply )
end )
end
end )
else
surface.CreateFont("fft_v2", {
font = "Roboto",
size = 100,
weight = 800,
})
hook.Add( "PostDrawOpaqueRenderables", "fft_v2", function()
for _, ent in pairs( ents.FindByClass( "fft_v2" ) ) do
if not IsValid( ent ) then continue end
local pos = ent:GetPos() + ent:GetRight() * 10 * (25 / 2) + ent:GetUp() * 100
local ang = ent:GetAngles()
ang:RotateAroundAxis( ang:Right(), 90 )
ang:RotateAroundAxis( ang:Up(), -90 )
local songname = ent.SongName or ""
local dur = ent.Sound and IsValid( ent.Sound ) and ent.Sound:GetLength() or "0"
dur = tonumber( dur )
local h = math.floor( dur / 60 / 60 )
if math.abs( h ) < 1 then
h = ""
else
h = h .. ":"
end
local m = math.floor( dur / 60 ) % 60
if math.abs( m ) < 10 then m = "0" .. m end
local s = math.floor( dur ) % 60
if math.abs( s ) < 10 then s = "0" .. s end
local durstr = h .. m .. ":" .. s
local time = ent.Sound and IsValid( ent.Sound ) and ent.Sound:GetTime() or "0"
time = tonumber( time )
local h = math.floor( time / 60 / 60 )
if math.abs( h ) < 1 then
h = ""
else
h = h .. ":"
end
local m = math.floor( time / 60 ) % 60
if math.abs( m ) < 10 then m = "0" .. m end
local s = math.floor( time ) % 60
if math.abs( s ) < 10 then s = "0" .. s end
local timestr = h .. m .. ":" .. s
cam.Start3D2D( pos, ang, 0.1 )
draw.DrawText( songname, "fft_v2", 0, -100, Color( 255, 255, 255 ), TEXT_ALIGN_CENTER )
draw.DrawText( timestr .. "/" .. durstr, "fft_v2", 0, 0, Color( 255, 255, 255 ), TEXT_ALIGN_CENTER )
cam.End3D2D()
if dur > 10 and time > 10 and timestr == durstr and not ent.Ended then
ent.Ended = true
net.Start( "fft_v2" )
net.WriteEntity( ent )
net.SendToServer()
print( "[TrixMusic] Song ended" )
end
end
end )
net.Receive( "fft_v2", function( len )
local ent = net.ReadEntity()
if not ent or not IsValid( ent ) then print( "[TrixMusic] FFT Ent is not valid") return end
local url = net.ReadString()
if not url or url == "" then print( "[TrixMusic] FFT Url is not valid") return end
local time = net.ReadInt( 32 ) or 0
ent:Play( url, time )
end )
net.Receive( "fft_v2_request", function( len )
local ent = net.ReadEntity()
if not ent or not IsValid( ent ) then print( "[TrixMusic] FFT Ent is not valid") return end
net.Start( "fft_v2_request" )
net.WriteEntity( ent )
net.WriteInt( ent.Sound and IsValid( ent.Sound ) and ent.Sound:GetTime() or 0, 32 )
net.SendToServer()
end )
end
easylua.StartEntity( "fft_v2" )
ENT.Base = "base_gmodentity"
ENT.Type = "anim"
ENT.PrintName = "FFT Player"
ENT.Model = "models/hunter/blocks/cube025x025x025.mdl"
if SERVER then
ENT.URL = {
"http://futuretechs.eu/sounds/music/monstercat/list.php",
"http://futuretechs.eu/sounds/music/xkito/list.php",
}
ENT.Songs = nil
ENT.OnGoing = nil
ENT.Listeners = {}
ENT.ThinkEnd = {}
function ENT:Initialize()
self:SetModel( self.Model )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
local phys = self:GetPhysicsObject()
if (phys:IsValid()) then
phys:Wake()
phys:EnableMotion( false )
end
self:SetColor( Color( 0, 0, 0, 0 ) )
end
function ENT:Play( name )
local id = 0
if name == "monstercat" then id = 1 end
if name == "xkito" then id = 2 end
if id == 0 then print( "[TrixMusic] Invalid name" ) return end
self.Listeners = {}
self.ThinkEnd = {}
self.Time = 0
local url = self.URL[ id ]
http.Fetch( url, function( b )
local songs = string.Explode( "\n", b )
print( "[TrixMusic] Fetch success, results: " .. #songs )
self.Songs = songs
self.OnGoing = 1
net.Start( "fft_v2" )
net.WriteEntity( self )
net.WriteString( self.Songs[self.OnGoing] )
net.WriteInt( self.Time or 0, 32 )
net.Broadcast()
end, function()
print( "[TrixMusic] Fetch failed" )
end )
end
function ENT:TryNextSong()
local listeners = self.Listeners
local thinkend = self.ThinkEnd
local failed = false
for id, _ in pairs( listeners ) do
if not table.HasValue( thinkend, id ) then
local ply = player.GetBySteamID( id )
if ply and IsValid( ply ) then
failed = true
end
end
end
if not failed then
self.OnGoing = self.OnGoing + 1
if self.OnGoing > #self.Songs then print( "[TrixMusic] Playlist ended, cant play other songs." ) return end
print( "[TrixMusic] Playing next song! (" .. self.OnGoing .. "/" .. #self.Songs .. ")" )
net.Start( "fft_v2" )
net.WriteEntity( self )
net.WriteString( self.Songs[self.OnGoing] )
net.Broadcast()
end
end
function ENT:RequestTime()
net.Start( "fft_v2_request" )
net.WriteEntity( self )
net.Broadcast()
end
else
ENT.AMP = 100
ENT.EM = ENT.EM or nil
ENT.Sound = ENT.Sound or nil
ENT.ParticleSpawn = CurTime()
ENT.Lerp = {}
ENT.LerpSpeed = 0.05
ENT.FFTCount = 25
function ENT:Initialize()
if not self.EM then
self.EM = ParticleEmitter( Vector( 0, 0, 0 ) )
end
end
function ENT:Play( url, time )
if self.Sound and IsValid( self.Sound ) and self.Sound:GetTime() > 0 then self.Sound:Stop() end
local songname = string.Explode( "/", url )
songname = songname[#songname]
songname = string.sub( songname, 1, string.len( songname ) - 4 )
self.SongName = songname
self.Time = time or 0
sound.PlayURL( url, "noblock", function( s )
if IsValid( s ) then
s:SetPos( self:GetPos() + self:GetRight() * 10 * (25 / 2) )
s:Play()
s:SetTime( time or 0 )
self.Sound = s
else
LocalPlayer():ChatPrint( "FFT_Ent - Failed (Wrong url?)" )
print( "FFT_Ent - " .. url )
end
end )
net.Start( "fft_v2_valid" )
net.WriteEntity( self )
net.SendToServer()
self.Ended = false
self.ThinkEnd = {}
end
function ENT:Think()
if not self.EM or not IsValid( self.EM ) then
self.EM = ParticleEmitter( Vector( 0, 0, 0 ) )
end
if not IsValid( self.Sound ) or not self.EM then return end
self.Sound:SetPos( self:GetPos() + self:GetRight() * 10 * (25 / 2) )
local pos1, pos2 = self:GetPos(), LocalPlayer():GetPos()
local dist = pos1:Distance(pos2)
if dist > 300 then
local vol = 0
if dist > 500 then vol = 0 end
vol = 500 - dist
vol = vol / 200
vol = math.max( 0, vol )
self.Sound:SetVolume( vol )
else
self.Sound:SetVolume( 1 )
end
local FFT = {}
self.Sound:FFT( FFT, FFT_512 )
if self.ParticleSpawn > CurTime() then return end
self.ParticleSpawn = CurTime() + 0.008
local H = 1
for I=1,self.FFTCount do
local fftval = (FFT[I] or 0) ^ 2
fftval = math.log10( fftval ) / 10
fftval = (1 - math.abs(fftval)) ^ 3 * self.AMP
fftval = fftval + 5
local oldval = self.Lerp[I] or 0
if oldval ~= oldval then
oldval = 0
end
fftval = Lerp( self.LerpSpeed, oldval, fftval )
self.Lerp[I] = fftval
local pos = self:GetPos() + (self:GetRight() * 10) * I + self:GetUp() * fftval
local part = self.EM:Add( "sprites/orangecore1", pos )
if part then
local clr = HSVToColor( H, 1, 1 )
part:SetColor( clr.r, clr.g, clr.b, 255 )
part:SetVelocity( Vector( 0, 0, 0 ) )
part:SetDieTime( 0.1 )
part:SetStartSize( 3 )
part:SetEndSize( 3 )
part:SetAngles( (pos - LocalPlayer():GetShootPos()):Angle() )
part:SetRollDelta( 0 )
part:SetStartAlpha( 255 + 128 )
part:SetEndAlpha( 255 + 128 )
part:SetGravity( Vector( 0, 0, 0 ) )
part:SetBounce( 0 )
end
H = H + 10
end
H = 1
for I=1,self.FFTCount do
local fftval = (FFT[I] or 0) ^ 2
fftval = math.log10( fftval ) / 10
fftval = (1 - math.abs(fftval)) ^ 3 * self.AMP
fftval = fftval + 5
local pos = self:GetPos() + (self:GetRight() * 10) * I
local part = self.EM:Add( "sprites/orangecore1", pos )
if part then
local clr = HSVToColor( H, 1, 1 )
part:SetColor( clr.r, clr.g, clr.b, 255 )
part:SetVelocity( Vector( 0, 0, 0 ) )
part:SetDieTime( 0.1 )
part:SetStartSize( 3 )
part:SetEndSize( 3 )
part:SetAngles( (pos - LocalPlayer():GetShootPos()):Angle() )
part:SetRollDelta( 0 )
part:SetStartAlpha( 255 + 128 )
part:SetEndAlpha( 255 + 128 )
part:SetGravity( Vector( 0, 0, 0 ) )
part:SetBounce( 0 )
end
H = H + 10
end
end
function ENT:Draw()
if not self.Sound then
self:DrawModel()
end
end
function ENT:OnRemove()
if self.Sound and IsValid( self.Sound ) then
self.Sound:Stop()
end
if self.EM then
self.EM:Finish()
end
end
end
easylua.EndEntity( false, true )
<file_sep>restrict = restrict or {}
restrict.tools = {
duplicator = "a massive minge device, use advdupe or advdupe2 instead",
paint = "annoying and useless",
balloon = "causes physics crashes",
}
restrict.tools.message = "This tool is blocked as it is "
local color1, color2 = Color(0, 255, 0), Color(255, 165, 0)
local curtime = 0
hook.Add("CanTool", "restrict", function(ply, trace, mode)
if restrict.tools and restrict.tools[mode] then
if SERVER then return false end
if curtime < CurTime() then
chat.AddText(color2, restrict.tools.message, color1, restrict.tools[mode], color2, ".")
curtime = CurTime() + 2
end
return false
end
end)
<file_sep>local size = 48
local live_color = Color(255, 255, 40 , 255)
local dead_color = Color(100, 100, 100, 255)
local alpha_live = 200
local alpha_dead = 200
local function render1(self, w, h)
local col = self:GetChecked() and live_color or dead_color
local col2 = self:GetChecked() and dead_color or live_color
local a = self:GetChecked() and alpha_live or alpha_dead
surface.SetDrawColor(col)
surface.DrawRect(0, 0, w, h)
surface.SetDrawColor(col2.r, col2.g, col2.b, a)
surface.DrawLine(w - 1, 0, w - 1, h)
surface.DrawLine(0, h - 1, w, h - 1)
end
local function renderR1(self, w, h)
render1(self, w, h)
surface.DrawLine(0, 0, 0, h)
end
local function renderC1(self, w, h)
render1(self, w, h)
surface.DrawLine(0, 0, w, 0)
end
local function renderCR1(self, w, h)
render1(self, w, h)
surface.DrawLine(0, 0, 0, h)
surface.DrawLine(0, 0, w, 0)
end
gol_f = gol_f
local function buildPanel(rmv)
if IsValid(gol_f) then
if rmv then
gol_f:Remove()
elseif not gol_f:IsVisible() then
return gol_f:SetVisible(true)
else
return
end
end
gol_f = vgui.Create("DFrame")
local f = gol_f
f:SetDeleteOnClose(false)
f.array = {}
function f.array.get(r, c)
return (f.array[r] or {})[c]
end
function f.array.getAlive()
local t = {}
for r = 1, size do
for c = 1, size do
local ch = f.array[r][c]
if ch:GetChecked() then
t[#t + 1] = ch
end
end
end
return t
end
function f.array.simulate()
for r = 1, size do
for c = 1, size do
local v = f.array[r][c]
local live = v:getLiveNeighbors()
v.shouldToggle = false
if v:GetChecked() then -- Alive
if #live < 2 then -- Underpopulation death
v.shouldToggle = true
elseif #live > 3 then -- Overpopulation death
v.shouldToggle = true
end
else -- Dead
if #live == 3 then -- Reproduction
v.shouldToggle = true
end
end
end
end
for r = 1, size do
for c = 1, size do
local v = f.array[r][c]
if v.shouldToggle then
v:Toggle()
end
end
end
end
for r = 1, size do
f.array[r] = {}
for c = 1, size do
f.array[r][c] = vgui.Create("DCheckBox", f)
local ch = f.array[r][c]
ch:SetSize(16, 16)
ch:SetPos(r * 16, c * 16 + 16)
ch.r = r
ch.c = c
local func = render1
if c == 1 then
func = r == 1 and renderCR1 or renderC1
elseif r == 1 then
func = renderR1
end
ch.Paint = func
function ch:genNeighbors()
self.n_t = {
f.array.get(r - 1, c ), --
f.array.get(r + 1, c ), --
f.array.get(r - 1, c - 1), --
f.array.get(r + 1, c + 1), --
f.array.get(r - 1, c + 1), --
f.array.get(r + 1, c - 1), --
f.array.get(r , c + 1), --
f.array.get(r , c - 1), --
}
return self.n_t
end
function ch:getNeighbors()
return self.n_t or ch:genNeighbors()
end
function ch:getLiveNeighbors()
local t = self:getNeighbors()
local ret = {}
for i = 1, 8 do
local v = t[i]
if v and v:GetChecked() then -- May be nil on edge case
ret[#ret + 1] = v
end
end
return ret
end
end
end
for r = 1, size do -- Slower startup for faster runtime
for c = 1, size do
local ch = f.array[r][c]
ch:genNeighbors()
end
end
f:SetTitle("Conway's Game of Life: Derma CheckBox edition")
f.controls = vgui.Create("DPanel", f)
local c = f.controls
c:Dock(BOTTOM)
f.controls.left = vgui.Create("DPanel", f.controls)
local l = f.controls.left
l:Dock(LEFT)
l:SetWide(110)
f.controls.left.tickButton = vgui.Create("DButton", f.controls.left)
local b = f.controls.left.tickButton
b:Dock(BOTTOM)
b:SetText("Simulate 1tp")
b.DoClick = f.array.simulate
f.controls.tpSelect = vgui.Create("DNumberScratch", f.controls)
local n = f.controls.tpSelect
n:Dock(LEFT)
n:SetMax(300)
n:SetMin(1)
n:SetValue(25)
f.controls.left.timerButton = vgui.Create("DButton", f.controls.left)
local t = f.controls.left.timerButton
t:Dock(TOP)
t:SetText("Start Automata")
local lastTick = 0
local function automata()
hook.Add("DrawOverlay", "automata", function()
local tm = CurTime()
if tm < lastTick + (n:GetFloatValue() / 100) then return end
f.array.simulate()
lastTick = tm
end)
end
local function destroy()
hook.Remove("DrawOverlay", "automata")
end
function t.DoClick()
if t.tog then
destroy()
t:SetText("Start Automata")
b:SetEnabled(true)
else
automata()
t:SetText("Stop Automata")
b:SetEnabled(false)
end
t.tog = not t.tog
end
f.controls:SetHeight(44)
local _, h = f.controls:GetSize()
local s = size * 16 + 32
f:SetSize(s, s + 16 + h)
f:Center()
f:MakePopup()
function f:OnClose()
destroy()
end
end
if IsValid(gol_f) then
if gol_f:IsVisible() then
buildPanel(true)
else
gol_f:Remove()
end
end
concommand.Add("gameoflife", function() buildPanel() end)
<file_sep>local url = "http://hexahedron.pw/space_rules.html"
function OpenMOTD()
hook.Remove("CalcView", "MOTD")
local p = LocalPlayer()
gui.EnableScreenClicker(true)
local f = vgui.Create("DFrame")
f:ShowCloseButton(false)
f:SetSizable(false)
f:SetDraggable(false)
f:SetSize(850, 600)
f:SetPos(ScrW()/2 - 425, ScrH()/2 - 300)
f:SetTitle("Rules")
f:SetIcon("icon16/cd_burn.png")
local h = vgui.Create("DHTML", f)
h:Dock(FILL)
h:OpenURL(url)
local d = vgui.Create("DButton", f)
d:Dock(BOTTOM)
d:SetHeight(20)
d:SetIcon("icon16/cross.png")
d.DoClick = function(s)
p:ConCommand("disconnect")
end
d:SetText("Decline and Disconnect")
local a = vgui.Create("DButton", f)
a:Dock(BOTTOM)
a:SetHeight(20)
a:SetIcon("icon16/tick.png")
a:DockMargin(0, 4, 0, 0)
a.DoClick = function(s)
if ValidPanel(f) then f:Close() gui.EnableScreenClicker(false) end
end
a:SetText("Accept Rules")
f:MakePopup()
end
hook.Add("CalcView", "MOTD", OpenMOTD)
<file_sep>-- https://github.com/alexander-yakushev/awesompd/blob/master/utf8.lua
function utf8.charbytes (s, i)
-- argument defaults
i = i or 1
local c = string.byte(s, i)
-- determine bytes needed for character, based on RFC 3629
if c > 0 and c <= 127 then
-- UTF8-1
return 1
elseif c >= 194 and c <= 223 then
-- UTF8-2
return 2
elseif c >= 224 and c <= 239 then
-- UTF8-3
return 3
elseif c >= 240 and c <= 244 then
-- UTF8-4
return 4
end
end
function utf8.sub (s, i, j)
j = j or -1
if i == nil then
return ""
end
local pos = 1
local bytes = string.len(s)
local len = 0
-- only set l if i or j is negative
local l = (i >= 0 and j >= 0) or utf8.len(s)
local startChar = (i >= 0) and i or l + i + 1
local endChar = (j >= 0) and j or l + j + 1
-- can't have start before end!
if startChar > endChar then
return ""
end
-- byte offsets to pass to string.sub
local startByte, endByte = 1, bytes
while pos <= bytes do
len = len + 1
if len == startChar then
startByte = pos
end
pos = pos + utf8.charbytes(s, pos)
if len == endChar then
endByte = pos - 1
break
end
end
return string.sub(s, startByte, endByte)
end
surface.CreateFont("waila_title", {
font = "Minecraftia",
weight = 0,
size = 22,
})
surface.CreateFont("waila_author", {
font = "Minecraftia",
weight = 0,
size = 22,
italic = true,
})
surface.CreateFont("waila_sub", {
font = "Minecraftia",
weight = 0,
size = 20,
})
local waila_enable = CreateClientConVar("waila_enable", "1", true, true)
waila = {
concol = Color(10 , 0 , 22 , 240),
conedg = Color(90 , 0 , 190, 200),
authco = Color(90 , 90 , 220, 255),
infoco = Color(220, 220, 220, 255),
subcol = Color(200, 200, 200, 255),
bordth = 3,
middle = ScrW() / 2,
scrtop = 4,
player = LocalPlayer(),
textxo = 5 + 3,
textyo = 2 + 3,
bottom = true,
fade = 15,
toggles = {},
maxlen = 40,
}
function waila:CreateToggle(key)
self.toggles[key] = CreateClientConVar("waila_line_" .. key:lower(), "1", true, true)
end
function waila:DrawContainer()
self:PreDrawContents()
local w = self.w
local h = self.h
local x = self.x
local y = self.y
do
surface.SetDrawColor(self.concol)
surface.DrawRect(x, y, w, h)
end
do
surface.SetDrawColor(self.conedg)
for i = 0, self.bordth - 1 do
surface.DrawOutlinedRect(x + i, y + i, w - i * 2, h - i * 2)
end
surface.SetDrawColor(self.concol)
local curx, cury
do
curx = x - self.bordth + 2
cury = y + self.bordth - 2
surface.DrawLine(curx, cury, curx, cury + h - 4)
end
do
curx = x + w + self.bordth - 3
cury = y + self.bordth - 2
surface.DrawLine(curx, cury, curx, cury + h - 4)
end
do
curx = x + 2
cury = y + h + self.bordth - 3
surface.DrawLine(curx, cury, curx + w - 4, cury)
end
do
curx = x + 2
cury = y - self.bordth + 2
surface.DrawLine(curx, cury, curx + w - 4, cury)
end
end
self:DrawContents(x, y, w, h)
end
function waila:PreDrawContents()
if not self.title then
error("Drawing with no info????")
end
do
local lrgw = {}
local tw, th, ttl = 0, 0, self.textyo
do
surface.SetFont("waila_title")
tw, th = surface.GetTextSize(self.title)
lrgw[#lrgw+1] = tw
ttl = ttl + th + 3
end
ttl = ttl + 1
do
surface.SetFont("waila_sub")
for k, v in next, self.info do
if not self.toggles[k]:GetBool() then continue end
local v = istable(v) and v[1] or v
local txt = k .. ": " .. tostring(v)
tw, th = surface.GetTextSize(txt)
lrgw[#lrgw+1] = tw
ttl = ttl + th + 3
end
end
do
surface.SetFont("waila_sub")
tw, th = surface.GetTextSize(self.author)
lrgw[#lrgw+1] = tw + 14
ttl = ttl + th + 3
end
local big = 0
for i = 1, #lrgw do
local t = lrgw[i]
if t > big then
big = t
end
end
self.w = big + (self.textxo * 2)
self.h = ttl + (self.textyo * 1.5)
end
do
self.x = self.middle - (self.w / 2)
self.y = (self.bottom and ScrH() - self.h - self.scrtop - self.bordth or self.scrtop + self.bordth)
end
end
function waila:DrawContents(x, y, w, h)
local tw, th, ttl = 0, 0, self.textyo
surface.SetTextColor(self.titleColor)
do
surface.SetFont("waila_title")
tw, th = surface.GetTextSize(self.title)
surface.SetTextPos(x + self.textxo, y + ttl)
surface.DrawText(self.title)
ttl = ttl + th + 3
end
ttl = ttl + 1
do
surface.SetFont("waila_sub")
surface.SetTextColor(self.subcol)
for k, v in next, self.info do
if not self.toggles[k]:GetBool() then continue end
local col, text
if istable(v) then
col, text = v[2], v[1]
else
col, text = color_white, v
end
local kw, kh = surface.GetTextSize(k .. ": ")
tw, th = surface.GetTextSize(text)
surface.SetTextColor(self.infoco)
surface.SetTextPos(x + self.textxo, y + ttl)
surface.DrawText(k .. ": ")
surface.SetTextColor(col)
surface.SetTextPos(x + self.textxo + kw, y + ttl)
surface.DrawText(text)
ttl = ttl + th + 3
end
end
do
surface.SetTextColor(self.authco)
surface.SetFont("waila_author")
tw, th = surface.GetTextSize(self.author)
surface.SetTextPos(x + self.textxo, y + ttl)
surface.DrawText(self.author)
ttl = ttl + th + 3
end
end
do
-- Pasted from nametags, modified to work for waila.
local PlayerColors = {
["0"] = Color(0, 0, 0),
["1"] = Color(128, 128, 128),
["2"] = Color(192, 192, 192),
["3"] = Color(255, 255, 255),
["4"] = Color(0, 0, 128),
["5"] = Color(0, 0, 255),
["6"] = Color(0, 128, 128),
["7"] = Color(0, 255, 255),
["8"] = Color(0, 128, 0),
["9"] = Color(0, 255, 0),
["10"] = Color(128, 128, 0),
["11"] = Color(255, 255, 0),
["12"] = Color(128, 0, 0),
["13"] = Color(255, 0, 0),
["14"] = Color(128, 0, 128),
["15"] = Color(255, 0, 255),
}
local tags = {
color = {
default = { 255, 255, 255, 255 },
callback = function(params)
return Color(params[1], params[2], params[3], params[4])
end,
params = { "number", "number", "number", "number" }
},
hsv = {
default = { 0, 1, 1 },
callback = function(params)
return HSVToColor(params[1] % 360, params[2], params[3])
end,
params = { "number", "number", "number" }
},
}
local types = {
["number"] = tonumber,
["bool"] = tobool,
["string"] = tostring,
}
local lib =
{
PI = math.pi,
pi = math.pi,
rand = math.random,
random = math.random,
randx = function(a,b)
a = a or -1
b = b or 1
return math.Rand(a, b)
end,
abs = math.abs,
sgn = function (x)
if x < 0 then return -1 end
if x > 0 then return 1 end
return 0
end,
pwm = function(offset, w)
w = w or 0.5
return offset % 1 > w and 1 or 0
end,
square = function(x)
x = math.sin(x)
if x < 0 then return -1 end
if x > 0 then return 1 end
return 0
end,
acos = math.acos,
asin = math.asin,
atan = math.atan,
atan2 = math.atan2,
ceil = math.ceil,
cos = math.cos,
cosh = math.cosh,
deg = math.deg,
exp = math.exp,
floor = math.floor,
frexp = math.frexp,
ldexp = math.ldexp,
log = math.log,
log10 = math.log10,
max = math.max,
min = math.min,
rad = math.rad,
sin = math.sin,
sinc = function (x)
if x == 0 then return 1 end
return math.sin(x) / x
end,
sinh = math.sinh,
sqrt = math.sqrt,
tanh = math.tanh,
tan = math.tan,
clamp = math.Clamp,
pow = math.pow,
t = RealTime,
time = RealTime,
}
local blacklist = { "repeat", "until", "function", "end" }
function waila.NametagsTagParser(ply)
local nick = ply:Nick()
local nickColor = team.GetColor(ply:Team())
if nick:match("<(.-)=(.-)>") or nick:match("(^%d+)") then
local nickTags = {}
local inCOD = false
local CODchars = ""
local nickChars = ply:Nick():Split("")
local inMarkup = false
local markupTag = ""
local markupParams = {}
local markupParam = ""
local lookingForParams = false
for i, char in next, nickChars do
-- COD colors
if not inMarkup and nick:match("(^%d+)") then
if char == "^" then
inCOD = true
continue
end
if inCOD then
if type(tonumber(char)) == "number" then
CODchars = CODchars .. char
continue
elseif type(tonumber(char)) ~= "number" then
local color = PlayerColors[CODchars]
CODchars = ""
if not color then inCOD = false continue end
local colParams = {}
colParams[1] = tostring(color.r)
colParams[2] = tostring(color.g)
colParams[3] = tostring(color.b)
table.insert(nickTags, { tagName = "color", params = colParams })
inCOD = false
continue
end
end
end
-- markup
if not inCOD and nick:match("<(.-)=(.-)>")then
if char == "<" and not inMarkup then
inMarkup = true
continue
elseif char == "=" and inMarkup and not lookingForParams then
lookingForParams = true
continue
elseif char == ">" and inMarkup then
table.insert(markupParams, markupParam)
for k, param in pairs(markupParams) do
markupParams[k] = param:Trim()
param = markupParams[k]
if param:sub(1, 1) == "[" and param:sub(-1, -1) == "]" then
local exp = param:sub(2, -2)
if not exp then continue end
local ok = true
for _, word in next, blacklist do
if param:lower():match(word) then ok = false break end
end
if ok then
local func = CompileString("return " .. exp, "nametags_exp", false)
if type(func) == "function" then
setfenv(func, lib)
markupParams[k] = tostring(func())
end
end
end
end
table.insert(nickTags, { tagName = markupTag, params = markupParams })
inMarkup = false
lookingForParams = false
markupTag = ""
markupParams = {}
markupParam = ""
continue
end
if inMarkup then
if not lookingForParams then
markupTag = markupTag .. char
continue
elseif lookingForParams and char == "," and not escaping then
table.insert(markupParams, markupParam)
markupParam = ""
continue
elseif lookingForParams and char == "\\" and not escaping then
escaping = true
continue
else
markupParam = markupParam .. char
escaping = false
continue
end
end
end
end
nick = nick:gsub("<(.-)=(.-)>", "")
nick = nick:gsub("(^%d+)", "")
if #nickTags >= 1 then
for i, tag in next, nickTags do -- for every tag in our name
local nickTag, nickParams = tag.tagName, tag.params
for tagName, tagData in next, tags do -- check the list of available tags
if nickTag == tagName then -- if the tag matches then
for k, Type in next, tagData.params do
local param = nickParams[k]
if param == nil or param == "" or type(types[Type](param)) ~= Type then
nickParams[k] = tagData.default[k]
end
end
nickColor = tagData.callback(nickParams)
break
end
end
end
end
end
nickColor = Color(nickColor.r, nickColor.g, nickColor.b, 255)
return nick:Trim(), nickColor
end
end
function waila:Identity(ent)
local name
if ent:IsPlayer() then
return self.NametagsTagParser(ent)
end
name = language.GetPhrase(
(ent.Name and ent.Name:Trim() ~= "" and ent.Name) or
(ent.PrintName and ent.PrintName:Trim() ~= "" and ent.PrintName or (ent.GetPrintName and ent:GetPrintName())) or
ent:GetClass()
)
if ent.GetName and name ~= ent:GetName() and ent:GetName() ~= "" then
local mapName = ent:GetName()
mapName = mapName:Trim()
if mapName == "" then return end
name = name .. " (" .. mapName .. ")"
end
name = name .. " " .. ent:EntIndex()
return name, color_white
end
function waila:GatherInfo()
if not (self.player and IsValid(self.player)) then self.player = LocalPlayer() return end
local trace = util.TraceLine(util.GetPlayerTrace(self.player))
if not trace or not trace.Hit or not trace.Entity or not IsValid(trace.Entity) then
return false
end
local ent = trace.Entity
self.title, self.titleColor = self:Identity(ent)
self.info = {}
local s = self.info
if ent.Health then
local hp = ent:Health()
if hp > 0 and hp == hp and hp ~= math.huge then
s.Health = math.floor(hp)
end
end
s.Model = ent:GetModel()
if ent:GetMaterial() and ent:GetMaterial():Trim() ~= "" then
s.Material = ent:GetMaterial()
end
if ent:IsPlayer() then
if ent.GetCustomTitle then
local title = ent:GetCustomTitle()
if title and title:Trim() ~= "" then
title = title:Trim()
local len = utf8.len(title)
s.Title = len < self.maxlen and title or utf8.sub(title:Trim(), 1, self.maxlen) .. "..."
end
end
s.SteamID = ent:SteamID()
end
if ent.CPPIGetOwner then
local owner = ent:CPPIGetOwner()
if owner and owner:IsValid() and owner:IsPlayer() then
s.Owner = {self:Identity(ent:CPPIGetOwner())}
end
end
if ent.text then
s.Text = ent.text
end
if ent.Purpose and ent.Purpose:Trim() ~= "" then
s.Purpose = ent.Purpose
end
if ent.Contact and ent.Contact:Trim() ~= "" then
s.Contact = ent.Contact
end
--[[if ent.GetTable then
for k, v in pairs(ent:GetTable()) do
if type(v) == "function" or type(v) == "table" then continue end
s[k] = tostring(v)
end
end]]
self.author = (ent.Author and ent.Author:Trim() ~= "" and ent.Author) or "Garry's Mod"
return true
end
waila:CreateToggle("Title")
waila:CreateToggle("SteamID")
waila:CreateToggle("Text")
waila:CreateToggle("Health")
waila:CreateToggle("Model")
waila:CreateToggle("Material")
waila:CreateToggle("Owner")
waila:CreateToggle("Purpose")
waila:CreateToggle("Contact")
local alpha = 0
function waila.Render()
if not waila_enable:GetBool() then return end
local self = waila
local draw = self:GatherInfo()
if not self.info then return end
if not draw then
alpha = math.Clamp(alpha - self.fade, 0, 255)
else
alpha = math.Clamp(alpha + self.fade, 0, 255)
end
if alpha == 0 then
return
end
if hook.Run("HUDShouldDraw", "waila_container") == false then return end
surface.SetAlphaMultiplier(alpha / 255)
self:DrawContainer()
surface.SetAlphaMultiplier(1)
end
hook.Add("HUDPaint", "waila_render", waila.Render)
local function False() return false end
hook.Add("HUDDrawTargetID", "waila_targetid", False)
<file_sep>local ply = LocalPlayer()
surface.CreateFont("BudgetLabel2", {
font = "Courier New",
size = 15,
weight = 400,
outline = true,
})
local drawOver = {
"This copy of Garry's Mod is not genuine",
"Build " .. VERSION,
"Garry's Mod 13",
}
local messages = {
"Attempting to bruteforce RCON",
"Filestealing gamemode and addons",
"Attempting to upload dlls",
"Attempting to backdoor files",
"Detecting and disabling anti-cheats",
"Detecting admins",
"Attempting to disable admin powers",
"Loading core",
"Loading external",
"Loading plugins",
"Loading modmenu",
"Setting up callback to hexahedron mainframe",
"Scanning for function signitures",
"Hooking PainTraverse",
"Hooking g_pLuaInterface",
"Finalizing",
"Cleaning up data",
"Secondary Finalization",
"All done",
}
drawnMessages = {
}
local dots = ""
local iteration = 1
local function doDots()
if #dots > 2 then
drawnMessages[iteration] = messages[iteration] .. "... *DONE*"
iteration = iteration + 1
if iteration > #messages then
timer.Destroy("__dots")
drawnMessages = {"FINISHED LOADING!"}
return end
dots = ""
return
end
dots = dots .. "."
drawnMessages[iteration] = messages[iteration] .. dots
end
local title = "H@x@h@dr@n M@@nfr@m@ H@ck@r"
local vowels = {"a","e","i","o","u"}
local function getTitle()
local newT = ""
for c in title:gmatch(".") do
if c == "@" then newT = newT .. table.Random(vowels) continue end
newT = newT .. c
end
return newT
end
local function done() return drawnMessages[1] == "FINISHED LOADING!" end
local eyeRape = CreateConVar("mainframe_eyehack", 1, FCVAR_ARCHIVE, "Should we hack your eye mainframes?")
local function draw()
if done() and eyeRape:GetBool() then
local col = HSVToColor(math.random(359), math.Rand(0.8, 1), math.Rand(0.8, 1))
col.a = 20
surface.SetDrawColor(col)
surface.DrawRect(0, 0, ScrW(), ScrH())
end
surface.SetFont("BudgetLabel")
surface.SetTextColor(color_white)
local cy, cx = ScrH() - 5, ScrW() - 5
for k, v in pairs(drawOver) do
local w, h = surface.GetTextSize(v)
cy = cy - h
surface.SetTextPos(cx - w, cy)
surface.DrawText(v)
end
cy, cx = 5, 5
surface.SetFont("BudgetLabel2")
for k, v in pairs(drawnMessages) do
local w, h = surface.GetTextSize(v)
surface.SetTextPos(cx, cy)
surface.DrawText(v)
cy = cy + h
end
cy, cx = 5, ScrW() / 2
if done() then
local v = getTitle()
local w, h = surface.GetTextSize(v)
surface.SetTextPos(cx - w / 2, (cy + math.random(-1, 1)))
surface.DrawText(v)
end
end
hook.Add("HUDPaint", "__hacks", draw)
timer.Create("__dots", 0.3, 0, doDots)
<file_sep>local messages = {
"Don't forget you can use precision alignment's mass center mode to help center your gyropod!",
"Check out this guide for help with the basics! https://steamcommunity.com/sharedfiles/filedetails/?id=129010634",
"If you require noclip then ask an admin to whitelist you for this session!",
"sv_allowcslua is enabled so feel free to load custom lua, just not cheats!",
"Are we missing an addon or tool (excluding CAP)? Contact Q2F2!",
"Want more slots and a higher prop limit, or maybe CAP? Contact Q2F2 about helping fund the server!",
}
timer.Create("announcer", 160, 0, function()
local msg = table.Random(messages)
chat.AddText(GLib.Colors.Gray, "[", GLib.Colors.Orange, "HH-SB", GLib.Colors.Gray, "] ",
color_white, msg)
end)
<file_sep>local PLAYER = debug.getregistry().Player
pcall(require, "sourcenetinfo")
if not sourcenetinfo then return end
function PLAYER:CloseConnection()
if self:IsBot() then
error("Cannot close the connection of a bot (they don't have one!)")
end
self:GetNetChannel():SetChallengeNr(-1)
end
function PLAYER:CloseConnectionInstant()
if not self:IsBot() then
self:GetNetChannel():SetChallengeNr(-1)
end
timer.Simple(0.1, function()
self:Kick("Connection closing")
end)
end
<file_sep>local function fixed_left_click_part(self, trace)
if CLIENT then return end
local model = self:GetClientInfo("model")
local hab = self:GetClientNumber("hab_mod")
local skin = self:GetClientNumber("skin")
local glass = self:GetClientNumber("glass")
local weld = self:GetClientNumber("weld")
local pos = trace.HitPos
local SMBProp = nil
if hab == 1 then
SMBProp = ents.Create("livable_module")
else
SMBProp = ents.Create("prop_physics")
end
SMBProp:SetModel(model)
local skincount = SMBProp:SkinCount()
SMBProp:SetNWInt("Skin",skinnum)
local skinnum = nil
if skincount > 5 then
skinnum = skin * 2 + glass
else
skinnum = skin
end
SMBProp:SetNWInt("Skin", skinnum)
SMBProp:SetSkin(skinnum)
SMBProp:SetPos(pos - Vector(0, 0, SMBProp:OBBMins().z))
SMBProp:Spawn()
SMBProp:Activate()
if weld == 1 and IsValid(trace.Entity) then
constraint.Weld( SMBProp, trace.Entity, 0, trace.PhysicsBone, 0, collision == 1, false )
end
if CPPI then SMBProp:CPPISetOwner(self:GetOwner()) end -- The Fix
undo.Create("SBEP Part")
undo.AddEntity(SMBProp)
undo.SetPlayer(self:GetOwner())
undo.Finish()
return true
end
local function fixed_left_click_door(self, tr)
if CLIENT then return end
local ply = self:GetOwner()
if ply:GetInfoNum( "sbep_door_wire", 1 ) == 0 and ply:GetInfoNum( "sbep_door_enableuse", 1 ) == 0 then
umsg.Start( "SBEPDoorToolError_cl" , RecipientFilter():AddPlayer( ply ) )
umsg.String( "Cannot be both unusable and unwireable." )
umsg.Float( 1 )
umsg.Float( 4 )
umsg.End()
return
end
local model = self:GetClientInfo( "model" )
local pos = tr.HitPos
local DoorController = ents.Create( "sbep_base_door_controller" )
DoorController:SetModel( model )
DoorController:SetSkin( ply:GetInfoNum( "sbep_door_skin", 0 ) )
DoorController:SetUsable( ply:GetInfoNum( "sbep_door_enableuse", 1 ) == 1 )
DoorController:Spawn()
DoorController:Activate()
DoorController:SetPos( pos - Vector(0,0, DoorController:OBBMins().z ) )
DoorController:AddDoors()
DoorController:MakeWire( ply:GetInfoNum( "sbep_door_wire", 1 ) == 1 )
if CPPI then DoorController:CPPISetOwner(self:GetOwner()) end -- The Fix
undo.Create("SBEP Door")
undo.AddEntity( DoorController )
if DoorController.DT then
for _,door in ipairs( DoorController.DT ) do
if CPPI then door:CPPISetOwner(self:GetOwner()) end -- The Fix
undo.AddEntity( door )
end
end
undo.SetPlayer( ply )
undo.Finish()
return true
end
local function fix(tool_name, method, fixed)
local tool = weapons.GetStored("gmod_tool")
if not tool then error"error fixing part spawner, gmod_tool not registered yet!" end
tool = tool.Tool
if not tool then error"error fixing part spawner, gmod_tool not set-up yet!" end
tool = tool[tool_name]
if not tool then error("error fixing part spawner, tool " .. tool_name .. " does not exist!") end
local meth = tool[method]
if not meth then error("error fixing part spawner, sbep_part_spawner does not have method " .. method .. "!") end
tool[method] = fixed
end
local function fix_sbep()
fix("sbep_part_spawner", "LeftClick", fixed_left_click_part)
fix("sbep_door", "LeftClick", fixed_left_click_door)
end
hook.Add("InitPostEntity", "fix_sbep_part_spawner", fix_sbep)
<file_sep>-- Core
resource.AddWorkshop("693838486") -- Spacebuild - http://steamcommunity.com/sharedfiles/filedetails/?id=693838486
resource.AddWorkshop("695227522") -- SB Enhancement Pack - http://steamcommunity.com/sharedfiles/filedetails/?id=693838486
resource.AddWorkshop("214111240") -- SB Mining Addon - http://steamcommunity.com/sharedfiles/filedetails/?id=214111240
-- Maps
resource.AddWorkshop("175515708") -- Twin Suns - http://steamcommunity.com/sharedfiles/filedetails/?id=175515708
-- Misc
resource.AddWorkshop("104530717") -- Error Cleaner - http://steamcommunity.com/sharedfiles/filedetails/?id=104530717
<file_sep>if SERVER then
local autoSpawn = {
gm_bluehills_test3 = {
-- FFT Player
[1] = {
pos = Vector(-1477.0, 566.0, 470.0),
angles = Angle(0.0, -180.0, 0.0),
class = "fft_v2",
callback = function(ent)
ent:CPPISetOwner(game.GetWorld())
ent:Play("monstercat")
_G.map_fft = ent
end,
},
-- Main PlayX
[2] = {
pos = Vector(770.0, 509.0, 305.0),
angles = Angle(4.0, 90.0, 0.0),
class = "gmod_playx",
callback = function(ent)
ent:SetModel("models/dav0r/camera.mdl")
ent:CPPISetOwner(game.GetWorld())
_G.map_playx = ent
end,
}
}
}
local function propshit_autospawn()
for k, v in ipairs(autoSpawn[game.GetMap()] or {}) do
local e = ents.Create(v.class)
e:SetPos(v.pos)
e:SetAngles(v.angles)
e:Spawn()
e:Activate()
e._propshit = true
v.callback(e)
end
end
hook.Add("InitPostEntity", "propshit_autospawn", propshit_autospawn)
concommand.Add("propshit_respawn_ents", function(p)
if IsValid(p) and not p:IsAdmin() then return end
for k, v in ipairs(ents.GetAll()) do if v._propshit then v:Remove() end end
propshit_autospawn()
end)
end
local modelBlacklist = {
["models/props_vehicles/tanker001a.mdl"] = true,
["models/props_vehicles/apc001.mdl"] = true,
["models/props_combine/combinetower001.mdl"] = true,
["models/cranes/crane_frame.mdl"] = true,
["models/items/item_item_crate.mdl"] = true,
["models/props/cs_militia/silo_01.mdl"] = true,
["models/props/cs_office/microwave.mdl"] = true,
["models/props/de_train/biohazardtank.mdl"] = true,
["models/props_buildings/building_002a.mdl"] = true,
["models/props_buildings/collapsedbuilding01a.mdl"] = true,
["models/props_buildings/project_building01.mdl"] = true,
["models/props_buildings/row_church_fullscale.mdl"] = true,
["models/props_c17/consolebox01a.mdl"] = true,
["models/props_c17/oildrum001_explosive.mdl"] = true,
["models/props_c17/paper01.mdl"] = true,
["models/props_c17/trappropeller_engine.mdl"] = true,
["models/props_canal/canal_bridge01.mdl"] = true,
["models/props_canal/canal_bridge02.mdl"] = true,
["models/props_canal/canal_bridge03a.mdl"] = true,
["models/props_canal/canal_bridge03b.mdl"] = true,
["models/props_combine/combine_citadel001.mdl"] = true,
["models/props_combine/combine_mine01.mdl"] = true,
["models/props_combine/combinetrain01.mdl"] = true,
["models/props_combine/combinetrain02a.mdl"] = true,
["models/props_combine/combinetrain02b.mdl"] = true,
["models/props_combine/prison01.mdl"] = true,
["models/props_combine/prison01c.mdl"] = true,
["models/props_industrial/bridge.mdl"] = true,
["models/props_junk/garbage_takeoutcarton001a.mdl"] = true,
["models/props_junk/gascan001a.mdl"] = true,
["models/props_junk/glassjug01.mdl"] = true,
["models/props_junk/trashdumpster02.mdl"] = true,
["models/props_phx/amraam.mdl"] = true,
["models/props_phx/ball.mdl"] = true,
["models/props_phx/cannonball.mdl"] = true,
["models/props_phx/huge/evildisc_corp.mdl"] = true,
["models/props_phx/misc/flakshell_big.mdl"] = true,
["models/props_phx/misc/potato_launcher_explosive.mdl"] = true,
["models/props_phx/mk-82.mdl"] = true,
["models/props_phx/oildrum001_explosive.mdl"] = true,
["models/props_phx/torpedo.mdl"] = true,
["models/props_phx/ww2bomb.mdl"] = true,
["models/props_wasteland/cargo_container01.mdl"] = true,
["models/props_wasteland/cargo_container01.mdl"] = true,
["models/props_wasteland/cargo_container01b.mdl"] = true,
["models/props_wasteland/cargo_container01c.mdl"] = true,
["models/props_wasteland/depot.mdl"] = true,
["models/xqm/coastertrack/special_full_corkscrew_left_4.mdl"] = true,
["models/props_junk/propane_tank001a.mdl"] = true,
["models/props_c17/fountain_01.mdl"] = true,
["models/props_trainstation/train003.mdl"] = true,
["models/props_foliage/tree_poplar_01.mdl"] = true,
["models/mechanics/solid_steel/i_beam2_32.mdl"] = true,
["models/props_c17/furnituredrawer001a_chunk06.mdl"] = true,
["models/mechanics/solid_steel/i_beam2_32.mdl"] = true,
["models/props_phx/mechanics/slider2.mdl"] = true,
["models/props_phx/gears/rack70.mdl"] = true,
["models/mechanics/gears2/pinion_80t1.mdl"] = true,
["models/nova/airboat_seat.mdl"] = true,
["models/mechanics/robotics/a4.mdl"] = true,
["models/mechanics/roboticslarge/claw_hub_8.mdl"] = true,
["models/perftest/loader_static.mdl"] = true,
["models/mechanics/robotics/e4.mdl"] = true,
["models/mechanics/roboticslarge/e4.mdl"] = true,
["models/perftest/rocksground01b.mdl"] = true,
["models/mechanics/roboticslarge/g4.mdl"] = true,
["models/mechanics/roboticslarge/e4.mdl"] = true,
["models/mechanics/roboticslarge/j4.mdl"] = true,
["models/props_animated_breakable/smokestack.mdl"] = true,
["models/props_animated_breakable/smokestack_gib_01.mdl"] = true,
["models/xqm/rails/slope_down_90.mdl"] = true,
["models/props_animated_breakable/smokestack_gib_02.mdl"] = true,
["models/props_animated_breakable/smokestack_gib_03.mdl"] = true,
["models/props_animated_breakable/smokestack_gib_04.mdl"] = true,
["models/props_animated_breakable/smokestack_gib_05.mdl"] = true,
["models/props_animated_breakable/smokestack_gib_06.mdl"] = true,
["models/props_animated_breakable/smokestack_gib_07.mdl"] = true,
["models/props_animated_breakable/smokestack_gib_08.mdl"] = true,
["models/xqm/coastertrack/special_full_loop_3.mdl"] = true,
["models/props_animated_breakable/smokestack_gib_09.mdl"] = true,
["models/props_animated_breakable/smokestack_gib_10.mdl"] = true,
["models/xqm/coastertrack/special_full_corkscrew_right_4.mdl"] = true,
["models/props_buildings/collapsedbuilding01awall.mdl"] = true,
["models/props_buildings/collapsedbuilding02a.mdl"] = true,
["models/props_buildings/collapsedbuilding02b.mdl"] = true,
["models/xqm/coastertrack/special_half_corkscrew_right_4.mdl"] = true,
["models/props_buildings/collapsedbuilding02c.mdl"] = true,
["models/props_buildings/project_destroyedbuildings01.mdl"] = true,
["models/props_buildings/project_building03_skybox.mdl"] = true,
["models/props_buildings/project_building03.mdl"] = true,
["models/props_buildings/project_building02_skybox.mdl"] = true,
["models/props_buildings/project_building02.mdl"] = true,
["models/props_buildings/project_building01_skybox.mdl"] = true,
["models/props_buildings/factory_skybox001a.mdl"] = true,
["models/xqm/coastertrack/special_full_corkscrew_right_3.mdl"] = true,
["models/props_buildings/row_res_1_fullscale.mdl"] = true,
["models/props_buildings/watertower_002a.mdl"] = true,
["models/props_buildings/watertower_001c.mdl"] = true,
["models/props_buildings/watertower_001a.mdl"] = true,
["models/props_buildings/short_building001a.mdl"] = true,
["models/props_buildings/row_res_2_fullscale.mdl"] = true,
["models/props_buildings/row_res_2_ascend_fullscale.mdl"] = true,
["models/xqm/coastertrack/special_full_corkscrew_left_2.mdl"] = true,
["models/props_canal/generator01.mdl"] = true,
["models/props_canal/generator02.mdl"] = true,
["models/props_canal/locks_large.mdl"] = true,
["models/props_canal/locks_large_b.mdl"] = true,
["models/props_canal/locks_small.mdl"] = true,
["models/props_canal/locks_small_b.mdl"] = true,
["models/xqm/coastertrack/special_half_corkscrew_right_4.mdl"] = true,
["models/props_canal/canal_bars001.mdl"] = true,
["models/props_trainstation\train003.mdl"] = true,
["models/props_canal/canal_bridge04.mdl"] = true,
["models/props_canal/pipe_bracket001.mdl"] = true,
["models/props_canal/canal_bridge_railing_lamps.mdl"] = true,
["models/props_canal/canal_bridge_railing02.mdl"] = true,
["models/props_canal/canal_bridge_railing01.mdl"] = true,
["models/xqm/coastertrack/special_half_corkscrew_right_3.mdl"] = true,
["models/props_canal/winch01.mdl"] = true,
["models/props_canal/rock_riverbed01c.mdl"] = true,
["models/props_canal/rock_riverbed01d.mdl"] = true,
["models/props_canal/rock_riverbed02a.mdl"] = true,
["models/props_canal/rock_riverbed02b.mdl"] = true,
["models/props_canal/winch02c.mdl"] = true,
["models/props_canal/winch02d.mdl"] = true,
["models/props_canal/rock_riverbed01b.mdl"] = true,
["models/props_canal/refinery_04.mdl"] = true,
["models/props_canal/refinery_05.mdl"] = true,
["models/xqm/rails/twist_90_left.mdl"] = true,
["models/props_canal/canal_bars001.mdl"] = true,
["models/props_canal/bridge_pillar02.mdl"] = true,
["models/xqm/rails/loop_right.mdl"] = true,
["models/props_citizen_tech/windmill_blade002a.mdl"] = true,
["models/props_citizen_tech/till001a_base01.mdl"] = true,
["models/props_citizen_tech/steamengine001a.mdl"] = true,
["models/props_citizen_tech/guillotine001a_base01.mdl"] = true,
["models/props_citizen_tech/firetrap_gashose01c.mdl"] = true,
["models/props_citizen_tech/firetrap_gashose01b.mdl"] = true,
["models/props_citizen_tech/firetrap_button01a.mdl"] = true,
["models/props_citizen_tech/windmill_blade004a.mdl"] = true,
["models/props_phx/misc/potato_launcher_chamber.mdl"] = true,
["models/props_combine/combine_train02a.mdl"] = true,
}
local noSounds = {
"vo/engineer_no01.mp3",
"vo/engineer_no02.mp3",
"vo/engineer_no03.mp3",
}
local log = CreateConVar("propshit_log", "1", FCVAR_ARCHIVE, "Enables the logging of prop spawns by propshit.")
local function PlayerSpawnProp(ply, model)
local escapedModel = model:lower():gsub("\\","/"):gsub("//", "/"):Trim()
if modelBlacklist[escapedModel] then
if SERVER then ply:EmitSound(noSounds[math.random(1, #noSounds)], 140) end
return false end
if SERVER and log:GetBool() then print("PROP EVENT: ", ply, " -> ", escapedModel) end
return true
end
hook.Add("PlayerSpawnProp", "propshit", PlayerSpawnProp)
local function CanDrive()
return false
end
hook.Add("CanDrive", "propshit", CanDrive)
local function PlayerSpawnNPC()
return false
end
hook.Add("PlayerSpawnNPC", "propshit", PlayerSpawnNPC)
local function PlayerSpawnRagdoll()
return false
end
hook.Add("PlayerSpawnRagdoll", "propshit", PlayerSpawnRagdoll)
local spam = CurTime()
local function CanTool(ply, trace, mode)
if mode == "duplicator" then
if SERVER then ply:ChatPrint("The duplicator is not allowed here. Build your own stuff or use advdupe2!") end
return false end
if mode == "paint" then
if SERVER and spam < CurTime() - 1 then ply:ChatPrint("Paint is banned here, there is no legitimate use for it.") spam = CurTime() end
return false end
if mode == "physprop" and trace.Entity:IsValid() and trace.Entity:GetClass() == "prop_vehicle_jeep" then
return false
end
if trace.Entity.m_tblToolsAllowed then
local vFound = false
for k, v in pairs(trace.Entity.m_tblToolsAllowed) do
if mode == v then vFound = true end
end
if not vFound then return false end
end
if trace.Entity.CanTool then
return trace.Entity:CanTool(ply, trace, mode)
end
return true
end
hook.Add("CanTool", "propshit", CanTool)
| a1955ad942cdfc5c3a641358d4f789dd1c972407 | [
"Markdown",
"Lua"
] | 22 | Lua | CaveeJohnson/misc-scripts | 541ef60354c80e3f57f7c172110b51cd95fc7910 | eb55b21e1aa3b09d21f823113128859bc2589803 |
refs/heads/master | <repo_name>suhass92/Shittydotsh<file_sep>/int-auto-recon.sh
#!/bin/bash
#<NAME>
#@lixmk
#http://exfil.co
# TODO: Check dependancies
# TODO: Install missing dependancies
# TODO: Make sure I'm spelling dependancies correctly
echo " "
echo "###################################################################################"
echo "# int-auto-recon.sh performs recon, enumeration, and vulnerability identification #"
echo "# #"
echo "# Some Alpha ass shit right here. #"
echo "# Probably riddled with typos, don't run in prod. #"
echo "# #"
echo "# WARNING: This is NOT QUIET. In fact, it's FUCKING LOUD. #"
echo "# WARNING: This is NOT QUIET. In fact, it's FUCKING LOUD. #"
echo "# WARNING: This is NOT QUIET. In fact, it's FUCKING LOUD. #"
echo "# #"
echo "# Please check the readme for a list of tools used and dependecies. #"
echo "# # TODO: create readme #"
echo "###################################################################################"
echo " "
EXPECTED_ARGS=1;
if [ $# -ne $EXPECTED_ARGS ]
then
echo "Usage: `basename $0` <target file (nmap format)>"
exit 1
fi
#Creating directory structure
mkdir ./int-auto-recon
mkdir ./int-auto-recon/nmap
mkdir ./int-auto-recon/nmap/targets
mkdir ./int-auto-recon/ports
mkdir ./int-auto-recon/nikto
mkdir ./int-auto-recon/initial
mkdir ./int-auto-recon/medusa
mkdir ./int-auto-recon/ssh-ciphers
mkdir ./int-auto-recon/ssl-ciphers
mkdir ./int-auto-recon/robots
mkdir ./int-auto-recon/enum4linux
mkdir ./int-auto-recon/enum4linux/users
mkdir ./int-auto-recon/enum4linux/shares
#Checking whether or not to start responder
echo "Do you want to start Responder in a screen session?"
echo -n "'yes' or 'no': "
read -e RESPYN
if [ "$RESPYN" = "yes" ]
then
echo -n "Local IP:"
read -e LIP
echo "Starting responder session with -i $LIP. Other tests continuing."
echo ""
screen -dmS responder -m responder -i $LIP
else
echo "No Responder session started. Testing will continue."
echo ""
fi
# TODO: Add Ping scan option for large scopes
#Nmap All TCP ports on all tagets
echo '[*] Initiating Full TCP port scan of all targets'
echo '[*] Timing updates provided every 120 seconds'
nmap -Pn --stats-every 120s --max-rtt-timeout 250ms --max-retries 3 --open --top-ports=65535 -oA ./int-auto-recon/nmap/fullscan -iL $1 | egrep '(remaining|Stats: )'
echo '[*] Full Scan Complete - Sorting Output'
cat ./int-auto-recon/nmap/fullscan.gnmap | grep open | cut -d " " -f 2 | grep -v Nmap > ./int-auto-recon/nmap/targets/listening_hosts.txt
echo '[*] Creating port file for next Nmap scan'
cat ./int-auto-recon/nmap/fullscan.gnmap | grep -v Status | grep -v Nmap | cut -d ':' -f 3 | sed "s|/open/tcp/||g" |cut -f 1 | sed 's|///|\n|g' | sed 's/ //g' | sed 's/,//g' | cut -d '/' -f 1 | sort -u | sed ':a;N;$!ba;s/\n/,/g' | sed 's/,//' > ./int-auto-recon/nmap/targets/portfile.txt
echo '[*] Port file complete'
echo ""
#Nmap Script/Service Scan only againt listening hosts/ports
ports=$(cat ./int-auto-recon/nmap/targets/portfile.txt)
echo '[*] Initiating Script and Service scan of open ports on all responding hosts'
echo "[*] Open ports: $ports"
echo '[*] Timing updates provided every 60 seconds'
nmap -Pn -sC -sV --open --stats-every 60s -oA ./int-auto-recon/nmap/script_service -iL ./int-auto-recon/nmap/targets/listening_hosts.txt -p $ports | egrep '(remaining|Stats: )'
echo '[*] Script/Service Scan Complete'
echo ""
#Sorting Nmap Outputs for common ports
cd ./int-auto-recon/
echo '[*] Sorting nmap output'
cat ./nmap/fullscan.gnmap | grep '21/open' | cut -d " " -f 2 > ./ports/ftp.txt
cat ./nmap/fullscan.gnmap | grep '22/open' | cut -d " " -f 2 > ./ports/ssh.txt
cat ./nmap/fullscan.gnmap | grep '23/open' | cut -d " " -f 2 > ./ports/telnet.txt
cat ./nmap/fullscan.gnmap | grep '53/open' | cut -d " " -f 2 > ./ports/dns.txt
cat ./nmap/fullscan.gnmap | grep '80/open' | cut -d " " -f 2 > ./ports/80.txt
cat ./nmap/fullscan.gnmap | grep '443/open' | cut -d " " -f 2 > ./ports/443.txt
cat ./nmap/fullscan.gnmap | grep '445/open' | cut -d " " -f 2 > ./ports/445.txt
cat ./nmap/fullscan.gnmap | grep '8080/open' | cut -d " " -f 2 > ./ports/8080.txt
cat ./nmap/fullscan.gnmap | grep '8443/open' | cut -d " " -f 2 > ./ports/8443.txt
cat ./nmap/fullscan.gnmap | grep '1433/open' | cut -d " " -f 2 > ./ports/mssql.txt
cat ./nmap/fullscan.gnmap | grep '3306/open' | cut -d " " -f 2 > ./ports/mysql.txt
cat ./nmap/fullscan.gnmap | grep '3389/open' | cut -d " " -f 2 > ./ports/rdp.txt
cat ./nmap/fullscan.gnmap | grep open | cut -d " " -f 2 | grep -v Nmap | sort -u > ./ports/allips.txt
echo '[*] Sorting Complete'
echo ""
#Creating csv of nmap results
echo '[*] Creating .csv of Nmap script/service results'
xmlstarlet sel --net -T -t -m "//state[@state='open']" -m ../../.. -v "address[@addrtype='ipv4']/@addr" -o "," -v hostnames/hostname[1]/@name -o "," -v os/osmatch[1]/@name -o "," -b -m .. -v @portid -o '/' -v @protocol -o "," -m service -i "@tunnel" -v @tunnel -o "|" -b -v @name -o "," -v @product -o ' ' -v @version -v @extrainfo -o "," -m ../script -v @id -o ',' -b -n -b -b -n -b -b ./nmap/script_service.xml | grep -v '^$' | sed 's/ *$//;s/,*$//' | sed "s/' */'/g" | awk -F'\t' '{ sub(/[,;][^()]*/,"",$3);for (i=1; i<NF; i++){printf "%s%s",$i,FS};printf "%s\n",$i}' | awk -F'\t' '{ sub(/ or [^()]*/,"",$3);for (i=1; i<NF; i++){printf "%s%s",$i,FS};printf "%s\n",$i}' | sed "s/\tssl|\([^\t]*\)/\t\1s/;s/\thttpss\t/\thttps\t/" | sort -uV | cut -d ',' -f 1,2,4,5,6 | sed '1iIP,Host,Port,Services,Notes' > nmap.csv
echo '[*] csv saved as nmap.csv'
echo ""
#Creating host port table for Report
echo '[*] Creating Host/Port table'
/root/tools/josko_pentest/net_discovery_reporter.rb -f ./nmap/script_service.xml
echo '[*] Thanks JoSko! Creation complete, saved to ./Net_Discovery_Report.docx'
echo ""
#Launching EyeWitness against Web, RDP, VNC
echo '[*] Launching EyeWitness for Web'
/root/tools/eyewitness/EyeWitness.py -f ./nmap/script_service.xml -d ./eyewitnessWEB --results 10000 --web --no-prompt --no-dns
echo '[*] EyeWitness for Web Complete'
echo ""
echo '[*] Launching EyeWitness for RDP'
/root/tools/eyewitness/EyeWitness.py -f ./nmap/script_service.xml -d ./eyewitnessRDP --results 10000 --rdp --no-prompt --no-dns
echo '[*] EyeWitness for RDP Complete'
echo ""
echo '[*] Launching EyeWitness for VNC'
/root/tools/eyewitness/EyeWitness.py -f ./nmap/script_service.xml -d ./eyewitnessVNC --results 10000 --vnc --no-prompt --no-dns
echo '[*] EyeWitness for VNC Complete'
echo ""
#Tar'ing up the basics
echo '[*] Adding intital results to initial.tar'
cp -R ./nmap ./initial/
cp ./Net_Discovery_Report.docx ./initial/
cp -R ./eyewitness* ./initial/
tar -cf initial.tar ./initial/
rm -rf ./initial/
echo "[*] Tar'ing complete"
echo ""
#Enumerating Windows hosts for null sessions. Will pull lists of usernames
echo '[*] Enumerating username from Windows boxes with null sessions'
for i in $(cat ./ports/445.txt); do
enum4linux -U $i >> ./enum4linux/users/$i.txt;
done
cat ./enum4linux/users/*.txt | grep index | cut -d " " -f 8 | cut -f 1 | sort -u > ./enum4linux/identified-users.txt
echo '[*] User enumeration complete'
echo ""
#Starting basic password guessing for identified users against possible domain controllers
#Only making two guesses to help prevent lockouts
# TODO: Figure out better way to identify possible DC's
# TODO: Attempt to automate finding account lockout threshold and implimenting as a var.
echo "[*] Guessing user-as-pass and Password1 for enumerated users against possible DC's"
medusa -M smbnt -H ./ports/dns.txt -U ./enum4linux/identified-users.txt -p <PASSWORD> -e s -O UAP-Password1-medusa.txt
echo "[*] Password guessing complete"
echo ""
# TODO: Parse these results into enum4linux for full DC dump
# TODO: Parse these results into enum4linux for finding accessible shares across all hosts with 445 (LOUD AF)
# TODO: Parse these results into GPP recovery script
#SSH Cipher Enumeration
echo '[*] Testing SSH Ciphers on port 22'
nmap --script ssh2-enum-algos -iL ./ports/ssh.txt -p 22 -oA ./ssh-ciphers/ciphers
echo '[*] SSH Cipher Enumeration Complete'
echo ""
#SSL Cipher Scanning
echo '[*] Testing SSL Ciphers on ports 443, 8443, and 3389'
for i in $(cat ./ports/443.txt); do
java -jar /root/tools/TestSSLServer.jar $i 443 > ./ssl-ciphers/$i.443.txt && echo "[*] $i:443 Complete";
done
for i in $(cat ./ports/8443.txt); do
java -jar /root/tools/TestSSLServer.jar $i 8443 > ./ssl-ciphers/$i.8443txt && echo "[*] $i:8443 Complete";
done
for i in $(cat ./ports/rdp.txt); do
java -jar /root/tools/TestSSLServer.jar $i 3389 > ./ssl-ciphers/$i.3389txt && echo "[*] $i:3389 Complete";
done
echo '[*] SSL Cipher Test Complete'
echo '[*] Sorting Cipher Outputs'
grep RC4 ./ssl-ciphers/* | cut -d " " -f 1 | cut -d '.' -f 2,3,4,5,6 | sed 's|/||g' | sort -u | sed 's/.443/:443/g' | sed 's/.8443/:8443/g' | sed 's/.3389/:3389/g' > ./ssl-ciphers/RC4.txt
grep CBC ./ssl-ciphers/* | cut -d " " -f 1 | cut -d '.' -f 2,3,4,5,6 | sed 's|/||g' | sort -u | sed 's/.443/:443/g' | sed 's/.8443/:8443/g' | sed 's/.3389/:3389/g' > ./ssl-ciphers/CBC.txt
grep SSLv2 ./ssl-ciphers/* | cut -d " " -f 1 | cut -d '.' -f 2,3,4,5,6 | sed 's|/||g' | sort -u | sed 's/.443/:443/g' | sed 's/.8443/:8443/g' | sed 's/.3389/:3389/g' > ./ssl-ciphers/SSLv2.txt
grep SSLv3 ./ssl-ciphers/* | cut -d " " -f 1 | cut -d '.' -f 2,3,4,5,6 | sed 's|/||g' | sort -u | sed 's/.443/:443/g' | sed 's/.8443/:8443/g' | sed 's/.3389/:3389/g' > ./ssl-ciphers/SSLv3.txt
echo '[*] Sorting Complete'
echo ""
#Testing Complete
echo '[*] Tests complete. Results written to ./int-auto-recon'
echo "[*] Don't forget to check the rspndr screen for some free hashes"
<file_sep>/post-nikto.sh
################################
# Post Nikto Stuff #
# This should be run after the #
# nikto screens are completed #
################################
#Checking Nikto Results for Cookies without HTTPOnly flag set
echo "Checking Nikto Results for Cookies without HTTPOnly flag set"
for i in $(ls ./init-recon/nikto/*-nikto.txt); do cat $i | fgrep -q "httponly flag" && echo -n $i | cut -d '/' -f 3 | sed 's/-/:/g' | sed 's/.txt//g' >> cookie_httponly.txt && cat $i | grep "httponly flag" | awk -F " " '{ print " "$4}' >> cookie_httponly.txt; done
#Checking Nikto Results for Cookies without Secure flag set
echo "Checking Nikto Results for Cookies without Secure flag set"
for i in $(ls ./init-recon/nikto/*-nikto.txt); do cat $i | fgrep -q "without the secure flag" && echo -n $i | cut -d '/' -f 3 | sed 's/-/:/g' | sed 's/.txt//g' >> cookie_secure.txt && cat $i | grep "without the secure flag" | awk -F " " '{ print " "$5}' >> cookie_secure.txt; done
<file_sep>/ext-auto-recon.sh
#!/bin/bash
# <NAME>
# @lixmk
# http://exfil.co
echo " "
echo "###################################################################################"
echo "# ext-auto-recon.sh performs recon, enumeration, and vulnerability identification #"
echo "# #"
echo "# WARNING: This is NOT QUIET. In fact, it's FUCKING LOUD. #"
echo "# WARNING: This is NOT QUIET. In fact, it's FUCKING LOUD. #"
echo "# WARNING: This is NOT QUIET. In fact, it's FUCKING LOUD. #"
echo "# (Not for covert testing) #"
echo "# #"
echo "# Please check the readme for a list of tools used and dependencies. #"
echo "# This script can take a while, it's suggested to run within screen #"
echo "###################################################################################"
echo " "
EXPECTED_ARGS=1;
if [ $# -ne $EXPECTED_ARGS ]
then
echo "Usage: `basename $0` <target file (nmap format)>"
exit 1
fi
mkdir ./ext-auto-recon
mkdir ./ext-auto-recon/nmap
mkdir ./ext-auto-recon/nmap/targets
mkdir ./ext-auto-recon/ports
mkdir ./ext-auto-recon/nikto
mkdir ./ext-auto-recon/initial
mkdir ./ext-auto-recon/medusa
mkdir ./ext-auto-recon/ssh-ciphers
mkdir ./ext-auto-recon/ssl-ciphers
mkdir ./ext-auto-recon/robots
#All TCP ports on all tagets
echo '[*] Initiating Full TCP port scan of all targets'
echo '[*] Timing updates provided every 120 seconds'
nmap -Pn --stats-every 120s --max-rtt-timeout 250ms --max-retries 3 --open --top-ports=65535 -oA ./ext-auto-recon/nmap/fullscan -iL $1 | egrep '(remaining|Stats: )'
echo '[*] Full Scan Complete - Sorting Output'
cat ./ext-auto-recon/nmap/fullscan.gnmap | grep open | cut -d " " -f 2 | grep -v Nmap > ./ext-auto-recon/nmap/targets/listening_hosts.txt
echo '[*] Creating port file for next Nmap scan'
cat ./ext-auto-recon/nmap/fullscan.gnmap | grep -v Status | grep -v Nmap | cut -d ':' -f 3 | sed "s|/open/tcp/||g" |cut -f 1 | sed 's|///|\n|g' | sed 's/ //g' | sed 's/,//g' | cut -d '/' -f 1 | sort -u | sed ':a;N;$!ba;s/\n/,/g' | sed 's/,//' > ./ext-auto-recon/nmap/targets/portfile.txt
echo '[*] Port file complete'
echo ""
#Script/Service Scan
ports=$(cat ./ext-auto-recon/nmap/targets/portfile.txt)
echo '[*] Initiating Script and Service scan of open ports on all responding hosts'
echo "[*] Open ports: $ports"
echo '[*] Timing updates provided every 120 seconds'
nmap -Pn -sC -sV --open --stats-every 120s -oA ./ext-auto-recon/nmap/script_service -iL ./ext-auto-recon/nmap/targets/listening_hosts.txt -p $ports | egrep '(remaining|Stats: )'
echo '[*] Script/Service Scan Complete'
echo ""
#Quick Nmap UDP Scan (500, 161)
echo '[*] Initiating UDP can for 161, 500, and 4070 (HID discoveryd)'
echo '[*] Timing updates provided every 60 seconds'
nmap -Pn -sU -sV --open --stats-every 60s -p 161,500,4070 -oA ./ext-auto-recon/nmap/udp -iL ./ext-auto-recon/nmap/targets/listening_hosts.txt | egrep '(remaining|Stats: )'
echo '[*] UDP scan complete'
echo ""
#Sorting Nmap Outputs
cd ./ext-auto-recon/
echo '[*] Sorting nmap output'
cat ./nmap/fullscan.gnmap | grep '21/open' | cut -d " " -f 2 > ./ports/21.txt
cat ./nmap/fullscan.gnmap | grep '22/open' | cut -d " " -f 2 > ./ports/22.txt
cat ./nmap/fullscan.gnmap | grep '23/open' | cut -d " " -f 2 > ./ports/23.txt
cat ./nmap/fullscan.gnmap | grep '80/open' | cut -d " " -f 2 > ./ports/80.txt
cat ./nmap/fullscan.gnmap | grep '443/open' | cut -d " " -f 2 > ./ports/443.txt
cat ./nmap/fullscan.gnmap | grep '8080/open' | cut -d " " -f 2 > ./ports/8080.txt
cat ./nmap/fullscan.gnmap | grep '8443/open' | cut -d " " -f 2 > ./ports/8443.txt
cat ./nmap/fullscan.gnmap | grep '1433/open' | cut -d " " -f 2 > ./ports/1433.txt
cat ./nmap/fullscan.gnmap | grep '3306/open' | cut -d " " -f 2 > ./ports/3306.txt
cat ./nmap/fullscan.gnmap | grep '3389/open' | cut -d " " -f 2 > ./ports/3389.txt
cat ./nmap/udp.gnmap | grep '161/open' | cut -d " " -f 2 > ./ports/161.txt
cat ./nmap/udp.gnmap | grep '500/open' | cut -d " " -f 2 > ./ports/500.txt
cat ./nmap/fullscan.gnmap | grep open | cut -d " " -f 2 | grep -v Nmap | sort -u > ./ports/allips.txt
echo '[*] Sorting Complete'
echo ""
#Creating csv of nmap results
echo '[*] Creating csv of Nmap results'
xmlstarlet sel --net -T -t -m "//state[@state='open']" -m ../../.. -v "address[@addrtype='ipv4']/@addr" -o "," -v hostnames/hostname[1]/@name -o "," -v os/osmatch[1]/@name -o "," -b -m .. -v @portid -o '/' -v @protocol -o "," -m service -i "@tunnel" -v @tunnel -o "|" -b -v @name -o "," -v @product -o ' ' -v @version -v @extrainfo -o "," -m ../script -v @id -o ',' -b -n -b -b -n -b -b ./nmap/script_service.xml | grep -v '^$' | sed 's/ *$//;s/,*$//' | sed "s/' */'/g" | awk -F'\t' '{ sub(/[,;][^()]*/,"",$3);for (i=1; i<NF; i++){printf "%s%s",$i,FS};printf "%s\n",$i}' | awk -F'\t' '{ sub(/ or [^()]*/,"",$3);for (i=1; i<NF; i++){printf "%s%s",$i,FS};printf "%s\n",$i}' | sed "s/\tssl|\([^\t]*\)/\t\1s/;s/\thttpss\t/\thttps\t/" | sort -uV | cut -d ',' -f 1,2,4,5,6 | sed '1iIP,Host,Port,Services,Notes' > nmap.csv
echo '[*] csv saved as nmap.csv'
echo ""
#Creating host port table for Report
echo '[*] Creating Host/Port table'
/root/tools/josko_pentest/net_discovery_reporter.rb -f ./nmap/script_service.xml
echo '[*] Thanks JoSko! Creation complete, saved to ./Net_Discovery_Report.docx'
#Launching EyeWitness
echo '[*] Launching EyeWitness for Web'
/root/tools/eyewitness/EyeWitness.py -f ./nmap/script_service.xml -d ./eyewitnessWEB --results 10000 --web --no-prompt --no-dns
echo '[*] EyeWitness for Web Complete'
echo ""
echo '[*] Launching EyeWitness for RDP'
/root/tools/eyewitness/EyeWitness.py -f ./nmap/script_service.xml -d ./eyewitnessRDP --results 10000 --rdp --no-prompt --no-dns
echo '[*] EyeWitness for RDP Complete'
echo ""
echo '[*] Launching EyeWitness for VNC'
/root/tools/eyewitness/EyeWitness.py -f ./nmap/script_service.xml -d ./eyewitnessVNC --results 10000 --vnc --no-prompt --no-dns
echo '[*] EyeWitness for VNC Complete'
echo ""
#Tar'ing up the basics
echo '[*] Adding intital results to initial.tar'
cp -R ./nmap ./initial/
cp ./Net_Discovery_Report.docx ./initial/
cp -R ./eyewitness* ./initial/
tar -cf initial.tar ./initial/
rm -rf ./initial/
echo "[*] Tar'ing complete"
echo ""
#Launching Nikto against valid targets
cd ./nikto
#Creating target list
echo '[*] Creating target list'
for i in $(cat ../ports/80.txt); do
echo "nikto -Tuning x6 -maxtime 60m -output "$i-80-nikto.txt" -host http://$i" >> targets.txt;
done
for i in $(cat ../ports/8080.txt); do
echo "nikto -Tuning x6 -maxtime 60m -output "$i-8080-nikto.txt" -host http://$i:8080" >> targets.txt;
done
for i in $(cat ../ports/443.txt); do
echo "nikto -Tuning x6 -maxtime 60m -output "$i-443-nikto.txt" -host https://$i" >> targets.txt;
done
for i in $(cat ../ports/8443.txt); do
echo "nikto -Tuning x6 -maxtime 60m -output "$i-8443-nikto.txt" -host https://$i:8443" >> targets.txt;
done
#Splitting target list and launching backgrounded sessions
echo '[*] Splitting targets and launching backgrounded sessions'
split -e -n l/5 targets.txt nik2
for i in $(ls nik2*); do
echo " [*] Backgrounding Nikto Screen Session: $i"
screen -dmS $i sh $i;
done
echo '[*] Nikto sessions screened. Continuing additional tests'
cd ../
#Medusa some targets
echo '[*] Starting Basic Medusa password guesses'
echo '[*] Backgrounding SSH guesses'
screen -dmS ssh -m medusa -M ssh -H ./ports/22.txt -u root -p <PASSWORD> -e ns -O ./medusa/ssh.medusa
echo '[*] Backgrounding FTP guesses'
screen -dmS ftp -m medusa -M ftp -H ./ports/21.txt -U /root/wordlists/ftpusers.txt -p <PASSWORD> -e ns -O ./medusa/ftp.medusa
# TODO: Fix users for FTP
#SSH Cipher Enumeration
echo '[*] Testing SSH Ciphers on port 22'
echo '[*] Timing updates provided every 60 seconds'
nmap --script ssh2-enum-algos --stats-every 60s -iL ./ports/22.txt -p 22 -oA ./ssh-ciphers/ciphers | egrep '(remaining|Stats: )'
echo '[*] SSH Cipher Enumeration Complete'
echo ""
#SSL Cipher Scanning
echo '[*] Testing SSL Ciphers on ports 443, 8443, and 3389'
for i in $(cat ./ports/443.txt); do
java -jar /root/tools/TestSSLServer.jar $i 443 > ./ssl-ciphers/$i.443 && echo -n '.';
done
echo ""
for i in $(cat ./ports/8443.txt); do
java -jar /root/tools/TestSSLServer.jar $i 8443 > ./ssl-ciphers/$i.8443 && echo -n '.';
done
echo ""
for i in $(cat ./ports/3389.txt); do
java -jar /root/tools/TestSSLServer.jar $i 3389 > ./ssl-ciphers/$i.8443 && echo -n '.';
done
echo ""
echo '[*] SSL Cipher Test Complete'
echo '[*] Sorting Cipher Outputs'
grep RC4 ./ssl-ciphers/* | cut -d " " -f 1 | cut -d '/' -f 3 | cut -d '.' -f 2,3,4,5,6 | sed 's|:||g' | sort -u | sed 's/\.443/:443/g' | sed 's/\.8443/:8443/g' | sed 's/\.3389/:3389/g' > ./ssl-ciphers/RC4.txt
grep CBC ./ssl-ciphers/* | cut -d " " -f 1 | cut -d '/' -f 3 | cut -d '.' -f 2,3,4,5,6 | sed 's|:||g' | sort -u | sed 's/\.443/:443/g' | sed 's/.8443/:8443/g' | sed 's/.3389/:3389/g' > ./ssl-ciphers/CBC.txt
grep SSLv2 ./ssl-ciphers/* | cut -d " " -f 1 | cut -d '/' -f 3 | cut -d '.' -f 2,3,4,5,6 | sed 's|:||g' | sort -u | sed 's/\.443/:443/g' | sed 's/.8443/:8443/g' | sed 's/.3389/:3389/g' > ./ssl-ciphers/SSLv2.txt
grep SSLv3 ./ssl-ciphers/* | cut -d " " -f 1 | cut -d '/' -f 3 | cut -d '.' -f 2,3,4,5,6 | sed 's|:||g' | sort -u | sed 's/\.443/:443/g' | sed 's/.8443/:8443/g' | sed 's/.3389/:3389/g' > ./ssl-ciphers/SSLv3.txt
echo '[*] Sorting Complete'
echo ""
#Checking for robots.txt
echo '[*] Checking for robots.txt on common http(s) ports'
#Checking hosts with 80 open
echo '[*]Checking for robots.txt on port 80'
for i in $(cat ./ports/80.txt); do
wget --max-redirect 0 -q -t 1 -T 3 -O ./robots/$i-80 http://$i/robots.txt && fgrep -q "Disallow" ./robots/$i-80 || rm ./robots/$i-80; sed -i "1s/^/$i:80\n/" ./robots/$i-80 2> /dev/null && echo " [*]Robots.txt found for $i:80";
done
#Checking hosts with 443 open
echo '[*]Checking for robots.txt on port 443'
for i in $(cat ./ports/443.txt); do
wget --max-redirect 0 --no-check-certificate -q -t 1 -T 3 -O ./robots/$i-443 https://$i/robots.txt && fgrep -q "Disallow" ./robots/$i-443 || rm ./robots/$i-443; sed -i "1s/^/$i:443\n/" ./robots/$i-443 2> /dev/null && echo " [*]Robots.txt found for $i:443";
done
#Checking hosts with 8080 open
echo '[*]Checking for robots.txt on port 8080'
for i in $(cat ./ports/8080.txt); do
wget --max-redirect 0 -q -t 1 -T 3 -O ./robots/$i-8080 http://$i:8080/robots.txt && fgrep -q "Disallow" ./robots/$i-8080 || rm ./robots/$i-8080; sed -i "1s/^/$i:8080\n/" ./robots/$i-8080 2> /dev/null && echo " [*]Robots.txt found for $i:8080";
done
#Checking hosts with 8443 open
echo '[*]Checking for robots.txt on port 8443'
for i in $(cat ./ports/8443.txt); do
wget --max-redirect 0 --no-check-certificate -t 1 -T 3 --read-timeout=3 -O ./robots/$i-8443 https://$i:8443/robots.txt && fgrep -q "Disallow" ./robots/$i-8443 || rm ./robots/$i-8443; sed -i "1s/^/$i:8443\n/" ./robots/$i-8443 2> /dev/null && echo " [*]Robots.txt found for $i:8443";
done
echo '[*] robots.txt tests complete'
echo ""
#Checking common http(s) ports for TRACE
echo '[*] Testing common http(s) ports for TRACE'
#80
for i in $(cat ./ports/80.txt); do
curl -k -i -s -X TRACE -H "Cookie: Hail=Spydra" -H "Header: Proof_Of_Concept" http://$i/ | fgrep -q "Cookie: Hail=Spydra" && echo -e "\e[1;31m[Success]\e[0mTrace successful for $i on port 80" | tee -a trace_results.txt
done
#443
for i in $(cat ./ports/443.txt); do
curl -k -i -s -X TRACE -H "Cookie: Hail=Spydra" -H "Header: Proof_Of_Concept" https://$i/ | fgrep -q "Cookie: Hail=Spydra" && echo -e "\e[1;31m[Success]\e[0m Trace successful for $i on port 443" | tee -a trace_results.txt
done
#8080
for i in $(cat ./ports/8080.txt); do
curl -k -i -s -X TRACE -H "Cookie: Hail=Spydra" -H "Header: Proof_Of_Concept" http://$i:8080/ | fgrep -q "Cookie: Hail=Spydra" && echo -e "\e[1;31m[Success]\e[0m Trace successful for $i on port 8080" | tee -a trace_results.txt
done
#8443
for i in $(cat ./ports/8443.txt); do
curl -k -i -s -X TRACE -H "Cookie: Hail=Spydra" -H "Header: Proof_Of_Concept" https://$i:8443/ | fgrep -q "Cookie: Hail=Spydra" && echo -e "\e[1;31m[Success]\e[0m Trace successful for $i on port 8443" | tee -a trace_results.txt
done
#IKE VPN stuff
sudo -v
echo -e "[*] Running IKE tests.. "
# Encryption algorithms: DES, Triple-DES, AES/128, AES/192 and AES/256
ENCLIST="1 5 7/128 7/192 7/256"
# Hash algorithms: MD5 and SHA1
HASHLIST="1 2"
# Authentication methods: Pre-Shared Key, RSA Signatures, Hybrid Mode and XAUTH
AUTHLIST="1 3 64221 65001"
# Diffie-Hellman groups: 1, 2 and 5
GROUPLIST="1 2 5"
#
trans=""
for ENC in $ENCLIST; do
for HASH in $HASHLIST; do
for AUTH in $AUTHLIST; do
for GROUP in $GROUPLIST; do
trans="$trans $ENC,$HASH,$AUTH,$GROUP"
done
done
done
done
for b in $(cat ./ports/500.txt); do
echo -e "[*] Testing $b for Aggressive mode"
for i in $trans; do
sudo ike-scan --trans=$i -r 1 -A -M --id=admin --pskcrack=ike_results/$b.psk $b | fgrep -q "Aggressive Mode Handshake returned" && echo -e "[*] --trans=$i Returned Aggressive Mode Handshake - Writing PSK to ike_results/$b.psk" && echo "ike-scan --trans=$i -r 1 -A -M --id=admin --pskcrack=ike_results/$b.psk $b" >> ike_results/results.txt
done
done
cd ../
#Testing Complete
#TODO - Consider leaving script live until all nikto sessions are completed
#TODO - If above completed, merge post-nikto.sh to ext-auto-recon
echo '[*] Most tests complete. Results written to ./ext-auto-recon'
echo '[*] Nikto sessions may still be running. Confirm with "screen -dr nikto"'
echo '[*] Once all Nikto sessions are complete, consider running "post-nikto.sh"'
echo "[*] Or don't, I don't care"
<file_sep>/README.md
# Shittydotsh
My shitty .sh scripts
This are riddled with typos and bugs and require a number of other tools to be installed. I will eventually get them cleaned up and documented, but it's not currently a priority. Anybody is welcome to use these, but make sure you read/fix everything first. (I only put them here for myself)
| 36a934b6954c8c1b013e6e495c6f9e1f1ba9e6d1 | [
"Markdown",
"Shell"
] | 4 | Shell | suhass92/Shittydotsh | dc67a07df610caaca0adb42b8adcb14d6e79c87d | 4beb8b015edad1d0794feee30eb3c05982c5a9f7 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use App\Bike;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class BikeController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
Log::info('Showing All bikes: ');
$bikes = Bike::all();
return view('bikes.view', compact('bikes'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
Log::info('User entered the creation screen');
return view('bikes.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$make=$request['make'];
$model=$request['model'];
$year=$request['year'];
$bike=new Bike();
$bike->make=$make;
$bike->model=$model;
$bike->year=$year;
$bike->save();
Log::info([$bike->make,$bike->model,$bike->year. ' added to database']);
return redirect('/bikes');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Bike $bike)
{
Log::info('Showing Bikes: '.$bike);
return view('bikes.view', compact('bike'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
Log::info('Bike is being edited with the Id of: '.$id);
$bike = Bike::find($id);
return view('bikes.update', compact('bike'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'make' => 'required',
'model' => 'required',
'year' => 'required',
]);
$bike = Bike::find($id);
$bike->make = $request->get('make');
$bike->model = $request->get('model');
$bike->year = $request->get('year');
$bike->save();
Log::info('Bike has been updated with the Id of: '.$id);
return redirect('/bikes')->with('success', 'The bike was updated!');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$bike = Bike::find($id);
$bike->delete();
Log::info($bike.'has been deleted with the Id of'.$id);
return redirect('/bikes')->with('success', 'The bike was deleted!');
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function() {
return view('bikes.index');
});
Route::resource('bikes', 'BikeController');
Route::get('/bikes', 'BikeController@index');
Route::get('/create', 'BikeController@create');
Route::post('/create', 'BikeController@store');
// Route::get('/update', 'BikeController@edit');
// Route::get('/update', 'BikeController@update');
// Route::post('/delete', 'BikeController@destroy'); | bdb8f7133e5a0845478325dfd8cb90abe2b63add | [
"PHP"
] | 2 | PHP | Bcantrell1/Motorcycle-App | cb2a8f7fd14b2a8f706e6c611ae443c6ae84a558 | e1d101c1bb639930d7e7b380811f63a527271b88 |
refs/heads/master | <file_sep>import argparse
import json
import logging
import os
import fastparquet as fp
import psycopg2
import s3fs
from pandas import DataFrame
import Immobilienscout24
logger = logging.getLogger()
# Setting the threshold of logger to DEBUG
logger.setLevel(logging.DEBUG)
logging.basicConfig(
filename='app.log',
format='%(asctime)s %(levelname)s %(message)s', datefmt='%H:%M:%S',
filemode='w')
# Is to flatted the nested array we have
def flatten_arr(arr):
return [item for sublist in arr for item in sublist]
# Is to flatten the dict we have
def flatten_dict(dictionary, separator='_', prefix=''):
return {prefix + separator + k if prefix else k: v
for kk, vv in dictionary.items()
for k, v in flatten_dict(vv, separator, kk).items()
} if isinstance(dictionary, dict) else {prefix: dictionary}
# get the all flat data from the API
def get_json_data(summary):
# to get the total_page we need to iterate
for k, v in summary.items():
if k == "total_pages":
total_pages = v
flat_id = []
# iterate over the total page and get List from all the pages
for page in range(1, total_pages):
getList = Crsl.getList(page)
flat_id.append(getList)
all_flat_id = []
# get all the flat_id
for fid in flat_id:
for k, v in fid.items():
if k == 'ids':
all_flat_id.append(v)
flatten_flat_ids = flatten_arr(all_flat_id)
flat_data = []
# get all the data from the flatten flat_id
for flatten_flat_id in flatten_flat_ids:
flat_data.append(Crsl.getData(flatten_flat_id))
return flat_data
def process_json(flat_data):
# get all the relavent column out from the output
fact_flats_list = ['realEstate_@id',
'realEstate_livingSpace',
'realEstate_numberOfRooms',
'realEstate_floor',
'realEstate_apartmentType',
'realEstate_builtInKitchen',
'realEstate_lift',
'realEstate_balcony',
'realEstate_garden',
'realEstate_guestToilet',
'realEstate_handicappedAccessible',
'realEstate_heatingType',
'realEstate_thermalCharacteristic',
'realEstate_totalRent',
'realEstate_calculatedTotalRent',
'realEstate_baseRent',
'realEstate_serviceCharge',
'realEstate_deposit']
dim_address_list = ['realEstate_address_city',
'realEstate_address_quarter',
'realEstate_address_postcode',
'realEstate_address_street',
'realEstate_address_houseNumber',
'realEstate_address_wgs84Coordinate_longitude',
'realEstate_address_wgs84Coordinate_latitude'
]
dim_agency_list = ['contactDetails_company',
'contactDetails_firstname',
'contactDetails_lastname',
'contactDetails_salutation',
'contactDetails_email',
'contactDetails_email',
'contactDetails_phoneNumberCountryCode',
'contactDetails_phoneNumberAreaCode',
'contactDetails_phoneNumberSubscriber',
'contactDetails_phoneNumber',
'contactDetails_phoneNumber',
'contactDetails_address_city',
'contactDetails_address_street',
'contactDetails_address_postcode',
'contactDetails_address_houseNumber']
fact_flats = []
dim_address = []
dim_agency = []
for i in range(len(flat_data)):
for k, v in flat_data[i].items():
if k == 'expose.expose':
fact_flats.append(dict((k, flatten_dict(v)[k]) for k in fact_flats_list
if k in flatten_dict(v)))
dim_address.append(dict((k, flatten_dict(v)[k]) for k in dim_address_list
if k in flatten_dict(v)))
dim_agency.append(dict((k, flatten_dict(v)[k]) for k in dim_agency_list
if k in flatten_dict(v)))
return fact_flats, dim_address, dim_agency
def process_df(fact_flats, dim_address, dim_agency):
df_fact_flats = DataFrame(fact_flats)
df_fact_flats.rename(columns={'realEstate_@id': 'immoscout_id', 'realEstate_livingSpace': 'area_sq_m',
'realEstate_numberOfRooms': 'cnt_rooms',
'realEstate_floor': 'cnt_floors', 'floor': 'floor',
'realEstate_apartmentType': 'type',
'realEstate_builtInKitchen': 'has_fitted_kitchen', 'realEstate_lift': 'has_lift',
'realEstate_balcony': 'has_balcony',
'realEstate_garden': 'has_garden', 'realEstate_guestToilet': 'has_guest_toilet',
'realEstate_handicappedAccessible': 'is_barrier_free',
'realEstate_heatingType': 'heating_type',
'realEstate_thermalCharacteristic': 'thermal_characteristic',
'realEstate_totalRent': 'total_rent',
'realEstate_calculatedTotalRent': 'calculatedTotalRent',
'realEstate_baseRent': 'base_rent',
'realEstate_serviceCharge': 'service_charge', 'realEstate_deposit': 'deposit'}, inplace=True)
df_dim_address = DataFrame(dim_address)
df_dim_address.rename(columns={'realEstate_address_city': 'city', 'realEstate_address_quarter': 'district',
'realEstate_address_postcode': 'zip_code', 'realEstate_address_street': 'street',
'realEstate_address_houseNumber': 'house_number',
'realEstate_address_wgs84Coordinate_longitude': 'lng',
'realEstate_address_wgs84Coordinate_latitude': 'lat'}, inplace=True)
df_dim_agency = DataFrame(dim_agency)
# df_dim_agency['id'] = df_dim_agency.index + 1
df_dim_agency.rename(columns={'contactDetails_company': 'company_name',
'contactDetails_firstname': 'contactDetails_firstname',
'contact_lastname': 'contactDetails_lastname',
'contactDetails_salutation': 'salutation', 'contactDetails_email': 'email',
'contactDetails_phoneNumberCountryCode': 'phoneNumberCountryCode',
'contactDetails_phoneNumberAreaCode': 'phoneNumberAreaCode',
'contactDetails_phoneNumberSubscriber': 'phoneNumberSubscriber',
'contactDetails_phoneNumber': 'mobile_number',
'contactDetails_address_city': 'address_city',
'contactDetails_address_street': 'address_street',
'contactDetails_address_postcode': 'address_zipcode',
'contactDetails_address_houseNumber': 'address_house_number'}, inplace=True)
return df_fact_flats, df_dim_address, df_dim_agency
def write_to_s3(s3_path, df, partition_cols=None, file_scheme='hive'):
print(df.dtypes)
if partition_cols:
fp.write(s3_path, df, file_scheme=file_scheme, partition_on=partition_cols, open_with=s3fs.S3FileSystem().open)
else:
fp.write(s3_path, df, file_scheme=file_scheme, open_with=s3fs.S3FileSystem().open)
def insert_into_tables(config, insert_stmt, df_values):
""" create tables in the PostgreSQL database"""
conn = None
try:
# read the connection parameters
config = json.loads(config)
user = config.get("user")
password = config.get("password")
port = config.get("port")
host = config.get("host")
database = config.get("database")
logger.debug("user = %s, database = %s", user, database)
# connect to the PostgreSQL server
conn = psycopg2.connect(user=user,
password=<PASSWORD>,
host=host,
port=port,
database=database)
cur = conn.cursor()
logger.debug("Connection established for postgres")
# create table one by one
logger.debug("Executing commands in postgres")
psycopg2.extras.execute_batch(cur, insert_stmt, df_values)
cur.close()
# commit the changes
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
logger.error(error)
finally:
if conn is not None:
conn.close()
def insert_procees(df, table):
if len(df) > 0:
df_columns = list(df)
# create (col1,col2,...)
columns = ",".join(df_columns)
# create VALUES('%s', '%s",...) one '%s' per column
values = "VALUES({})".format(",".join(["%s" for _ in df_columns]))
# create INSERT INTO table (columns) VALUES('%s',...)
insert_stmt = "INSERT INTO {} ({}) {}".format(table, columns, values)
return insert_stmt, df.values
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--config', type=str, required=True)
args = parser.parse_args()
config = json.loads(args.config)
logger.debug("Done with all the config collection")
key = config.get("key")
Crsl = Immobilienscout24.Immobilienscout(key)
summary = Crsl.getSummary()
flat_data = get_json_data(summary)
fact_flats, dim_address, dim_agency = process_json(flat_data)
df_fact_flats, df_dim_address, df_dim_agency = process_df(fact_flats, dim_address, dim_agency)
logger.info("Writing into s3")
s3_output_location = config.get("s3_output_location")
logger.debug("s3 output location : %s", s3_output_location)
s3_path_flats = os.path.join(s3_output_location, 'flats/')
s3_path_address = os.path.join(s3_output_location, 'address/')
s3_path_agency = os.path.join(s3_output_location, 'agency/')
logger.debug("Writing to s3_path_flats = %s", s3_path_flats)
logger.debug("Writing to s3_path_address = %s", s3_path_address)
logger.debug("Writing to s3_path_agency = %s", s3_path_agency)
write_to_s3(s3_path_flats, df_fact_flats)
write_to_s3(s3_path_address, df_dim_address)
write_to_s3(s3_path_agency, df_dim_agency)
logger.info("Done: Writing into s3")
flat_insert_stmt, flat_df_values = insert_procees(df_fact_flats, "flats")
address_insert_stmt, address_df_values = insert_procees(df_dim_address, "address")
agency_insert_stmt, agency_df_values = insert_procees(df_dim_agency, "agency")
logger.info("Postgres: Inserting data into tables")
insert_into_tables(config, flat_insert_stmt, flat_df_values)
insert_into_tables(config, address_insert_stmt, address_df_values)
insert_into_tables(config, agency_insert_stmt, agency_df_values)
logger.info("Done :Inserting data into tables")
<file_sep>import requests
import logging
class Immobilienscout(object):
__HOST = "https://immoscout-api-ji3l2ohvha-lz.a.run.app"
def __init__(self, api_keys):
self.keys = api_keys
self.logger = logging.getLogger(__name__)
def _get_response(self, url):
host = self.__HOST
key = self.keys
url = host + "/" + url
headers = {'X-API-KEY': key,
'accept': 'application/json'}
resp = requests.get(url, headers=headers)
return resp
def getSummary(self):
self.logger.info("Started with API: getSummary")
response = self._get_response("get_summary")
if response.status_code not in (200, 202):
print(response.status_code)
print(response.text)
raise Exception("getSummary couldn't proceed")
self.logger.info("Done with API: getSummary")
return response.json()
def getList(self, page_number):
self.logger.info("Started with API: getList")
response = self._get_response("get_list?page={}".format(page_number))
if response.status_code not in (200, 202):
print(response.status_code)
print(response.text)
raise Exception("getList couldn't proceed")
self.logger.info("Done with API: getList")
return response.json()
def getData(self, flat_id):
self.logger.info("Started with API: getData")
response = self._get_response("/get_data?id={}".format(flat_id))
if response.status_code not in (200, 202):
print(response.status_code)
print(response.text)
raise Exception("getData couldn't proceed")
self.logger.info("Done with API: getData")
return response.json()
<file_sep>**Solution to Technical Task for a position of Data Engineer @ CrossLend**
[Description](https://github.com/crosslend/data_engineer_coding_exercise) :
We would like to propose that you familiarize yourself with the housing market in Berlin, and hence suggest that you to build a data pipeline to integrate the data for the flats available for rent in Berlin. The objective of this pipeline is to deliver data to the analytics layer for data science research.
**Approach:**
1. Create a class which will consist of all the API calls.
2. In the **main.py** create an object for the class and use the same
for any api call.
3. Modularise the code according to their functioning.
4. Add logging for better debugging.
5. Add required comments to increase the readability of the code.
6. Add the docker file to containerize the solution.
7. Add all the dependency in requirements.txt.
8. Write the DF to s3 as well as postgres.
9. Add the airflow DAG consider we have k8s to spin pods.
**Command:**
`python main.py
--config '{"key":"<KEY>", "s3_output_location": "s3://crosslen_datalake/homeloans/",
"user":"sysadmin", "password":"<PASSWORD>", "host":"127.0.0.1",
"port":"5432", "database":"postgres_db"}'`
**Config:**
*A variable to be created in Airflow named: immobilienscout24_conf*
{"key":"<KEY>",
"s3_output_location": "s3://crosslen_datalake/homeloans/",
"user":"sysadmin",
"password":"<PASSWORD>",
"host":"127.0.0.1", "port":"5432",
"database":"postgres_db"}
**Deployment:**
Image (named *flat-data-ingestion*) to be build using Jenkins and and update in the airflow variable *crosslend_images_config*
Schedule in the DAG is for everyday.
*P.S : All the scheduling assumption as per the current env. I am working. This can very accordingly.*
*P.P.S : The host am using is not working anymore. Hence the write to destination part is needs more testing.*
<file_sep>pandas==1.0.2
requests==2.23.0
fastparquet==0.3.2
s3fs==0.4.0
psycopg2==2.8.4
<file_sep>import json
from datetime import datetime, timedelta
from airflow import DAG
from airflow.contrib.operators.kubernetes_pod_operator \
import KubernetesPodOperator
from airflow.models import Variable
DEFAULT_ARGS = {
'owner': 'de',
'email': '<EMAIL>',
'email_on_retry': False,
'retries': 3,
'retry_delay': timedelta(minutes=5),
'start_date': datetime(2020, 3, 17)
}
IMAGE_CONFIG = Variable.get('crosslend_images_config', deserialize_json=True)
CONFIG = Variable.get('immobilienscout24_conf',
deserialize_json=True)
with DAG(
'flat-data-ingestion',
default_args=DEFAULT_ARGS,
schedule_interval='0 0 * * *'
) as dag:
KubernetesPodOperator(
namespace='Crosslend_Dataengineering',
image=IMAGE_CONFIG['flat-data-ingestion'],
cmds=["python", "main.py",
"--config", json.dumps(CONFIG)],
name="flat-data-ingestion",
task_id="flat-data-ingestion",
in_cluster=True
)
| e420be32a162375bcdb7c31f05b286de30cdcea6 | [
"Markdown",
"Python",
"Text"
] | 5 | Python | deepakksahu/Data_engineering_takehome | 5f5b43629c982523589656daca6b148379e283d6 | 0ab971cf1e1ab439f88580f7ed014556c392e0dd |
refs/heads/master | <file_sep>import React from 'react';
import '../App.css';
import axios from 'axios'
class List extends React.Component {
constructor(props){
super(props)
this.state={
'NobitexName': null,
'BinanceName': null
}
}
componentDidMount () {
this.interval = setInterval(() => {
this.handleMax()
}, 3000)
}
async handleMax(){
let data100 = {
symbol: "USDTIRT"
}
var audio = new Audio('https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3');
axios.post('https://api.nobitex.ir/v2/trades', data100,{})
.then((response) => {
this.setState({ tether: Number.parseFloat(response.data.trades[0].price, 10) })
})
.catch((error) => {
console.log('erroppppppp')
})
let coin_list = [
"btc",
"eth",
"ltc",
"bch",
"xlm",
"trx",
"doge",
"etc",
"bnb",
"eos",
"xrp",
]
let NobitexName=window.localStorage.getItem('NobitexName')
let dataNobitex = {
symbol: String(NobitexName)
}
// nobitex API
await axios.post('https://api.nobitex.ir/v2/trades', dataNobitex,{})
.then((response) => {
var price= Number.parseFloat(response.data.trades[0].price, 10)/this.state.tether
// this.setState({nobitex_volume2: response.data.trades[0].volume})
this.setState({ [`nobitex_price${0}`]: price })
})
.catch((error) => {
console.log('erroppppppp')
})
//binance API
let BinanceName=window.localStorage.getItem('BinanceName')
await axios.get("https://api.binance.com/api/v3/ticker/price?symbol="+String(BinanceName), {
})
.then(response => {
var price= Number.parseFloat(response.data.price, 10)
console.log('aaaaaaaa')
this.setState({ [`binance_price${0}`]: price })
})
.catch(error => {
console.log(error);
});
let Stop=window.localStorage.getItem('Stop')
if(Stop && NobitexName && BinanceName && this.state[`nobitex_price${0}`]<Stop ){
console.log('buyyyyyyyyyyyyyyy')
console.log("nobitex",this.state[`nobitex_price${0}`]*0.99*this.state.tether)
audio.play();
}
}
handleChange = (e) => {
this.setState({ 'Stop': e.target.value })
{ e.target.value === '' && this.setState({ 'Stop': null})}
}
handleChange1 = (e) => {
this.setState({ 'NobitexName': e.target.value })
{ e.target.value === '' && this.setState({ 'NobitexName': null})}
}
handleChange2 = (e) => {
this.setState({ 'BinanceName': e.target.value })
{ e.target.value === '' && this.setState({ 'BinanceName': null})}
}
handleClickButton = () => {
window.localStorage.setItem('Stop',this.state.Stop)
}
handleClickButton1 = () => {
window.localStorage.setItem('NobitexName',this.state.NobitexName)
}
handleClickButton2 = () => {
window.localStorage.setItem('BinanceName',this.state.BinanceName)
}
render(){
return (
<div className="Container">
<div className="Stop">
<p>قیمت کف به ریال</p>
<input
className="Stop"
onChange={(e) => this.handleChange(e)}
/>
<button
onClick={(e) => this.handleClickButton(e)}
>send</button>
</div>
<div>
<p>Nobitex name</p>
<input
placeholder="Nobitex name"
onChange={(e) => this.handleChange1(e)}
/>
<button
onClick={(e) => this.handleClickButton1(e)}
>send</button>
</div>
<div>
<p>Binance name</p>
<input
onChange={(e) => this.handleChange2(e)}
/>
<button
onClick={(e) => this.handleClickButton2(e)}
>send</button>
</div>
</div>
);
}
}
export default List;
| 11633a8fc6b1f97d251bd6393a966256778235c0 | [
"JavaScript"
] | 1 | JavaScript | mrkDeployment/stop | 628d767a26196ca505a64acdb83dbd6d4935aa77 | 00977b3b263a1219efa522e980a81c32f5d8e399 |
refs/heads/master | <repo_name>xzombiedev/datomed<file_sep>/application/controllers/Reserva.php
<?php
/**
* Description of Reserva
*
* @author ralf
*/
class Reserva extends CI_Controller {
/**
Solicitud de reserva de hora solo muestra clientes y centros medicos premium
**/
public function __construct(){
parent::__construct();
$this->load->model(array(
'inicio_model',
'admin_model',
'seccion_model',
'categorias_model',
'region_model',
'noticias_model',
'reserva_model',
'listado_model'
));
$this->load->library(array('ion_auth',
'notificaciones',
'form_validation',
'premium',
'publicaciones'
));
$this->load->helper('url');
}
public function index(){
$data['regiones'] = $this->listado_model->get_all_regiones();
if($this->ion_auth->logged_in()){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$params['usuario_is_logged'] = $this->ion_auth->user()->row();
$data['ispremium'] = $this->premium->check_ispremium($params['usuario_is_logged']->email);
$this->form_validation->set_rules('reserva_select', 'Doctor o centro médico', 'trim');
$this->form_validation->set_rules('fecha_solicitud', 'Fecha', 'trim');
$this->form_validation->set_rules('comentario', 'Comentario', 'trim');
if ($this->form_validation->run() == FALSE){
/**
* Bloque noticias
* el id para las noticias es 98
* **/
$data['noticias_lista'] = $this->inicio_model->get_noticias_lista();
/**
* Bloque categorías
* el id para las categorias es 99
* **/
//Get lista usuarios premium
$data['lista_premium'] = $this->admin_model->get_user_list_is_premium_for_reserva();
//
$data['categorias_sistema'] = $this->inicio_model->get_categorias_principales();
/**
* Bloque nosotros
* **/
$params['seccion'] = '1';
$params['categoria'] = '1';
$data['texto_nosotros'] = $this->inicio_model->get_texto_by_seccion($params);
$this->load->view('templates/header',$params);
$this->load->view('portal/reserva_hora',$data);
$this->load->view('templates/footer');
}else{
$data['profesional_id'] = $this->input->post('reserva_select');
$data['fec_reserva'] = $this->input->post('fecha_solicitud');
$data['comentario'] = $this->input->post('comentario');
$data['usuario_id'] = $this->ion_auth->user()->row();
//
$data['err'] = '1';
$data['glosa'] = 'Solicitud enviada con éxito';
$this->reserva_model->add_reserva($data);
$this->notificaciones->sent_correo($data['usuario_id']->email,1,1);
$this->load->view('templates/header',$params);
$this->load->view('templates/exito',$data);
$this->load->view('templates/footer');
}
}else{
/**
* Bloque noticias
* el id para las noticias es 98
* **/
$params['usuario_is_logged'] = '';
$data['noticias_lista'] = $this->inicio_model->get_noticias_lista();
/**
* Bloque categorías
* el id para las categorias es 99
* **/
//
$data['categorias_sistema'] = $this->inicio_model->get_categorias_principales();
/**
* Bloque nosotros
* **/
$params['seccion'] = '1';
$params['categoria'] = '1';
$data['texto_nosotros'] = $this->inicio_model->get_texto_by_seccion($params);
$data['err'] = '2';
$data['glosa'] = 'Debe iniciar sesión para utilizar este modulo';
$this->load->view('templates/header',$params);
$this->load->view('templates/exito',$data);
$this->load->view('templates/footer');
}
}
public function leido(){
if($this->ion_auth->logged_in()){
$data['id'] = base64_decode($this->input->get('a'));
/**
* Bloque noticias
* el id para las noticias es 98
* **/
$data['noticias_lista'] = $this->inicio_model->get_noticias_lista();
/**
* Bloque categorías
* el id para las categorias es 99
* **/
$data['categorias_sistema'] = $this->inicio_model->get_categorias_principales();
/**
* Bloque nosotros
* **/
$params['seccion'] = '1';
$params['categoria'] = '1';
$data['texto_nosotros'] = $this->inicio_model->get_texto_by_seccion($params);
//
$data['update_leido'] = $this->reserva_model->update_leido($data['id']);
if($data['update_leido'] == 1){
//OK
//
$data['err'] = '1';
$data['glosa'] = 'Cambio realizado con éxito';
$this->load->view('templates/header_usuarios');
$this->load->view('templates/exito',$data);
$this->load->view('templates/footer');
}else{
//
$data['err'] = '2';
$data['glosa'] = 'Imposible actualizar. Contacte al administrador';
$this->load->view('templates/header_usuarios');
$this->load->view('templates/exito',$data);
$this->load->view('templates/footer');
}
}else{
redirect("auth/login", 'refresh');
}
}
}
<file_sep>/application/views/portal/opiniones.php
<div class="bloque_noticias">
<div class="container">
<?php if($ispremium[0]['estado'] == 0){ ?>
<!-- consiga más con premium -->
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-12 centro">
<div class="alert alert-warning" role="alert">
Actualmente está utilizando el perfil básico con limitaciones. <a href="/portal/get_premium">Mejore su perfil</a>
</div>
</div>
</div>
</div>
<?php }else{ ?>
<ol class="breadcrumb">
<li><a href="/portal/index">Inicio</a></li>
<li class="active">
Opiniones
</li>
</ol>
<h1>Opiniones<span></span></h1>
<div class="panel panel-info">
<div class="panel-body">
<i class="fa fa-bullhorn" aria-hidden="true"></i> <strong>Conozca la opinión de los pacientes por sus servicios.</strong><br/>
Prestar atención a los comentarios puede ayudar a mejorar su servicio.
</div>
</div>
<div class="row">
<?php if(empty($get_aviso_by_id)){?>
<div class="alert alert-info" role="alert">
Aún no posee comentarios en sus publicaciones
</div>
<?php }else{?>
<table class="table table-striped" id="opiniones-user">
<thead>
<tr>
<td>Fecha comentario</td>
<td>Remitente</td>
<td>Comentario</td>
<td>Valoración</td>
<td>Acciones</td>
</tr>
</thead>
<tbody>
<?php
for($n = 0; $n < count($get_aviso_by_id); $n++){
echo '
<tr>
<td>'.$get_aviso_by_id[$n]['fec_creacion'].'</td>
<td>'.$get_aviso_by_id[$n]['first_name'].' '.$get_aviso_by_id[$n]['last_name'].'</td>
<td>'.$get_aviso_by_id[$n]['comentario'].'</td>
<td>'.$get_aviso_by_id[$n]['valoracion'].'</td>
<td>
<a href="/categorias/detalle/'.$get_aviso_by_id[$n]['aviso_id'].'" target=_blank"">
Revisar aviso
</a>
</td>
</tr>
';
}
?>
</tbody>
</table>
<?php }?>
</div>
<?php } ?>
</div>
</div>
<file_sep>/application/models/Reserva_model.php
<?php
/**
* Description of Reserva_model
*
* @author ralf
*/
class Reserva_model extends CI_Model {
protected $table = array(
'tbl_coreservas'=>'coreservas'
);
function __construct(){
parent::__construct();
}
function add_reserva($params){
$fecha = date('Y-m-d H:i:s');
$conditions = array(
'fec_reserva'=>$params['fec_reserva'],
'profesional_id'=>$params['profesional_id'],
'usuario_id'=>$params['usuario_id']->id,
'comentario'=>$params['comentario'],
'fec_creacion'=>$fecha
);
$this->db->insert($this->table['tbl_coreservas'], $conditions);
}
function get_reserva_by_id_doctor($id){
$string = "select u.first_name, u.last_name, r.comentario, r.visto, r.fec_reserva, r.fec_creacion, r.id from coreservas as r, users as u where r.profesional_id = u.id and u.id = ".$this->db->escape($id);
$qry = $this->db->query($string);
return $qry->result_array();
}
function update_leido($id){
$this->db->set('visto', 1, FALSE);
$this->db->where('id', $id);
$resp = $this->db->update($this->table['tbl_coreservas']);
return $resp;
}
}
<file_sep>/application/views/portal/solicitudes.php
<div class="bloque_noticias">
<div class="container">
<?php if($ispremium[0]['estado'] == 0){?>
<!-- consiga más con premium -->
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-12 centro">
<div class="alert alert-warning" role="alert">
Actualmente está utilizando el perfil básico con limitaciones. <a href="/portal/get_premium">Mejore su perfil</a>
</div>
</div>
</div>
</div>
<?php }else{?>
<ol class="breadcrumb">
<li><a href="/portal/index">Inicio</a></li>
<li class="active">
Solicitudes
</li>
</ol>
<h1>Solicitudes<span></span></h1>
<div class="panel panel-info">
<div class="panel-body">
<i class="fa fa-bullhorn" aria-hidden="true"></i> <strong>Cada vez son más las personas que solicitan citas por internet.</strong><br/>
Es rápido sin esperas y está disponible las 24hrs.
</div>
</div>
<div class="row">
<?php if(empty($lista_solicitudes)){?>
<div class="alert alert-info" role="alert">
Aún no posee comentarios en sus publicaciones
</div>
<?php }else{?>
<table class="table table-striped" id="solicitudes-user">
<thead>
<tr>
<td>Fecha Solicitada</td>
<td>Remitente</td>
<td>Comentario</td>
<td>Marcar como leído</td>
</tr>
</thead>
<tbody>
<?php
for($n = 0; $n < count($lista_solicitudes); $n++){
if($lista_solicitudes[$n]['visto'] == 0){
$label = 'label-danger';
$txt = 'No leído';
$ahref= '
<a href="/reserva/leido?a='.base64_encode($lista_solicitudes[$n]['id']).'">Marcar como leído</a>
';
}else{
$label = 'label-success';
$txt = 'Leído';
$ahref = '';
}
echo '
<tr>
<td>'.$lista_solicitudes[$n]['fec_reserva'].'</td>
<td>'.$lista_solicitudes[$n]['first_name'].' '.$lista_solicitudes[$n]['last_name'].'</td>
<td>'.$lista_solicitudes[$n]['comentario'].'</td>
<td>
<span class="label '.$label.'">
'.$txt.'
</span>
'.$ahref.'
</td>
</tr>
';
}
?>
</tbody>
</table>
<?php }?>
</div>
<?php }?>
</div>
</div>
<file_sep>/application/models/Comentarios_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Description of Comentarios_model
*
* @author ralf
*/
class Comentarios_model extends CI_Model {
protected $table = array(
'tbl_cocomentarios'=>'cocomentarios'
);
function __construct(){
parent::__construct();
}
function get_comentarios_by_id_servicio($id){
$conditions = array(
'aviso_id'=>$id,
'estado'=>0// 0 = no publicado 1 = publicado
);
$this->db->order_by('fec_creacion', 'DESC');
$qry = $this->db->get_where($this->table['tbl_cocomentarios'], $conditions);
$result = $qry->result_array();
return $result;
}
}
<file_sep>/application/views/portal/reserva_hora.php
<div class="row">
<div class="container">
<ol class="breadcrumb">
<li><a href="/portal/index">Portal</a></li>
<li class="active">
Solicitud reserva de hora
</li>
</ol>
<?php if($ispremium[0]['estado'] == 0){ ?>
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-12 centro">
<div class="alert alert-warning" role="alert">
Actualmente está utilizando el perfil básico con limitaciones. <a href="/portal/get_premium">Mejore su perfil</a>
</div>
</div>
</div>
</div>
<?php }?>
<h1>Solicitud reserva de hora*<span></span></h1>
<div class="col-md-9">
<p><span class="label label-info">Importante</span> El profesional o centro médico debe aceptar la solicitud de atención</p>
<?php echo validation_errors(); ?>
<?php echo form_open('reserva/index'); ?>
<table class="table table-bordered">
<tr>
<td>Doctor o Centro Médico</td>
<td>
<select name="reserva_select" class="form-control">
<?php
for($n = 0; $n < count($lista_premium); $n++){
echo '<option value="'.$lista_premium[0]['id'].'">'.$lista_premium[0]['first_name'].' '.$lista_premium[0]['last_name'].'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td>
Fecha a solicitar
</td>
<td>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" name="fecha_solicitud" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</td>
</tr>
<tr>
<td>
Comentario
</td>
<td>
<input type="text" class="form-control" name="comentario">
</td>
</tr>
<tr>
<td></td>
<td><button class="btn btn-primary" type="submit">Solicitar</button></td>
</tr>
</table>
</form>
</div>
<div class="col-md-3">
<div class="panel panel-primary">
<div class="panel-body celeste-bg">
<center>
<i class="fa fa-thumbs-o-up fa-6" aria-hidden="true"></i>
</center>
<center><h4>Rerserva online</h4></center>
<p>
Reserva de forma simple y gratuita cita con miles de profesionales en cientos de centros en todo Chile.<br /><br />
Escoge un doctor y envía la solcitud de reserva.
</p>
</div>
</div>
</div>
</div>
</div>
| 9141b6b95ecde1eea8d6d4f7f1e528ee7ba7f00f | [
"PHP"
] | 6 | PHP | xzombiedev/datomed | 493b7cfc71da1109c95ea78e08bec0b363d93897 | de384776188b44f959404cfb444ac219c06220f0 |
refs/heads/master | <repo_name>dongyuancaizi/UML_learning<file_sep>/UML_learning/src/Main.java
import com.ilike.classlearn.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
//这个人
Person person = new Person();
person.setAge(25);
person.setName("swd");
//这个人的车
Car car = new Car();
car.setBrand("法拉利");
car.setColor(" 黄色");
List<Wheel> wheels = new ArrayList<>();
for (int i = 0; i <4 ; i++) {
Wheel wheel = new Wheel();
wheel.setSize(25);
wheel.setWeight(100);
}
car.setWheels(wheels);
person.setCar(car);
//这个人的宠物
Cat cat = new Cat();
cat.setAge(3);
cat.setName("笑咪咪");
person.setCat(cat);
//这个人的孩子
List<Child> childs=new ArrayList<>();
Child child1= new Child();
child1.setAge(10);
child1.setName("贝贝");
child1.setGender(2);
child1.setParent(person);
childs.add(child1);
Child child2= new Child();
child2.setAge(6);
child2.setName("费费");
child2.setGender(1);
child2.setParent(person);
childs.add(child2);
person.setChilds(childs);
//这个人的腿
List<Leg> legs=new ArrayList<>();
Leg leg1=new Leg();
leg1.setLength(180);
legs.add(leg1);
Leg leg2=new Leg();
leg2.setLength(180);
legs.add(leg2);
person.setLegs(legs);
show(person);
}
public static void show(Person person){
StringBuilder sb = new StringBuilder();
sb.append("星期天").append(person.getAge()).append("岁的").append(person.getName()).append("开着他")
.append(person.getCar().getColor()).append("的").append(person.getCar().getBrand()).append("汽车");
sb.append("带着他的").append(person.getChilds().size()).append("个孩子,");
sb.append(person.getChilds().get(0).getAge()).append("岁的").append(person.getChilds().get(0).getName()).append("和");
sb.append(person.getChilds().get(1).getAge()).append("岁的").append(person.getChilds().get(1).getName());
sb.append("换有他").append(person.getCat().getAge()).append("岁的小猫").append(person.getCat().getName());
sb.append("去游玩");
System.out.println(sb.toString());
}
}
<file_sep>/README.md
# UML_learning
使用PlantUML绘制类图
<file_sep>/UML_learning/src/com/ilike/readme.txt
PlantUML是一个开源项目,支持快速绘制:
时序图
用例图
类图
活动图
组件图
状态图
对象图
<file_sep>/UML_learning/src/com/ilike/classlearn/ZooEnum.java
package com.ilike.classlearn;
/**
* 动物园动物的枚举类
*
* @author sangweidong
* @create 2019-08-15 11:55
**/
public enum ZooEnum {
CAT(1, "猫"),
EAGLE(2, "老鹰");
public Integer CODE;
public String NAME;
ZooEnum(Integer code, String name) {
this.CODE = code;
this.NAME = name;
}
public static ZooEnum get(Integer code) {
ZooEnum result = null;
if (code != null) {
for (ZooEnum value : ZooEnum.values()) {
if (code == value.CODE) {
result = value;
break;
}
}
}
return result;
}
public static boolean contain(Integer code) {
boolean result = false;
if (code != null) {
for (ZooEnum value : ZooEnum.values()) {
if (code == value.CODE) {
result = true;
break;
}
}
}
return result;
}
}
<file_sep>/UML_learning/src/com/ilike/classlearn/Car.java
package com.ilike.classlearn;
import java.util.List;
/**
* 汽车
*
* @author sangweidong
* @create 2019-08-15 14:17
**/
public class Car {
/**
* 颜色
*/
private String color;
/**
* 品牌
*/
private String brand;
/**
* 车轮
*/
private List<Wheel> wheels;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public List<Wheel> getWheels() {
return wheels;
}
public void setWheels(List<Wheel> wheels) {
this.wheels = wheels;
}
}
<file_sep>/UML_learning/src/com/ilike/classlearn/Fly.java
package com.ilike.classlearn;
/**
* 飞
*
* @author sangweidong
* @create 2019-08-15 11:43
**/
public interface Fly {
/**
* 怎样飞
*/
void fly();
}
<file_sep>/UML_learning/src/com/ilike/classlearn/Animal.java
package com.ilike.classlearn;
/**
* 动物
*
* @author sangweidong
* @create 2019-08-15 11:47
**/
public abstract class Animal {
/**
* 吃
*/
void eat(){
}
/**
* 睡
*/
void sleep(){
}
}
| 40140c1d5faf97e903772deec2130266bed838c4 | [
"Markdown",
"Java",
"Text"
] | 7 | Java | dongyuancaizi/UML_learning | 974129af217ff97d6121a901291c681e63fa6a80 | 4a15db7356bcd97018852206ea104e211efe43dd |
refs/heads/master | <repo_name>yangdekun/yangdekun<file_sep>/yangdekun/src/yangdekun/Test.java
package yangdekun;
public class Test
{
private void mian()
{
// TODO Auto-generated method stub
System.out.println("Hello World222222221111");
System.out.println("12345");
}
}
| cd3d412fb905159940aa1e63c4650c9c1a857d7a | [
"Java"
] | 1 | Java | yangdekun/yangdekun | 5f6c0d006ffd956033e57a91a4c5ba7906e2ad1d | c7d482dcc7c6d6686f18893b9d4495b3e769f028 |
refs/heads/master | <file_sep>import random
from typing import Type, Collection
import pygame
class GameObject:
images = []
def __init__(self, scene):
self.scene = scene
self.sprites = [
pygame.image.load(s).convert_alpha()
for s in self.images
]
self.x = 0
self.y = 0
def receive_event(self, event):
pass
def update(self):
pass
def draw(self, screen):
sprites = self.sprites
if sprites:
screen.blit(self.sprites[pygame.time.get_ticks() % 100 * len(sprites) // 100], (self.x, self.y))
class Background(GameObject):
images = ['resources/sprites/background-day.png']
class Bird(GameObject):
images = [
'resources/sprites/redbird-downflap.png',
'resources/sprites/redbird-midflap.png',
'resources/sprites/redbird-upflap.png'
]
def __init__(self, scene):
super().__init__(scene)
self.sprite_width, self.sprite_height = self.sprites[0].get_size()
self.sound_flap = pygame.mixer.Sound('resources/audio/swoosh.wav')
self.sound_hit = pygame.mixer.Sound('resources/audio/hit.wav')
self.sound_fall = pygame.mixer.Sound('resources/audio/die.wav')
self.sound_point = pygame.mixer.Sound('resources/audio/point.wav')
self.gravity = 0.5
self.lift = -15
self.pipe = self.scene.get_object('pipe')
self._set()
def _set(self):
self.points = 0
self.x = 50
self.y = self.scene.height / 2
self.alive = True
self.velocity = 0
self.pipe.set()
def update(self):
self.velocity += self.gravity
if self.y < self.scene.height + 20:
self.y += self.velocity
if self.alive:
if self._colliding():
self._hit()
if self.y > self.scene.height:
self._fall()
if self.x > self.pipe.x and not self.pipe.passed and self.alive:
self.pipe.passed = True
self.points += 1
self.sound_point.play()
print(self.points)
def _colliding(self):
return (self.pipe.x + self.pipe.sprite_width > self.x > self.pipe.x) and \
(self.y < self.pipe.top or self.y > self.pipe.bottom)
def receive_event(self, event):
if event.key == pygame.K_SPACE:
self._up() if self.alive else self._set()
def _up(self):
if self.alive:
self.sound_flap.play()
self.velocity += self.lift
def _fall(self):
self.sound_fall.play()
self.alive = False
def _hit(self):
self.sound_hit.play()
self.alive = False
class Pipe(GameObject):
images = ['resources/sprites/pipe-green.png']
def __init__(self, scene):
super().__init__(scene)
self.speed = 3
self.sprite_width, self.sprite_height = self.sprites[0].get_size()
self.spacing = 125
self.top = 0
self.passed = False
self.y = 0
self.set()
def set(self):
self.top = random.randint(int(self.scene.height / 7), int(3 / 5 * self.scene.height))
self.y = self.bottom = self.top + self.spacing
self.x = self.scene.width
self.passed = False
def update(self):
self.x -= self.speed
if self._offscreen():
self.set()
def draw(self, screen):
screen.blit(self.sprites[0], (self.x, self.bottom))
screen.blit(pygame.transform.flip(self.sprites[0], False, True), (self.x, self.top-self.sprite_height))
def _offscreen(self):
return self.x + self.sprite_width < 0
class ScoreCounter(GameObject):
images = [
f'resources/sprites/{i}.png'
for i in range(10)
]
def __init__(self, scene):
super().__init__(scene)
self.bird = self.scene.get_object('bird')
def draw(self, screen):
score_digits = [int(x) for x in str(self.bird.points)]
total_width = 0 # total width of all numbers to be printed
for digit in score_digits:
total_width += self.sprites[digit].get_width()
x_offset = 10
for digit in score_digits:
screen.blit(self.sprites[digit], (x_offset, 10))
x_offset += self.sprites[digit].get_width()
class Scene:
def __init__(self, width: int, height: int, objects: Collection[Type[GameObject]]):
self._objects = {}
self.width = width
self.height = height
for obj in objects:
self._objects[obj.__name__.lower()] = obj(self)
def get_object(self, name):
return self._objects.get(name)
def receive_event(self, event):
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.KEYDOWN:
for object_ in self._objects.values():
object_.receive_event(event)
def update(self):
for object_ in self._objects.values():
object_.update()
def draw(self, screen):
for object_ in self._objects.values():
object_.draw(screen)
<file_sep># Flappy Bird clone
Written in Python using pygame library for eKids education program. Still WIP.
![pic][pic]
[pic]: https://github.com/pashawnn/pygame_flappybird/blob/master/screenshot.png
## How to run
```
pip install -r requirements.txt
python3 main.py
```
Controls:
* `Space bar` - jump, restart
<file_sep>import pygame
from objects import Background, Bird, Pipe, Scene, ScoreCounter
fps = 60
width = 288
height = 512
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Flappy Bird')
scene = Scene(width, height, [Background, Pipe, Bird, ScoreCounter])
while True:
clock.tick(fps)
for event in pygame.event.get():
scene.receive_event(event)
scene.update()
scene.draw(screen)
pygame.display.update()
| add601499cf749136376d9162fb796cdc41a3133 | [
"Markdown",
"Python"
] | 3 | Python | PashaWNN/pygame_flappybird | 03b82d27ac5935fb1c8043e300988b28aa90fc5d | 412b3dfc1202bd73e010d180ca7e955537aaeaaf |
refs/heads/main | <repo_name>RAJVARDHAN123/Virtual-Pet<file_sep>/sketch.js
var database;
var dog,sadDog,happyDog, milk, milkImage, eatingFood, eatingFoodimage;
var feed, add, foodobj;
var foodS, foodStock;
var fedtime;
var lastfed;
var groun;
var groun2;
var submit;
var greeting2;
var input;
function preload(){
sadDog=loadImage("Images/Dog.png");
happyDog=loadImage("Images/happy dog.png");
milkImage = loadImage('Images/milkImage.png');
eatingFoodimage = loadImage("Images/eating food.png");
}
function setup() {
database = firebase.database();
createCanvas(1000,400);
foodobj = new Food();
groun = createSprite (500,330,1000,20);
groun.visible = false;
greeting2 = createElement('h3');
greeting2.position(250,150);
groun2 = createSprite (1000,330,20,500);
groun2.visible = false;
milk = createSprite(620, 45);
milk.addImage(milkImage);
milk.scale = 0.08;
eatingFood = createSprite(430, 45);
eatingFood.addImage(eatingFoodimage);
eatingFood.scale = 0.1;
foodStock = database.ref('Food');
foodStock.on("value", readStock)
feed = createButton("Feed Dog");
feed.class("customButton");
feed.position(660,95);
feed.mousePressed(feedDog);
add = createButton("Add Food");
add.class("customButton");
add.position(800,95);
add.mousePressed(addFoods);
dog=createSprite(800,200,150,150);
dog.addImage(sadDog);
dog.scale=0.15;
submit = createButton("Submit");
submit.class("customButton");
submit.position(250,105);
submit.mousePressed(readname);
nameBox = createInput('').attribute('placeholder','Your pet name');
nameBox.position(250,100);
}
function draw() {
background(46,139,87);
foodobj.display();
dog.collide(groun);
dog.collide(groun2);
fedtime = database.ref('FeedTime');
fedtime.on("value", function(data){
lastfed = data.val();
})
dog.velocityY = dog.velocityY + 0.8;
dog.velocityX = dog.velocityX + 0.8;
drawSprites();
fill(255, 255, 254);
textSize(15);
if(lastfed >= 12){
text("Last Fed : " + lastfed%12 + "PM", 250, 30);
}else if(lastfed == 0){
text("Last Fed : 12 PM", 250, 30);
}else{
text("Last Feed : " + lastfed + "PM", 250, 30);
}
}
//function to read food Stock
function readStock(data){
foodS = data.val();
foodobj.updateFoodStock(foodS);
}
//function to update food stock and last fed time
function feedDog(){
dog.addImage(happyDog);
dog.x =600;
dog.y = 150;
input = nameBox.value();
greeting2.html("now " + input + " is not hugry!");
foodobj.updateFoodStock(foodobj.getFoodStock()-1);
database.ref('/').update({
Food : foodobj.getFoodStock(),
FeedTime: hour()
})
}
//function to add food in stock
function addFoods(){
foodS++;
database.ref('/').update({
Food: foodS
})
}
function readname(){
input = nameBox.value();
nameBox.hide();
submit.hide();
var greeting = createElement('h3');
greeting.html("Wow! " + input + " name is too nice");
greeting2.html(input + " is hugry!");
greeting.position(250,100);
} | 43217c6a9c9c9c8a64e15c196c3fff69d64d3737 | [
"JavaScript"
] | 1 | JavaScript | RAJVARDHAN123/Virtual-Pet | 1f36dac94d80731eac50d049c13797fb12466baa | 2b098feb0104bc8e4eb7ca20eaa82d285cefc913 |
refs/heads/main | <repo_name>atmajisetya/Learn-Algorithms<file_sep>/mergeSort.php
<?php
//function for splits the array and sort recursively
function mergesort (&$Array, $left, $right){
if ($left < $right){
$mid = $left + (int) (($right - $left)/2);
mergeSort ($Array, $left, $mid);
mergeSort ($Array, $mid+1, $right);
merge ($Array, $left, $mid, $right);
}
}
//function to merge sub problem solution
function merge(&$Array, $left, $mid, $right){
//create two array to hold split
$n1 = $mid - $left +1; //size LeftArray
$n2 = $right - $mid; //size RightArray
$LeftArray = array_fill(0, $n1, 0);
$RightArray = array_fill(0, $n2, 0);
for ($i=0; $i < $n1; $i++){
$LeftArray[$i] = $Array[$left + $i];
}
for ($i=0; $i < $n2; $i++){
$RightArray[$i] = $Array[$mid + $i + 1];
}
$i = 0;
$j = 0;
$k = $left;
while ($i < $n1 && $j < $n2){
if ($LeftArray[$i] < $RightArray[$j]){
$Array[$k] = $LeftArray[$i];
$i++;
}else {
$Array[$k] = $RightArray[$j];
$j++;
}
$k++;
}
//copying the remaining elements of LeftArray
while ($i < $n1){
$Array[$k] = $LeftArray[$i];
$i++;
$k++;
}
//copying the remaining elements of RightArray
while ($j < $n2){
$Array[$k] = $RightArray[$j];
$j++;
$k++;
}
}
//function to print array
function PrintArray($Array, $n){
for ($i=0; $i<$n; $i++){
echo $Array[$i]. " ";
}
}
//test the code
$coba = array(10, 1, 23, 50, 4, 9, -4);
$n = sizeof($coba);
echo "Original Array\n";
PrintArray($coba, $n);
echo "\n";
mergesort ($coba, 0, $n-1);
echo "Sorted Array\n";
PrintArray($coba, $n);
?>
| cf8276bf9aeb31db26f7620ee5544bad1f3fe661 | [
"PHP"
] | 1 | PHP | atmajisetya/Learn-Algorithms | 7323ed51b2e4bef517b9c678722283997e162879 | 6a00e35ba530330c1944b510406fe5612cd448cc |
refs/heads/main | <file_sep><?php
require_once "Controller.php";
require_once "UserController.php";
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>Un pendu en JS</title>
<script src='https://code.jquery.com/jquery-1.12.4.js'></script>
<script src='https://code.jquery.com/ui/1.12.1/jquery-ui.js'></script>
<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css'>
<link rel='stylesheet' href='//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css'>
<link rel='stylesheet' href='css.css'>
<script src='https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js'></script>
<script src='https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js'></script>
</head>
<body id='body'>
<div class='container-fluid'>
<div class='row'>
<div class='col-12 text-center'>
<h1>Jeu du pendu en JS</h1>
</div>
<div class='col-12 marge text-center'>
<h3 id='nbVies'>Vies restantes : 10</h3>
</div>
<div class='col-12 text-center' id='timer'>5 : 00</div>
<div class='col-12 text-center' id='affichage'>
</div>
<div class='col-12 text-center'>
<input type='text' name='lettre' id='reponse' autofocus>
<button id='tester'>Tester la lettre</button>
</div>
<div class='col-12 text-center' id='erreur'></div>
</div>
</div>
<script src='js.js'></script>
</body>
</html><file_sep>let mot = "Charleville"; // Mot à deviner
mot = mot.toUpperCase();
let lettres = mot.split(""); // Division du mot en un tableau (une lettre par entrée du tableau)
let entrees = []; // Définition d'un tableau qui accueillera les lettres entrées par le joueur
let vieRestante = 10; // Nombre de vie restante par mot
let result = document.getElementById("affichage"); // Récupération de la div pour afficher les lettres
let affVie = document.getElementById("nbVies"); // Récupération de la div pour afficher le nombre de vies restantes
let btn = document.getElementById("tester"); // Récupération du bouton de test d'une lettre
let input = document.getElementById("reponse"); // Récupération de l'input où l'utilisateur écrit les lettres
let erreur = document.getElementById("erreur"); // Récupération de la div pour afficher les erreurs
let lettresValid = []; // Définition d'un tableau servant à comparer les lettres utilisateur et celles du mot
let gStarted = false; // Booléen servant à vérifier si le timer est en route ou non
// Boucle créant une div par lettre dans le tableau lettres
for(let i=1; i <= mot.length; i++) {
let div = document.createElement("div");
if(mot[i-1] == "-" || mot[i-1] == " ") {
div.setAttribute("class", "specialchars");
div.textContent = mot[i-1];
} else {
div.setAttribute("class", "lettre");
}
div.setAttribute("id", i);
result.appendChild(div);
}
let cases = document.querySelectorAll(".lettre"); // récupération de toutes les div créées ci-dessus (pour l'affichage des lettres)
// Ecouteur appelant la fonction main quand l'utilisateur appui sur entrée
input.addEventListener("keypress", function(b) {
if(b.keyCode == 13) {
main();
}
})
// Ecouteur appelant la fonction main quand l'utilisateur clique sur le bouton btn
btn.addEventListener("click", function() {
main();
});
// Fonction principale du programme
function main() {
if(gStarted == false) { // Condition démarrant le timer si ce dernier ne l'est pas déjà
let d = new Date().getTime();
callTimer(d);
gStarted = true;
}
let v = input.value.toUpperCase(); // Récupération de la valeur de l'input (convertie en majuscule)
input.value = ""; // Reset de la valeur de l'input
if(v == "") { // Condition vérifiant que la valeur de v est valide
erreur.textContent = "Veuillez renseigner une lettre";
} else if(v.length > 1) {
erreur.textContent = "Veuillez renseigner une lettre à la fois";
} else if(entrees.includes(v)) {
erreur.textContent = "Vous avez déjà entré cette lettre";
} else if (v.charCodeAt(0) < 65 || v.charCodeAt(0) > 90) {
erreur.textContent = "Veuillez entrer un caractère valide"
} else {
stringCheck(v, lettres); // Si v à une valeur correcte, appel de la fonction vérifiant si v est dans le tableau lettres
erreur.textContent = "";
}
if(vieRestante > 1) { // Condition gérant l'affichage de vie + game over
affVie.textContent = "Vies restantes : " + vieRestante;
} else if (vieRestante == 1) {
affVie.textContent = "Vie restante : " + vieRestante;
} else {
affVie.textContent = "Game over";
btn.disabled = true;
input.disabled = true;
}
if(arrayCompare(lettresValid, lettres)) {
affVie.textContent = "Victoire !";
}
entrees.push(v);
}
function callTimer(d) {
let x = setInterval(function(){
let now = new Date().getTime();
let distance = (d + 300000) - now;
let sec = Math.floor((distance % (1000 * 60)) / 1000);
let t = document.getElementById("timer");
t.innerHTML = Math.floor((distance % ((1000 * 60 * 60)) / (1000 * 60)));
if(sec < 10) {
t.innerHTML += " : 0" + sec;
} else {
t.innerHTML += " : " + sec;
}
if(distance < 0) {
clearInterval(x);
t.innerHTML = "0 : 00"
erreur.textContent = "Temps écoulé !";
btn.disabled = true;
input.disabled = true;
}
let cpt = 0;
if (cpt %2 == 0) {
t.style.color = "red";
} else {
t.style.color = "black";
}
}, 100);
}
function stringCheck(value, tab) {
let i = 1;
tab.forEach(lettre => {
if(value == lettre) {
document.getElementById(i).textContent = value;
lettresValid.push(value);
}
i++;
})
if(!tab.includes(value)) {
vieRestante--;
}
}
function arrayCompare(tab1, tab2){
if(tab1.length != tab2.length) {
return false;
} else {
return true;
}
}<file_sep>DROP DATABASE IF EXISTS pendu;
CREATE DATABASE pendu;
USE pendu;
CREATE TABLE categorie (
id_categorie int(3) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
libelle_categorie varchar(50)
)ENGINE=InnoDB;
CREATE TABLE mot (
libelle_mot varchar(25) NOT NULL PRIMARY KEY,
id_categorie int(3) UNSIGNED NOT NULL,
FOREIGN KEY(id_categorie) REFERENCES categorie(id_categorie)
)ENGINE=InnoDB;
CREATE TABLE utilisateur (
id_utilisateur int(5) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
pseudo_utilisateur varchar(50),
mdp_utilisateur text,
login_utilisateur varchar(150),
score_max_utilisateur int(3),
nb_essai_utilisateur int(5)
)ENGINE=InnoDB;
INSERT INTO categorie (libelle_categorie) VALUES
("sport"),
("animal"),
("ville"),
("fruit"),
("personnages");
INSERT INTO mot (libelle_mot, id_categorie) VALUES
("Football",1),
("Basketball",1),
("Handball",1),
("Ski de fond",1),
("Equitation",1),
("Alpaga",2),
("Ornithorynque",2),
("Chien",2),
("Loutre",2),
("Chouette",2),
("Charleville-Mezieres",3),
("Paris",3),
("Rome",3),
("Thilay",3),
("Banane",4),
("Grenade",4),
("Durian",4),
("Kiwi",4),
("<NAME>",5),
("Mario",5),
("<NAME>",5),
("<NAME>",5),
("Link",5),
("Ganondorf",5);<file_sep><?php
session_start();
Class UserController extends Controller {
// Fonction d'inscription d'un utilisateur dans la BDD
public function createUser($login, $pseudo, $pass) {
$req_ins = "INSERT INTO utilisateur VALUES (0, :pseudo, sha2(:mdp, 512), :login, 0, 0)";
$res_ins = $this->connex->prepare($req_ins);
$res_ins->execute(array(":pseudo"=>$pseudo,
":login"=>$login,
":mdp"=>$pass
));
}
// Vérifie l'existance d'un utilisateur dans la base de donnée en fonction d'un email et d'un mot de passe
public function testUser($login, $password) {
$req_con = "select count(id_utilisateur) from utilisateur where login_utilisateur=:login and mdp_utilisateur=sha2(:mdp, 512)";
$res_con = $this->connex->prepare($req_con);
$res_con->execute(array(":login"=>$login, ":mdp"=>$password));
$sel = $res_con->fetch();
if ($sel[0]==1):
return true;
else:
return false;
endif;
}
// Fonction de création de session pour l'utilisateur lors de la connexion
public function identification($login) {
$req_ses = "select id_utilisateur, pseudonyme_utilisateur, id_departement from utilisateur where login_utilisateur=:login";
$res_ses = $this->connex->prepare($req_ses);
$res_ses->execute(array(":login"=>$login));
$sel=$res_ses->fetch();
$_SESSION["id"] = session_id();
$_SESSION["id_user"] = $sel[0];
$_SESSION["pseudo"] = $sel[1];
$_SESSION["login"] = $login;
}
// Vérifie si l'email est disponible à l'utilisation
public function loginVerif($login) {
$req_ver = "select count(id_utilisateur) from utilisateur where login_utilisateur=:login";
$res_ver = $this->connex->prepare($req_ver);
$res_ver->execute(array(":login"=>$login));
$sel=$res_ver->fetch();
if ($sel[0] == 0):
return true;
else:
return false;
endif;
}
// Vérifie si le pseudonyme est disponible à l'utilisation
public function pseudoVerif($pseudo) {
$req_ver = "select count(id_utilisateur) from utilisateur where pseudonyme_utilisateur=:pseudo";
$res_ver = $this->connex->prepare($req_ver);
$res_ver->execute(array(":pseudo"=>$pseudo));
$sel=$res_ver->fetch();
if ($sel[0] == 0):
return true;
else:
return false;
endif;
}
// Vérifie si le pseudonyme est disponible à l'utilisation
public function mdpVerif($mdp, $mdpC) {
if($mdp != $mdpC): // Condition vérifiant si les deux mots de passe fournis sont identiques
echo "Les mots de passe ne correspondent pas";
//return false;
elseif(strlen($mdp) < 6): // Condition vérifiant la longueur du mot de passe (6 caractères minimum)
echo "Votre mot de passe doit contenir au moins 6 caractères";
return false;
elseif($mdp == strtoupper($mdp) || $mdp == strtolower($mdp)): // Condition vérifiant la présence d'au moins une minuscule et d'une majuscule dans le mot de passe
echo "Votre mot de passe doit contenir au moins une minuscule et une majuscule";
return false;
elseif(!preg_match("~[0-9]~", $mdp)): // Condition vérifiant la présence d'au moins un chiffre dans le mot de passe
echo "Votre mot de passe doit contenir un chiffre";
return false;
else:
return true;
endif;
}
// Permet de mettre à jour le mot de passe d'un utilisateur en fonction de son id
public function updatePassUser($pass, $id) {
$req_upd = "UPDATE utilisateur SET mdp_utilisateur = :pass WHERE id_utilisateur = :id";
$res_upd = $this->connex->prepare($req_upd);
$res_upd->execute(array(":pass"=>$pass,
":id"=>$id));
}
}
?><file_sep><?php
Class Controller {
// Déclaration des attributs
private $db = "mysql:host=localhost;dbname=pendu;charset=UTF8";
private $name = "root";
private $pass = "<PASSWORD>";
public $connex;
public function __construct() {
try {
$this->connex = new PDO($this->db, $this->name, $this->pass);
} catch(PDOException $e) {
echo "Connexion à la base de données impossible";
die();
}
}
}
?> | 524bd317760fd851e033410b8cf830b22f560cf0 | [
"JavaScript",
"SQL",
"PHP"
] | 5 | PHP | Ashkropht/penduJS | 638391f9bc5861b49e31226803cc33b9bba348fb | 0847384657e4822e20e9b3b805fad6780284e6ff |
refs/heads/master | <repo_name>SIRLA-FJULIS/sirla_helper_bot<file_sep>/README.md
# SIRLA幫手喵
## 開發中...
## 作者: 土豆
## 使用方法
* 喵喵講話
* 回覆: "話。"
* 喵喵講幹話
* 回覆: 隨機一段句子
* 喵喵誰最帥
* 回覆: "喵~<問話人名字>最帥了"
* 喵喵誰最美
* 回覆: "喵~<問話人名字>最美了"
* 喵喵誰最狂
* 回覆: "喵~統神最狂沒有之一"
* 喵喵亂數 *min*-*max*
* 回覆: 產生*min*到*max*之間(包含)任意數字
* 喵喵分*n*組 `<name1> <name2> <name3> <name...>`
* 回覆: 隨機將後面的名字分成n組<file_sep>/index_bot_v1.js
const SlackBot = require('slackbots');
const axios = require('axios');
// prevent heroku sleep
var http = require("http");
setInterval(function() {
http.get("http://sirla-helper-bot.herokuapp.com");
}, 300000);
const bot = new SlackBot({
token: `${process.env.BOT_TOKEN}`,
name: 'SIRLA幫手喵'
});
// Start Handler
bot.on('start', () => {
bot.postMessageToUser('samabc75', '喵喵喵~ 我是SIRLA好幫喵,上線喵喵喵,會叫的喵是好喵');
});
// Error Handler
bot.on('error', (err) => console.log(err));
// Message Handler
bot.on('message', (data) => {
if (data.type !== 'message') {
return;
}
handleMessage(data);
});
// Response to message
let words = ['喵喵喵喵喵喵喵貓喵喵喵喵喵喵', '櫻櫻沒袋子,沒事叫我講幹話做啥', '你有聽過無限貓咪理論嗎,貓咪有一天也能打出曠世巨作', '幹話。', '喵喵累了,喵喵不講幹話', '喵', '喵喵喵', '喵喵~喵喵喵~~咪邀~~~'];
function handleMessage(data) {
if (data.text.includes('喵喵講話')) {
bot.getChannels().then( (value) => {
let channel_name = value.channels.find(items => items.id === data.channel).name;
bot.postMessageToChannel(channel_name, '話。');
});
} else if (data.text.includes('喵喵講幹話')) {
bot.getChannels().then( (value) => {
let channel_name = value.channels.find(items => items.id === data.channel).name;
let response = words[Math.floor(Math.random() * words.length)];
bot.postMessageToChannel(channel_name, response);
});
} else if (data.text.includes('喵喵誰最帥')) {
bot.getChannels().then( (value) => {
let channel_name = value.channels.find(items => items.id === data.channel).name;
bot.getUserById(data.user).then( value => {
bot.postMessageToChannel(channel_name, `喵~ ${value.profile.display_name}最帥了!`);
});
});
} else if (data.text.includes('喵喵誰最美')) {
bot.getChannels().then( (value) => {
let channel_name = value.channels.find(items => items.id === data.channel).name;
bot.getUserById(data.user).then( value => {
bot.postMessageToChannel(channel_name, `喵~ ${value.profile.display_name}最美了!`);
});
});
}
} | 32c69422ee1210ff5c05be2305425ec552417e91 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | SIRLA-FJULIS/sirla_helper_bot | db63193fd79bcbde6b9dfd3484fa195ad8590aad | b1bd95d750a0a5181e62d5bd598af6c981e1bac6 |
refs/heads/master | <file_sep># BayesBall
Overview of Project:
This project is aimed at projecting future player performance using Bayesian Hierarchical Poisson regression
as a probability distribution over outcomes instead of a simple point estimate. We do this by using a
graphical structure of at-bat outcomes, modeling plate appearances, and then using each simulated parent
node to estimate each child node.
Connections with:
None
Packages used:
projections / projections_p: bnstruct, dplyr, tidyr, rjags, runjags, stringr, missMDA
server / ui: shiny, ggplot2, plotly, psych, reshape2, pracma, robustbase
input data (data_pred3, data_pred3_p, etc.): available upon request
Output:
The final output is a shiny application deployed at https://www.shinyapps.io/admin/#/application/858636
Details:
Extensive Write-Up and Full Model Specification Available Here:
https://community.fangraphs.com/projecting-risk-in-major-league-baseball-a-bayesian-approach/
The variables used in the projection were all taken from the FanGraphs seasonal leaderboard.
These include “standard” (G, AB, 1B), “advanced” (K%, ISO, wRC), “batted ball” (GB%, Pull%, Soft%), “pitch type” (FB%, FBv),
“pitch value” (wFB), and “plate discipline” (O-Swing%, Z-Contact%) statistics. All of these were collected over
the three years preceding the year of prediction and variables that were perfect linear combinations of others
were deleted (like K%-BB%). Playing time, injury prediction, and Statcast data were not included in this application.
In particular, plate appearances were estimated using a combination of previous major league performance and plate
appearances from the previous three years. As a result, the model does not project accurately for recent call-ups.
In an attempt to remedy this without manually and arbitrarily altering plate appearances, a “pro-rate” button was
added which linearly transforms the plate appearance distribution to be centered around 600 plate appearances.
Missing data was imputed using K-Nearest Neighbors (KNN) imputation using the 10 most comparable players from 2010-18. Due to computational resources and the strenuous task of Bayesian inference, principal components analysis (PCA) was used to obtain a lower-dimensional representation of the data and we only used the first 10 principal components for our computation. A similar approach was used to prepare the data for pitchers, however the size of the matrix made KNN imputation infeasible, so the Expectation Maximization (EM) algorithm was used to fill in missing values.
The mathematical calculations cannot be carried out exactly, so variance of a player’s projected performance was estimated using a hierarchical Poisson regression using the “Just Another Gibbs Sampler” (JAGS) library in R. Parameter estimation was performed using Markov Chain Monte Carlo (MCMC) simulation and states were accepted using the Metropolis-Hastings (MH) algorithm. The estimated outcomes were then linearly combined using the Wins Above Replacement formula to create an uncertain estimate of WAR.
For this app in particular, we chose the ex-ante Sharpe ratio as the method by which to evaluate risk,
due to its interpretability (excess return per unit of risk taken on by the investor / GM).
We use our calculated league average 1.3 Wins Above Replacement
as the risk-free rate of return. This is not a trivial statement,
because technically 0 Wins Above Replacement is truly “replacement level”.
However, we are not using “replacement level” and “risk free” as synonyms. We are
implicitly assuming that a major league team can, without assuming any risk in outcomes,
acquire a player capable of producing at 1.3 WAR (and if not, you are comparing production
to the best available minor league player, who is often times above replacement level).
<file_sep>#
# This is the user-interface definition of a Shiny web application. You can
# run the application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(shinythemes)
library(shinyWidgets)
library(tidyr)
library(shinycssloaders)
library(DT)
library(rsconnect)
data_pred3 = read.csv('data_pred.csv')
data_pred3_p = read.csv('data_pred_pitch.csv')
# Define UI for application that draws a histogram
shinyUI(fluidPage(
theme = shinytheme('cerulean'),
# Application title
titlePanel("BayesBall"),
sidebarLayout(
sidebarPanel(
radioButtons(inputId="pos", label="Hitters/Pitchers:",
choices=c("Hitters", "Pitchers")),
radioButtons(inputId="prorated", label="Prorated (600 PA):",
choices=c("No", "Yes")),
radioButtons(inputId="comp", label="Select Baseline:",
choices=c("None", "Display League Average (2018)", "Compare Two Players")),
conditionalPanel(
condition = "input.pos == 'Hitters'",
selectInput(
inputId = "name",
label = "Player:",
choices = data_pred3[order(data_pred3$Name),]$Name
)
),
conditionalPanel(
condition = "input.pos == 'Pitchers'",
selectInput(
inputId = "name_p",
label = "Player:",
choices = data_pred3_p[order(data_pred3_p$Name),]$Name
)
),
conditionalPanel(
condition = "input.pos == 'Hitters'",
selectInput(
inputId = "stat",
label = "Statistic:",
choices = c('PA', 'AB', 'H', 'x1B', 'x2B', 'x3B', 'HR', 'K', 'BB', 'SB', 'AVG',
'OBP', 'SLG', 'OPS', 'wOBA', 'BatWAR', 'Sharpe')
)
),
conditionalPanel(
condition = "input.pos == 'Pitchers'",
selectInput(
inputId = "stat_p",
label = "Statistic:",
choices = c('W', 'L', 'ERA', 'G', 'SV', 'IP', 'H', 'ER', 'HR', 'K', 'BB',
'WHIP', 'K9', 'BB9', 'FIP', 'WAR', 'Sharpe')
)
),
conditionalPanel(
condition = "input.comp == 'Compare Two Players' && input.pos == 'Hitters'",
selectInput(inputId = "name2",
label = "Player 2:",
choices = data_pred3[order(data_pred3$Name),]$Name)
),
conditionalPanel(
condition = "input.comp == 'Compare Two Players' && input.pos == 'Pitchers'",
selectInput(inputId = "name2_p",
label = "Player 2:",
choices = data_pred3_p[order(data_pred3_p$Name),]$Name)
)
),
# Show a plot of the generated distribution
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Projections", plotOutput("distPlot") %>% withSpinner(),
h2('Posterior Predictive Distribution Data', align = 'center'),
DT::dataTableOutput("mytable")),
tabPanel("Leaderboard",
h2('Leaderboard', align = 'center'),
radioButtons(inputId = 'leaderboard',
label = 'Sort By:',
choices = c('Upside','Bust Potential',
'High Variance', 'Low Variance')),
DT::dataTableOutput('tab1')),
tabPanel("Methodology", tags$br(), uiOutput("method")),
tabPanel("About", tags$br(), img(src = "me.png", height = 185, style="display: block; margin-left: auto; margin-right: auto;"),
uiOutput("about"))
)
)
))
)
<file_sep>###### GIBBS SAMPLING #######
## Read in Data and Drop Duplicate Columns
setwd('/Users/saulforman/Desktop/project')
proj = data.frame(
pa = rep(0, 3000),
bip = rep(0, 3000),
h = rep(0, 3000),
x1b = rep(0, 3000),
x2b = rep(0, 3000),
x3b = rep(0, 3000),
hr = rep(0, 3000),
k = rep(0, 3000),
bb = rep(0, 3000),
attempt = rep(0, 3000),
sb = rep(0, 3000)
)
library(dplyr)
join1 = read.csv('join1.csv')
join2 = read.csv('join2.csv')
join2 = select(join2, -c(PA, AVG, Team, Name))
join3 = read.csv('join3.csv')
join3 = select(join3, -c(Team, BABIP, Name))
join3 = rename(join3, FlyB=FB.)
join4 = read.csv('join4.csv')
join4 = select(join4, -c(Team, Name))
join4 = rename(join4, FastB=FB.)
join5 = read.csv('join5.csv')
join5 = select(join5, -c(Team, Name))
## Join All Metrics Together
data_full = join1 %>% left_join(join2, by = c('Season','playerid')) %>%
left_join(join3, by = c('Season','playerid')) %>%
left_join(join4, by = c('Season','playerid')) %>%
left_join(join5, by = c('Season','playerid'))
## Use Output Data from 2013 and After
data_output = filter(data_full, Season >= 2013)
## Join Stats for T-1, T-2, and T-3 Seasons
data_join1 = data_full %>%
mutate(Season = Season + 1)
colnames(data_join1)[c(4:23, 25:85)] = paste(colnames(data_join1)[c(4:23, 25:85)], 't1', sep = '_')
data_join1 = data_join1 %>%
select(-c(Name, Team))
data_join2 = data_full %>%
mutate(Season = Season + 2)
colnames(data_join2)[c(4:23, 25:85)] = paste(colnames(data_join2)[c(4:23, 25:85)], 't2', sep = '_')
data_join2 = data_join2 %>%
select(-c(Name, Team))
data_join3 = data_full %>%
mutate(Season = Season + 3)
colnames(data_join3)[c(4:23, 25:85)] = paste(colnames(data_join3)[c(4:23, 25:85)], 't3', sep = '_')
data_join3 = data_join3 %>%
select(-c(Name, Team))
## Join T-1, T-2, and T-3 Data to Output Data
data_pred = data_output %>% left_join(data_join1, by = c('Season','playerid')) %>%
left_join(data_join2, by = c('Season','playerid')) %>%
left_join(data_join3, by = c('Season','playerid'))
## Eliminate Advanced Stats for Output Year
data_pred2 = data_pred[, -c(24:86)]
## AB >= 15 to eliminate extreme probabilities
data_pred2 = data_pred2 %>%
filter(AB >= 15)
## Create Predictors Matrix
X = data_pred2[, c(24:265)]
## Turn Percentages into Factors
for(i in 1:length(X)) {
if(class(X[,i]) == 'factor') {
X[,i] = as.numeric(sub('%', '', as.character(X[,i])))/100
}
}
## KNN Imputation
library(bnstruct)
X = as.matrix(X)
X_imputed = knn.impute(X, k = 10, cat.var = NA, to.impute = 1:nrow(X),
using = 1:nrow(X))
## PCA
X_pca = prcomp(X_imputed, center = TRUE, scale = TRUE)
summary(X_pca)
head(data_pred2)
## Data Pred 3
data_pred3 = cbind(data_pred2[,1:2], X_pca$x[,1:10])
# Gibbs Sampling
library(rjags)
library(runjags)
mod_string = " model {
for (a in 1:length(PA)) {
PA[a] ~ dpois(lam[a])
log(lam[a]) = a1 + b1[1]*PC1[a] + b1[2]*PC2[a] + b1[3]*PC3[a] +
b1[4]*PC4[a] + b1[5]*PC5[a] + b1[6]*PC6[a] + b1[7]*PC7[a] +
b1[8]*PC8[a] + b1[9]*PC9[a] + b1[10]*PC10[a]
}
a1 ~ dnorm(0.0, 1.0/1e6)
for (b in 1:10) {
b1[b] ~ ddexp(0.0, sqrt(2.0))
}
for (c in 1:length(BIP)) {
BIP[c] ~ dbinom(p2[c], PA[c])
logit(p2[c]) = a2 + b2[1]*PC1[c] + b2[2]*PC2[c] + b2[3]*PC3[c] +
b2[4]*PC4[c] + b2[5]*PC5[c] + b2[6]*PC6[c] + b2[7]*PC7[c] +
b2[8]*PC8[c] + b2[9]*PC9[c] + b2[10]*PC10[c] + b2[11]*PA[c]
}
a2 ~ dnorm(0.0, 1.0/1e6)
for (d in 1:11) {
b2[d] ~ ddexp(0.0, sqrt(2.0))
}
for (e in 1:length(H)) {
H[e] ~ dbinom(p3[e], BIP[e])
logit(p3[e]) = a3 + b3[1]*PC1[e] + b3[2]*PC2[e] + b3[3]*PC3[e] +
b3[4]*PC4[e] + b3[5]*PC5[e] + b3[6]*PC6[e] + b3[7]*PC7[e] +
b3[8]*PC8[e] + b3[9]*PC9[e] + b3[10]*PC10[e] + b3[11]*PA[e] +
b3[12]*BIP[e]
}
a3 ~ dnorm(0.0, 1.0/1e6)
for (f in 1:12) {
b3[f] ~ ddexp(0.0, sqrt(2.0))
}
for (g in 1:length(x1B)) {
x1B[g] ~ dbinom(p4[g], H[g])
logit(p4[g]) = a4 + b4[1]*PC1[g] + b4[2]*PC2[g] + b4[3]*PC3[g] +
b4[4]*PC4[g] + b4[5]*PC5[g] + b4[6]*PC6[g] + b4[7]*PC7[g] +
b4[8]*PC8[g] + b4[9]*PC9[g] + b4[10]*PC10[g] + b4[11]*PA[g] +
b4[12]*H[g]
}
a4 ~ dnorm(0.0, 1.0/1e6)
for (i in 1:12) {
b4[i] ~ ddexp(0.0, sqrt(2.0))
}
for (h in 1:length(x2B)) {
x2B[h] ~ dbinom(p5[h], H[h])
logit(p5[h]) = a5 + b5[1]*PC1[h] + b5[2]*PC2[h] + b5[3]*PC3[h] +
b5[4]*PC4[h] + b5[5]*PC5[h] + b5[6]*PC6[h] + b5[7]*PC7[h] +
b5[8]*PC8[h] + b5[9]*PC9[h] + b5[10]*PC10[h] + b5[11]*PA[h] +
b5[12]*H[h]
}
a5 ~ dnorm(0.0, 1.0/1e6)
for (u in 1:12) {
b5[u] ~ ddexp(0.0, sqrt(2.0))
}
for (l in 1:length(K)) {
K[l] ~ dbinom(p6[l], TTO[l])
logit(p6[l]) = a6 + b6[1]*PC1[l] + b6[2]*PC2[l] + b6[3]*PC3[l] +
b6[4]*PC4[l] + b6[5]*PC5[l] + b6[6]*PC6[l] + b6[7]*PC7[l] +
b6[8]*PC8[l] + b6[9]*PC9[l] + b6[10]*PC10[l] + b6[11]*PA[l] +
b6[12]*BIP[l] + b6[13]*H[l]
}
a6 ~ dnorm(0.0, 1.0/1e6)
for (m in 1:13) {
b6[m] ~ ddexp(0.0, sqrt(2.0))
}
for (n in 1:length(HR)) {
HR[n] ~ dbinom(p7[n], PA[n]-BIP[n])
logit(p7[n]) = a7 + b7[1]*PC1[n] + b7[2]*PC2[n] + b7[3]*PC3[n] +
b7[4]*PC4[n] + b7[5]*PC5[n] + b7[6]*PC6[n] + b7[7]*PC7[n] +
b7[8]*PC8[n] + b7[9]*PC9[n] + b7[10]*PC10[n] + b7[11]*PA[n] +
b7[12]*BIP[n] + b7[13]*H[n] + b7[14]*K[n]
}
a7 ~ dnorm(0.0, 1.0/1e6)
for (o in 1:14) {
b7[o] ~ ddexp(0.0, sqrt(2.0))
}
for (r in 1:length(SB)) {
SB[r] ~ dbinom(p8, Attempts[r])
}
p8 ~ dbeta(.5, .5)
for (s in 1:length(Attempts)) {
Attempts[s] ~ dpois(lam2[s])
log(lam2[s]) = a8 + b8[1]*PC1[s] + b8[2]*PC2[s] + b8[3]*PC3[s] +
b8[4]*PC4[s] + b8[5]*PC5[s] + b8[6]*PC6[s] + b8[7]*PC7[s] +
b8[8]*PC8[s] + b8[9]*PC9[s] + b8[10]*PC10[s]
}
a8 ~ dnorm(0.0, 1.0/1e6)
for (t in 1:14) {
b8[t] ~ ddexp(0.0, sqrt(2.0))
}
} "
X_pca_m = as.matrix(X_pca$x[,1:10])
data_jags = list(PA=data_pred2$PA,
BIP=(data_pred2$PA-(data_pred2$SO + data_pred2$BB + data_pred2$HR)),
H=(data_pred2$H - data_pred2$HR),
TTO=(data_pred2$SO + data_pred2$BB + data_pred2$HR),
x1B=(data_pred2$H-(data_pred2$HR + data_pred2$X2B + data_pred2$X3B)),
x2B=data_pred2$X2B,
HR=data_pred2$HR,
K=data_pred2$SO,
SB=data_pred2$SB,
Attempts=(data_pred2$SB + data_pred2$CS),
PC1=X_pca_m[,1],
PC2=X_pca_m[,2],
PC3=X_pca_m[,3],
PC4=X_pca_m[,4],
PC5=X_pca_m[,5],
PC6=X_pca_m[,6],
PC7=X_pca_m[,7],
PC8=X_pca_m[,8],
PC9=X_pca_m[,9],
PC10=X_pca_m[,10])
params = c("a1","b1",
"a2","b2","p2",
"a3","b3","p3",
"a4","b4","p4",
"a5","b5","p5",
"a6","b6","p6",
"a7","b7","p7",
"a8","b8","p8")
mod = jags.model(textConnection(mod_string), data=data_jags, n.chains=3)
rm("data_full", "data_join1", "data_join2", "data_join3", "data_output",
"data_pred", "join1", "join2", "join3", "join4", "join5", "X",
"X_imputed")
update(mod, 5e2)
mod_sim = coda.samples(model=mod,
variable.names=params,
n.iter=1e3)
mod_csim = as.mcmc(do.call(rbind, mod_sim))
par(mar=c(2,2,2,2))
plot(mod_sim, ask = TRUE)
summary(mod_sim)
data_pred3 = data_pred3[which(data_pred3$Season == 2018),]
save(mod_csim, file = "mod_csim.rda")
write.csv(data_pred3, file = "data_pred.csv")
write.csv(data_pred2, file = "data_pred2.csv")
<file_sep>setwd('/Users/saulforman/Desktop/project/BayesBall')
library(dplyr)
join1 = read.csv('pitch1.csv')
join2 = read.csv('pitch2.csv')
join2 = select(join2, -c(Team, Name)) %>%
select(-ERA)
join3 = read.csv('pitch3.csv')
join3 = select(join3, -c(Team, Name)) %>%
rename(FlyB = FB.) %>%
select(-BABIP)
join4 = read.csv('pitch4.csv')
join4 = select(join4, -c(Team, Name))
join5 = read.csv('pitch5.csv')
join5 = select(join5, -c(Team, Name))
## Join All Metrics Together
data_full = join1 %>% left_join(join2, by = c('Season','playerid')) %>%
left_join(join3, by = c('Season','playerid')) %>%
left_join(join4, by = c('Season','playerid')) %>%
left_join(join5, by = c('Season','playerid'))
## Use Output Data from 2013 and After
data_output = filter(data_full, Season >= 2013)
## Join Stats for T-1, T-2, and T-3 Seasons
data_join1 = data_full %>%
mutate(Season = Season + 1)
colnames(data_join1)[c(4:25, 27:90)] = paste(colnames(data_join1)[c(4:25, 27:90)], 't1', sep = '_')
data_join1 = data_join1 %>%
select(-c(Name, Team))
data_join2 = data_full %>%
mutate(Season = Season + 2)
colnames(data_join2)[c(4:25, 27:90)] = paste(colnames(data_join2)[c(4:25, 27:90)], 't2', sep = '_')
data_join2 = data_join2 %>%
select(-c(Name, Team))
data_join3 = data_full %>%
mutate(Season = Season + 3)
colnames(data_join3)[c(4:25, 27:90)] = paste(colnames(data_join3)[c(4:25, 27:90)], 't3', sep = '_')
data_join3 = data_join3 %>%
select(-c(Name, Team))
## Join T-1, T-2, and T-3 Data to Output Data
data_pred = data_output %>% left_join(data_join1, by = c('Season','playerid')) %>%
left_join(data_join2, by = c('Season','playerid')) %>%
left_join(data_join3, by = c('Season','playerid'))
## Eliminate Advanced Stats for Output Year
data_pred2 = data_pred[, -c(26:47,50:90)]
## AB >= 15 to eliminate extreme probabilities
data_pred2 = data_pred2 %>%
filter(TBF >= 30)
## Create Predictors Matrix
X = data_pred2[, c(26:283)]
## Turn Percentages into Factors
for(i in 1:length(X)) {
if(class(X[,i]) == 'factor') {
X[,i] = as.numeric(sub('%', '', as.character(X[,i])))/100
}
}
data_pred2$Name = as.character(data_pred2$Name)
data_pred2$Team = as.character(data_pred2$Team)
for(i in 1:length(data_pred2)) {
if(class(data_pred2[,i]) == 'factor') {
data_pred2[,i] = as.numeric(sub('%', '', as.character(data_pred2[,i])))/100
}
}
library(stringr)
data_pred2$IP = as.character(data_pred2$IP)
data_pred2$IP = str_replace(data_pred2$IP, '0.1', '0.3333')
data_pred2$IP = str_replace(data_pred2$IP, '0.2', '0.6666')
data_pred2$IP = as.numeric(data_pred2$IP)
data_pred2$Outs = data_pred2$TBF-data_pred2$H-data_pred2$BB-data_pred2$HBP-data_pred2$IBB
write.csv(data_pred2, 'data_pred2_pitch.csv')
## KNN Imputation
library(bnstruct)
library(missMDA)
X = as.matrix(X)
X_impute = imputePCA(X)
X_imp = as.matrix(X_impute$completeObs)
## PCA
X_pca = prcomp(X_imp, center = TRUE, scale = TRUE)
summary(X_pca)
## Data Pred 3
which(data_pred3_p$Name == '<NAME>')
data_pred3 = cbind(data_pred2[,1:2], X_pca$x[,1:10])
# Gibbs Sampling
library(rjags)
library(runjags)
mod_string = " model {
for (a in 1:length(TBF)) {
TBF[a] ~ dpois(lam[a])
log(lam[a]) = a1 + b1[1]*PC1[a] + b1[2]*PC2[a] + b1[3]*PC3[a] +
b1[4]*PC4[a] + b1[5]*PC5[a] + b1[6]*PC6[a] + b1[7]*PC7[a] +
b1[8]*PC8[a] + b1[9]*PC9[a] + b1[10]*PC10[a]
}
a1 ~ dnorm(0.0, 1.0/1e6)
for (b in 1:10) {
b1[b] ~ ddexp(0.0, sqrt(2.0))
}
for (c in 1:length(BIP)) {
BIP[c] ~ dbinom(p2[c], TBF[c])
logit(p2[c]) = a2 + b2[1]*PC1[c] + b2[2]*PC2[c] + b2[3]*PC3[c] +
b2[4]*PC4[c] + b2[5]*PC5[c] + b2[6]*PC6[c] + b2[7]*PC7[c] +
b2[8]*PC8[c] + b2[9]*PC9[c] + b2[10]*PC10[c] + b2[11]*TBF[c]
}
a2 ~ dnorm(0.0, 1.0/1e6)
for (d in 1:11) {
b2[d] ~ ddexp(0.0, sqrt(2.0))
}
for (e in 1:length(H)) {
H[e] ~ dbinom(p3[e], BIP[e])
logit(p3[e]) = a3 + b3[1]*PC1[e] + b3[2]*PC2[e] + b3[3]*PC3[e] +
b3[4]*PC4[e] + b3[5]*PC5[e] + b3[6]*PC6[e] + b3[7]*PC7[e] +
b3[8]*PC8[e] + b3[9]*PC9[e] + b3[10]*PC10[e] + b3[11]*BIP[e]
}
a3 ~ dnorm(0.0, 1.0/1e6)
for (f in 1:11) {
b3[f] ~ ddexp(0.0, sqrt(2.0))
}
for (l in 1:length(K)) {
K[l] ~ dbinom(p6[l], TTO[l])
logit(p6[l]) = a6 + b6[1]*PC1[l] + b6[2]*PC2[l] + b6[3]*PC3[l] +
b6[4]*PC4[l] + b6[5]*PC5[l] + b6[6]*PC6[l] + b6[7]*PC7[l] +
b6[8]*PC8[l] + b6[9]*PC9[l] + b6[10]*PC10[l] + b6[11]*TBF[l] +
b6[12]*BIP[l]
}
a6 ~ dnorm(0.0, 1.0/1e6)
for (m in 1:12) {
b6[m] ~ ddexp(0.0, sqrt(2.0))
}
for (n in 1:length(HR)) {
HR[n] ~ dbinom(p7[n], TBF[n]-BIP[n])
logit(p7[n]) = a7 + b7[1]*PC1[n] + b7[2]*PC2[n] + b7[3]*PC3[n] +
b7[4]*PC4[n] + b7[5]*PC5[n] + b7[6]*PC6[n] + b7[7]*PC7[n] +
b7[8]*PC8[n] + b7[9]*PC9[n] + b7[10]*PC10[n] + b7[11]*TBF[n] +
b7[12]*BIP[n]
}
a7 ~ dnorm(0.0, 1.0/1e6)
for (o in 1:12) {
b7[o] ~ ddexp(0.0, sqrt(2.0))
}
for (u in 1:length(IFFB)) {
IFFB[u] ~ dbinom(p9[u], BIP[u])
logit(p9[u]) = a9 + b9[1]*PC1[u] + b9[2]*PC2[u] + b9[3]*PC3[u] +
b9[4]*PC4[u] + b9[5]*PC5[u] + b9[6]*PC6[u] + b9[7]*PC7[u] +
b9[8]*PC8[u] + b9[9]*PC9[u] + b9[10]*PC10[u] + b9[11]*TBF[u] +
b9[12]*BIP[u] + b9[13]*K[u] + b9[14]*HR[u]
}
a9 ~ dnorm(0.0, 1.0/1e6)
for (v in 1:14) {
b9[v] ~ ddexp(0.0, sqrt(2.0))
}
for (w in 1:length(Outs)) {
Outs[w] ~ dbinom(p11[w], TBF[w])
logit(p11[w]) = a10 + b10[1]*PC1[w] + b10[2]*PC2[w] + b10[3]*PC3[w] +
b10[4]*PC4[w] + b10[5]*PC5[w] + b10[6]*PC6[w] + b10[7]*PC7[w] +
b10[8]*PC8[w] + b10[9]*PC9[w] + b10[10]*PC10[w] + b10[11]*TBF[w] +
b10[12]*BIP[w] + b10[13]*K[w] + b10[14]*HR[w]
}
a10 ~ dnorm(0.0, 1.0/1e6)
for (x in 1:14) {
b10[x] ~ ddexp(0.0, sqrt(2.0))
}
for (aa in 1:length(ER)) {
ER[aa] ~ dbinom(p12[aa], TBF[aa])
logit(p12[aa]) = a12 + b12[1]*PC1[aa] + b12[2]*PC2[aa] + b12[3]*PC3[aa] +
b12[4]*PC4[aa] + b12[5]*PC5[aa] + b12[6]*PC6[aa] + b12[7]*PC7[aa] +
b12[8]*PC8[aa] + b12[9]*PC9[aa] + b12[10]*PC10[aa] + b12[11]*TBF[aa] +
b12[12]*HR[aa]
}
a12 ~ dnorm(0.0, 1.0/1e6) # intercept
for (aa in 1:15){
b12[aa] ~ ddexp(0.0, sqrt(2.0))
}
for (bb in 1:length(GS)) {
GS[bb] ~ dpois(lam4[bb])
log(lam4[bb]) = a13 + b13[1]*PC1[bb] + b13[2]*PC2[bb] + b13[3]*PC3[bb] +
b13[4]*PC4[bb] + b13[5]*PC5[bb] + b13[6]*PC6[bb] + b13[7]*PC7[bb] +
b13[8]*PC8[bb] + b13[9]*PC9[bb] + b13[10]*PC10[bb] + b13[11]*TBF[bb] +
b13[12]*BIP[bb] + b13[13]*K[bb] + b13[14]*HR[bb] + b13[15]*Outs[bb]
}
a13 ~ dnorm(0.0, 1.0/1e6)
for (dd in 1:15){
b13[dd] ~ ddexp(0.0, sqrt(2.0))
}
for (y in 1:length(W)) {
W[y] ~ dbinom(p10[y], G[y])
logit(p10[y]) = a11 + b11[1]*PC1[y] + b11[2]*PC2[y] + b11[3]*PC3[y] +
b11[4]*PC4[y] + b11[5]*PC5[y] + b11[6]*PC6[y] + b11[7]*PC7[y] +
b11[8]*PC8[y] + b11[9]*PC9[y] + b11[10]*PC10[y] + b11[11]*TBF[y] +
b11[12]*BIP[y] + b11[13]*K[y] + b11[14]*HR[y] + b11[15]*Outs[y]
}
a11 ~ dnorm(0.0, 1.0/1e6)
for (z in 1:15) {
b11[z] ~ ddexp(0.0, sqrt(2.0))
}
for (ff in 1:length(SV)) {
SV[ff] ~ dpois(lam6[ff])
log(lam6[ff]) = a15 + b15[1]*PC1[ff] + b15[2]*PC2[ff] + b15[3]*PC3[ff] +
b15[4]*PC4[ff] + b15[5]*PC5[ff] + b15[6]*PC6[ff] + b15[7]*PC7[ff] +
b15[8]*PC8[ff] + b15[9]*PC9[ff] + b15[10]*PC10[ff]
}
a15 ~ dnorm(0.0, 1.0/1e6)
for (ii in 1:10){
b15[ii] ~ ddexp(0.0, sqrt(2.0))
}
for (gg in 1:length(G)) {
G[gg] ~ dpois(lam7[gg])
log(lam7[gg]) = a16 + b16[1]*PC1[gg] + b16[2]*PC2[gg] + b16[3]*PC3[gg] +
b16[4]*PC4[gg] + b16[5]*PC5[gg] + b16[6]*PC6[gg] + b16[7]*PC7[gg] +
b16[8]*PC8[gg] + b16[9]*PC9[gg] + b16[10]*PC10[gg]
}
a16 ~ dnorm(0.0, 1.0/1e6)
for (hh in 1:10){
b16[hh] ~ ddexp(0.0, sqrt(2.0))
}
for (cc in 1:length(L)) {
L[cc] ~ dbinom(p14[cc], G[cc])
logit(p14[cc]) = a14 + b14[1]*PC1[cc] + b14[2]*PC2[cc] + b14[3]*PC3[cc] +
b14[4]*PC4[cc] + b14[5]*PC5[cc] + b14[6]*PC6[cc] + b14[7]*PC7[cc] +
b14[8]*PC8[cc] + b14[9]*PC9[cc] + b14[10]*PC10[cc] + b14[11]*TBF[cc] +
b14[12]*BIP[cc] + b14[13]*K[cc] + b14[14]*HR[cc] + b14[15]*Outs[cc]
}
a14 ~ dnorm(0.0, 1.0/1e6)
for (ee in 1:15){
b14[ee] ~ ddexp(0.0, sqrt(2.0))
}
} "
X_pca_m = as.matrix(X_pca$x[,1:10])
data_jags = list(TBF=data_pred2$TBF,
BIP=(data_pred2$TBF-(data_pred2$SO + data_pred2$BB + data_pred2$HR)),
IFFB=round((data_pred2$TBF-(data_pred2$SO + data_pred2$BB))*data_pred2$FlyB*data_pred2$IFFB., 0),
H=(data_pred2$H - data_pred2$HR),
TTO=(data_pred2$SO + data_pred2$BB + data_pred2$HR),
HR=data_pred2$HR,
K=data_pred2$SO,
Outs=data_pred2$Outs,
GS=data_pred2$GS,
G=data_pred2$G,
SV=data_pred2$SV,
W=data_pred2$W,
L=data_pred2$L,
ER=data_pred2$ER,
PC1=X_pca_m[,1],
PC2=X_pca_m[,2],
PC3=X_pca_m[,3],
PC4=X_pca_m[,4],
PC5=X_pca_m[,5],
PC6=X_pca_m[,6],
PC7=X_pca_m[,7],
PC8=X_pca_m[,8],
PC9=X_pca_m[,9],
PC10=X_pca_m[,10])
params = c("a1","b1",
"a2","b2","p2",
"a3","b3","p3",
"a6","b6","p6",
"a7","b7","p7",
"a9","b9","p9",
"a10", "b10",
"a11", "b11",
"a12", "b12",
"a13", "b13",
"a14", "b14",
"a15", "b15",
"a16", "b16")
mod = jags.model(textConnection(mod_string), data=data_jags, n.chains=3)
update(mod, 5e2)
mod_sim = coda.samples(model=mod,
variable.names=params,
n.iter=1e3)
mod_csim_p = as.mcmc(do.call(rbind, mod_sim))
data_pred3 = data_pred3[which(data_pred3$Season == 2018),]
save(mod_csim_p, file = "mod_csim_p.rda")
write.csv(data_pred3, file = "data_pred_pitch.csv")
<file_sep>mat = matrix(0, ncol = 676, nrow = 3000)
bwar = as.data.frame(mat)
for(i in 1:nrow(data_pred3)){
name = as.character(data_pred3[i,]$Name)
row = data_pred3[which(data_pred3$Name == name),]
x = as.numeric(row[,4:13])
loglam = mod_csim[,1] + mod_csim[,9:18] %*% x
lam = exp(loglam)
## num_sims
n_sim = length(lam)
## plot PAs
pa = rpois(n_sim, lam)
## plot BIP
logit_p1 = mod_csim[,2] + mod_csim[,19:28] %*% x + as.matrix(mod_csim[,29]) * as.matrix(pa)
p1 = exp(logit_p1)/(1+exp(logit_p1))
bip = rbinom(n_sim, pa, p1)
## plot H - HR
logit_p2 = mod_csim[,3] + mod_csim[,30:39] %*% x + as.matrix(mod_csim[,40]) * as.matrix(pa) +
as.matrix(mod_csim[,41]) * as.matrix(bip)
p2 = exp(logit_p2)/(1+exp(logit_p2))
h2 = rbinom(n_sim, bip, p2)
## plot 1B
logit_p3 = mod_csim[,4] + mod_csim[,42:51] %*% x + as.matrix(mod_csim[,52]) * as.matrix(pa) +
as.matrix(mod_csim[,53]) * as.matrix(h)
p3 = exp(logit_p3)/(1+exp(logit_p3))
x1b = rbinom(n_sim, h2, p3)
## plot 2B
logit_p4 = mod_csim[,5] + mod_csim[,54:63] %*% x + as.matrix(mod_csim[,64]) * as.matrix(pa) +
as.matrix(mod_csim[,65]) * as.matrix(h)
p4 = exp(logit_p4)/(1+exp(logit_p4))
x2b = rbinom(n_sim, h2, p4)
## plot 3b
x3b = rbinom(n_sim, h2, max(1-p3-p4, 0))
## plot H
h = h2 + hr
## plot Ks
logit_p6 = mod_csim[,6] + mod_csim[,66:75] %*% x + as.matrix(mod_csim[,76]) * as.matrix(pa) +
as.matrix(mod_csim[,77]) * as.matrix(bip) + as.matrix(mod_csim[,78]) * as.matrix(h2)
p6 = exp(logit_p6)/(1+exp(logit_p6))
k = rbinom(n_sim, (pa-bip), p6)
## plot HR
logit_p7 = mod_csim[,7] + mod_csim[,79:88] %*% x + as.matrix(mod_csim[,89]) * as.matrix(pa) +
as.matrix(mod_csim[,90]) * as.matrix(bip) + as.matrix(mod_csim[,91]) * as.matrix(h2) +
as.matrix(mod_csim[,92]) * as.matrix(k)
p7 = exp(logit_p7)/(1+exp(logit_p7))
hr = rbinom(n_sim, (pa-bip), p7)
## plot BBs
bb = (pa-bip)-(hr+k)
## plot Attempts
loglam2 = mod_csim[,8] + mod_csim[,93:102] %*% x
lam2 = exp(loglam2)
attempt = rpois(n_sim, lam2)
## plot SBs
sb = rpois(n_sim, (lam2*0.7))
cs = attempt - sb
## plot ABs
ab = pa - bb
## plot AVG
avg = h/ab
## plot OBP
obp = (h+bb)/pa
## plot SLG
slg = (x1b + 2*x2b + 3*x3b + 4*hr)/ab
## plot OPS
ops = obp + slg
## plot wOBA
woba = (0.696*bb + 0.881*x1b + 1.238*x2b + 1.560*x3b + 1.987*hr)/pa
wraa = (woba - .317)/1.195 * pa
lgrpa = 21630/185139
row2 = data_pred2[which(data_pred2$Name == name),]
row2 = row2[which(row2$Season == 2018),]
rownum = which(as.character(pf$Team) == as.character(row2$Team))
pf2 = pf[rownum,]$Basic
if (as.character(row2$Team) %in% c('Yankees', 'Orioles', 'Red Sox', 'Blue Jays', 'Rays',
'Indians', 'White Sox', 'Twins', 'Tigers', 'Royals',
'Athletics', 'Astros', 'Angels', 'Mariners', 'Rangers')){
natamrpa = 10982/91924
} else {
natamrpa = 10432/88080
}
if (length(pf2) == 0) {
pf2 = 100
}
br = wraa + (lgrpa - ((pf2/100)*lgrpa))*pa + (lgrpa - natamrpa)*pa
rpw = 10
batwar = br/rpw
bwar[,i] = batwar
colnames(bwar)[i] = name
}
t = round(psych::describe(bwar), 3)
t2 = t[-which(rownames(t) %in% data_pred3_p$Name),]
t2$Name = rownames(t2)
rownames(t2) = 1:nrow(t2)
t2[,1] = t2$Name
t2 = t2[,-14]
colnames(t2)[1] = 'Name'
t2 = t2 %>% arrange(-skew)
write.csv(t2, 'bwar.csv')
| bf1b017f8933efe7856e3a0769665df138396937 | [
"Markdown",
"R"
] | 5 | Markdown | saulforman/BayesBall | e7e01dd57456dcb4f47f110211d47a4191384db5 | 6d5604026a3bc605b0aeaa8f963a0cdf04270bd2 |
refs/heads/master | <file_sep><?php
// Подключения БД
require_once ('Db.php');
// Debug всех массивов
function dd($arr)
{
echo "<pre>";
print_r($arr);
echo "</pre>";
}
// Регистрация нового контакта
function regUser($email,$password)
{
// Подключение к БД
$pdo = pdo();
// Если email and password то уже работаем
if(!empty($email) and !empty($password))
{
$email = htmlspecialchars($email);
//$password = password_hash($password,PASSWORD_DEFAULT);
$password = md5(md5($password));
$data = [
'email' => $email,
'password' => $<PASSWORD>
];
$user_exist = checkUser($email);
if($user_exist != $email)
{
$sql = "INSERT INTO user_secure (email,password) VALUES (:email,:password)";
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
$user_id = $pdo->lastInsertId();
}
}
return $user_id;
}
// Редактировать профиль контакта
function setUserInfo($username = '', $second_name = '', $login = '', $phone = '', $user_id)
{
// Подключение к БД
$pdo = pdo();
if(!empty($user_id))
{
$username = htmlspecialchars($username);
$second_name = htmlspecialchars($second_name);
$login = htmlspecialchars($login);
$phone = htmlspecialchars($phone);
$data = [
'username' => $username,
'second_name' => $second_name,
'login' => $login,
'phone' => $phone,
'user_id' => $user_id
];
$sql = "INSERT INTO user_profile (user_id) VALUES (:user_id);";
$sql .= "UPDATE user_profile SET
username =:username,
second_name =:second_name,
login =:login,
phone =:phone
WHERE user_id =:user_id;";
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
}
}
// Редактировать аватар контакта
function setUserAvatar($files = '', $user_id)
{
// Подключения к БД
$pdo = PDO();
// Если user_id то уже работаем
if(!empty($user_id) and !empty($files))
{
$orig_name = $files['name'];
$tmp_name = $files['tmp_name'];
$type = $files['type'];
$size = $files['size'];
if($type == 'image/jpeg' and $size <= 1024 * 1024)
{
$split = explode('.',strtolower($orig_name));
$name = $split[0];
$ext = $split[1];
$changed_name = $name . uniqid() . '.'. $ext;
$dist = 'uploads/'. $changed_name;
$data = [
'dist' => $dist,
'user_id' => $user_id,
];
$sql = "INSERT INTO user_photo (user_id) VALUES (:user_id);";
$sql .= "UPDATE user_photo SET avatar =:dist WHERE user_id =:user_id;";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
move_uploaded_file($tmp_name,$dist);
}
}
}
// Проверка на существования контакта в БД
function checkUser($email)
{
// Подключения к БД
$pdo = PDO();
$stmt = $pdo->prepare("SELECT email FROM user_secure WHERE email=:email");
$stmt->execute(['email' => $email]);
$user = $stmt->fetchColumn();
return $user;
}
// Редактировать пароль контакта
function setUserPass($email, $password, $user_id)
{
// code here
}
function userAuth($email,$password)
{
// Подключения к БД
$pdo = PDO();
if(!empty($email) and !empty($password))
{
// Получаем данные из past
$email = $email;
$password = md5(md5($password));
// Выборка и извлечение данных из БД
$stmt = $pdo->prepare("SELECT email,password FROM user_secure WHERE email=:email");
$stmt->execute(['email' => $email]);
$userInfo = $stmt->fetchObject();
// Проверка на совпадение данных
if(($userInfo->email == $email) and ($userInfo->password == $password))
{
$_SESSION['pass'] = $password;
header('Location: /personal.php');
}
}
}
// Выход из системы
function exitUser($get)
{
if($get === 'logout')
{
unset($_SESSION['pass']);
header('Location: /');
}
}<file_sep><?php
session_start();
require_once ('libs/functions.php');
// Вызов фукцию exitUser
$userExit = exitUser($_GET['user']);
if(isset($userExit))
{
header('Location: /');
}
?>
<a href="<?=$_SERVER['REQUEST_URI'].'?user=logout'?>">Выйти</a>
<file_sep><?php
/**
* Created by PhpStorm.
* User: Ziyodjon
* Date: 02.07.2020
* Time: 17:31
*/<file_sep># regauth
Registration and Authorization
<file_sep><?php
require_once ('libs/functions.php');
// Собираем все данные из post & files
$name = $_POST['username'];
$second_name = $_POST['second_name'];
$login = $_POST['login'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$password = $_POST['password'];
$avatar = $_FILES['avatar'];
if(!empty($email) and !empty($password))
{
// Регистрация нового контакта
$user_id = regUser($email, $password);
// Редактировать данные контакта
setUserInfo($name, $second_name, $login, $phone, $user_id);
// Редактировать аватар контакта
setUserAvatar($avatar, $user_id);
}
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/all.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<title>Регистрация и Авторизация</title>
</head>
<body>
<header>
<div class="container">
<h1><i class="fa fa-address-card-o" aria-hidden="true"></i> Регистрация и Авторизация</h1>
</div>
</header>
<div class="main-wrap">
<div class="container">
<h5>Форма регистрации</h5>
<form action="reg.php" method="post" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-md-6">
<label>Name</label>
<input type="text" class="form-control" name="username">
</div>
<div class="form-group col-md-6">
<label>Second Name</label>
<input type="text" class="form-control" name="second_name">
</div>
<div class="form-group col-md-6">
<label>Login</label>
<input type="text" class="form-control" name="login">
</div>
<div class="form-group col-md-6">
<label>Email</label>
<input type="email" class="form-control" name="email">
</div>
<div class="form-group col-md-6">
<label>Phone</label>
<input type="text" class="form-control" name="phone">
</div>
<div class="form-group col-md-6">
<label>Password</label>
<input type="<PASSWORD>" class="form-control" name="password">
</div>
<div class="form-group col-12">
<input type="file" name="avatar">
</div>
</div>
<button type="submit" class="btn btn-success">Сохранить</button>
</form>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html> | 621426df94579820c94ebbf82428ddc7749bf48a | [
"Markdown",
"PHP"
] | 5 | PHP | iziyodjon/regauth | 378c842d8b2954498757bbd681ae5630af70f0b4 | 92a9b02cfdfda870f5269a0cce4e1875078bdf75 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
import asyncio
import aiohttp
import aiofiles
import os
import sys
from crawler import Crawler
URLS_PATH = '/home/leo/MyCodes/FER/emotioNet_URLs' # url files directory
SAVE_PATH = os.path.join(os.path.dirname(__file__), 'IMAGES') # images will download into the director
TEST_FILE = './url_list.txt' # There are 1,000 urls in this file
if not os.path.exists(SAVE_PATH):
os.mkdir(SAVE_PATH)
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
headers={"User-Agent":user_agent}
def get_txtfiles(urls_path):
files = os.listdir(urls_path)
for file in files:
name, ext = os.path.splitext(file)
if ext != '.txt':
files.remove(file)
return sorted(files)
def get_urls(url_file):
with open(url_file) as file:
return (line.strip('\n') for line in file.readlines())
if __name__ == '__main__':
# # ----------- test get_txtfiles ----------------
# file_list = get_txtfiles(URLS_PATH)
# print(file_list)
# # ----------------------------------------------
# ------------- test get_urls --------------------
urls = get_urls(TEST_FILE)
# for url in urls:
# print(url)
# ------------------------------------------------
loop = asyncio.get_event_loop()
crawler = Crawler(links=urls, download_to=SAVE_PATH, headers=headers, loop=loop)
try:
loop.run_until_complete(crawler.run())
except KeyboardInterrupt:
sys.stderr.flush()
print('\nInterrupted\n')
finally:
crawler.close()
loop.stop()
loop.run_forever()
loop.close()<file_sep>## 异步下载器
通过这一个多星期的摸索,终于写出了一个稳定的异步下载样例
---
该下载器下载使用异步IO下载urls列表文件中的图片,通过调整并行任务数,可以快速下载百万级的图片。
---
### 使用:
使用时,修改main.py文件中的url文件路径即可,根据网络速度和机器性能,调整`max_tasks`和`max_sem`。
### 注意
当max_tasks过大,可能会造成IO错误“too many open files”的错误,这是因为同时保存过多的文件,程序打开的文件/socket连接数量超过系统设定值。
#### 解决方案
- 使用`ulimit -a`查看用户最大允许打开文件数量,其中`open files (-n) 1024`表示每个用户最大允许打开的文件数量是1024
- 设置open files数值
```
$ ulimit -n 2048
```
这样就可以把当前用户的最大允许打开文件数量设置为2048了,但这种设置方法在重启后会还原成默认值
#### 永久设置方法
```
$ vim /etc/security/limits.conf
# 在最后加入
* soft nofile 4096 # 最前面的 * 表示所用用户,也可根据需要设置某一用户
* hard nofile 4096
```
改完后注销一下就能生效
<file_sep>import time
import logging
import os
import asyncio
import aiohttp
class Downloader:
def __init__(self, links, download_to, log_file, headers=None,
concurrency=10, streaming=False, verbose=True):
self.links = links
self.path = download_to
self.log_file = log_file
self.client = aiohttp.ClientSession(headers=headers, conn_timeout=10)
self.queue = asyncio.Queue()
self.concurrency = concurrency
self._is_streaming = streaming
self.sem = asyncio.Semaphore(1000)
logging.basicConfig(level='INFO', filename=self.log_file, filemode='w')
self.log = logging.getLogger()
# if not verbose:
# self.log.disabled = True
def close(self):
self.client.close()
async def download(self, url, path):
async with self.client.get(url) as response:
if response.status != 200:
self.log.error('BAD RESPONSE: {}'.format(response.status))
return
content = await response.read()
with open(path, 'wb') as file:
file.write(content)
self.log.info('File has been stored at {}'.format(path))
async def stream_download(self, url, path):
async with self.sem:
async with self.client.get(url, allow_redirects=False) as response:
if response.status != 200:
self.log.error('BAD RESPONSE: {}'.format(response.status))
return
# Here we write file in blocking mode.
# The only benefit here is that, memory consumed more carefully.
tmp = path + '.chunks'
with open(tmp, 'ab') as file:
while True:
chunk = await response.content.read(1024)
if not chunk:
break
file.write(chunk)
os.rename(tmp, path)
self.log.info('FILE HAS BEEN STORED AT {}'.format(path))
async def worker(self):
self.log.info('Starting worker')
while True:
link = await self.queue.get()
try:
self.log.info('PROCESSING {}'.format(link))
path = os.path.join(self.path, link.split('/')[-1])
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
if not os.path.exists(path):
if self._is_streaming:
await self.stream_download(link, path)
else:
await self.download(link, path)
self.log.info('REMAINED {}'.format(self.queue.qsize()))
print('REMAINED {}'.format(self.queue.qsize()))
except Exception:
self.log.error('An error has occurred during downloading {}'.
format(link), exc_info=False)
finally:
self.queue.task_done()
async def run(self):
start = time.time()
print('Starting downloading')
await asyncio.wait([self.queue.put(link) for link in self.links])
tasks = [asyncio.ensure_future(self.worker())
for _ in range(self.concurrency)]
await self.queue.join()
self.log.info('Finishing...')
for task in tasks:
task.cancel()
self.client.close()
end = time.time()
print('FINISHED AT {} secs'.format(end-start))
<file_sep># -*- coding: utf-8 -*-
import asyncio
import aiohttp
import aiofiles
import time
import os
class Crawler:
def __init__(self,
links, # image urls
headers = None,
streaming = True, # content type is file streaming
download_to = './', # which director to save downloaded images
max_tries = 5, # Per-ure limits
max_tasks = 100, # Concurrence limits
loop = None):
self.loop = loop
self.links = links
self._is_streaming = streaming
self.path = download_to
self.max_tries = max_tries
self.max_tasks = max_tasks
self.queue = asyncio.Queue()
self.session = aiohttp.ClientSession(loop=self.loop, headers= headers, conn_timeout=2, read_timeout=5)
self.t0 = time.time()
self.t1 = None
def close(self):
self.session.close()
# 下载图片文件
async def fetch_stream(self, url, save_path):
tries = 0
exception = None
while tries < self.max_tries:
try:
print("get {0}...".format(url))
response = await self.session.get(url, allow_redirects=False)
print("")
if tries > 1:
print('try {} for {} success'.format(tries, url))
break
except aiohttp.ClientError as client_error:
print('try {} for {} rasied {}'.format(tries, url, client_error))
exception = client_error
tries += 1
else:
print('{} failed after {} tries, exception:{}'.format(url, self.max_tries, exception))
return
try:
if response.status != 200:
print("DOWNLOAD ERROR:{}-{}".format(response.status, url))
else:
tmp = save_path + '.chunks'
with open(tmp, 'ab') as file:
while True:
chunk = await response.content.read(1024)
if not chunk:
break
file.write(chunk)
os.rename(tmp, save_path)
print('FILE HAS BEEN STORED AT {}'.format(save_path))
except Exception:
print('DOWNLOAD ERROR')
finally:
await response.release()
# 下载文档
async def fetch_content(self, url, save_path):
pass
async def worker(self):
try:
url = 'none'
while True:
url = await self.queue.get()
# print('PROCESSING {}'.format(url))
path = os.path.join(self.path, url.split('/')[-1])
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
if self._is_streaming:
await self.fetch_stream(url, path)
else:
await self.fetch_content(url, path)
print('REMAINED {}'.format(self.queue.qsize()))
self.queue.task_done()
except asyncio.CancelledError:
print('An error has occurred during downloading {}'.format(url))
async def run(self):
await asyncio.wait([self.queue.put(link) for link in self.links])
tasks = [asyncio.ensure_future(self.worker()) for _ in range(self.max_tasks)]
await self.queue.join()
for task in tasks:
task.cancel()
self.session.close()
# workers = [asyncio.Task(self.work(), loop=self.loop) for _ in range(self.max_tasks)]
# print('Startiing downloading')
# self.t0 = time.time()
# await self.queue.join()
# self.t1 = time.time()
# for w in workers:
# w.cancel()
<file_sep># --*0-- coding: utf-8 -*-
import asyncio
import aiohttp
import aiofiles
import time
import os
import logging
thread_sleep = 1 # 防爬虫,停顿1秒
class Crawler:
def __init__(self, links, max_tries=4, max_tasks=10, loop=None, save_path='./', log_file='./log.txt'):
self.loop = loop or asyncio.get_event_loop()
self.links = links
self.max_tries = max_tries
self.max_tasks = max_tasks
self.save_path = save_path
self.log_file = log_file
self.url_queue = asyncio.Queue(loop=self.loop)
self.session = aiohttp.ClientSession(loop=self.loop, conn_timeout=3) # 这里最好最好加上conn_time
logging.basicConfig(level='INFO', filename=log_file, filemode='w', format='%(message)s')
self.log = logging.getLogger()
def close(self):
self.session.close()
async def work(self):
try:
while True:
link = await self.url_queue.get()
print('url队列数量: {}'.format(self.url_queue.qsize()))
await self.fetch(link, self.url_queue.qsize())
self.url_queue.task_done()
await asyncio.sleep(thread_sleep)
except asyncio.CancelledError:
pass
async def save_image(self, response, num):
if response.status == 200:
async with aiofiles.open(os.path.join(self.save_path, '{:07d}.jpg'.format(num)), 'wb') as f:
await f.write(await response.read())
else:
print('RESPONSE ERROR {}:{}'.format(response.status, response.url))
self.log.info('RESPONSE ERROR {}:{}'.format(response.status, response.url))
return
async def fetch(self, link, numbers):
tries = 0
while tries < self.max_tries:
try:
print('请求图片: {}'.format(link))
response = await self.session.get(link)
break
except aiohttp.ClientError:
pass
tries += 1
else:
# 如果没有进入循环体,则执行此条语句
print('connect error: {}'.format(link))
self.log.info('CONNECTED ERROR:{}'.format(link))
return
try:
await self.save_image(response, numbers)
print('{} STORED AT {}'.format(response.url, os.path.join(self.save_path, '{:07d}.jpg'.format(numbers))))
except Exception as e:
print('Save Error! {}-{}'.format(e, link))
self.log.info('SAVE ERROR:{}-{}'.format(e, link))
finally:
await response.release()
async def run(self):
start = time.time()
print("Starting Download")
await asyncio.wait([self.url_queue.put(link) for link in self.links])
workers = [asyncio.ensure_future(self.work()) for _ in range(self.max_tasks)]
await self.url_queue.join()
for w in workers:
w.cancel()
end = time.time()
print("Total Time: {}".format(end - start))
<file_sep># --*0-- coding: utf-8 -*-
import asyncio
import os
import sys
from crawler import Crawler
CURRENT_PATH = os.path.dirname(__file__) # 当前路径
URLS_PATH = os.path.join(CURRENT_PATH, 'emotioNet_URLs') # urls 文件目录
BASE_SAVE_PATH = '/mnt/F/emotioNet_Database' # 图片保存根路径
if not os.path.exists(BASE_SAVE_PATH):
os.makedirs(BASE_SAVE_PATH)
BASE_LOG_PATH = os.path.join(CURRENT_PATH, 'download_logs') # 日志保存路径
if not os.path.exists(BASE_LOG_PATH):
os.makedirs(BASE_LOG_PATH)
log_file = os.path.join(os.path.dirname(__file__), './download.log')
# urls_file = 'test_urls.txt'
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) "
"AppleWebKit 537.36 (KHTML, like Gecko) Chrome",
"Accept": "text/html,application/xhtml+xml,"
"application/xml;q=0.9,image/webp,*/*;q=0.8"}
def get_urls(urls_file):
with open(urls_file) as f:
return (url.strip('\n') for url in f.readlines())
def get_file_list(urls_path):
file_list = os.listdir(urls_path)
for f in file_list:
_, fext = os.path.splitext(f)
if fext != '.txt':
file_list.remove(f)
return [os.path.join(URLS_PATH, f) for f in sorted(file_list)]
if __name__ == "__main__":
for file in get_file_list(URLS_PATH):
# ----------- 日志文件命名 -----------
tmp = os.path.basename(file)
name, ext = os.path.splitext(tmp)
log_file = os.path.join(BASE_LOG_PATH, 'log_{}.log'.format(name))
# ----------------------------------
links = get_urls(file) # 获取url生成器
# --------------文件保存路径----------
save_path = os.path.join(BASE_SAVE_PATH, name)
if not os.path.exists(save_path):
os.mkdir(save_path)
# ----------------------------------
loop = asyncio.get_event_loop()
crawler = Crawler(links=links, max_tries=4, max_tasks=50, save_path=save_path, log_file=log_file)
try:
loop.run_until_complete(crawler.run())
except KeyboardInterrupt:
sys.stderr.flush()
finally:
crawler.close()
# -------- 这个地方要尤其注意,一定要加上loop.stop() -----------------
# next two lines are required for actual aiohttp resource cleanup
loop.stop()
# ---------------------------------------------------------------
loop.run_forever()
loop.close()
print('DONE!')<file_sep># -*- coding: utf-8 -*-
import asyncio
import aiohttp
import aiofiles
import os
import logging
import time
class Downloader:
def __init__(self, links, download_to, log_file, headers=None,
max_tasks=10, max_tries=4, max_sem=1000, streaming=True,
conn_time=5, loop=None):
"""
:param links: 需要下载的链接
:param download_to: 图片保存路径
:param log_file: 下载日志,下载失败的链接保存在此文件
:param headers: request headers,防爬虫
:param max_tasks: 最大并行数
:param max_tries: 请求最大重试次数
:param streaming: 默认为True,下载图片
:param max_sem:
:param conn_time: 请求最大时间
"""
self.loop = loop
self.links = links
self.download_to = download_to
self.log_file = log_file
self.headers = headers
self.max_tasks = max_tasks
self.max_tries = max_tries
self.streaming = True
self.queue = asyncio.Queue(loop=self.loop)
self.client = aiohttp.ClientSession(loop=self.loop, headers=headers, conn_timeout=conn_time)
self.sem = asyncio.Semaphore(max_sem)
self._is_streaming = streaming
def close(self):
"""
关闭session
:return:
"""
self.client.close()
async def download(self, url, path):
"""
爬取网页时使用此函数
:param url:
:param path:
:return:
"""
pass
def rename(self, url):
exts = ['.jpg', '.png', 'jif', '.bmp', 'jpeg']
name = url.strip('\n').split('/')[-1]
fname, ext = os.path.splitext(name)
if ext.lower() in exts:
ext = ext.lower()
elif ext[:4].lower() in exts:
ext = ext[:4].lower()
elif ext[:5].lower() in exts:
ext = ext[:5].lower()
else:
ext = '.jpg'
return '{}{}'.format(fname, ext)
async def stream_download(self, url, path):
"""
爬取媒体文件时,使用此函数
:param url: 图片url
:param path: 文件保存路径
:return:
"""
async with self.sem:
tries = 0
while tries < self.max_tries:
try:
response = await self.client.get(url, allow_redirects=False)
if tries > 1:
print("TRY {} FOR {} SUCCESS".format(tries, url))
break
except aiohttp.ClientError as ce:
print("CLIENT ERROR {}".format(ce)) # 如果请求发生错误,重试
tries += 1
else:
print("CONNECTED ERROR!{}".format(url)) # 如果连接失败,则停止连接
async with aiofiles.open(self.log_file, 'a') as log:
await log.write("CONNECTED ERROR:{}\n".format(url))
return
if response.status == 200:
try:
tmp = path + '.chunks'
with open(tmp, 'ab') as file:
while True:
chunk = await response.content.read(1024)
if not chunk:
break
file.write(chunk)
os.rename(tmp, path)
print("SAVE SUCCESSED AT {}".format(path))
except Exception as e:
print("SAVE ERROR {}:{}".format(e, url))
finally:
response.release()
else:
print("RESPONSE ERROR {}:{}".format(response.status, url))
async with aiofiles.open(self.log_file, 'a') as log:
await log.write("RESPONSE ERROR {}:{}\n".format(response.status, url))
async def work(self):
while True:
link = await self.queue.get()
try:
# path = os.path.join(self.download_to, link.split('/')[-1])
path = os.path.join(self.download_to, self.rename(link))
if self._is_streaming:
await self.stream_download(link, path)
else:
await self.download(link, path)
print('REMAINED {}'.format(self.queue.qsize()))
except Exception as de:
print("An Error Has Occurred During Downloading {}:{}".format(de, link))
finally:
self.queue.task_done()
async def run(self):
start = time.time()
print("Beginning Download")
await asyncio.wait([self.queue.put(link) for link in self.links])
tasks = [asyncio.ensure_future(self.work()) for _ in range(self.max_tasks)]
await self.queue.join()
for task in tasks:
task.cancle()
self.close()
end = time.time()
print("FINISED AT {} secs".format(end - start))
<file_sep>import os
import asyncio
from urllib.parse import urljoin
from downloader import Downloader
import random
BASE_URL_PATH = './emotioNet_URLs/emotioNet_3'
CURRENT_PATH = os.path.dirname(__file__)
BASE_SAVE_PATH = '/home/leo/Images/emotionNet_3'
def get_urls(links_file):
# Any custom logic that represents list with links
with open(links_file) as file:
return (line.strip() for line in file.readlines())
def get_files(urls_path):
file_list = os.listdir(urls_path)
for f in file_list:
_, fext = os.path.splitext(f)
if fext != '.txt':
file_list.remove(f)
random.shuffle(file_list)
return file_list
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) "
"AppleWebKit 537.36 (KHTML, like Gecko) Chrome",
"Accept": "text/html,application/xhtml+xml,"
"application/xml;q=0.9,image/webp,*/*;q=0.8"}
if __name__ == '__main__':
for links_file in get_files(BASE_URL_PATH):
# oldloop = asyncio.get_event_loop()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop=loop)
links = get_urls(os.path.join(BASE_URL_PATH, links_file))
file_name, _ = os.path.splitext(links_file)
save_path = os.path.join(BASE_SAVE_PATH, file_name)
if not os.path.exists(save_path):
os.makedirs(save_path)
log_file = os.path.join(BASE_SAVE_PATH, file_name+'.log')
downloader = Downloader(links, save_path, log_file, concurrency=50, headers=headers, streaming=True)
try:
loop.run_until_complete(downloader.run())
except Exception:
print('ERROR')
finally:
loop.stop()
loop.run_forever()
loop.close()
# asyncio.set_event_loop(oldloop)
print("==============================================================================================")
<file_sep># -*- coding: utf-8 -*-
import asyncio
import aiohttp
import aiofiles
import time
import os
class Downloader:
def __init__(self, links, download_to, log_file, max_tries=6, max_tasks=20,
max_sem=1000, conn_timeout=5, headers=None, loop=None):
self.loop = loop or asyncio.get_event_loop()
self.links = links
self.download_to = download_to
self.log_success = log_file + '_success.log'
self.log_failed = log_file + '_failed.log'
self.max_tries = max_tries
self.max_tasks = max_tasks
self.sem = asyncio.Semaphore(max_sem)
self.headers = headers
self.queue = asyncio.Queue(loop=self.loop)
self.session = aiohttp.ClientSession(loop=self.loop, headers=headers, conn_timeout=conn_timeout)
def close(self):
self.session.close()
@staticmethod
def rename(url):
exts = ['.jpg', '.png', 'jif', '.bmp', 'jpeg']
name = url.strip('\n').split('/')[-1]
fname, ext = os.path.splitext(name)
if ext.lower() in exts:
ext = ext.lower()
elif ext[:4].lower() in exts:
ext = ext[:4].lower()
elif ext[:5].lower() in exts:
ext = ext[:5].lower()
else:
ext = '.jpg'
return '{}{}'.format(fname, ext)
async def download(self, url, save_path):
async with self.sem:
tries = 0
while tries < self.max_tries:
try:
async with self.session.get(url) as response:
if response.status == 200:
try:
async with aiofiles.open(save_path, 'wb') as f:
await f.write(await response.read())
print('save successed {} to {}'.format(url, save_path))
# 将下载成功的url保存到下载成功日志中
async with aiofiles.open(self.log_success, 'a') as log:
await log.write(url + '\n')
except Exception as e:
print('save error {}'.format(e))
async with aiofiles.open(self.log_failed, 'a') as log:
await log.write(url + '\n')
break
except aiohttp.ClientError as client_error:
pass
tries += 1
else:
print("try {} times but still unconnected".format(self.max_tries))
# 将连接超时的url保存到下载失败日志中
async with aiofiles.open(self.log_failed, 'a') as log:
await log.write(url+'\n')
async def worker(self):
while True:
url = await self.queue.get()
print("processing {}".format(url))
save_name = self.rename(url)
save_path = os.path.join(self.download_to, save_name)
if os.path.exists(save_path):
self.queue.task_done()
continue
try:
await self.download(url, save_path)
print('remained {}'.format(self.queue.qsize()))
except Exception as e:
print('save error. except: {}, url: {}'.format(e, url))
finally:
self.queue.task_done()
async def run(self):
start = time.time()
print("Starting ...")
await asyncio.wait([self.queue.put(link) for link in self.links])
tasks = [asyncio.ensure_future(self.worker()) for _ in range(self.max_tasks)]
await self.queue.join()
for task in tasks:
task.cancle()
self.close()
end = time.time()
print("FINISED AT {} secs".format(end - start))<file_sep># -*- coding: utf-8 -*-
import os
import math
URLS_PATH = '..\\emotioNet_URLs'
SAVE_PATH = 'emotioNet_URLs'
NUMBERS = 1000 # 每个文件分割的大小
def get_file_list(urls_path):
file_list = os.listdir(urls_path)
for f in file_list:
_, fext = os.path.splitext(f)
if fext != '.txt':
file_list.remove(f)
return sorted(file_list)
def split_file(file):
name, _ = os.path.splitext(file)
file_path = os.path.join(URLS_PATH, file)
save_path = os.path.join(SAVE_PATH, name)
if not os.path.exists(save_path):
os.makedirs(save_path)
print('{}-{}-{}'.format(name, file_path, save_path))
with open(file_path) as f:
lines = f.readlines()
lines_num = len(lines)
files_num = math.ceil(lines_num / NUMBERS)
# print(lines_num, files_num)
for i in range(files_num):
with open(os.path.join(save_path, '{}_{:03d}.txt'.format(name, i)), 'a+') as f:
for line in lines[i*NUMBERS:(i+1)*NUMBERS]:
f.write(line)
if __name__ == '__main__':
file_list = get_file_list(URLS_PATH)
for file in file_list:
split_file(file)
# file = 'test_urls.txt'
# split_file(file)<file_sep># -*- coding: utf-8 -*-
import asyncio
import os
from download.downloader import Downloader
import aiofiles
BASE_URL_PATH = '../emotioNET_URLs'
BASE_SAVE_PATH = '../IMAGES'
BASE_LOGS_PATH = '../log_files'
def get_urls(links_file):
# Any custom logic that represents list with links
with open(links_file) as file:
return (line.strip() for line in file.readlines())
def get_files(urls_path):
file_list = os.listdir(urls_path)
for f in file_list:
_, fext = os.path.splitext(f)
if fext != '.txt':
file_list.remove(f)
return file_list
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) "
"AppleWebKit 537.36 (KHTML, like Gecko) Chrome",
"Accept": "text/html,application/xhtml+xml,"
"application/xml;q=0.9,image/webp,*/*;q=0.8"}
if __name__ == '__main__':
urls_file = 'emotioNet_1.txt'
links = get_urls(os.path.join(BASE_URL_PATH, urls_file))
loop = asyncio.get_event_loop()
f_name, ext = os.path.splitext(urls_file)
save_path = os.path.join(BASE_SAVE_PATH, f_name)
if not os.path.exists(save_path):
os.makedirs(save_path)
log_file = os.path.join(BASE_LOGS_PATH, f_name+'.log')
downloader = Downloader(links, save_path, log_file, headers, max_tasks=150,
max_tries=4, max_sem=1000, conn_time=30, loop=loop)
try:
loop.run_until_complete(downloader.run())
except Exception as e:
print(e)
finally:
loop.stop()
loop.run_forever()
loop.close()
| 3777bd2025c28e448e7ee4c98fd60d41bb7158fd | [
"Markdown",
"Python"
] | 11 | Python | Emotiva/emotioNet_URLs_Download | 77c69774c1b83ed6f53906d92fbcfedbd1069a35 | 3ab00a9d232a1c7f69f5ef6336cc066057f5621a |
refs/heads/master | <file_sep>class ModuleFkRename < ActiveRecord::Migration[5.2]
def change
rename_column :uimodule_stats, :module_id, :uimodule_id
end
end
<file_sep>class BusinessSegment < ApplicationRecord
has_many :users
has_many :uimodule_stats
has_many :layout_presets
has_many :user_role
end
<file_sep>class UimoduleStat < ApplicationRecord
belongs_to :uimodule
belongs_to :business_segment
end
<file_sep>class UimoduleController < ApplicationController
def list
@stats_small = UimoduleStat.where("business_segment_id = ?", 1)
@stats_medium = UimoduleStat.where("business_segment_id = ?", 2)
@stats_large = UimoduleStat.where("business_segment_id = ?", 3)
@segment_sum_small = @stats_small.sum(:segment_actuality)
@segment_sum_medium = @stats_medium.sum(:segment_actuality)
@segment_sum_large = @stats_large.sum(:segment_actuality)
end
def show
end
end
<file_sep>class Uimodule < ApplicationRecord
has_many :uimodule_stats
end
<file_sep>class Layout < ApplicationRecord
has_many :users
has_many :layout_presets
end
<file_sep>class UserRole < ApplicationRecord
belongs_to :business_segment, optional: true
has_many :users
end
<file_sep>class LayoutController < ApplicationController
skip_before_action :verify_authenticity_token
def add
json = JSON.parse(request.raw_post)
@layout = Layout.new({ :structure => json["data"] })
@layout.save
if !json["user"].empty?
User.find_by_id(json["user"]).update({ :layout_id => @layout.id })
redirect_to root_path
end
if !json["preset"].empty?
LayoutPreset.find_by_id(json["preset"]).update({ :layout_id => @layout.id })
redirect_to root_path
end
end
def generator
@user = params[:user]
@preset = params[:preset]
end
end
<file_sep>class CreateUimoduleStats < ActiveRecord::Migration[5.2]
def change
create_table :uimodule_stats do |t|
t.integer :segment_actuality
t.integer :role_actuality
t.belongs_to :module, index: true
t.belongs_to :business_segment, index: true
t.timestamps
end
end
end
<file_sep>FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /Smart_UI
WORKDIR /Smart_UI
COPY Gemfile /Smart_UI/Gemfile
COPY Gemfile.lock /Smart_UI/Gemfile.lock
RUN bundle install
COPY . /Smart_UI<file_sep>## Synopsis
### What is the problem of the clients?
They need to get the services and information for their businesses in fast and easy way. They have no time for doing mechanic work. As we know “Time is money”.
The goal of the project is to provide clients with adaptive, informative and customizable interface
### What’s the solution?
To organize the sets of service modules which the clients would get depending on their business segment. They would get the suggestions with sets of suitable modules or they would be able to construct and change these sets how they need. There are different functionality for the user’s side and administrator’s / manager’s side.
**For administrator:**
* Opportunity to set up initial menu for the certain segment;
* Opportunity to see the analytics about using of modules by different types of segments and roles of clients to create more effective UI.
**For manager (if the client has one):**
* Opportunity of agile setup of few templates within each segments for different types of clients (clients with different roles) which can be done based on the following mechanics:
* Clients survey on main functions for the first login and templates displaying based on answers (the question: “What’s your position?”);
* Show templates and choosing one of them in interactive mode.
**For user:**
* Different content based on the segment;
* Customization of module sets.
An expected results of implementation:
* Increasing of availability of information;
* Interaction improvement;
* Reduction of time for operations.
## What it does
Usable smart modular interface for different types of clients.
## How we built it
Ruby on Rails client-server application.
## Authors
[@NEWESTERS](https://github.com/NEWESTERS) — backend (Ruby On Rails)
[@vgreen](https://github.com/vgreen) — frontend (Javascript)
<file_sep>class ClientUiController < ApplicationController
def view
@user = User.find_by_id(params[:user_id])
if @user.user_role.name != "admin"
@layout = JSON.parse(@user.layout.structure.to_json)
end
end
end
<file_sep>class LayoutPreset < ApplicationRecord
belongs_to :business_segment
belongs_to :layout
belongs_to :user_role
end
<file_sep>class RenameFKs < ActiveRecord::Migration[5.2]
def change
rename_column :users, :role_id, :user_role_id
rename_column :layout_presets, :role_id, :user_role_id
end
end
<file_sep>class SegmentTypeRename < ActiveRecord::Migration[5.2]
def change
rename_column :business_segments, :type, :name
end
end
<file_sep>class User < ApplicationRecord
belongs_to :layout, optional: true
belongs_to :business_segment, optional: true
belongs_to :user_role
end
<file_sep>require 'test_helper'
class ClientUiControllerTest < ActionDispatch::IntegrationTest
test "should get view" do
get client_ui_view_url
assert_response :success
end
end
<file_sep>Rails.application.routes.draw do
get 'uimodule/list'
get 'uimodule/show'
get 'client_ui/view'
get 'roles/list'
get 'main_ui/view'
root 'roles#list'
get 'layout/generator'
post 'layout/add'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| 0bbce01112ba97709574f3204761699854880c9a | [
"Markdown",
"Ruby",
"Dockerfile"
] | 18 | Ruby | NEWESTERS/rosbank_smartui | 3eeb25b2875961095ea8fef9b3019209ab812f58 | e20c14e1abda7c668270a97f51bf6983f2fef866 |
refs/heads/master | <repo_name>TwoPennySpark/Chat<file_sep>/Makefile
all:
gcc serv.c -o serv -Wall --std=c99
gcc clnt.c -o clnt -Wall --std=c99 -pthread
<file_sep>/serv.c
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
#include <poll.h>
#include <fcntl.h>
#define BUFFER_SIZE 512
#define MAX_CLIENT 128
#define NICKNAME_LEN 32
#define INFTIM ((int)-1)
enum commands
{
SHOW_LIST = 1,
CHOOSE_INTERLOCUTOR
};
typedef struct client
{
uint16_t interlocutor;
uint16_t port;
char nickname[NICKNAME_LEN];
char addr[32];
}client_info;
client_info clients[MAX_CLIENT];
struct pollfd fds[MAX_CLIENT];
const char const instructions[] =
"1 - Show possible interlocutors\n"
"2 - Choose an interlocutor:\n"
"[*]To create a conversation with one of "
"the users write number 2 and the NAME "
"of the interlocutor separated by SPACE\n"
"(Ex.: \"2 John\")\n";
void dieWithError(const char *msg)
{
perror(msg);
exit(-1);
}
void warn(const char *msg)
{
printf("[-]{%m}ERROR: %s\n", msg);
fflush(stdout);
}
void show_client_list(const int sock)
{
char temp[BUFFER_SIZE/4] = {0};
char list[BUFFER_SIZE] = {0};
uint8_t count = 0;
for (uint8_t i = 1; i < MAX_CLIENT; i++)
{
if ((fds[i].fd > 0) && (clients[i].interlocutor == 0) && (fds[i].fd != sock))
{
count++;
snprintf(temp, strlen(clients[i].nickname) + 8, "[%d]%s\n", count, clients[i].nickname);
strncat(list, temp, strlen(temp));
memset(temp, '\0', sizeof(temp));
}
}
if (!count)
{
if (send(sock, "[*]No other users yet\n", 22, 0) < 0)
warn("send msg");
}
else
if (send(sock, list, strlen(list)-1, 0) < 0)
warn("send list");
}
void parse_commands(const int index, const char *command)
{
if (command[0] == '~' && !strlen(clients[index].nickname))
{
strncpy(clients[index].nickname, &command[1], strlen(command) - 1);
printf("newname: %s\n", clients[index].nickname);
return;
}
switch (atoi(&command[0]))
{
case SHOW_LIST:
show_client_list(fds[index].fd);
break;
case CHOOSE_INTERLOCUTOR:
if (command[1] == ' ')
{
for(uint16_t i = 1; i < MAX_CLIENT;i++)
{
if (strlen(clients[i].nickname) != 0)
{
if (!strncmp(clients[i].nickname, &command[2], strlen(clients[i].nickname)))
{
clients[index].interlocutor = fds[i].fd;
clients[i].interlocutor = fds[index].fd;
if (send(fds[index].fd, "[!]A new conversation was created\n", 34, 0) < 0)
warn("send");
if (send(fds[i].fd, "[!]A new conversation was created\n", 34, 0) < 0)
warn("send");
printf("[!]A new conversation was created:\n%s with %s\n", clients[i].nickname, clients[index].nickname);
return;
}
}
}
}
if (send(fds[index].fd, "[-]Unknown user, try again\n", 27, 0) < 0)
warn("send unknown");
break;
default:
if (send(fds[index].fd, "[-]Unknown command, try again\n", 30, 0) < 0)
warn("send unknown");
break;
}
}
int main(const int const argc, const char ** const argv)
{
int16_t clntSock;
int16_t listenSock;
int16_t ready;
int16_t flags;
uint16_t j;
uint16_t maxfd;
int32_t recvSize;
char buffer[BUFFER_SIZE];
struct sockaddr_in servAddr;
struct sockaddr_in clntAddr;
if (argc != 2)
dieWithError("Usage: <port>");
if ((listenSock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
dieWithError("socket");
memset(&clients, 0, sizeof(clients));
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = INADDR_ANY;
servAddr.sin_port = htons(atoi(argv[1]));
if (bind(listenSock, (struct sockaddr*)&servAddr, sizeof(servAddr)) < 0)
dieWithError("bind");
if ((flags = fcntl(listenSock, F_GETFL)) < 0)
dieWithError("fcntl getfl");
flags |= O_NONBLOCK;
if (fcntl(listenSock, F_SETFL, flags) < 0)
dieWithError("fcntl setfl");
if (listen(listenSock, MAX_CLIENT) < 0)
dieWithError("listen");
// initialize 1st element of pollfd's structure array with server socket
fds[0].fd = listenSock;
fds[0].events = POLLIN;
// initialize all other elements with -1 (means they are not used by other clients)
for(uint16_t i = 1; i < MAX_CLIENT; i++)
fds[i].fd = -1;
maxfd = 0;
for (;;)
{
for(uint16_t i = 0; i < MAX_CLIENT; i++)
fds[i].revents = 0;
// check our sockets for incoming data
if ((ready = poll(fds, maxfd + 1, INFTIM)) < 0)
dieWithError("epoll_wait");
if (fds[0].revents & POLLIN)
{// if a new connection has arrived on the server socket
socklen_t clntLen = sizeof(clntAddr);
if ((clntSock = accept4(listenSock, (struct sockaddr*)&clntAddr, &clntLen, SOCK_NONBLOCK)) < 0)
{
if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
{
if (--ready <= 0)
continue;
}
else
{
warn("accept");
continue;
}
}
for (j = 1; j < MAX_CLIENT; j++)
{// look for an empty spot
if (fds[j].fd < 0)
{
fds[j].fd = clntSock;
fds[j].events = POLLIN;
if (inet_ntop(AF_INET, &clntAddr.sin_addr.s_addr, clients[j].addr, 32) < 0)
warn("inet_ntop");
if ((clients[j].port = ntohs(clntAddr.sin_port)) < 0)
warn("ntohs");
if (send(fds[j].fd, instructions, strlen(instructions), 0) < 0)
warn("send");
printf("[!]New connection on socket: %d from IP: %s port: %d\n",
fds[j].fd, clients[j].addr, clients[j].port);
break;
}
}
if (j == MAX_CLIENT)
printf("Too many clients\n");
if (j > maxfd)
maxfd = j;
// if there is no data recieved on client sockets
if (--ready <= 0)
continue;
}
for (int16_t i = 1; i < maxfd + 1; i++)
{// if there is some information received for one or more client socket
if (fds[i].fd < 0)
continue;
memset(buffer, '\0', BUFFER_SIZE);
if (fds[i].revents & POLLIN)
{
if ((recvSize = recv(fds[i].fd , buffer, BUFFER_SIZE, 0)) < 0)
{
if (errno == EAGAIN || errno == EWOULDBLOCK)
continue;
else
{
warn("recv");
shutdown(fds[i].fd, 2);
close(fds[i].fd);
fds[i].fd = -1;
continue;
}
}
if (recvSize == 0)
{
printf("[*]Client closed the connection\n");
/* if user closed the connection while he had a coversation,
* tell his interlocutor that the conversation is over
*/
if (clients[i].interlocutor)
{
for (int16_t j = 1; j < MAX_CLIENT; j++)
{
if (clients[i].interlocutor == fds[j].fd)
{
char convEndMsg[] = "[*]Your conversation partner left the chat\n";
strncat(convEndMsg, instructions, strlen(instructions));
if (send(fds[j].fd, convEndMsg, 43 + strlen(instructions), 0) < 0)
warn("send");
clients[j].interlocutor = 0;
}
}
}
memset(&clients[i], 0, sizeof(struct client));
shutdown(fds[i].fd, 2);
close(fds[i].fd);
fds[i].fd = -1;
break;
}
printf("[%d]buffer: %s\n",fds[i].fd, buffer);
// if user doesn't have any interlocutor means he's sending commands to server
if (!clients[i].interlocutor)
parse_commands(i, buffer);
else
if (send(clients[i].interlocutor, buffer, strlen(buffer), 0) < 0)
warn("send message");
if (--ready <= 0)
break;
}
}
}
return 0;
}<file_sep>/clnt.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <pthread.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
#include <fcntl.h>
#include <time.h>
#define BUFFER_SIZE 512
#define MAX_CLIENT 128
#define MAX_NAME_SIZE 32
void dieWithError(char *msg)
{
perror(msg);
exit(-1);
}
void warn(char *msg)
{
printf("[-]{%m}ERROR: %s\n", msg);
fflush(stdout);
}
void *chatRead(void *arg)
{
int16_t sock = *((int*)arg);
int32_t recvSize;
time_t rawtime;
struct tm* timeinfo;
char buffer[BUFFER_SIZE];
char timebuf[BUFFER_SIZE];
for (;;)
{
memset(&buffer, '\0', BUFFER_SIZE);
if ((recvSize = recv(sock, buffer, BUFFER_SIZE, 0)) < 0)
{
if (errno == ECONNRESET)
{
printf("Connection is reset by client\n");
shutdown(sock, 2);
close(sock);
break;
}
else
dieWithError("chatRead recv() failed");
}
else if (recvSize == 0)
{
printf("Client closed connection\n");
shutdown(sock, 2);
close(sock);
break;
}
else
{
time(&rawtime);
timeinfo = localtime(&rawtime);
sprintf(timebuf, "%d:%d", timeinfo->tm_hour, timeinfo->tm_min);
printf("*********************\n\t%s\n---------------------\n"
"%s\n*********************\n", timebuf, buffer);
}
}
pthread_exit(0);
}
void *chatWrite(void *arg)
{
uint16_t sock = *((int*)arg);
char buffer[BUFFER_SIZE];
memset(&buffer, '\0', BUFFER_SIZE);
for (;;)
{
if (fgets(buffer, BUFFER_SIZE, stdin) < 0)
dieWithError("chatWrite fgets() failed");
if (send(sock, buffer, strlen(buffer), 0) < 0)
dieWithError("chatWrite send() failed");
memset(&buffer, '\0', BUFFER_SIZE);
}
pthread_exit(0);
}
int main(int argc, char** argv)
{
int16_t size = 0;
int16_t sock;
char buffer[BUFFER_SIZE];
char nickname[MAX_NAME_SIZE] = "~";
struct sockaddr_in servAddr;
pthread_t readPth, writePth;
while (size < 4 || size > MAX_NAME_SIZE - 1)
{
printf("[*]Enter your nickname (it must consist of at least 3"
"characters and be no longer than 31 characters):\n");
memset(&nickname[1], '\0', MAX_NAME_SIZE - 1);
if ((size = read(1, &nickname[1], BUFFER_SIZE)) < 0)
dieWithError("read");
}
printf("[*]Your nickname is: %s\n", &nickname[1]);
if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
dieWithError("scoket");
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
if (inet_pton(AF_INET, argv[1], &servAddr.sin_addr.s_addr) < 0)
dieWithError("inet_pton");
servAddr.sin_port = htons(atoi(argv[2]));
if (connect(sock, (struct sockaddr*)&servAddr, sizeof(servAddr)) < 0)
dieWithError("connect");
if (send(sock, nickname, strlen(nickname), 0) < 0)
dieWithError("send");
memset(&buffer, '\0', BUFFER_SIZE);
if (recv(sock, buffer, BUFFER_SIZE, 0) < 0)
dieWithError("recv");
printf("%s\n", buffer);
if (pthread_create(&writePth, NULL, &chatWrite, &sock) < 0)
dieWithError("pthread_create() failed");
if (pthread_create(&readPth, NULL, &chatRead, &sock) < 0)
dieWithError("pthread_create() failed");
if (pthread_join(writePth, NULL) < 0)
dieWithError("join() failed");
if (pthread_join(readPth, NULL) < 0)
dieWithError("join() failed");
return 0;
}<file_sep>/README.md
# Chat
Simple chat written in C
| b43a6f26ebd1ea2eadf0e63dbf07c46967d8e69d | [
"Markdown",
"C",
"Makefile"
] | 4 | Makefile | TwoPennySpark/Chat | e9071d3e6e70f5b8a680691cb0f09aa57728f623 | 67d7227e972c3c128319403d390bbf8eaf50314e |
refs/heads/master | <repo_name>a270443177/DynameUpstream<file_sep>/schema.lua
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by Administrator.
--- DateTime: 2019/5/22 9:58
---
local iputils = require "resty.iputils"
local function validate_ips(v, t, column)
if v and type(v) == "table" then
for _, ip in ipairs(v) do
local _, err = iputils.parse_cidr(ip)
if type(err) == "string" then -- It's an error only if the second variable is a string
return false, "cannot parse '" .. ip .. "': " .. err
end
end
end
return true
end
return {
fields = {
upstream = {type = "string", required = true},
ip = {type = "array", required = true, func = validate_ips},
}
}<file_sep>/handler.lua
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by Administrator.
--- DateTime: 2019/5/22 9:59
---
local BasePlugin = require "kong.plugins.base_plugin"
local iputils = require "resty.iputils"
local new_tab
do
local ok
ok, new_tab = pcall(require, "table.new")
if not ok then
new_tab = function() return {} end
end
end
-- cache of parsed CIDR values
local cache = {}
local DynameUpstreamHandler = BasePlugin:extend()
DynameUpstreamHandler.PRIORITY = 480
DynameUpstreamHandler.VERSION = "0.0.1"
local function cidr_cache(cidr_tab)
local cidr_tab_len = #cidr_tab
local parsed_cidrs = new_tab(cidr_tab_len, 0) -- table of parsed cidrs to return
-- build a table of parsed cidr blocks based on configured
-- cidrs, either from cache or via iputils parse
-- TODO dont build a new table every time, just cache the final result
-- best way to do this will require a migration (see PR details)
for i = 1, cidr_tab_len do
local cidr = cidr_tab[i]
local parsed_cidr = cache[cidr]
if parsed_cidr then
parsed_cidrs[i] = parsed_cidr
else
-- if we dont have this cidr block cached,
-- parse it and cache the results
local lower, upper = iputils.parse_cidr(cidr)
cache[cidr] = { lower, upper }
parsed_cidrs[i] = cache[cidr]
end
end
return parsed_cidrs
end
function DynameUpstreamHandler:new()
DynameUpstreamHandler.super.new(self, "DynameUpstream")
end
function DynameUpstreamHandler:init_worker()
DynameUpstreamHandler.super.init_worker(self)
local ok, err = iputils.enable_lrucache()
if not ok then
ngx.log(ngx.ERR, "[DynameUpstream] Could not enable lrucache: ", err)
end
end
function DynameUpstreamHandler:access(conf)
DynameUpstreamHandler.super.access(self)
local AllowIp = false
local binary_remote_addr = ngx.var.binary_remote_addr
-- your custom code here
if conf.ip and #conf.ip > 0 then
AllowIp = iputils.binip_in_cidrs(binary_remote_addr, cidr_cache(conf.ip))
end
if AllowIp and binary_remote_addr then
local ok, err = kong.service.set_upstream(conf.upstream)
if not ok then
kong.log.err(err)
return
end
end
end
return DynameUpstreamHandler<file_sep>/README.md
# DynameUpstream
支持版本 0.10.0以上版本可以使用,目前测试版本为 0.14.1 正常稳定使用
根据来源IP 进行不同的upstream选择。通过此方法可以相应的减少预上线环境,尽可能的接近生产环境。
注意注意了, 原有的Service必须使用的是upstream方式,不然不行的
| 6c70d925cd732ebdf3b627634c9040d884efa185 | [
"Markdown",
"Lua"
] | 3 | Lua | a270443177/DynameUpstream | a30c82005d67a1eb8ebae4c19a1f751642380756 | ab7fd650a178d43a09795a97b94e1a1c7ffe426c |
refs/heads/master | <repo_name>chenzhitong/getnewaddress<file_sep>/json_rpc/Program.cs
using Newtonsoft.Json.Linq;
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace json_rpc
{
class Program
{
/// <summary>
/// API 参考:http://docs.neo.org/zh-cn/node/api.html
/// API Reference: http://docs.neo.org/en-us/node/api.html
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Console.WriteLine("输入要创建地址的数量");
var input = Console.ReadLine();
int.TryParse(input, out int count);
Console.WriteLine($"创建地址数量:{count},并发:4线程");
Task t1 = Task.Factory.StartNew(() => CreateAddress(count / 4, 1));
Task t2 = Task.Factory.StartNew(() => CreateAddress(count / 4, 2));
Task t3 = Task.Factory.StartNew(() => CreateAddress(count / 4, 3));
Task t4 = Task.Factory.StartNew(() => CreateAddress(count - (count / 4) * 3, 4));
Console.ReadLine();
}
public static void CreateAddress(int count, int thread)
{
for (int i = 0; i < count; i++)
{
var r = PostWebRequest("http://localhost:10332", "{'jsonrpc': '2.0', 'method': 'getnewaddress', 'params': [], 'id': 1}");
if (string.IsNullOrEmpty(r))
{
Console.WriteLine("请打开neo-cli");
}
var address = JObject.Parse(r)["result"];
if (address != null)
{
Console.WriteLine(address);
}
else {
var error = JObject.Parse(r)["error"];
Console.WriteLine(error);
}
}
Console.WriteLine($"线程{thread},OK");
}
public static string PostWebRequest(string postUrl, string paramData)
{
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(paramData);
WebRequest webReq = WebRequest.Create(postUrl);
webReq.Method = "POST";
using (Stream newStream = webReq.GetRequestStream())
{
newStream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = webReq.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return sr.ReadToEnd();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return "";
}
}
}
| 770de081c2715cf114ed5594b7fa8caeece2b8ca | [
"C#"
] | 1 | C# | chenzhitong/getnewaddress | b2d3a3bd9ae53a5996992a6fcb18a763a89d8104 | 145ee1e65357574eafa902a80fb744970eb3334b |
refs/heads/master | <repo_name>FhBeast/Course-workPL<file_sep>/imageFilter.py
import pygame
class ImageFilter:
@staticmethod
def blur(image, power, quality):
width = image.get_width()
height = image.get_height()
for i in range(quality):
image = pygame.transform.smoothscale(image, (int(width / power), int(height / power)))
image = pygame.transform.smoothscale(image, (width, height))
return image
<file_sep>/game.py
import pygame
import os
from list_of_level import get_list
from levelLoader import LevelLoader
from player import Player, IMG_FOLDER
from levelController import LevelController
from imageFilter import ImageFilter
from effect import Effect
from menu import Menu
CONSOLE_NAME = "Game controller"
class Game:
def __init__(self, width, height):
pygame.init()
pygame.mixer.init()
pygame.display.set_icon(pygame.image.load(os.path.join(IMG_FOLDER, 'icon.bmp')))
pygame.display.set_caption("My Game")
self.width = width
self.height = height
self.screen = pygame.display.set_mode((width, height), pygame.DOUBLEBUF)
self.clock = pygame.time.Clock()
self.level_list = get_list()
self.fps = 60
self.effect = Effect(width, height)
self.effects = pygame.sprite.Group()
self.effects.add(self.effect)
self.running_game = True
self.running_level = True
self.restarting_level = False
def runGame(self):
number_level = 0
try:
f = open('save.bin', 'rb')
number_level = int(f.read())
f.close()
print(f"{CONSOLE_NAME}: Game loaded")
except Exception:
print(f"{CONSOLE_NAME}: Failed to open save")
answer = Menu.mainMenu(self.screen, self.fps)
if answer == "Quit":
self.closeGame()
elif answer == "New game":
number_level = 0
self.nextLevel()
# Цикл игры
while self.running_game:
pygame.mouse.set_visible(False)
player = Player() # Создаем игрока
level = LevelLoader.load_level(self.level_list[number_level]) # Загружаем уровень
level.platforms.append(player)
level.entities_upper.add(player) # Добавляем игрока в список объектов
player.rect.midbottom = level.playerStartPosition # Получаем стартовое местоположение игрока
# Цикл уровня
flag_is_complete = False
flag_is_restart = False
self.running_level = True
while self.running_level:
# Держим цикл на правильной скорости
self.clock.tick(self.fps)
# По умолчанию - стоим и не прыгаем
left = right = False
jump = False
use = False
attack = False
# Проверяем одиночные нажатия клавиш
# События
for event in pygame.event.get():
# Проверяем закрыли ли мы окно
if event.type == pygame.QUIT:
self.closeGame()
# Управление
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
use = True
if event.key == pygame.K_SPACE:
attack = True
if event.key == pygame.K_ESCAPE:
sub = self.screen.subsurface(pygame.Rect(0, 0, self.width, self.height))
bg = pygame.Surface((self.width, self.height))
bg.blit(sub, (0, 0))
bg = ImageFilter.blur(bg, 10, 8)
answer = Menu.pauseMenu(self.screen, self.fps, bg)
if answer == "Quit":
self.closeGame()
elif answer == "Restart":
self.restartLevel()
pygame.mouse.set_visible(False)
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
left = True
if keys[pygame.K_d]:
right = True
if keys[pygame.K_w]:
jump = True
# Обновление
level.particles.update()
player.update(left, right, jump, attack, level.platforms) # Обновляем игрока
LevelController.updateLevel(player, level, use) # Обновляем логику уровня
if level.isComplete and not flag_is_complete:
print(f"{CONSOLE_NAME}: Level completed")
self.effect.blackout()
flag_is_complete = True
if player.rect.top > self.height:
self.effect.blackout()
flag_is_restart = True
if self.effect.update():
if flag_is_complete:
self.nextLevel()
elif flag_is_restart:
self.restartLevel()
# Рендеринг
# Фон
self.screen.blit(level.bgImg, (0, 0))
# Объекты
level.entities.draw(self.screen)
level.entities_upper.draw(self.screen)
level.particles.draw(self.screen)
self.effects.draw(self.screen)
# Обновляем экран
pygame.display.update()
if self.restarting_level:
self.restarting_level = False
elif number_level + 1 < len(self.level_list) and self.running_game:
number_level += 1
else:
self.closeGame()
try:
f = open('save.bin', 'wb')
f.write(str(number_level).encode())
f.close()
print(f"{CONSOLE_NAME}: Game saved")
except Exception:
print(f"{CONSOLE_NAME}: Failed to save game")
def closeGame(self):
self.running_level = False
self.running_game = False
print(f"{CONSOLE_NAME}: Game closed")
def nextLevel(self):
self.running_level = False
def restartLevel(self):
self.running_level = False
self.restarting_level = True
print(f"{CONSOLE_NAME}: Reload level")
<file_sep>/key.py
import pygame
KEY_WIDTH = 34
KEY_HEIGHT = 18
KEY_X = 50 - (KEY_WIDTH / 2)
KEY_Y = 70 - (KEY_HEIGHT / 2)
class Key(pygame.sprite.Sprite):
def __init__(self, x, y, image):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((KEY_WIDTH, KEY_HEIGHT))
self.image = image
self.rect = pygame.Rect(x + KEY_X, y + KEY_Y, KEY_WIDTH, KEY_HEIGHT)
<file_sep>/box.py
import pygame
PUSH_SPEED = 20
DECELERATION_RATE = 0.7
GRAVITY = 0.7
WIDTH = 100
HEIGHT = 100
class Box(pygame.sprite.Sprite):
def __init__(self, x, y, image):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((WIDTH, HEIGHT))
self.rect = pygame.Rect(x, y, WIDTH, HEIGHT)
self.image = image
self.speed = 0
self.speedFall = 0
self.fall = False
def update(self, platforms):
if self.speed > 0:
if self.speed < DECELERATION_RATE:
self.speed = 0
else:
self.speed -= DECELERATION_RATE
elif self.speed < 0:
if self.speed > -DECELERATION_RATE:
self.speed = 0
else:
self.speed += DECELERATION_RATE
if self.fall:
self.speedFall += GRAVITY
if self.rect.top > 2000:
self.kill()
self.fall = True
self.rect.y += self.speedFall # Двигаемся по оси y
self.collide(0, self.speedFall, platforms) # Проверяем пересекаемся ли мы с чем-нибудь
self.rect.x += self.speed # Двигаемся по оси x
self.collide(self.speed, 0, platforms) # Проверяем пересекаемся ли мы с чем-нибудь
def push(self, right=True):
if right:
self.speed = PUSH_SPEED
else:
self.speed = -PUSH_SPEED
def collide(self, speed_x, speed_y, platforms):
for platform in platforms:
if pygame.sprite.collide_rect(self, platform) and platform != self: # Если есть пересечение
if speed_x > 0: # Если двигались вправо
self.rect.right = platform.rect.left # То возвращаем игрока обратно
self.speed = 0
if speed_x < 0: # Если двигались влево
self.rect.left = platform.rect.right # То возвращаем игрока обратно тоже
self.speed = 0
if speed_y > 0: # Если падали вниз
self.rect.bottom = platform.rect.top # То возвращаем игрока на платформу
self.fall = False # Отключаем падение
self.speedFall = 0 # Скорость падения обнуляется
if speed_y < 0: # Если двигались вверх
self.rect.top = platform.rect.bottom # То не поднимаем игрока дальше
self.speedFall = 0 # Скорость падения обнуляется
<file_sep>/crystal.py
import pygame
class Crystal(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, image, destroy_img):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((width, height))
self.image = image
self.images = destroy_img
self.rect = pygame.Rect(x, y, width, height)
self.__isDestroy = False
self.frame = 0
def destroy(self):
self.__isDestroy = True
def update(self):
if self.__isDestroy:
if not self.frame + 1 >= len(self.images): # Меняем кадр анимации частицы
self.frame += 1
else:
self.kill()
self.image = self.images[self.frame]
@property
def isDestroy(self):
return self.__isDestroy
<file_sep>/level.py
import pygame
class Level:
def __init__(self):
self.__entities = pygame.sprite.Group()
self.__entities_upper = pygame.sprite.Group()
self.__particles = pygame.sprite.Group()
self.__dynamicEntity = []
self.__platforms = []
self.__bgImg = None
self.__playerStartPosition = ()
self.__isComplete = False
@property
def particles(self):
return self.__particles
@particles.setter
def particles(self, value):
self.__particles = value
@property
def entities(self):
return self.__entities
@entities.setter
def entities(self, value):
self.__entities = value
@property
def entities_upper(self):
return self.__entities_upper
@entities_upper.setter
def entities_upper(self, value):
self.__entities_upper = value
@property
def dynamicEntity(self):
return self.__dynamicEntity
@dynamicEntity.setter
def dynamicEntity(self, value):
self.__dynamicEntity = value
@property
def platforms(self):
return self.__platforms
@platforms.setter
def platforms(self, value):
self.__platforms = value
@property
def bgImg(self):
return self.__bgImg
@bgImg.setter
def bgImg(self, value):
self.__bgImg = value
@property
def playerStartPosition(self):
return self.__playerStartPosition
@playerStartPosition.setter
def playerStartPosition(self, value):
self.__playerStartPosition = value
@property
def isComplete(self):
return self.__isComplete
def complete(self):
self.__isComplete = True
<file_sep>/player.py
import pygame
import os
RUN_SPEED = 10
WIDTH = 52
HEIGHT = 90
JUMP_POWER = 17
GRAVITY = 0.7 # Гравитация
ATTACK_COOLDOWN = 15
GAME_FOLDER = os.path.dirname(__file__) # Таков путь к каталогу с файлами
IMG_FOLDER = os.path.join(GAME_FOLDER, 'img')
ANIMATION_DECELERATION = 3
ANIMATION_STAY_RIGHT = pygame.image.load(os.path.join(IMG_FOLDER, 'idle.png'))
ANIMATION_STAY_LEFT = pygame.transform.flip(ANIMATION_STAY_RIGHT, True, False)
ANIMATION_JUMP_RIGHT = pygame.image.load(os.path.join(IMG_FOLDER, 'idle_jump.png'))
ANIMATION_JUMP_LEFT = pygame.transform.flip(ANIMATION_JUMP_RIGHT, True, False)
ANIMATION_FALL_RIGHT = pygame.image.load(os.path.join(IMG_FOLDER, 'idle_fall.png'))
ANIMATION_FALL_LEFT = pygame.transform.flip(ANIMATION_FALL_RIGHT, True, False)
ANIMATION_RUN_RIGHT = [pygame.image.load(os.path.join(IMG_FOLDER, 'idle_run.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'idle_run2.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'idle_run3.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'idle_run4.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'idle_run5.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'idle_run6.png'))]
ANIMATION_RUN_LEFT = [pygame.transform.flip(image, True, False) for image in ANIMATION_RUN_RIGHT]
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.speed = 0
self.speedFall = 0
self.__lookRight = True
self.fall = True
self.image = pygame.Surface((WIDTH, HEIGHT))
self.rect = pygame.Rect(0, 0, WIDTH, HEIGHT)
self.frame = 0 # необходимо для анимации
self.__attackNow = False
self.__attackCooldown = 0
self.__key = False
def update(self, left, right, jump, attack, platforms):
if jump: # Прыжок
if not self.fall:
self.speedFall = -JUMP_POWER
if self.__lookRight:
self.image = ANIMATION_JUMP_RIGHT
else:
self.image = ANIMATION_JUMP_LEFT
if left: # идем влево
self.__lookRight = False
self.speed = -RUN_SPEED
self.image = ANIMATION_RUN_LEFT[self.frame // ANIMATION_DECELERATION]
if right: # идем вправо
self.__lookRight = True
self.speed = RUN_SPEED
self.image = ANIMATION_RUN_RIGHT[self.frame // ANIMATION_DECELERATION]
if not (left or right): # стоим, когда не идем
self.speed = 0
if not jump:
if self.__lookRight:
self.image = ANIMATION_STAY_RIGHT
else:
self.image = ANIMATION_STAY_LEFT
else:
if self.frame + 1 != len(ANIMATION_RUN_RIGHT) * ANIMATION_DECELERATION: # Меняем кадр анимации если бежим
self.frame += 1
else:
self.frame = 0
if self.speedFall > GRAVITY: # Если падаем, то одна анимация
if self.__lookRight:
self.image = ANIMATION_FALL_RIGHT
else:
self.image = ANIMATION_FALL_LEFT
elif self.speedFall < 0: # Если летим вверх, то другая
if self.__lookRight:
self.image = ANIMATION_JUMP_RIGHT
else:
self.image = ANIMATION_JUMP_LEFT
if self.fall: # Если падаем, то увеличиваем скорость падения
self.speedFall += GRAVITY
self.fall = True # Падаем каждый раз. Если падать не нужно, коллайдеры это исправят
self.__attackNow = False # Обработка атаки
if attack:
if not self.__attackCooldown:
self.__attackCooldown = ATTACK_COOLDOWN
self.__attackNow = True
if self.__attackCooldown > 0:
self.__attackCooldown -= 1
self.rect.y += self.speedFall # Двигаемся по оси y
self.collide(0, self.speedFall, platforms) # Проверяем пересекаемся ли мы с чем-нибудь
self.rect.x += self.speed # Двигаемся по оси x
self.collide(self.speed, 0, platforms) # Проверяем пересекаемся ли мы с чем-нибудь
def collide(self, speed_x, speed_y, platforms):
for platform in platforms:
if pygame.sprite.collide_rect(self, platform) and platform != self: # Если есть пересечение
if speed_x > 0: # Если двигались вправо
self.rect.right = platform.rect.left # То возвращаем игрока обратно
if speed_x < 0: # Если двигались влево
self.rect.left = platform.rect.right # То возвращаем игрока обратно тоже
if speed_y > 0: # Если падали вниз
self.rect.bottom = platform.rect.top # То возвращаем игрока на платформу
self.fall = False # Отключаем падение
self.speedFall = 0 # Скорость падения обнуляется
if speed_y < 0: # Если двигались вверх
self.rect.top = platform.rect.bottom # То не поднимаем игрока дальше
self.speedFall = 0 # Скорость падения обнуляется
@property
def key(self):
return self.__key
@key.setter
def key(self, value):
self.__key = value
@property
def attack(self):
return self.__attackNow
@attack.setter
def attack(self, value):
self.__attackNow = value
@property
def lookRight(self):
return self.__lookRight
@lookRight.setter
def lookRight(self, value):
self.__lookRight = value
<file_sep>/effect.py
import pygame
DECAY_SPEED = 10
class Effect(pygame.sprite.Sprite):
def __init__(self, width, height):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((width, height))
self.image.fill(0)
self.image.set_alpha(0)
self.rect = pygame.Rect(0, 0, width, height)
self.isBlackout = False
self.isDecay = True
self.frame = 0
def blackout(self):
self.isBlackout = True
def update(self):
if self.isBlackout:
if self.isDecay:
self.frame += DECAY_SPEED
if self.frame > 255:
self.frame = 255
self.isDecay = False
self.image.set_alpha(self.frame)
return True
else:
self.frame -= DECAY_SPEED
if self.frame < 0:
self.frame = 0
self.isDecay = True
self.isBlackout = False
self.image.set_alpha(self.frame)
return False
<file_sep>/levelLoader.py
import pygame
import os
from entity import Entity
from key import Key
from box import Box
from door import Door
from crystal import Crystal
from level import Level
# Настройка местоположения ассетов
GAME_FOLDER = os.path.dirname(__file__)
IMG_FOLDER = os.path.join(GAME_FOLDER, 'img')
BG_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'bg2.jpg'))
WALL_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'wall.jpg'))
WALL_GRASS_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'wall_grass.jpg'))
DOOR_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'door.jpg'))
DOOR_LOCKED_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'door_locked.jpg'))
TABLE_IMG = [pygame.image.load(os.path.join(IMG_FOLDER, 'table_0.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'table_1.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'table_2.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'table_3.png'))]
CRYSTAL_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'crystal.png'))
CRYSTAL_DESTROY_IMG = [pygame.image.load(os.path.join(IMG_FOLDER, 'crystal_1.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'crystal_2.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'crystal_3.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'crystal_4.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'crystal_5.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'crystal_6.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'crystal_7.png'))]
BOX_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'box.png'))
STONE_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'stone.png'))
STONE_SMALL_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'stone_small.png'))
KEY_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'key.png'))
WIN_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'you_win.png'))
CAKE_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'cake.png'))
SHRUB_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'shrub.png'))
PLATFORM_IMG = [pygame.image.load(os.path.join(IMG_FOLDER, 'platform_single.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'platform_right.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'platform_left.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'platform_center.png'))]
WALL_WIDTH = 100
WALL_HEIGHT = 100
PLATFORM_WIDTH = WALL_WIDTH
PLATFORM_HEIGHT = 30
WALL = "="
PLATFORM = "-"
PLAYER = "P"
DOOR = "D"
DOOR_LOCKED = "L"
KEY = "K"
SHRUB = "*"
BOX = "B"
STONE = "#"
STONE_SMALL = "_"
CRYSTAL = "+"
WIN = "W"
CAKE = "C"
TABLE_0 = 0 # Табличка с изображением кнопок вправо и влево
TABLE_1 = 1 # Табличка с изображением кнопки E
TABLE_2 = 2 # Табличка с изображением кнопки вверх
TABLE_3 = 3 # Табличка с изображением кнопки пробел
class LevelLoader:
@staticmethod
def load_level(level_map):
level = Level()
level.bgImg = BG_IMG
# Подготавливаем локацию
x = y = 0 # Координаты
for row in range(len(level_map)): # Вся строка
for col in range(len(level_map[row])): # Каждый символ
# Если это стена
if level_map[row][col] == WALL:
# Создаем блок
wall_img_temp = WALL_IMG
if row: # Если над ним нет других блоков, накладываем на него текстуру с травой
if level_map[row - 1][col] != WALL:
wall_img_temp = WALL_GRASS_IMG
wall = Entity(x, y, WALL_WIDTH, WALL_HEIGHT, wall_img_temp)
level.entities.add(wall)
level.platforms.append(wall)
# Если это платформа
elif level_map[row][col] == PLATFORM:
variant = 0
if col: # Если есть платформа слева
if level_map[row][col - 1] == PLATFORM or level_map[row][col - 1] == WALL:
variant += 1
if col + 1 != len(level_map[row]): # Если есть платформа справа
if level_map[row][col + 1] == PLATFORM or level_map[row][col + 1] == WALL:
variant += 2
platform = Entity(x, y, PLATFORM_WIDTH, PLATFORM_HEIGHT, PLATFORM_IMG[variant])
level.entities.add(platform)
level.platforms.append(platform)
# Если это куст
elif level_map[row][col] == SHRUB:
shrub = Entity(x, y, 0, 0, SHRUB_IMG)
level.entities.add(shrub)
# Если это табличка №0
elif level_map[row][col] == str(TABLE_0):
table = Entity(x, y, 0, 0, TABLE_IMG[TABLE_0])
level.entities.add(table)
# Если это табличка №1
elif level_map[row][col] == str(TABLE_1):
table = Entity(x, y, 0, 0, TABLE_IMG[TABLE_1])
level.entities.add(table)
# Если это табличка №2
elif level_map[row][col] == str(TABLE_2):
table = Entity(x, y, 0, 0, TABLE_IMG[TABLE_2])
level.entities.add(table)
# Если это табличка №2
elif level_map[row][col] == str(TABLE_3):
table = Entity(x, y, 0, 0, TABLE_IMG[TABLE_3])
level.entities.add(table)
# Если это надпись "You win"
elif level_map[row][col] == WIN:
table = Entity(x, y, 0, 0, WIN_IMG)
level.entities.add(table)
# Если это торт (Cake is lie)
elif level_map[row][col] == CAKE:
table = Entity(x, y, 0, 0, CAKE_IMG)
level.entities.add(table)
# Если это ящик
elif level_map[row][col] == BOX:
box = Box(x, y, BOX_IMG)
level.dynamicEntity.append(box)
level.entities_upper.add(box)
level.platforms.append(box)
# Если это камень
elif level_map[row][col] == STONE:
stone = Entity(x, y, WALL_WIDTH, WALL_HEIGHT, STONE_IMG)
level.entities.add(stone)
level.platforms.append(stone)
# Если это маленький камень
elif level_map[row][col] == STONE_SMALL:
stone_small = Entity(x, y + 70, WALL_WIDTH, 30, STONE_SMALL_IMG)
level.entities.add(stone_small)
level.platforms.append(stone_small)
# Если это кристалл
elif level_map[row][col] == CRYSTAL:
crystal = Crystal(x, y, WALL_WIDTH, WALL_HEIGHT, CRYSTAL_IMG, CRYSTAL_DESTROY_IMG)
level.dynamicEntity.append(crystal)
level.entities.add(crystal)
level.platforms.append(crystal)
# Если это дверь
elif level_map[row][col] == DOOR:
door = Door(x, y, WALL_WIDTH, WALL_HEIGHT, DOOR_IMG)
level.dynamicEntity.append(door)
level.entities.add(door)
if col == len(level_map[row]) - 1:
wall = Entity(x + WALL_WIDTH, y, WALL_WIDTH, WALL_HEIGHT, WALL_IMG)
level.entities.add(wall)
level.platforms.append(wall)
elif col == 0:
wall = Entity(x - WALL_WIDTH, y, WALL_WIDTH, WALL_HEIGHT, WALL_IMG)
level.entities.add(wall)
level.platforms.append(wall)
# Если это запертая дверь
elif level_map[row][col] == DOOR_LOCKED:
door = Door(x, y, WALL_WIDTH, WALL_HEIGHT, DOOR_LOCKED_IMG)
door.isLocked = True
level.dynamicEntity.append(door)
level.entities.add(door)
if col == len(level_map[row]) - 1:
wall = Entity(x + WALL_WIDTH, y, WALL_WIDTH, WALL_HEIGHT, WALL_IMG)
level.entities.add(wall)
level.platforms.append(wall)
elif col == 0:
wall = Entity(x - WALL_WIDTH, y, WALL_WIDTH, WALL_HEIGHT, WALL_IMG)
level.entities.add(wall)
level.platforms.append(wall)
# Если это ключ
elif level_map[row][col] == KEY:
key = Key(x, y, KEY_IMG)
level.dynamicEntity.append(key)
level.entities.add(key)
# Если это персонаж
elif level_map[row][col] == PLAYER:
level.playerStartPosition = (x + (WALL_WIDTH / 2), y + WALL_HEIGHT)
x += WALL_WIDTH # блоки платформы ставятся на ширине блоков
y += WALL_HEIGHT # то же самое и с высотой
x = 0
return level
<file_sep>/button.py
import pygame
class Button(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, image_default, image_select, number):
pygame.sprite.Sprite.__init__(self)
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((width, height))
self.image = image_default
self.image_default = image_default
self.image_select = image_select
self.rect = pygame.Rect(x, y, width, height)
self.selected = False
self.number = number
def select(self):
self.selected = True
def remove_select(self):
self.selected = False
def update(self):
if self.selected:
self.image = self.image_select
else:
self.image = self.image_default
@property
def selected(self):
return self.__selected
@selected.setter
def selected(self, value):
self.__selected = value
<file_sep>/particle.py
import pygame
class Particle(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, images):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((width, height))
self.images = images
self.imagesReverse = [pygame.transform.flip(image, True, False) for image in images]
self.image = images[0]
self.frame = 0
self.rect = pygame.Rect(x, y, width, height)
def update(self):
if self.frame + 1 != len(self.images): # Меняем кадр анимации частицы
self.frame += 1
else:
self.kill()
self.image = self.images[self.frame]
def reverse(self):
self.images = self.imagesReverse
self.image = self.imagesReverse[0]
<file_sep>/menu.py
import pygame
import os
from entity import Entity
from button import Button
FORM_WIDTH = 500
FORM_HEIGHT = 538
BUTTON_WIDTH = 354
BUTTON_HEIGHT = 89
GAME_FOLDER = os.path.dirname(__file__)
IMG_FOLDER = os.path.join(GAME_FOLDER, 'img')
BG_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'bg.jpg'))
FORM_MENU_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'form_menu.png'))
BUTTON_CONTINUE_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'button_continue.png'))
BUTTON_CONTINUE_S_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'button_continue_s.png'))
BUTTON_NEW_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'button_new.png'))
BUTTON_NEW_S_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'button_new_s.png'))
BUTTON_RESTART_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'button_restart.png'))
BUTTON_RESTART_S_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'button_restart_s.png'))
BUTTON_EXIT_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'button_exit.png'))
BUTTON_EXIT_S_IMG = pygame.image.load(os.path.join(IMG_FOLDER, 'button_exit_s.png'))
class Menu:
@staticmethod
def pauseMenu(screen, fps, bg):
clock = pygame.time.Clock()
result = "Continue"
pygame.mouse.set_visible(True)
menu_elements = pygame.sprite.Group()
buttons = []
form_menu = Entity(350, 130, FORM_WIDTH, FORM_HEIGHT, FORM_MENU_IMG)
menu_elements.add(form_menu)
button = Button(423, 250, BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_CONTINUE_IMG, BUTTON_CONTINUE_S_IMG, 0)
menu_elements.add(button)
buttons.append(button)
button = Button(423, 370, BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_RESTART_IMG, BUTTON_RESTART_S_IMG, 1)
menu_elements.add(button)
buttons.append(button)
button = Button(423, 490, BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_EXIT_IMG, BUTTON_EXIT_S_IMG, 2)
menu_elements.add(button)
buttons.append(button)
menu_is_open = True
while menu_is_open:
# Держим цикл на правильной скорости
clock.tick(fps)
# События
for event in pygame.event.get():
# Проверяем закрыли ли мы окно
if event.type == pygame.QUIT:
menu_is_open = False
result = "Quit"
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
menu_is_open = False
result = "Continue"
elif event.type == pygame.MOUSEMOTION:
for button in buttons:
mouse_col = pygame.sprite.Sprite()
mouse_col.rect = pygame.Rect(event.pos[0], event.pos[1], 1, 1)
if pygame.sprite.collide_rect(mouse_col, button):
button.select()
else:
button.remove_select()
elif event.type == pygame.MOUSEBUTTONUP:
for button in buttons:
mouse_col = pygame.sprite.Sprite()
mouse_col.rect = pygame.Rect(event.pos[0], event.pos[1], 1, 1)
if pygame.sprite.collide_rect(mouse_col, button):
if button.number == 0:
menu_is_open = False
result = "Continue"
elif button.number == 1:
menu_is_open = False
result = "Restart"
elif button.number == 2:
menu_is_open = False
result = "Quit"
# Обновление
menu_elements.update()
# Рендеринг
screen.blit(bg, (0, 0))
menu_elements.draw(screen)
# Обновляем экран
pygame.display.update()
return result
@staticmethod
def mainMenu(screen, fps):
clock = pygame.time.Clock()
result = "Continue"
pygame.mouse.set_visible(True)
menu_elements = pygame.sprite.Group()
buttons = []
button = Button(423, 250, BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_CONTINUE_IMG, BUTTON_CONTINUE_S_IMG, 0)
menu_elements.add(button)
buttons.append(button)
button = Button(423, 370, BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_NEW_IMG, BUTTON_NEW_S_IMG, 1)
menu_elements.add(button)
buttons.append(button)
button = Button(423, 490, BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_EXIT_IMG, BUTTON_EXIT_S_IMG, 2)
menu_elements.add(button)
buttons.append(button)
menu_is_open = True
while menu_is_open:
# Держим цикл на правильной скорости
clock.tick(fps)
# События
for event in pygame.event.get():
# Проверяем закрыли ли мы окно
if event.type == pygame.QUIT:
menu_is_open = False
result = "Quit"
elif event.type == pygame.MOUSEMOTION:
for button in buttons:
mouse_col = pygame.sprite.Sprite()
mouse_col.rect = pygame.Rect(event.pos[0], event.pos[1], 1, 1)
if pygame.sprite.collide_rect(mouse_col, button):
button.select()
else:
button.remove_select()
elif event.type == pygame.MOUSEBUTTONUP:
for button in buttons:
mouse_col = pygame.sprite.Sprite()
mouse_col.rect = pygame.Rect(event.pos[0], event.pos[1], 1, 1)
if pygame.sprite.collide_rect(mouse_col, button):
if button.number == 0:
menu_is_open = False
result = "Continue"
elif button.number == 1:
menu_is_open = False
result = "New game"
elif button.number == 2:
menu_is_open = False
result = "Quit"
# Обновление
menu_elements.update()
# Рендеринг
screen.blit(BG_IMG, (0, 0))
menu_elements.draw(screen)
# Обновляем экран
pygame.display.update()
return result
<file_sep>/levelController.py
import pygame
import os
from key import Key
from door import Door
from box import Box
from crystal import Crystal
from levelLoader import DOOR_IMG
from particle import Particle
GAME_FOLDER = os.path.dirname(__file__)
IMG_FOLDER = os.path.join(GAME_FOLDER, 'img')
ATTACK_IMG = [pygame.image.load(os.path.join(IMG_FOLDER, 'attack_1.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'attack_2.png')),
pygame.image.load(os.path.join(IMG_FOLDER, 'attack_3.png'))]
CONSOLE_NAME = "Level controller"
class LevelController:
@staticmethod
def updateLevel(player, level, use):
attack_zone = None
if player.attack: # Если игрок толкает что-либо
attack_zone = Particle(0, 0, 50, 90, ATTACK_IMG)
level.particles.add(attack_zone)
if player.lookRight:
attack_zone.rect.topleft = player.rect.topright
elif not player.lookRight:
attack_zone.rect.topright = player.rect.topleft
attack_zone.reverse()
for entity in level.dynamicEntity:
if pygame.sprite.collide_rect(player, entity): # Если есть пересечение с игроком
if isinstance(entity, Key): # С ключом
player.key = True
entity.remove(level.entities)
level.dynamicEntity.remove(entity)
print(f"{CONSOLE_NAME}: Key has been picked")
if isinstance(entity, Door): # С дверью
if entity.isLocked:
if player.key:
player.key = False
entity.isLocked = False
entity.image = DOOR_IMG
print(f"{CONSOLE_NAME}: Door has been unlocked")
else:
if use:
level.complete()
if isinstance(entity, Box):
if player.attack and pygame.sprite.collide_rect(attack_zone, entity):
entity.push(player.lookRight)
entity.update(level.platforms)
if isinstance(entity, Crystal):
if player.attack and pygame.sprite.collide_rect(attack_zone, entity):
if not entity.isDestroy:
level.platforms.remove(entity)
entity.destroy()
entity.update()
| 73a7181813e640c49c3029b08b31b05b3024d1d4 | [
"Python"
] | 13 | Python | FhBeast/Course-workPL | 5b5b422ca51189382239ffd4394be55367025a0c | bc8f4dc28a1e488f8a765f5d22fc20f7ed6cb407 |
refs/heads/master | <repo_name>baghayi/ExpenseManager<file_sep>/src/org/adeveloper/expensemanager/lib/Balance.java
package org.adeveloper.expensemanager.lib;
import org.adeveloper.expensemanager.db.ExpensemanagerHelper;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.database.sqlite.SQLiteDatabase;
public class Balance {
SQLiteDatabase database = null;
private long lastInsertId;
public Balance(SQLiteDatabase database){
this.database = database;
}
public boolean add(double amount)
{
double totalBalance = getCurrentBalance() + amount;
return calculateBalance(amount, totalBalance);
}
public boolean subtract(double amount)
{
double totalBalance = getCurrentBalance() - amount;
return calculateBalance(amount, totalBalance);
}
private boolean calculateBalance(double amount, double totalBalance)
{
ContentValues values = new ContentValues();
values.put("NewBalance", amount);
values.put("TotalBalance", totalBalance);
values.put("UpdateTime", System.currentTimeMillis());
long result = database.insert(ExpensemanagerHelper.TABLE_NAME_BALANCE, null, values);
lastInsertId = result;
if(result == -1){
return false;
}else{
return true;
}
}
public long getLastInsertId()
{
return lastInsertId;
}
public double getCurrentBalance() {
String query = "SELECT TotalBalance FROM " + ExpensemanagerHelper.TABLE_NAME_BALANCE + " ORDER BY Id DESC LIMIT 1;";
Cursor result = database.rawQuery(query, null);
result.moveToFirst();
int columnIndex = result.getColumnIndex("TotalBalance");
try{
return result.getInt(columnIndex);
}catch(CursorIndexOutOfBoundsException e){
return 0;
}
}
}
<file_sep>/src/org/adeveloper/expensemanager/ExpenseDetailActivity.java
package org.adeveloper.expensemanager;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Date;
import org.adeveloper.expensemanager.model.Expense;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ExpenseDetailActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expense_detail);
Bundle bundle = getIntent().getExtras();
Expense expense = bundle.getParcelable(".model.Expense");
TextView captionField = (TextView) findViewById(R.id.expense_detail_caption);
captionField.setText(expense.getCaption());
TextView priceField = (TextView) findViewById(R.id.expense_detail_price);
NumberFormat numberformatter = NumberFormat.getInstance();
priceField.setText(numberformatter.format(expense.getPrice()));
DateFormat dateformatter = DateFormat.getDateInstance(DateFormat.FULL);
String formattedDate = dateformatter.format(new Date(expense.getUpdateTime()));
TextView updatetimeField = (TextView) findViewById(R.id.expense_detail_updatetime);
updatetimeField.setText(formattedDate);
}
}
<file_sep>/src/org/adeveloper/expensemanager/ExpensesListActivity.java
package org.adeveloper.expensemanager;
import java.util.ArrayList;
import java.util.List;
import org.adeveloper.expensemanager.db.Database;
import org.adeveloper.expensemanager.db.DatabaseConnectionFactory;
import org.adeveloper.expensemanager.db.ExpensemanagerDatasource;
import org.adeveloper.expensemanager.model.Expense;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ExpensesListActivity extends ListActivity
{
private List<ExpenseItem> dataList;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expenses_list);
dataList = getExpensesList();
ArrayAdapter<ExpenseItem> adapter = new ArrayAdapter<ExpenseItem>(this,
R.layout.expense_list_item,
dataList);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Intent intent = new Intent(this, ExpenseDetailActivity.class);
intent.putExtra(".model.Expense", dataList.get(position).getExpense());
startActivity(intent);
}
private List<ExpensesListActivity.ExpenseItem> getExpensesList()
{
ExpensemanagerDatasource datasource = getDatabaseConnection();
org.adeveloper.expensemanager.lib.Expense expenseObject =
new org.adeveloper.expensemanager.lib.Expense(datasource.open());
List<ExpensesListActivity.ExpenseItem> list = new ArrayList<ExpensesListActivity.ExpenseItem>();
for (Expense expense : expenseObject.getAllExpenses())
{
ExpenseItem expenseItem = new ExpenseItem(expense);
list.add(expenseItem);
}
datasource.close();
return list;
}
private ExpensemanagerDatasource getDatabaseConnection()
{
return new DatabaseConnectionFactory(this).create(Database.ExpenseManager);
}
private class ExpenseItem
{
private Expense expense;
public ExpenseItem(Expense expense)
{
this.expense = expense;
}
private Expense getExpense()
{
return this.expense;
}
@Override
public String toString()
{
return " - " + this.getExpense().getCaption();
}
}
}
<file_sep>/Readme.txt
A Main goal of this project is to help a person control his or her expenses.
This project is under constuction and mainly is created for personal usage but is under MIT license so everybody interesed in the project may use it for free.
There are some other features which I am thinking of adding them to the project such as:
- Ability to backup / restore inserted data.
- Ability to backup/restore data to/from dropbox.
- Project app by a password so it will only be accessible by who actually knows the password.
- Listing of all expenses added to app. (Done)
Other than mentioned features there of codes need refactoring which by the time of developing will be taken care of as well.
And last but not lease, this is my first JAVA and Andorid project so do not expect a perfect application, its definetly going to have lots of problem :D .
Also that I am not a good designer, which may make the application ugly too :D .
<file_sep>/src/org/adeveloper/expensemanager/util/Notification.java
package org.adeveloper.expensemanager.util;
import org.adeveloper.expensemanager.R;
import android.content.Context;
import android.view.Gravity;
import android.widget.Toast;
public class Notification
{
/**
* Bases on the result parameter, it will show proper text.
*
* @param context
* @param result
*/
public static void successFailureToastMessage(Context context, boolean result)
{
Toast message = null;
if(result){
message = Toast.makeText(context, R.string.lang_mission_succeed, Toast.LENGTH_SHORT);
}else{
message = Toast.makeText(context, R.string.lang_mission_failed, Toast.LENGTH_SHORT);
}
message.setGravity(Gravity.CENTER, 0, 0);
message.show();
}
}
<file_sep>/src/org/adeveloper/expensemanager/db/ExpensemanagerDatasource.java
package org.adeveloper.expensemanager.db;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.adeveloper.expensemanager.util.FileUtils;
import android.annotation.SuppressLint;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
public class ExpensemanagerDatasource implements Closeable
{
private SQLiteOpenHelper helper;
private SQLiteDatabase database;
private static final String DATABASE_FILE_PATH =
"//data//org.adeveloper.expensemanager//databases//" + ExpensemanagerHelper.DATABASE_NAME;
private static final String BACKUP_PATH =
Environment.getExternalStorageDirectory().toString() + "/Expensemanager";
/**
* Only used when taking backup.
*
* Which in this case database file MUST not be touched.
*/
public ExpensemanagerDatasource(){}
public ExpensemanagerDatasource(SQLiteOpenHelper helper)
{
this.helper = helper;
}
public SQLiteDatabase open()
{
database = helper.getWritableDatabase();
return database;
}
@Override
public void close()
{
database.close();
helper.close();
}
@SuppressLint("SimpleDateFormat")
public boolean backup()
{
File sd = new File(BACKUP_PATH);
if(!sd.exists() && !sd.mkdirs()){
return false;
}
if (sd.canWrite()) {
Locale locale = new Locale("en_US");
Locale.setDefault(locale);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
String backupFilename = formatter.format(new Date());
File backupFile = new File(sd, backupFilename);
File originalDatabase = new File(Environment.getDataDirectory(),
DATABASE_FILE_PATH);
if (originalDatabase.exists()) {
try
{
FileUtils.copyFile(new FileInputStream(originalDatabase),
new FileOutputStream(backupFile));
return true;
} catch (FileNotFoundException e){
return false;
} catch (IOException e){
return false;
}
}
}
return false;
}
public boolean restore(String backupfileName) {
String dbPath = BACKUP_PATH + "//" + backupfileName;
File newDb = new File(dbPath);
File oldDb = new File(Environment.getDataDirectory().toString() + DATABASE_FILE_PATH);
if (newDb.exists()) {
try
{
FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
} catch (FileNotFoundException e)
{
return false;
} catch (IOException e)
{
return false;
}
// Access the copied database so SQLiteHelper will cache it and mark
// it as created.
open();
close();
return true;
}
return false;
}
}
<file_sep>/src/org/adeveloper/expensemanager/EventListener/CalculateBalance.java
package org.adeveloper.expensemanager.EventListener;
import org.adeveloper.expensemanager.db.Database;
import org.adeveloper.expensemanager.db.DatabaseConnectionFactory;
import org.adeveloper.expensemanager.db.ExpensemanagerDatasource;
import org.adeveloper.expensemanager.lib.Balance;
import org.adeveloper.expensemanager.util.Notification;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
public final class CalculateBalance implements OnClickListener
{
public final static String BALANCE_DECREASE = "add to balance :D";
public final static String BALANCE_INCREASE = "subtract from balance :|";
private Context context;
private String balanceType;
private EditText balanceField;
private TextView realtimeBalance;
public CalculateBalance(Context context, String balanceType, EditText balanceField, TextView realtimeBalance)
{
this.context = context;
this.balanceType = balanceType;
this.balanceField = balanceField;
this.realtimeBalance = realtimeBalance;
}
private double getPrice(){
String price = balanceField.getText().toString();
if(price.length() <= 0){
return 0;
}
return Double.parseDouble(price);
}
@Override
public void onClick(View v)
{
if(getPrice() == 0){
return;
}
// TODO Ask user for confirmation.
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setMessage("آیا از انجام عمل مورد نظر اطمینان داری؟");
alertBuilder.setCancelable(false);
alertBuilder.setNegativeButton("نه نمی دونم!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertBuilder.setPositiveButton("آره داداش", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
ExpensemanagerDatasource datasource = CalculateBalance.this.getDatabaseConnection();
Balance balance = new Balance(datasource.open());
boolean result;
if(balanceType == BALANCE_INCREASE){
result = balance.add(getPrice());
}else if (balanceType == BALANCE_DECREASE){
result = balance.subtract(getPrice());
}else {
result = false;
}
datasource.close();
Notification.successFailureToastMessage(context, result);
if(result){
CalculateBalance.this.resetBalanceField();
}
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
}
// TODO this method feels like a code smell!
private ExpensemanagerDatasource getDatabaseConnection()
{
return new DatabaseConnectionFactory(context)
.create(Database.ExpenseManager);
}
private void resetBalanceField()
{
balanceField.setText("0");
if(realtimeBalance != null){
realtimeBalance.setText("0");
}
}
}
<file_sep>/src/org/adeveloper/expensemanager/db/Database.java
package org.adeveloper.expensemanager.db;
public enum Database
{
ExpenseManager
}
<file_sep>/src/org/adeveloper/expensemanager/lib/Expense.java
package org.adeveloper.expensemanager.lib;
import java.util.ArrayList;
import java.util.List;
import org.adeveloper.expensemanager.db.ExpensemanagerHelper;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class Expense
{
private SQLiteDatabase database;
public Expense(SQLiteDatabase database)
{
this.database = database;
}
/**
* Adds a new row to expense table as expense with caption and price.
*
* @param caption
* @param price
* @param balanceId
* @return
*/
public boolean add(String caption, double price, Balance balanceObject)
{
if(!balanceObject.subtract(price)){
return false;
}
ContentValues values = new ContentValues();
values.put("Caption", caption);
values.put("BalanceId", balanceObject.getLastInsertId());
values.put("UpdateTime", System.currentTimeMillis());
long insertId = database.insert(ExpensemanagerHelper.TABLE_NAME_EXPENSE, null, values);
if(insertId == -1){
return false;
}else {
return true;
}
}
public List<org.adeveloper.expensemanager.model.Expense> getAllExpenses()
{
String query = "SELECT "
+ ExpensemanagerHelper.TABLE_NAME_EXPENSE + ".Id, "
+ ExpensemanagerHelper.TABLE_NAME_EXPENSE + ".Caption, "
+ ExpensemanagerHelper.TABLE_NAME_BALANCE + ".NewBalance, "
+ ExpensemanagerHelper.TABLE_NAME_EXPENSE + ".UpdateTime "
+ "FROM " + ExpensemanagerHelper.TABLE_NAME_EXPENSE +
" INNER JOIN " + ExpensemanagerHelper.TABLE_NAME_BALANCE +
" ON " + ExpensemanagerHelper.TABLE_NAME_EXPENSE + ".BalanceId=" +
ExpensemanagerHelper.TABLE_NAME_BALANCE + ".Id ORDER BY " +
ExpensemanagerHelper.TABLE_NAME_EXPENSE + ".UpdateTime DESC";
Cursor resultset = database.rawQuery(query, null);
List<org.adeveloper.expensemanager.model.Expense> list =
new ArrayList<org.adeveloper.expensemanager.model.Expense>();
while (resultset.moveToNext())
{
org.adeveloper.expensemanager.model.Expense expense =
new org.adeveloper.expensemanager.model.Expense();
expense.setId(
resultset.getLong(resultset.getColumnIndex("Id")));
expense.setCaption(
resultset.getString(resultset.getColumnIndex("Caption")));
expense.setPrice(
resultset.getDouble(resultset.getColumnIndex("NewBalance")));
expense.setUpdateTime(
resultset.getLong(resultset.getColumnIndex("UpdateTime")));
list.add(expense);
}
return list;
}
}
| ed902b39bd2091fc0db65dc794e1b895c4e946da | [
"Java",
"Text"
] | 9 | Java | baghayi/ExpenseManager | b1acc283126fcb6234f667ff0370eea9a8917c8b | 6a0af2074b5e8b08d07e12983994b2f2d967571f |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TestingAzure.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
List<Tuple<string, string>> records = new List<Tuple<string, string>>();
string connString = ConfigurationManager.ConnectionStrings["TestAzure"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connString))
{
if (connection.State != System.Data.ConnectionState.Open)
{
connection.Open();
}
string query = "select Name, Url from dbo.Blogs";;
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
records.Add(new Tuple<string, string>(reader.GetString(0), reader.GetString(1)));
}
}
}
}
ViewBag.Records = records;
return View();
}
}
} | ecbdef30a2acf23c98d2e2c80d920831110b9b3e | [
"C#"
] | 1 | C# | nhodder/testing-azure | f47a48fec7aaec66f10c45a245277a23bb31e2ce | 36041277964f390391cb0deacb3368d30aa85817 |
refs/heads/master | <repo_name>h-jp/Lua_170703<file_sep>/README.md
# Lua
The repository saves many models and tasks for natural language processing and machine learning using [Torch](http://torch.ch/) deep learning framework.<file_sep>/src/hjp.edu.torch.ml.mnn/data.lua
require('paths')
local stringx = require('pl.stringx')
local file = require('pl.file')
function g_read_words(fname, vocab, ivocab)
local data = file.read(fname)
local lines = stringx.splitlines(data)
local c = 0
for n = 1, #lines do
local w = stringx.split(lines[n])
c = c + #w + 1
end
local words = torch.Tensor(c, 1)
c = 0
for n = 1, #lines do
local w = stringx.split(lines[n])
for i = 1, #w do
c = c + 1
if not vocab[w[i]] then
ivocab[#vocab+1] = w[i]
vocab[w[i]] = #vocab + 1
end
words[c][1] = vocab[w[i]]
end
c = c + 1
words[c][1] = vocab['<eos>']
end
print('Read ' .. c .. ' words from ' .. fname)
return words
end
<file_sep>/src/hjp.edu.torch.ml.mnn/README.md
## End-to-End Memory Networks in TensorFlow for Language Model
End-to-End Memory Networks implementation in [Torch](http://torch.ch/) for language model on the Penn Treebank (ptb) data.
### Dependencies
You will need the following packages:
* nn
* nngraph
* paths
* xlua
### Quickstart
The ptb data is from:
* [<NAME>'s lstm repo](https://github.com/wojzaremba/lstm)
and put the 'data' folder into current directionary.
Use 'main.lua' for running a model with 2 hops and memory size of 20, run the following command:
$ th main.lua --nhop 2 --memsize 20
To see all training options, run the following command:
$ th main.lua --help
### Reference
The memory model is from:
* [Memory Networks](https://arxiv.org/pdf/1410.3916.pdf). Weston et al., ICLR 2016.
* [End-to-End Memory Networks](https://papers.nips.cc/paper/5846-end-to-end-memory-networks.pdf). Sukhbaatar et al., NIPS 2015.
### Acknowledgments
Our implementation utilizes code from the following:
* [facebook's MemNN repo](https://github.com/facebook/MemNN)
### License
[Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0)
| 02851f33bc443a275d3399ed74ab0380123db01c | [
"Markdown",
"Lua"
] | 3 | Markdown | h-jp/Lua_170703 | a8ce850a03b698996db15a552f0d4b2b1ec33055 | 12dd7a2479823fc5f8cc6128319edbc3f11d3c39 |
refs/heads/master | <file_sep>package com.karpuk.clashtrack.ui.core.page;
import com.karpuk.clashtrack.ui.core.model.enums.LightBarracksTroopsEnum;
import com.karpuk.clashtrack.ui.core.model.enums.TownHallLevelsEnum;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.Select;
import java.util.List;
import static com.karpuk.clashtrack.core.listener.TestListener.logError;
import static com.karpuk.clashtrack.core.listener.TestListener.logInfo;
import static com.karpuk.clashtrack.ui.core.util.Waiters.waitAndClickJS;
import static com.karpuk.clashtrack.ui.core.util.Waiters.waitForVisibility;
public class TroopCostCalculatorPage extends BasePage {
@FindBy(xpath = "//span[@class='button js-settings-level']")
private List<WebElement> levelButtons;
@FindBy(xpath = "//select[@id='army-camps']")
private WebElement armyCampDropDown;
@FindBy(xpath = "//td[@class='js-col-light-quantity']/input[contains(@class,'js-comp-quantity')]")
private List<WebElement> quantityInputs;
@FindBy(xpath = "//span[@id='light-quantity']")
private WebElement availableQuantityLightBarracks;
@FindBy(xpath = "//span[contains(@class,' message_negative') and @id='light-exceeded']")
private WebElement errorLightBarracks;
@FindBy(xpath = "//span[@data-reset='light' and @data-scope='quantity']/i")
private WebElement resetQuantityLightBarracksButton;
@FindBy(xpath = "//span[@class='icon-favorite']")
private WebElement saveArmyCompositionButton;
@FindBy(xpath = "//td[@class='result js-col-light-quantity']/span[@class='text-middle']")
private WebElement capacityResultInLightBarracks;
@FindBy(xpath = "//div[@class='favorite__capacity']")
private WebElement savedCompositionCapacity;
@FindBy(xpath = "//span[@class='button js-favorite-load']")
private WebElement loadArmyCompositionButton;
@FindBy(xpath = "//span[not(@style='display: none')]/span[@class='help-link js-help-link']")
private List<WebElement> helpToolTips;
@FindBy(xpath = "//div[@class='help-tooltip help-tooltip_visible']")
private List<WebElement> helpToolTipsDisplayed;
@FindBy(xpath = "//h2[@id='favorites-anchor']/span[@class='help-link js-help-link']")
private WebElement saveArmyHelpToolTip;
@FindBy(xpath = "//div[@class='js-light-object']/h2")
private WebElement lightBarracksTitle;
public void selectTownHallLevel(TownHallLevelsEnum levelEnum) {
int level = levelEnum.getValue();
if (level > 0 && level < 12) {
logInfo("Select town hall level: " + level);
levelButtons.stream()
.filter(levelActual -> Integer.parseInt(levelActual.getText()) == level)
.findFirst()
.get()
.click();
} else {
logError("Unsupported town hall level");
}
}
public void selectArmyCapacity(Integer capacity) {
logInfo("Select army capacity: " + capacity);
waitForVisibility(armyCampDropDown);
new Select(armyCampDropDown).selectByValue(capacity.toString());
}
public void selectTroopsCapacityByTypes(LightBarracksTroopsEnum type, Integer quantity) {
logInfo("Select " + type.getTroopType() + " with quantity: " + quantity + ". Capacity executing: " + type.getArmySpace() * quantity);
for (WebElement input : quantityInputs) {
if (input.getAttribute("id").equalsIgnoreCase(type.getTroopType())) {
input.sendKeys(quantity.toString());
}
}
}
public int getAvailableQuantityOfLightBarracks() {
return Integer.parseInt(availableQuantityLightBarracks.getText().replaceAll("−", "-"));
}
public String getErrorMessageLightBarracks() {
return errorLightBarracks.getText();
}
public void resetQuantityInLightBarracks() {
logInfo("Reset quantity in light barracks");
waitAndClickJS(resetQuantityLightBarracksButton);
}
public void saveArmyComposition() {
logInfo("Save army composition");
saveArmyCompositionButton.click();
waitForVisibility(savedCompositionCapacity);
}
public String getCapacityResultInLightBarracks() {
return capacityResultInLightBarracks.getText();
}
public String getSavedCompositionCapacity() {
return savedCompositionCapacity.getText();
}
public void loadArmyComposition() {
logInfo("Load army composition");
loadArmyCompositionButton.click();
}
public void openFirstHelpToolTip() {
logInfo("Open first help tooltip");
if (!helpToolTips.isEmpty()) {
helpToolTips.get(0).click();
}
}
public boolean isHelpToolTipPresented() {
return !helpToolTipsDisplayed.isEmpty();
}
public String getFirstHelpToolTipPresented() {
waitForVisibility(helpToolTipsDisplayed.get(0));
return helpToolTipsDisplayed.get(0).getText();
}
public void openSaveArmyHelpToolTip() {
logInfo("Open help tooltip in Save Army block");
saveArmyHelpToolTip.click();
}
public void closeHelpToolTip() {
lightBarracksTitle.click();
}
}
<file_sep>#clashtrack.ui.user.login= This value should be provided by executor
#clashtrack.ui.user.password= This value should be provided by executor
#clashtrack.ui.user.name= This value should be provided by executor
<file_sep>package com.karpuk.clashtrack.ui.test;
import com.karpuk.clashtrack.ui.test.base.BaseTestData;
import org.testng.annotations.Test;
import static com.karpuk.clashtrack.core.listener.TestListener.logInfo;
public class SignInTest extends BaseTestData {
@Test()
void testSuccessSignInWithGoogleAccount() {
logInfo("Verify success sign in with google account.");
homePage.navigate(baseUrl);
signInService.signInWithGoogleAccount(user);
softAssert.assertThat(dashboardPage.getCurrentUseName())
.as("Verify Account Name")
.isEqualToIgnoringCase(user.getName());
softAssert.assertAll();
}
}
<file_sep>package com.karpuk.clashtrack.ui.test.base;
import com.karpuk.clashtrack.ui.core.driver.WebDriverManager;
import com.karpuk.clashtrack.ui.core.page.*;
import com.karpuk.clashtrack.ui.test.context.AccountsContext;
import com.karpuk.clashtrack.ui.test.context.ConfigurationContext;
import com.karpuk.clashtrack.ui.test.service.SignInService;
import com.karpuk.clashtrack.ui.test.service.TroopCalculationService;
import com.karpuk.clashtrack.ui.test.service.WarWeightCalculationService;
import org.assertj.core.api.SoftAssertions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.AfterMethod;
@ContextConfiguration(classes = {ConfigurationContext.class, AccountsContext.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class SpringAwareTestBase extends AbstractTestNGSpringContextTests {
@Autowired
protected HomePage homePage;
@Autowired
protected DashboardPage dashboardPage;
@Autowired
protected BasesCollectionPage basesCollectionPage;
@Autowired
protected TroopCostCalculatorPage troopCostCalculatorPage;
@Autowired
protected BaseLayoutPage baseLayoutPage;
@Autowired
protected WarWeightCalculatorPage warWeightCalculatorPage;
@Autowired
protected SignInService signInService;
@Autowired
protected TroopCalculationService troopCalculationService;
@Autowired
protected WarWeightCalculationService warWeightCalculationService;
@Value("${application.url}${application.url.lang}")
protected String baseUrl;
@Autowired
protected SoftAssertions softAssert;
@AfterMethod
public void cleanUp() {
WebDriverManager.closeDriver();
}
}
<file_sep>package com.karpuk.clashtrack.ui.core.page;
import com.karpuk.clashtrack.ui.core.model.enums.TownHallLevelsEnum;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import java.util.List;
import static com.karpuk.clashtrack.core.listener.TestListener.logError;
import static com.karpuk.clashtrack.core.listener.TestListener.logInfo;
public class WarWeightCalculatorPage extends BasePage {
@FindBy(xpath = "//div[contains(@class,'slider-tick custom')]")
private List<WebElement> levelSliderButtons;
@FindBy(xpath = "//div[@class='col-xs-6 col-md-6 col-lg-3' and not(@style='display: none;' or @style='display:none')]//input")
private List<WebElement> storageInputs;
@FindBy(xpath = "//a[@id='calc_button']")
private WebElement calculateButton;
@FindBy(xpath = "//span[@id='weight_result']")
private WebElement calculatedWeightResult;
public void selectTownHallLevel(TownHallLevelsEnum levelEnum) {
int level = levelEnum.getValue();
if (level > 3 && level < 13) {
logInfo("Select town hall level: " + level);
levelSliderButtons.get(level - 3).click();
} else {
logError("Unsupported town hall level");
}
}
public void selectGoldInStorage(int storageNumber, int gold) {
if (storageInputs.size() >= storageNumber) {
logInfo("Select " + gold + " gold amount in the storage number " + storageNumber);
storageInputs.get(storageNumber - 1).clear();
storageInputs.get(storageNumber - 1).sendKeys(String.valueOf(gold));
} else {
throw new UnsupportedOperationException("Invalid storage number for selected level");
}
}
public void calculateWarWeight() {
logInfo("Calculate war weight");
calculateButton.click();
}
public int getCalculatedWarWeight() {
return Integer.parseInt(calculatedWeightResult.getText());
}
public int getNumberOfStorage() {
return storageInputs.size();
}
}
<file_sep>package com.karpuk.clashtrack.ui.test.context;
import com.karpuk.clashtrack.ui.core.page.*;
import com.karpuk.clashtrack.ui.test.service.SignInService;
import com.karpuk.clashtrack.ui.test.service.TroopCalculationService;
import com.karpuk.clashtrack.ui.test.service.WarWeightCalculationService;
import org.assertj.core.api.SoftAssertions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySource("classpath:${env}.properties")
public class ConfigurationContext {
@Bean
@Scope("prototype")
public static PropertySourcesPlaceholderConfigurer propertyConfig() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
@Scope("prototype")
public SoftAssertions getSoftAssertions() {
return new SoftAssertions();
}
@Bean
@Scope("prototype")
public HomePage getHomePage() {
return new HomePage();
}
@Bean
@Scope("prototype")
public AccountsGooglePage getAccountsGooglePage() {
return new AccountsGooglePage();
}
@Bean
@Scope("prototype")
public DashboardPage getDashboardPage() {
return new DashboardPage();
}
@Bean
@Scope("prototype")
public BasesCollectionPage getBasesCollectionPage() {
return new BasesCollectionPage();
}
@Bean
@Scope("prototype")
public TroopCostCalculatorPage getTroopCostCalculatorPage() {
return new TroopCostCalculatorPage();
}
@Bean
@Scope("prototype")
public BaseLayoutPage getBaseLayoutPage() {
return new BaseLayoutPage();
}
@Bean
@Scope("prototype")
public WarWeightCalculatorPage getWarWeightCalculatorPage() {
return new WarWeightCalculatorPage();
}
@Bean
@Scope("prototype")
public SignInService getSignInService() {
return new SignInService();
}
@Bean
@Scope("prototype")
public TroopCalculationService getTroopCalculationService() {
return new TroopCalculationService();
}
@Bean
@Scope("prototype")
public WarWeightCalculationService getWarWeightCalculationService() {
return new WarWeightCalculationService();
}
}
<file_sep>package com.karpuk.clashtrack.api.test.base;
import org.testng.annotations.DataProvider;
public class ClansSearchTestData extends SpringAwareTestBaseApi {
@DataProvider(name = "dp-min-clan-level")
public Object[][] dataProviderMinClassLevel() {
return new Object[][]{{"3"}, {"10"}, {"12"}
};
}
@DataProvider(name = "dp-incorrect-min-clan-level")
public Object[][] dataProviderIncorrectMinClassLevel() {
return new Object[][]{{"0"}, {"1"}, {"-10"}
};
}
@DataProvider(name = "dp-limits")
public Object[][] dataProviderLimitNumberOfClans() {
return new Object[][]{{"100"}, {"1"}, {"0"}
};
}
@DataProvider(name = "dp-valid-clan-tags")
public Object[][] dataProviderValidClanTags() {
return new Object[][]{{"#PPGQJVC8"}, {"#RY089V89"}, {"#YLYQJ2QG"}
};
}
@DataProvider(name = "dp-invalid-clan-tags")
public Object[][] dataProviderInvalidClanTags() {
return new Object[][]{{"invalid_class_tag"}, {"#0000000"}, {"=)"}
};
}
}
<file_sep>package com.karpuk.clashtrack.api.test.base;
import com.karpuk.clashtrack.api.test.context.ConfigurationContext;
import com.karpuk.clashtrack.api.test.service.ClanSearchService;
import org.assertj.core.api.SoftAssertions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
@ContextConfiguration(classes = {ConfigurationContext.class})
public class SpringAwareTestBaseApi extends AbstractTestNGSpringContextTests {
@Autowired
protected SoftAssertions softAssert;
@Autowired
protected ClanSearchService clanSearchService;
}
<file_sep>package com.karpuk.clashtrack.ui.core.page;
import com.karpuk.clashtrack.ui.core.driver.WebDriverManager;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import static com.karpuk.clashtrack.core.listener.TestListener.logInfo;
public class HomePage extends BasePage {
@FindBy(xpath = "//div[@class='start']//a[contains(@class,'btn-google')]")
private WebElement signInWithGoogleButton;
public void navigate(String url) {
WebDriverManager.getInstance().get(url);
logInfo("Open page " + url);
}
public void clickSignInWithGoogle() {
signInWithGoogleButton.click();
}
}
<file_sep>package com.karpuk.clashtrack.ui.test;
import com.karpuk.clashtrack.ui.core.model.enums.LightBarracksTroopsEnum;
import com.karpuk.clashtrack.ui.core.model.enums.TownHallLevelsEnum;
import com.karpuk.clashtrack.ui.test.base.BaseTestData;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static com.karpuk.clashtrack.core.listener.TestListener.logInfo;
public class TroopCostCalculationTest extends BaseTestData {
@DataProvider(name = "data-provider-light-barracks")
public Object[][] dataProviderLightBarracks() {
return new Object[][]{{100, TownHallLevelsEnum.TH3, LightBarracksTroopsEnum.BARBARIAN, 100, LightBarracksTroopsEnum.BARBARIAN.getArmySpace() * 100},
{150, TownHallLevelsEnum.TH7, LightBarracksTroopsEnum.BALLOON, 5, LightBarracksTroopsEnum.BALLOON.getArmySpace() * 5}
};
}
@DataProvider(name = "data-provider-exceeded-capacity-light-barracks")
public Object[][] dataProviderExceededCapacity() {
return new Object[][]{{200, TownHallLevelsEnum.TH10, LightBarracksTroopsEnum.P_E_K_K_A, 30, LightBarracksTroopsEnum.P_E_K_K_A.getArmySpace() * 30},
// {200, TownHallLevelsEnum.TH9, LightBarracksTroopsEnum.BABY_DRAGON, 25, LightBarracksTroopsEnum.BABY_DRAGON.getArmySpace() * 25} //known issue
};
}
@Test(dataProvider = "data-provider-light-barracks")
void testCalculateQuantityLightBarracks(int armyCapacity, TownHallLevelsEnum townHallLevel, LightBarracksTroopsEnum troopType, int quantity, int capacityExecuting) {
logInfo("Verify troops calculation in light barracks.");
homePage.navigate(baseUrl);
signInService.signInWithGoogleAccount(user);
dashboardPage.openTroopCalculator();
troopCalculationService.selectTroopsInLightBarracksCalculator(armyCapacity, townHallLevel, troopType, quantity);
softAssert.assertThat(troopCostCalculatorPage.getAvailableQuantityOfLightBarracks())
.as("Verify available quantity").isEqualTo(armyCapacity - capacityExecuting);
softAssert.assertAll();
}
@Test(dataProvider = "data-provider-exceeded-capacity-light-barracks")
void testExceededCapacityLightBarracks(int armyCapacity, TownHallLevelsEnum townHallLevel, LightBarracksTroopsEnum troopType, int quantity, int capacityExecuting) {
logInfo("Verify error message with exceeded capacity in Light Barracks.");
homePage.navigate(baseUrl);
signInService.signInWithGoogleAccount(user);
dashboardPage.openTroopCalculator();
troopCalculationService.selectTroopsInLightBarracksCalculator(armyCapacity, townHallLevel, troopType, quantity);
softAssert.assertThat(troopCostCalculatorPage.getErrorMessageLightBarracks())
.as("Verify error message in Light Barracks calculator").contains("Exceeded training capacity of the Barracks");
softAssert.assertAll();
}
@Test(dataProvider = "data-provider-light-barracks")
void testResetQuantityLightBarracks(int armyCapacity, TownHallLevelsEnum townHallLevel, LightBarracksTroopsEnum troopType, int quantity, int capacityExecuting) {
logInfo("Verify result of quantity reset in Light Barracks.");
homePage.navigate(baseUrl);
signInService.signInWithGoogleAccount(user);
dashboardPage.openTroopCalculator();
troopCalculationService.selectTroopsInLightBarracksCalculator(armyCapacity, townHallLevel, troopType, quantity);
troopCostCalculatorPage.resetQuantityInLightBarracks();
softAssert.assertThat(troopCostCalculatorPage.getAvailableQuantityOfLightBarracks())
.as("Verify quantity reset in Light Barracks").isEqualTo(armyCapacity);
softAssert.assertAll();
}
@Test(dataProvider = "data-provider-light-barracks")
void testSaveArmyCompositionLightBarracks(int armyCapacity, TownHallLevelsEnum townHallLevel, LightBarracksTroopsEnum troopType, int quantity, int capacityExecuting) {
logInfo("Verify saving of the army composition.");
homePage.navigate(baseUrl);
signInService.signInWithGoogleAccount(user);
dashboardPage.openTroopCalculator();
troopCalculationService.selectTroopsInLightBarracksCalculator(armyCapacity, townHallLevel, troopType, quantity);
troopCostCalculatorPage.saveArmyComposition();
softAssert.assertThat(troopCostCalculatorPage.getSavedCompositionCapacity())
.as("Verify saved composition capacity").contains(troopCostCalculatorPage.getCapacityResultInLightBarracks());
softAssert.assertAll();
}
@Test(dataProvider = "data-provider-light-barracks")
void testLoadArmyCompositionLightBarracks(int armyCapacity, TownHallLevelsEnum townHallLevel, LightBarracksTroopsEnum troopType, int quantity, int capacityExecuting) {
logInfo("Verify loading of the saved army composition.");
homePage.navigate(baseUrl);
signInService.signInWithGoogleAccount(user);
dashboardPage.openTroopCalculator();
troopCalculationService.selectTroopsInLightBarracksCalculator(armyCapacity, townHallLevel, troopType, quantity);
troopCostCalculatorPage.saveArmyComposition();
troopCostCalculatorPage.resetQuantityInLightBarracks();
troopCostCalculatorPage.loadArmyComposition();
softAssert.assertThat(troopCostCalculatorPage.getCapacityResultInLightBarracks())
.as("Verify capacity in loaded army").contains(troopCostCalculatorPage.getSavedCompositionCapacity());
softAssert.assertAll();
}
@Test
void testOpenHelpToolTip() {
logInfo("Verify opening of help tooltip.");
homePage.navigate(baseUrl);
signInService.signInWithGoogleAccount(user);
dashboardPage.openTroopCalculator();
troopCostCalculatorPage.openFirstHelpToolTip();
softAssert.assertThat(troopCostCalculatorPage.isHelpToolTipPresented())
.as("Verify help tooltip presence").isTrue();
softAssert.assertAll();
}
@Test
void testCloseHelpToolTip() {
logInfo("Verify closing of help tooltip.");
homePage.navigate(baseUrl);
signInService.signInWithGoogleAccount(user);
dashboardPage.openTroopCalculator();
troopCostCalculatorPage.openFirstHelpToolTip();
troopCostCalculatorPage.closeHelpToolTip();
softAssert.assertThat(troopCostCalculatorPage.isHelpToolTipPresented())
.as("Verify help tooltip presence").isFalse();
softAssert.assertAll();
}
@Test
void testOpenSaveArmyHelpToolTip() {
logInfo("Verify save army help tool tip text.");
homePage.navigate(baseUrl);
signInService.signInWithGoogleAccount(user);
dashboardPage.openTroopCalculator();
troopCostCalculatorPage.openSaveArmyHelpToolTip();
softAssert.assertThat(troopCostCalculatorPage.getFirstHelpToolTipPresented())
.as("Verify help tooltip text").contains("You can save your army compositions for future use");
softAssert.assertAll();
}
}
<file_sep>package com.karpuk.clashtrack.ui.core.model.enums;
public enum LightBarracksTroopsEnum {
BARBARIAN("Barbarian", 1),
ARCHER("Archer", 1),
GIANT("Giant", 5),
GOBLIN("Goblin", 1),
WALL_BREAKER("Wall_Breaker", 2),
BALLOON("Balloon", 5),
WIZARD("Wizard", 4),
HEALER("Healer", 14),
DRAGON("Dragon", 20),
P_E_K_K_A("P-E-K-K-A-", 25),
BABY_DRAGON("BabyDragon", 10),
MINER("Miner", 6);
private String troopType;
private int armySpace;
LightBarracksTroopsEnum(String troopType, int armySpace) {
this.troopType = troopType;
this.armySpace = armySpace;
}
public String getTroopType() {
return this.troopType;
}
public int getArmySpace() {
return this.armySpace;
}
}
<file_sep>package com.karpuk.clashtrack.ui.test;
import com.karpuk.clashtrack.ui.core.model.enums.TownHallLevelsEnum;
import com.karpuk.clashtrack.ui.test.base.BaseTestData;
import org.assertj.core.data.Percentage;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static com.karpuk.clashtrack.core.listener.TestListener.logInfo;
public class WarWeightCalculationTest extends BaseTestData {
@DataProvider(name = "data-provider-same-gold-amоunt")
public Object[][] dataSameGoldAmount() {
return new Object[][]{{TownHallLevelsEnum.TH8, 100000},
{TownHallLevelsEnum.TH10, 11111111},
{TownHallLevelsEnum.TH5, 222}
};
}
@Test(dataProvider = "data-provider-same-gold-amоunt")
void testCalculatedWithSameStorage(TownHallLevelsEnum townHallLevel, int goldAmount) {
logInfo("Verify calculation with the same amount of gold in storage.");
homePage.navigate(baseUrl);
signInService.signInWithGoogleAccount(user);
dashboardPage.openWarWeightCalculator();
warWeightCalculationService.calculateWarWeight(townHallLevel, 1, goldAmount);
softAssert.assertThat((double) warWeightCalculatorPage.getCalculatedWarWeight())
.as("Verify calculated war weight").isCloseTo(Math.ceil((double) goldAmount * (warWeightCalculatorPage.getNumberOfStorage() + 1) / 1000), Percentage.withPercentage(1));
softAssert.assertAll();
}
@Test(dataProvider = "data-provider-same-gold-amоunt")
void testCalculatedIncreaseGold(TownHallLevelsEnum townHallLevel, int goldAmount) {
logInfo("Verify changing of war weight with increasing gold in storage.");
homePage.navigate(baseUrl);
signInService.signInWithGoogleAccount(user);
dashboardPage.openWarWeightCalculator();
warWeightCalculationService.calculateWarWeight(townHallLevel, 1, goldAmount);
int goldWithFirstAmount = warWeightCalculatorPage.getCalculatedWarWeight();
warWeightCalculatorPage.selectGoldInStorage(1, goldAmount * 2);
softAssert.assertThat(goldWithFirstAmount)
.as("Verify war weight changing").isLessThanOrEqualTo(warWeightCalculatorPage.getCalculatedWarWeight());
softAssert.assertAll();
}
@Test(dataProvider = "data-provider-same-gold-amоunt")
void testCalculatedDecreaseGold(TownHallLevelsEnum townHallLevel, int goldAmount) {
logInfo("Verify changing of war weight with decreasing gold in storage.");
homePage.navigate(baseUrl);
signInService.signInWithGoogleAccount(user);
dashboardPage.openWarWeightCalculator();
warWeightCalculationService.calculateWarWeight(townHallLevel, 1, goldAmount);
int goldWithFirstAmount = warWeightCalculatorPage.getCalculatedWarWeight();
warWeightCalculatorPage.selectGoldInStorage(1, goldAmount / 2);
softAssert.assertThat(goldWithFirstAmount)
.as("Verify war weight changing").isGreaterThanOrEqualTo(warWeightCalculatorPage.getCalculatedWarWeight());
softAssert.assertAll();
}
}
<file_sep># ClashTrack test automation
## Prerequisites
##### For running UI tests:
Setup ClashTrack on https://www.clashtrack.com/en/war-weight using **google account.**
##### For running API tests:
Create authorization token on https://developer.clashofclans.com/
## Execution
#### UI tests:
_(Running from **clashtrack-at-ui** dir)_
```
mvn clean test -Denv=prod -Dclashtrack.ui.user.login=...@gmail.com -Dclashtrack.ui.user.password=... -Dclashtrack.ui.user.name.=...
```
For running UI tests without setup user (limited cases):
```
mvn clean test -Denv=prod -DsuiteXmlFile=testng-no-sign-in.xml
```
#### API tests:
_(Running from **clashtrack-at-api** dir)_
```
mvn clean test -Denv=prod -Dclash.api.authorization.token=...
```
## Reporting
Extent report will be generated automaticaly in {user.dir}/target/test_report/ExtentReports-Version3-Test-Automaton-Report.html
<file_sep>package com.karpuk.clashtrack.ui.test.service;
import com.karpuk.clashtrack.ui.core.model.User;
public class SignInService extends BaseService {
public void signInWithGoogleAccount(User user) {
homePage.clickSignInWithGoogle();
accountsGooglePage.enterEmail(user.getEmail());
accountsGooglePage.clickNextToPassword();
accountsGooglePage.enterPassword(<PASSWORD>());
accountsGooglePage.clickNextToSignIn();
}
}
<file_sep>package com.karpuk.clashtrack.api.core.utils;
import org.springframework.util.MultiValueMap;
public class RestContextHolder {
private String urlBase;
private MultiValueMap<String, String> defaultHeaders;
public RestContextHolder() {
}
public RestContextHolder(String urlBase, MultiValueMap<String, String> defaultHeaders) {
this.urlBase = urlBase;
this.defaultHeaders = defaultHeaders;
}
public RestContextHolder(MultiValueMap<String, String> defaultHeaders) {
this.defaultHeaders = defaultHeaders;
}
public String getUrlBase() {
return urlBase;
}
public MultiValueMap<String, String> getDefaultHeaders() {
return defaultHeaders;
}
public String getClansSearchUrl() {
return urlBase + "/clans";
}
public String getClanRetrieveUrl() {
return urlBase + "/clans/{clanTag}";
}
}
<file_sep>package com.karpuk.clashtrack.api.core.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public class ClansSearchResponse {
private List<Clan> items;
public ClansSearchResponse() {
}
public List<Clan> getItems() {
return items;
}
public void setItems(List<Clan> items) {
this.items = items;
}
@Override
public String toString() {
return "ClansSearchResponse{" +
"items=" + items +
'}';
}
}
<file_sep>package com.karpuk.clashtrack.ui.core.model.enums;
public enum TownHallLevelsEnum {
ALL(0),
TH1(1),
TH2(2),
TH3(3),
TH4(4),
TH5(5),
TH6(6),
TH7(7),
TH8(8),
TH9(9),
TH10(10),
TH11(11),
TH12(12),
TH13(13);
private int value;
TownHallLevelsEnum(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
| e070be44278f549bafcc022be0c196bc641ff892 | [
"Markdown",
"Java",
"INI"
] | 17 | Java | monte-kotte/clash-track-test-automation | 1566067323cf027828312fad1d984bf210b25a8f | 9ffcfe4bf499a7e53e7ec6e6700a09a9dbbcd684 |
refs/heads/master | <repo_name>jonatasleon/video-aulas-android<file_sep>/Aula04/app/src/main/java/br/com/jonatasleon/aula04/PrimeiraActivity.java
package br.com.jonatasleon.aula04;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by jonatasleon on 14/06/15.
*/
public class PrimeiraActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.primeiro_layout);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(onClickListener);
}
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Outro texto");
}
};
}
<file_sep>/README.md
Video-aulas Android
===================
Índice para as vídeo-aulas sobre Android e código-fonte de cada aula.
Índice
-------------
1. [Introdução](https://youtu.be/bkRW4HGyjNA?list=PL43Ux4e1eoZTetV5xwVM1pcXYeoelm725)
2. [Instalação Android Studio](https://youtu.be/VPaKDQ1qBDA?list=PL43Ux4e1eoZTetV5xwVM1pcXYeoelm725)
3. [Instalação Genymotion e Plugin para Android Studio](https://youtu.be/AV3_yUlZei8?list=PL43Ux4e1eoZTetV5xwVM1pcXYeoelm725)
4. [Evento Click e findViewById](https://youtu.be/1aomyMsqCIw?list=PL43Ux4e1eoZTetV5xwVM1pcXYeoelm725)
5. [Ciclo de vida e transição entre Activities](https://youtu.be/fMTX5lb76R8?list=PL43Ux4e1eoZTetV5xwVM1pcXYeoelm725)
| 16383d990b511c251d0f62cde8e8e810a85f2007 | [
"Markdown",
"Java"
] | 2 | Java | jonatasleon/video-aulas-android | 73a6f71abf4c54ff4e6a8eae59347a7f72eb9200 | 6d71dde4f0d7c93bc481203d6753b6e6a8dab7c6 |
refs/heads/master | <repo_name>varunv997/anticollision<file_sep>/README.md
# anticollision
Anti collision system for a quad rotor
<file_sep>/casesforoa.ino
#include <Servo.h>
#define trigPin1 10 //left
#define echoPin1 11
#define trigPin2 8 //back
#define echoPin2 9
#define trigPin3 2 //right
#define echoPin3 3
#define trigPin4 4 //fronta
#define echoPin4 5
#define rollRead 15
#define pitchRead 14
//gray, yellow, orange, purple
//g, brown, green, black
Servo pitch, roll;
int pwm_roll, pwm_pitch;
long duration, distance, RightSensor,BackSensor,FrontSensor,LeftSensor;
void setup()
{
Serial.begin (115200);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(trigPin3, OUTPUT);
pinMode(echoPin3, INPUT);
pinMode(trigPin4, OUTPUT);
pinMode(echoPin4, INPUT);
pinMode(rollRead, INPUT);
pinMode(pitchRead, INPUT);
pitch.attach(13);
roll.attach(12);
}
void loop() {
SonarSensor(trigPin1, echoPin1);
RightSensor = distance;
Serial.print("Right: ");
Serial.println(RightSensor);
SonarSensor(trigPin2, echoPin2);
FrontSensor = distance;
Serial.print("Front: ");
Serial.println(FrontSensor);
SonarSensor(trigPin3, echoPin3);
LeftSensor = distance;
Serial.print("Left: ");
Serial.println(LeftSensor);
SonarSensor(trigPin4, echoPin4);
BackSensor = distance;
Serial.print("Back: ");
Serial.println(BackSensor);
pwm_roll = pulseIn(rollRead, HIGH);
pwm_pitch = pulseIn(pitchRead, HIGH);
Serial.print("Pwm Roll : ");
Serial.println(pwm_roll);
Serial.print("Pwm Pitch : ");
Serial.println(pwm_pitch);
//16 Cases for 4 Sensors
//case 1: no obstacle at any sensor
if (FrontSensor > 60 && BackSensor > 60 && LeftSensor > 60 && RightSensor > 60) {
//Do nothing
}
//case 2: Obstacle at right sensor
else if (FrontSensor > 60 && BackSensor > 60 && LeftSensor > 60 && RightSensor <= 60) {
//Roll Left
//pitch from rx.
pwm_roll=1250;
}
//case 3: Obstacle at left sensor
else if (FrontSensor > 60 && BackSensor > 60 && LeftSensor <= 60 && RightSensor > 60) {
//Roll Right
//pitch from rx.
pwm_roll=1750;
}
//case 4: Obstacle at both left and right sensor
else if (FrontSensor > 60 && BackSensor > 60 && LeftSensor <= 60 && RightSensor <= 60) {
//Send zero roll
//Pitch from rx.
pwm_roll=1500;
}
//case 5: Obstacle at back sensor
else if (FrontSensor > 60 && BackSensor <= 60 && LeftSensor > 60 && RightSensor > 60) {
//Send roll from rx.
//Pitch forward
pwm_pitch=1250;
}
//case 6: Obstacle at back and right sensor
else if (FrontSensor > 60 && BackSensor <= 60 && LeftSensor > 60 && RightSensor <= 60) {
//Roll Left
//Pitch forward
pwm_roll=1250;
pwm_pitch=1250;
}
//case 7: Obstacle at back and left sensor
else if (FrontSensor > 60 && BackSensor <= 60 && LeftSensor <= 60 && RightSensor > 60) {
//Roll Right
//Pitch forward
pwm_roll=1750;
pwm_pitch=1250;
}
//case 8: Obstacle at back, left and right sensor
else if (FrontSensor > 60 && BackSensor <= 60 && LeftSensor <= 60 && RightSensor <= 60) {
//Zero Roll
//Pitch forward
pwm_roll=1500;
pwm_pitch=1250;
}
//case 9: Obstacle at Front sensor
else if (FrontSensor <= 60 && BackSensor > 60 && LeftSensor > 60 && RightSensor > 60) {
//Roll from rx.
//Pitch backward
pwm_pitch=1750;
}
//case 9: Obstacle at Front sensor
else if (FrontSensor <= 60 && BackSensor > 60 && LeftSensor > 60 && RightSensor > 60) {
//Roll from rx.
//Pitch backward
pwm_pitch=1750;
}
//case 10: Obstacle at Front and right sensor
else if (FrontSensor <= 60 && BackSensor > 60 && LeftSensor > 60 && RightSensor <= 60) {
//Roll left.
//Pitch backward
pwm_roll=1250;
pwm_pitch=1750;
}
//case 11: Obstacle at Front and left sensor
else if (FrontSensor <= 60 && BackSensor > 60 && LeftSensor <= 60 && RightSensor > 60) {
//Roll right.
//Pitch backward
pwm_roll=1750;
pwm_pitch=1750;
}
//case 12: Obstacle at Front, left and right sensor
else if (FrontSensor <= 60 && BackSensor > 60 && LeftSensor <= 60 && RightSensor <= 60) {
//Roll zero.
//Pitch backward
pwm_roll=1500;
pwm_pitch=1750;
}
//case 13: Obstacle at Front and back sensor
else if (FrontSensor <= 60 && BackSensor <= 60 && LeftSensor > 60 && RightSensor > 60) {
//Roll from rx.
//Pitch zero.
pwm_pitch=1500;
}
//case 14: Obstacle at Front, back and right sensor
else if (FrontSensor <= 60 && BackSensor <= 60 && LeftSensor > 60 && RightSensor <= 60) {
//Roll left.
//Pitch zero.
pwm_roll=1250;
pwm_pitch=1500;
}
//case 15: Obstacle at Front, back and left sensor
else if (FrontSensor <= 60 && BackSensor <= 60 && LeftSensor <= 60 && RightSensor > 60) {
//Roll right.
//Pitch zero
pwm_roll=1750;
pwm_pitch=1500;
}
//case 16: Obstacle at Front, left, right and back sensor
else if (FrontSensor <= 60 && BackSensor <= 60 && LeftSensor <= 60 && RightSensor <= 60) {
//loiter
}
pitch.writeMicroseconds(pwm_pitch);
roll.writeMicroseconds(pwm_roll);
delayMicroseconds(5);
}
void SonarSensor(int trigPin,int echoPin)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH, 4500);
distance = (duration/2) / 29.1;
if (distance==0)
distance = 100;
}
| f16829fbf493d31451ce7a685397d48e523740ec | [
"Markdown",
"C++"
] | 2 | Markdown | varunv997/anticollision | bc7fbaab44c060fbfe8eee5bd1ac98854139ddc4 | ec5d15b40524298a22c14824092ca16ba525347b |
refs/heads/master | <file_sep>import { Controller, Get, HttpCode, HttpException, Param, Delete, Put, Post, Body, HttpStatus, Res, Logger } from '@nestjs/common';
import { UsersDataService } from 'src/services/users-data/users-data.service';
import { DailyService } from 'src/services/daily/daily.service';
import { UserDto } from 'src/models/userDto';
import { User } from 'src/models/user';
import { Daily } from 'src/models/daily';
import { response } from 'express';
@Controller('daily')
export class DailyController {
private readonly logger = new Logger(DailyController.name);
constructor(private usersService: UsersDataService,
private dailyService: DailyService) {}
@Get()
async getDailys() {
return await this.dailyService.getDailys()
.catch( (e) => {
this.logger.error(e);
throw e;
});
}
@Get('all')
async getAllData() {
const users = await this.usersService.getUsers();
const daily = await this.dailyService.getDailys();
const result: UserDto[] = [];
users.map( (user) => {
result.push(
new UserDto(user, daily.filter(
(task) => task.userId === user.id )),
);
} );
return result;
}
@Post()
async createDaily(@Body() daily: Daily) {
await this.dailyService.createDaily(daily.task as string, daily.userId);
}
@Delete(':id')
async deleteDaily(@Param() params) {
await this.dailyService.deleteDaily(params.id);
}
@Put(':id')
async editDaily(@Param() params, @Body() daily: Daily) {
if (daily.id !== parseInt(params.id, 10) ) {
throw new HttpException(`id mismatch, param: ${params.id}, daily: ${daily.id}`, HttpStatus.BAD_REQUEST);
}
await this.dailyService.editDaily(daily);
}
}
<file_sep>import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { PsqlService } from 'src/services/psql/psql.service';
import { User } from 'src/models/user';
import { Daily } from 'src/models/daily';
import { UserDto } from 'src/models/userDto';
import { DataType } from 'ts-postgres';
@Injectable()
export class UsersDataService {
private readonly logger = new Logger(UsersDataService.name);
constructor(private psql: PsqlService) {}
async getUsers() {
const client = await this.psql.getClient();
const result = await client.query(
`SELECT * from users`,
);
return result.rows.map( (user) => new User(user[1] as string, user[0] as number) );
}
async getUserByUsername(userName: string) {
const client = await this.psql.getClient();
return await client.query(
`SELECT * from users
WHERE name = '' || $1 || ''`, [userName],
);
}
async getUserById(id: number) {
const client = await this.psql.getClient();
return await client.query(
`SELECT * from users
WHERE id = ${id}`, [id],
);
}
async createUser(userName: string) {
const client = await this.psql.getClient();
const user = await this.getUserByUsername(userName);
if (user.rows.length !== 0) {
throw Error('User exist');
}
const newUser = await client.query(
`INSERT INTO users(name)
VALUES(''||$1||'')`, [userName],
);
return await this.getUserByUsername(userName);
}
async deleteUser(id: number) {
const client = await this.psql.getClient();
const deletedUser = await client.query(
`DELETE FROM users
WHERE id = ${id}`, [id],
).catch( (e) => {
this.logger.error('error in deleteUser method of users-data.service: ', e);
throw new HttpException('Query error', HttpStatus.BAD_REQUEST);
} );
if (deletedUser.status === 'DELETE 0') {
throw new HttpException('User id does not exist', HttpStatus.NOT_FOUND);
}
return 'ok';
}
async editUser(id: number, name: string) {
const client = await this.psql.getClient();
const users: User[] = await this.getUserById(id)
.then( (response) => response.rows
.map( (user) => new User(user[1] as string, user[0] as number) ) );
if (users.length !== 1) {
throw new HttpException('User does not exist', HttpStatus.NOT_FOUND);
}
const updateUser = await client.query(
`UPDATE users
SET name = ''||$1||''
WHERE id = ${id}`, [name],
);
if (updateUser.status !== 'UPDATE 1') {
this.logger.warn(updateUser);
throw new HttpException('Update error:' + updateUser.status, HttpStatus.BAD_REQUEST);
}
return 'ok';
}
}
<file_sep>import { Injectable } from '@nestjs/common';
import { Client, Configuration } from 'ts-postgres';
import { from } from 'rxjs';
import { User } from '../../models/user';
import { Daily } from 'src/models/daily';
import { config } from 'src/config/config';
// const config: Configuration = {
// host: '127.0.0.1',
// port: 5432,
// database: 'home',
// user: 'home',
// password: '<PASSWORD>',
// };
const dbCongig = config;
@Injectable()
export class PsqlService {
private client: Client;
async getClient() {
if (this.client === undefined) {
this.client = new Client(dbCongig);
await this.client.connect();
}
return this.client;
}
async addUser() {
const client = new Client(dbCongig);
await client.connect();
const users: Daily[] = [];
const result = await client.query(
// `SELECT '' || $1 || '' AS message`,
// ['world']
`INSERT INTO users(name) VALUES('' || $1 || '')`, ['Marek'],
).catch( (e) => console.log(e) ).then( (res) => console.log(res));
await client.end();
}
}
<file_sep>import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { PsqlService } from '../psql/psql.service';
import { Daily } from 'src/models/daily';
import { Result } from 'ts-postgres';
@Injectable()
export class DailyService {
constructor(private psql: PsqlService) {}
private readonly logger = new Logger(DailyService.name);
async getDailys() {
const client = await this.psql.getClient();
const result = await client.query(
`SELECT * from daily`,
)
.then( (dailies) => this.mapResultToDailies(dailies))
.catch( (e) => {
this.logger.error('Error querying dailyies', e);
throw new QueryError(`Querry error`);
});
return result;
}
async getDailyById(id: number) {
const client = await this.psql.getClient();
const result = await client.query(
`SELECT * from daily
WHERE id = ${id}`, [id],
).then( (dailies) => this.mapResultToDailies(dailies))
.catch( (e) => {
this.logger.error('Error querying dailyies', e);
throw new QueryError('Error querying dailyies');
});
return result;
}
async getDailyByUserId(id: number) {
const client = await this.psql.getClient();
const result = await client.query(
`SELECT * from daily
WHERE user_id = ${id}`, [id],
)
.then( (dailies) => this.mapResultToDailies(dailies))
.catch( (e) => {
this.logger.error('Error querying dailyies', e);
throw new QueryError('Error querying dailyies');
});
return result;
}
async createDaily(taskName: string, userId: number) {
const client = await this.psql.getClient();
const newDaily = await client.query(
`INSERT INTO daily(name, user_id)
VALUES(''||$1||'', ${userId})`, [taskName],
);
if (newDaily.status !== 'INSERT 0 1') {
this.logger.warn('Daily creation error: ' + newDaily.status);
throw new HttpException('Daily creation error: ' + newDaily.status, HttpStatus.BAD_GATEWAY);
}
}
async deleteDaily(id: number) {
const client = await this.psql.getClient();
const deletedUser = await client.query(
`DELETE FROM daily
WHERE id = ${id}`, [id],
).catch( (e) => {
this.logger.error('error in deleteDaily method of daily.service: ', e);
throw new HttpException('Query error', HttpStatus.BAD_REQUEST);
} );
if (deletedUser.status === 'DELETE 0') {
this.logger.warn(`Daily of id: ${id} not found`);
throw new HttpException('Daily id does not exist', HttpStatus.NOT_FOUND);
}
}
async editDaily(daily: Daily) {
const client = await this.psql.getClient();
const dailys: Daily[] = await this.getDailyById(daily.id);
if (dailys.length !== 1) {
this.logger.warn(`Daily of id ${daily.id} not found`);
throw new HttpException('Daily does not exist', HttpStatus.NOT_FOUND);
}
const updateUser = await client.query(
`UPDATE daily
SET name = ''||$1||''
WHERE id = ${daily.id}`, [daily.task as string],
);
if (updateUser.status !== 'UPDATE 1') {
this.logger.warn(`error by: ${updateUser}`);
throw new HttpException('Update error:' + updateUser.status, HttpStatus.BAD_REQUEST);
}
}
private mapResultToDailies(result: Result) {
return result.rows.map( (daily) => new Daily(daily[1] as string, daily[2] as number, daily[0] as number) );
}
}
<file_sep>import { Controller, Get, Inject, HttpException, HttpStatus, HttpCode, Post, Body, Param } from '@nestjs/common';
import { UsersDataService } from 'src/services/users-data/users-data.service';
import { UserDto } from 'src/models/userDto';
import { DailyService } from 'src/services/daily/daily.service';
import { User } from 'src/models/user';
@Controller('users')
export class UsersController {
constructor(private usersService: UsersDataService,
private dailyService: DailyService){}
@Get()
async getUsers(){
return await this.usersService.getUsers()
}
@Get('all')
async getAllData(){
let users = await this.usersService.getUsers();
let daily = await this.dailyService.getDailys();
let result: UserDto[] = []
users.map( (user) => {
result.push(
new UserDto(user, daily.filter(
(daily) => daily.userId === user.id ))
)
} )
return result
}
@Post()
@HttpCode(201)
async addUser(@Body() user: User){
await this.usersService.createUser(user.name)
.catch( (error) => {throw new HttpException('user exist', HttpStatus.CONFLICT); } );
}
@Get('deleteUser')
async deleteUser() {
await this.usersService.deleteUser(10);
}
@Get('editUser')
async editUser() {
await this.usersService.editUser(3, 'maretzky');
}
@Get('/:id/daily')
async getDailyForUser(@Param() params) {
return this.dailyService.getDailyByUserId(params.id);
}
}
<file_sep>export class Daily {
constructor(task: string, userId: number, id?: number){
this.id = id;
this.task = task;
this.userId = userId;
}
id?: number;
task: string;
userId: number;
}<file_sep>import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersController } from './controllers/users/users.controller';
import { UsersDataService } from './services/users-data/users-data.service';
import { PsqlService } from './services/psql/psql.service';
import { DailyService } from './services/daily/daily.service';
import { DailyController } from './controllers/daily/daily.controller';
@Module({
imports: [],
controllers: [AppController, UsersController, DailyController],
providers: [AppService, UsersDataService, PsqlService, DailyService],
})
export class AppModule {}
<file_sep>import { Test, TestingModule } from '@nestjs/testing';
import { UsersDataService } from './users-data.service';
describe('UsersDataService', () => {
let service: UsersDataService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UsersDataService],
}).compile();
service = module.get<UsersDataService>(UsersDataService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
<file_sep>import { User } from './user';
import { Daily } from './daily';
export class UserDto {
constructor(user: User, tasks: Daily[]) {
this.tasks = tasks,
this.user = user;
}
user: User;
tasks: Daily[];
} | ad670413b5ec4bedbeb7d26b365d3f9afccfdc54 | [
"TypeScript"
] | 9 | TypeScript | Maretzky85/home-list | 9ee6d57f50538caf9be3dc61e871dd3612d55dbb | 96d44294efb65e143f8fd54955d9c99ed3dd634c |
refs/heads/master | <repo_name>devendrachaplot/Virtual-Memory-Management<file_sep>/src/kern/arch/mips/vm/pagetable.c
#include <pagetable.h>
// write these
int add_page_entry(page_table tbl&, page_table_entry pentr){
if(size==MAX_PT_SZ) return 1; // not found
table[size]=pentr;
present_bit[size]=true;
dirty_bit[size]=false;
modified_bit[size]=false;
size++;
return 0;
}
int change_page_entry(page_table tbl&, page_table_entry pentr){
int i=0;
for(;i<size;i++){
if(pentr.virtual_addr==table[i].virtual_addr){
table[i].physical_addr=pentr.physical_addr;
return 0;
}
}
// not found
return 1;
}
int delete_page_entry(page_table tbl&, vaddr_t vaddr){
// TODO : check if dirty, and perform a swap out if it is
int i=0;
for(;i<size;i++){
if(pentr.virtual_addr==table[i].virtual_addr){
table[i].physical_addr=pentr.physical_addr;
present_bit[i]=false;
return 0;
}
}
// not found
return 1;
}
int page_table_bootstrap(page_table tbl&){
tbl.size=0;
return 0;
}
<file_sep>/src/kern/vm/page_frame.c
#define NUMFRAMES 1024
//pageframe contains a frame id, a bit showing whether or not it contains an actual page and a pointer to the next pageframe
typedef struct pageframe
{
int frame_id;
bool valid_bit;
uint32_t paddr;
int pid;
pageframe *next;
} pageframe;
//frame table is an array of frames
pageframe pframetable[NUMFRAMES];
//the find_free_frame function returns the id of first empty frame (if any).. if all frames are //occupied, it returns -1
int find_free_frame()
{
int i;
int free=-1;
for(i=0;i<NUMFRAMES;i++)
{
if(!pframetable[i].valid_bit)
{
free=i;
break;
}
}
return free;
}
void bring_to_mem(uint_32 swap_paddr)
{
//create space for a page using kmalloc
page pnew = kmalloc(SIZEOFPAGE);
//use the address from swap_paddr and write from the swapped page into the new page
write_into_page(pnew, swap_paddr);
// get the id for a free frame
int x=find_free_frame();
if(x==-1)
{
//if free frame not found, remove some page from memory using the replacement policy and find free frame again
remove_page(); //using relevant replacement policy
x=find_free_frame();
}
pframetable[x].valid_bit=1;
pframetable[x].paddr=&pnew;
}
<file_sep>/src/dbs.sh
#!/bin/bash
cd kern/conf/
./config ASST0
cd ../compile/ASST0
bmake depend
bmake WERROR=
bmake install
cd ../../../
# bmake
cd ../root
sys161 -w kernel
<file_sep>/src/kern/vm/page_replacement.c
extern clock_angle;
extern size_page_table next_to_be_replaced;
extern size_page_table rear_hand = 0;
extern size_page_table front_hand = CLOCK_ANGLE;
extern size_pft clock_hand = 0;
enum page_replacement_policy {LRU, FIFO, Random, One_Handed, Second_Chance};
paddr_t lru_replace(page_table* pt){
size_page_table sz = pt->size; //size_page_table is a typedef : such as int : depicts number of entries in page_table
size_page_table i;
size_page_table selected_page_index = 0;
time_stamp t_min = pt->array[0].t_stamp;
for(i=1; i<sz; i++){
if(t_min>pt->array[i].t_stamp){
t_min = pt->array[i].t_stamp;
selected_page_index = i;
}
}
return pt->array[selected_page_index].physical_addr;
}
paddr_t fifo_replace(page_table* pt){
return pt->array[next_to_be_replaced++].physical_addr;
}
paddr_t random_replace(page_table* pt){
size_page_table r = rand(0, pt->size - 1);
return pt->array[r].physical_addr;
}
paddr_t second_chance_replace(){
size_pft num_page_frames = MAX_PM_SIZE;
size_pft i = 0;
for(i; i<=clock_angle; i++){
if(pft.table[rear_hand].ref_bit == false){
break;
}
else{
pft.table[front_hand].ref_bit = false;
rear_hand++;
front_hand++;
rear_hand%=sz;
front_hand%=sz;
}
}
paddr_t new_page_frame = pft.table[rear_hand%num_page_frames].physical_addr;
addrspace* p_space_old = pft.table[new_page_frame].p_space;
vaddr_t old_page = pft.table[new_page_frame].virtual_addr;
vaddr_t old_page_lvl_1 = LEVEL1INDEX(old_page);
vaddr_t old_page_lvl_2 = LEVEL2INDEX(old_page);
p_space_old->table[old_page_lvl_1]->table[old_page_lvl_2].valid_bit = false;
return new_page_frame;
}
typedef int size_pft;
paddr_t one_handed_replace(){
size_pft num_page_frames = MAX_PM_SIZE;
for(int i=0; i<num_page_frames; i++){
if(pft.table[clock_hand].ref_bit == false){
break;
}
else {
pft.table[clock_hand].ref_bit = false;
clock_hand++;
clock_hand %= num_page_frames;
}
}
paddr_t new_page_frame = pft.table[clock_hand%num_page_frames].physical_addr;
addrspace* p_space_old = pft.table[new_page_frame].p_space;
vaddr_t old_page = pft.table[new_page_frame].virtual_addr;
vaddr_t old_page_lvl_1 = LEVEL1INDEX(old_page);
vaddr_t old_page_lvl_2 = LEVEL2INDEX(old_page);
p_space_old->table[old_page_lvl_1]->table[old_page_lvl_2].valid_bit = false;
return new_page_frame;
}
<file_sep>/src/kern/syscall/file.c
#include <types.h>
#include <lib.h>
#include <synch.h>
#include <array.h>
#include <vfs.h>
#include <vnode.h>
#include <fs.h>
#include <uio.h>
#include <device.h>
#include <kern/limits.h>
#include <kern/unistd.h>
#include <kern/errno.h>
#include <thread.h>
#include <current.h>
#include <file.h>
#include <kern/fcntl.h>
#include <copyinout.h>
#include <kern/seek.h>
#include <file.h>
#include <limits.h>
#include <kern/stat.h>
#include <spl.h>
#include <current.h>
int _write(int filehandle,void *buf, size_t size,int* retval){
if(filehandle < 0 || filehandle > MAX_FILE_FILETAB){
*retval = -1;
return EBADF;
}
if(curthread->fdesc[filehandle] == NULL)
{
*retval = -1;
return EBADF;
}
if(! (curthread->fdesc[filehandle]->flags != O_WRONLY || curthread->fdesc[filehandle]->flags!=O_RDWR) )
{
*retval = -1;
return EINVAL;
}
lock_acquire(curthread->fdesc[filehandle]->f_lock);
struct uio writeuio;
struct iovec iov;
size_t size1;
char *buffer = (char*)kmalloc(size);
copyinstr((userptr_t)buf,buffer,strlen(buffer),&size1);
uio_kinit(&iov, &writeuio, (void*) buffer, size, curthread->fdesc[filehandle]->offset, UIO_WRITE);
int result=VOP_WRITE(curthread->fdesc[filehandle]->vnode, &writeuio);
if (result) {
kfree(buffer);
lock_release(curthread->fdesc[filehandle]->f_lock);
*retval = -1;
return result;
}
curthread->fdesc[filehandle]->offset = writeuio.uio_offset;
*retval = size - writeuio.uio_resid;
kfree(buffer);
lock_release(curthread->fdesc[filehandle]->f_lock);
return 0;
}
<file_sep>/src/as.sh
#!/bin/bash
cd kern/conf/
./config ASST1
cd ../compile/ASST1
bmake -m ~/os161temp/bmake/mk/ depend
bmake -m ~/os161temp/bmake/mk/ WERROR=
bmake -m ~/os161temp/bmake/mk/ install
cd ../../../
bmake
cd ../root
sys161 kernel
<file_sep>/src/bs.sh
#!/bin/bash
cd kern/conf/
./config ASST0
cd ../compile/ASST0
bmake depend
bmake WERROR=
bmake install
cd ../../../
#bmake WERROR=
cd ../root
sys161 kernel
<file_sep>/src/kern/arch/mips/include/pagetable.h
#ifndef _MIPS_PT_H_
#define _MIPS_PT_H_
typedef struct page_table_entry{
// write this
vaddr_t virtual_addr;
paddr_t physical_addr;
} page_table_entry;
typedef int size_page_table;
const int MAX_PT_SZ =2048;
typedef struct page_table{
pid_t pid; // the process having this information
size_page_table size; // number of entries
page_table_entry table[MAX_PT_SZ]; // address space
bool present_bit[MAX_PT_SZ];
bool dirty_bit[MAX_PT_SZ];
} page_table;
// add new entry
int add_page_entry(page_table tbl&, page_table_entry pentr);
// change existing entry. pentr must have the intended physical_addr for the previous virtual_addr;
int change_page_entry(page_table tbl&, page_table_entry pentr);
// remove the entry
int delete_page_entry(page_table tbl&, vaddr_t vaddr);
// initiate the page table
int page_table_bootstrap(page_table tbl&);
#endif
<file_sep>/src/kern/syscall/simple_syscalls.c
/*
* Sample/test code for running a user program. You can use this for
* reference when implementing the execv() system call. Remember though
* that execv() needs to do more than this function does.
*/
#include <types.h>
#include <kern/errno.h>
#include <kern/fcntl.h>
#include <lib.h>
#include <thread.h>
#include <current.h>
#include <addrspace.h>
#include <vm.h>
#include <vfs.h>
#include <syscall.h>
#include <test.h>
/*
* Load program "progname" and start running it in usermode.
* Does not return except on error.
*
* Calls vfs_open on progname and thus may destroy it.
*/
int
_helloworld()
{
char *buf=kmalloc(30*sizeof(char));
strcpy(buf,"Hello World\n");
int err=kprintf("%s",buf);
kfree(buf);
return err;
}
int
_printint(int n)
{
int tmp=n;
int err=kprintf("%d",tmp);
return err;
}
int
_printstring(char* c,int numchars)
{
numchars;
int err=kprintf("%s\n",c);
return err;
}
int cnt=0;
void *thread_handle(void* ptr, unsigned int nargs){
int local=++cnt,i;
int j;
for(j=0;j<10;j++){
if(j%local==0 && j%1000==0){
kprintf("%d",local);
}
}
return NULL;
}
int
_threaddemo()
{
cnt=0;
int j;
kprintf("Demonstrating thread working\n");
int i=0;
for(;i<10;i++){
char name[4];
name[0]=i+'0';
name[1]='\0';
thread_fork(name,thread_handle,NULL,0,NULL);
}
return 0;
}
int
_sleepdemo()
{
kprintf("step1\n");
clocksleep(1);
kprintf("step2\n");
}
/*
int
_write(int filehandle,void *buf, size_t size,int* retval)
{
if(filehandle < 0 || filehandle > MAX_FILE_FILETAB){
*retval = -1;
return EBADF;
}
if(curthread->fdesc[filehandle] == NULL)
{
*retval = -1;
return EBADF;
}
if(! (curthread->fdesc[filehandle]->flags != O_WRONLY || curthread->fdesc[filehandle]->flags!=O_RDWR) )
{
*retval = -1;
return EINVAL;
}
lock_acquire(curthread->fdesc[filehandle]->f_lock);
struct uio writeuio;
struct iovec iov;
size_t size1;
char *buffer = (char*)kmalloc(size);
copyinstr((userptr_t)buf,buffer,strlen(buffer),&size1);
uio_kinit(&iov, &writeuio, (void*) buffer, size, curthread->fdesc[filehandle]->offset, UIO_WRITE);
int result=VOP_WRITE(curthread->fdesc[filehandle]->vnode, &writeuio);
if (result) {
kfree(buffer);
lock_release(curthread->fdesc[filehandle]->f_lock);
*retval = -1;
return result;
}
curthread->fdesc[filehandle]->offset = writeuio.uio_offset;
*retval = size - writeuio.uio_resid;
kfree(buffer);
lock_release(curthread->fdesc[filehandle]->f_lock);
return 0;
}*/
<file_sep>/src/kern/vm/swapspace.c
#include <types.h>
#include <kern/errno.h>
#include <lib.h>
#include <addrspace.h>
#include <vm.h>
#include <bitmap.h>
#include <mainbus.h>
#include <vfs.h>
#include <vnode.h>
#include <current.h>
#include <synch.h>
#include <kern/fcntl.h>
#include <stat.h>
#include <uio.h>
#include <spl.h>
#include <generic/random.h>
#include <clock.h>
#include <mips/trapframe.h>
#include <spinlock.h>
#include <thread.h>
#include <mips/tlb.h>
/* under dumbvm, always have 48k of user stack */
#define INIT_STACKPAGES 12
struct vnode *swap_file;
page_table_entry *swapspace;
struct page_table_entry *pf_table;
uint32_t swapspace_size;
struct lock *vm_lock;
static struct spinlock stealmem_lock = SPINLOCK_INITIALIZER;
int last_tlb_entry;
paddr_t physical_base_addr;
int swap_insertions;
/******************************* PIYUSH AND VIPUL's MASTERPIECE ***************************************************************************/
void swapspace_init() {
struct stat temp;
VOP_STAT(swap_file, &temp);
swapspace_size = temp.st_size/PAGE_SIZE;
swapspace = (struct page_table_entry*)kmalloc(swapspace_size * sizeof(struct page_table_entry));
struct iovec swap_iov;
struct uio swap_uio;
//char *zero_page=kmalloc(PAGE_SIZE);
//bzero(zero_page,PAGE_SIZE);
int swapspace_start=0;
for(int i = 0; i < swapspace_size; i++)
{
//kprintf("printing %d\n",i);
swapspace[i].physical_addr = (swapspace_start + (i * PAGE_SIZE));
//int spl=splhigh();
//unsigned int offset=i*PAGE_SIZE;
//uio_kinit(&swap_iov, &swap_uio, (void*)zero_page, PAGE_SIZE, offset, UIO_WRITE);
//int result=VOP_WRITE(swap_file, &swap_uio);
//if(result) {
// panic("VM: SWAP out Failed");
//}
//splx(spl);
}
}
void
vm_bootstrap(void)
{
swap_insertions = 0;
page_frame_table_bootstrap();
char fname[] = "lhd0raw:";
vm_lock = lock_create("vm_lock");
int result = vfs_open(fname, 0, O_RDWR , &swap_file);
if(result){
panic("Virtual Memory: Swap space could not be created \n");
}
swapspace_init();
last_tlb_entry=0;
}
uint32_t swapspace_insert (uint32_t vaddr, int pid) {
swap_insertions++;
// kprintf("Swap :\t Insert \t V%x \n",vaddr);
int spl=splhigh();
// find the next empty space in swap space to insert this entry
int pos=0;
for(;pos<swapspace_size;pos++){
if(swapspace[pos].valid_bit==false){
break;
}
}
KASSERT(pos<swapspace_size);
swapspace[pos].virtual_addr = vaddr;
swapspace[pos].counter = 0;
swapspace[pos].pid = pid;
swapspace[pos].valid_bit=true;
splx(spl);
return 0;
}
void swapspace_load_as(struct addrspace *as){
int i;
kprintf("Swap : Segment 1 size : %d\n",as->as_npages1);
for(i=0;i<as->as_npages1;i++){
swapspace_insert(as->as_vbase1+i*PAGE_SIZE,as->pid);
}
kprintf("Swap : Segment 2 size : %d\n",as->as_npages2);
for(i=0;i<as->as_npages2;i++){
swapspace_insert(as->as_vbase2+i*PAGE_SIZE,as->pid);
}
kprintf("Swap : Stack size : %d\n",INIT_STACKPAGES);
for(i=0;i<INIT_STACKPAGES;i++){
swapspace_insert(USERSTACK-(i+1)*PAGE_SIZE,as->pid);
}
}
/*
* remove all pages of this pid
*/
uint32_t swapspace_remove (int pid) {
int spl=splhigh();
int pos=0;
for(;pos<swapspace_size;pos++){
if(swapspace[pos].pid==pid){
swapspace[pos].valid_bit=false;
}
}
splx(spl);
return 0;
}
struct bitmap *mem_map;
void swap_in(page_table_entry pte) {
int spl=splhigh();
struct iovec swap_iov;
struct uio swap_uio;
paddr_t paddr=pte.physical_addr;
int offset,i;
for(i=0;i<swapspace_size;i++){
// if(swapspace[i].pid==pte.pid && swapspace[i].virtual_addr==pte.virtual_addr){
if(swapspace[i].virtual_addr==pte.virtual_addr){
offset=swapspace[i].physical_addr;
break;
}
}
// kprintf("Swap :\t In \t V%x P%x O%x\n",pte.virtual_addr,pte.physical_addr,offset);
KASSERT(i<swapspace_size);
// kprintf("swap_address: %x\n",paddr);
uio_kinit(&swap_iov, &swap_uio, (void*)PADDR_TO_KVADDR(paddr & PAGE_FRAME), PAGE_SIZE, offset, UIO_READ);
splx(spl);
int result=VOP_READ(swap_file, &swap_uio);
if(result) {
panic("VM: SWAP in Failed");
}
}
void swap_out(page_table_entry pte) {
int spl=splhigh();
struct iovec swap_iov;
struct uio swap_uio;
paddr_t paddr=pte.physical_addr;
int offset,i;
for(i=0;i<swapspace_size;i++){
if(/*swapspace[i].pid==pte.pid &&*/ swapspace[i].virtual_addr==pte.virtual_addr){
offset=swapspace[i].physical_addr;
break;
}
}
// kprintf("Swap :\t Out \t V%x P%x O%x\n",pte.virtual_addr,pte.physical_addr,offset);
KASSERT(i<swapspace_size);
uio_kinit(&swap_iov, &swap_uio, (void*)PADDR_TO_KVADDR(paddr & PAGE_FRAME), PAGE_SIZE, offset, UIO_WRITE);
splx(spl);
int result=VOP_WRITE(swap_file, &swap_uio);
if(result) {
panic("VM: SWAP out Failed");
}
// tlb_invalidate(paddr);
}
int num_swap_insertions(){
return swap_insertions;
}
| 816c78c5fb5c46038637f76040a95f2bbe18a207 | [
"C",
"Shell"
] | 10 | C | devendrachaplot/Virtual-Memory-Management | fa55896b31adb6bd650035ce5a855461695ed78c | 430254c3c65cb58196027fa389d2e117989be5da |
refs/heads/master | <repo_name>DaniloBeluco/devsnotesAPI-php<file_sep>/README.md
# devsnotesAPI
API feita com php
<file_sep>/api/insert.php
<?php
require('../config.php');
/* Pega o metodo da requisição que veio */
$method = strtolower($_SERVER['REQUEST_METHOD']);
$json = file_get_contents('php://input');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers");
/* Se o metodo é POST */
if ($method === 'post') {
$header = json_decode($json, true);
/* Pega os campos que vieram no post */
$title = $header['title'];
$body = $header['body'];
/* Se os campos tao preenchidos */
if ($title && $body) {
$sql = $pdo->prepare("INSERT INTO notes (title, body) VALUES (:title, :body)");
$sql->bindValue(":title", $title);
$sql->bindValue(":body", $body);
$sql->execute();
/* Pega o ultimo id inserido, usando PDO */
$id = $pdo->lastInsertId();
/* Array de retorno com o dado inserido */
$array['result'] = [
'id' => $id,
'title' => $title,
'body' => $body
];
} else {
$array['error'] = 'Precisa enviar title e body';
}
} else {
$array['error'] = 'Apenas é permitido o método POST';
}
require('../return.php');
<file_sep>/api/delete.php
<?php
require('../config.php');
/* Pega o metodo da requisição que veio */
$method = strtolower($_SERVER['REQUEST_METHOD']);
/* Se o metodo é PUT */
if ($method === 'delete') {
/* Le o input raiz, transf em array e pega o put */
parse_str(file_get_contents('php://input'), $input);
$id = $input['id'] ?? null;
$id = filter_var($id);
if ($id) {
$sql = $pdo->prepare("SELECT * FROM notes WHERE id = :id");
$sql->bindValue(":id", $id);
$sql->execute();
if ($sql->rowCount > 0) {
$sql = $pdo->prepare("DELETE * FROM notes WHERE id = :id");
$sql->bindValue(":id", $id);
$sql->execute();
} else {
$array['error'] = "ID não existente";
}
} else {
$array['error'] = "ID não enviado";
}
} else {
$array['error'] = 'Apenas é permitido o método DELETE';
}
require('../return.php');
<file_sep>/config.php
<?php
global $pdo;
try {
$pdo = new PDO("mysql:dbname=devsnotes;host=localhost", "root", "");
} catch (PDOException $e) {
//except
}
//se holve algum erro joga no error, se holve resultado joga no result
$array = [
'error' => '',
'result' => [],
];<file_sep>/return.php
<?php
/* Diz que qualquer domínio pode fazer requisição nessa API */
header("Access-Control-Allow-Origin: *");
/* Diz o tipo de requisições permitidos */
header("Acess-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers");
/* Diz que o retorno vai ser um json */
header("Content-Type: application/json");
echo json_encode($array);
exit;
| 5d1b8b33bcb130e176463bb051dc326f6e886afd | [
"Markdown",
"PHP"
] | 5 | Markdown | DaniloBeluco/devsnotesAPI-php | 961b1d5f3ddab373c80cb88f70fab0026f0def48 | 5121e06c22477fc7607dae87f104930022ab8b3a |
refs/heads/main | <repo_name>handestudiomawa/solikuche<file_sep>/main.js
$(document).ready(function(){
var distance = $('.header').offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() > distance) {
$('.header').addClass("affix");
} else {
$('.header').removeClass("affix");
}
});
/* function calls */
wow = new WOW(
{
boxClass: 'wow',
animateClass: 'animate__animated',
offset: 0,
mobile: true,
live: true
}
)
wow.init();
var contentSections = $('.cd-section'),
navigationItems = $('#cd-vertical-nav a');
updateNavigation();
$(window).on('scroll', function(){
updateNavigation();
});
function updateNavigation() {
contentSections.each(function(){
$this = $(this);
var activeSection = $('#cd-vertical-nav a[href="#'+$this.attr('id')+'"]').data('number') - 1;
if ( ( $this.offset().top - $(window).height()/2 < $(window).scrollTop() ) && ( $this.offset().top + $this.height() - $(window).height()/2 > $(window).scrollTop() ) ) {
navigationItems.eq(activeSection).addClass('is-selected');
}else {
navigationItems.eq(activeSection).removeClass('is-selected');
}
});
}
/* top menu start */
$(".menu-button").click(function(){
$(".overlay .menu-button").toggleClass("is-active");
$("body").toggleClass("menuActive")
});
/* top menu end */
/* services start */
$('.slick').slick({
dots: true,
infinite: true,
arrows :false,
speed: 300,
slidesToShow: 1,
slidesToScroll: 1,
touchThreshold : 100,
});
/* services end */
});
| 751d0521987a44a128d58d352c3277b3458f4bbb | [
"JavaScript"
] | 1 | JavaScript | handestudiomawa/solikuche | 6a718faac2894fefd92b37ca823f3c71c09293a3 | 214e1f0eafbfebc866ce0c57b41318461aca89b6 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use App\Http\Requests\BrandRequest;
use App\Models\Brand;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class BrandsController extends Controller
{
public function index()
{
$brand = Brand::orderBy('id','DESC')->paginate(PAGENATION_COUNT);
return view('dashboard.brands.index',compact('brand'));
}
public function create()
{
return view('dashboard.brands.create');
}
public function store(BrandRequest $req)
{
if(!$req->has('is_active'))
$req->request->add(['is_active' => 0]);
else
$req->request->add(['is_active' => 1]);
$fileName =null;
if($req->has('photo')){
$fileName = uploadImage('brands',$req->photo);
}
try {
DB::beginTransaction();
$brand = Brand::create(['is_active'=>$req->is_active,'photo'=>$fileName]);
$brand->name = $req->name;
$brand->save();
DB::commit();
return redirect()->route('admin.brands')->with(['success'=>'تمت العنليه بنجاح']);
}catch (\Exception $ex){
DB::rollBack();
}
}
public function edit($id)
{
$brand = Brand::find($id);
return view('dashboard.brands.edit',compact('brand'));
}
public function update($id, BrandRequest $req)
{
try {
if(!$req->has('is_active'))
$req->request->add(['is_active'=>0]);
else
$req->request->add(['is_active'=>1]);
$fileName ='';
if($req->has('photo')){
$fileName = uploadImage('brands',$req->photo);
}
$brnad = Brand::find($id);
$brnad->update(['is_active'=>$req->is_active,'photo'=>$fileName]);
$brnad->name = $req->name;
$brnad->save();
return redirect()->route('admin.brands')->with(['success'=>'مت العمليه بالنجاح']);
}catch (\Exception $ex){
}
}
public function delete($id)
{
try {
$brand = Brand::find($id);
$action = $brand->delete();
if($action == 1 )
return redirect()->route('admin.brands')->with(['success'=>'تم حذف العنصر']);
else
return redirect()->route('admin.brands')->with(['error'=>'هنالك خطاء']);
}catch (\Exception $ex){
}
}
public function changeStatus()
{
}
}
<file_sep><?php
return [
'Active' => 'Active',
'not Active'=>'Not Active',
'mainCategory'=>'Main Category',
];
<file_sep><?php
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Setting;
use phpDocumentor\Reflection\DocBlock\Tags\See;
use App\Http\Requests\ShippingRequest;
use DB;
class SittingsController extends Controller
{
//
public function editShippingMethods($type)
{
$shippingMethod = null;
if ($type === 'free') {
$shippingMethod = Setting::where('key', 'free_shipping_label')->first();
} elseif ($type === 'inner') {
$shippingMethod = Setting::where('key', 'local_label')->first();
} elseif ($type === 'outer') {
$shippingMethod = Setting::where('key', 'outer_label')->first();
} else
$shippingMethod = Setting::where('key', 'free_shipping_label')->first();
return view('dashboard.settings.shippings.edit',compact('shippingMethod'));
//return $shippingMethod;
}
public function updateShippingMethods(ShippingRequest $req,$id){
//validation
try {
//update
$shipping_method =Setting::find($id);
DB::beginTransaction();
$shipping_method->update(['plain_value'=>$req-> plain_value]);
//update translations
$shipping_method->value = $req->value;
$shipping_method->save();
DB::commit();
return redirect()->back()->with(['success'=>'Update Done ']);
}catch (\Exception $ex){
DB::rollbak();
return redirect()->back()->with(['error'=>'هنالك خطا ما يرجى المحاوله ']);
}
}
}
<file_sep><?php
namespace App\Http\Interfaces;
interface RepositoryInerface
{
public function all();
public function crate(array $date);
public function update(array $data ,$id );
public function delete($id);
public function show($id);
}
<file_sep><?php
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use App\Models\Option;
use App\Models\Product;
use App\Models\Attribute;
use App\Http\Requests\OptionRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class OptionController extends Controller {
public function viewOption() {
//$options = Option::with(['product','attripute'])->select('id', 'product_id', 'attribute_id', 'price')->paginate(PAGENATION_COUNT);
$options = Option::with(['product'=> function($query){
$query->select('id');
},'attribute'=>function($query){
$query->select('id');
}])->select('id', 'product_id', 'attribute_id', 'price')->paginate(PAGENATION_COUNT);
return view('dashboard.products.option.index', compact('options'));
}
public function createOption() {
$data = [];
$data['product'] = Product::active()->select('id')->get();
$data['attribute'] = Attribute::select('id')->get();
return view("dashboard.products.option.create", compact('data'));
}
public function saveOption(OptionRequest $req) {
try {
DB::beginTransaction();
$option = Option::create([
"product_id" => $req->product,
"price" => $req->price,
"attribute_id" => $req->attribute
]);
$option->name = $req->name;
$option->save();
DB::commit();
return redirect()->route('admin.Option')->with(['success' => 'تمت اضافة منتج جديد ']);
} catch (\Exception $ex) {
DB::rollBack();
return redirect()->back()->with(['error' => 'هنالك خطا ']);
}
}
public function editOption($id) {
$data = [];
$option = Option::find($id);
$data['product'] = Product::active()->select('id')->get();
$data['attribute'] = Attribute::select('id')->get();
return view('dashboard.products.option.edit', compact('option','data'));
}
public function updateOption(OptionRequest $req, $id) {
try {
DB::beginTransaction();
$option = Option::find($id);
$option->update([
'product_id'=>$req->product,
'attribute_id'=>$req->attribute,
'price'=>$req->price,
]);
$option->name = $req->name;
$option->save();
DB::commit();
return redirect()->route('admin.Option')->with(['success' => 'تمت تعديل قيمة خاصيه جديده ']);
} catch (\Exception $ex) {
DB::rollback();
return redirect()->back()->with(['error' => 'هنالك خطا ']);
}
}
public function deleteOption($id) {
try {
DB::beginTransaction();
$option = Option::find($id);
$option->translations[0]->delete();
$option->delete();
DB::commit();
return redirect()->route('admin.Option')->with(['success' => 'تمت حذف قيمة خاصيه ']);
} catch (\Exception $ex) {
DB::rollback();
return redirect()->back()->with(['error' => 'هنالك خطا ']);
}
}
}
<file_sep><?php
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use App\Http\Requests\ProfileRequest;
use App\Models\Admin;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
//
public function editProfile(){
$id = auth('admin')->user()->id;
$user = Admin::find($id);
return view('dashboard.profile.edit',compact('user'));
}
public function updateProfile(ProfileRequest $req){
//validation
//update
try {
$user = Admin::find($req->id);
if($req->filled('password')){
$req->merge(['password'=><PASSWORD>($req->password)]);
$user->update(['name'=>$req->userName,'email'=>$req->email,'password'=>$req->password]);
}
else{
$user->update(['name'=>$req->userName,'email'=>$req->email]);
}
$user->save();
return redirect()->back()->with(['success'=>'تمت العمليه بالنجاح']);
}catch (\Exception $ex){
}
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
protected $fillable =['product_id','photo'];
//public $timestamps=false;
public function product(){
return $this->belongsTo(Product::class,'product_id');
}
public function getPhotoAttribute($val){
return ($val !== null) ? asset('assets/images/products/'.$val) : "";
}
}
<file_sep><?php
namespace App\Models;
use Astrotomic\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model;
use phpDocumentor\Reflection\Types\Boolean;
class Option extends Model
{
//
use Translatable;
protected $with=['translations'];
protected $translatedAttributes =['name'];
protected $fillable =['id','product_id','attribute_id','price'];
protected $hidden =['translations'];//return translations when I need it
protected $casts=[
'is_active'=>'boolean',
];
public function scopeActive($query){
return $query->where('is_active',1);
}
public function getActive(){
return $this->is_active == 1 ? 'Active' : 'not Active';
}
public function product(){
return $this->belongsTo(Product::class,'product_id');
}
public function attribute() {
return $this->belongsTo(Attribute::class,'attribute_id');
}
}
<file_sep><?php
return [
'settings' => 'الأعدادات',
'shipping-method'=>'انواع التوصيل',
'free-shipping'=>'التوصيل المجاني',
'inner-shipping'=>'التوصيل الداخلي',
'outer-shipping'=>'التوصيل الخارجي',
'slider'=>"الصور الرئيسيه ",
];
<file_sep><?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Site Routes
|--------------------------------------------------------------------composer------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::group([
'prefix' => LaravelLocalization::setLocale(),
'middleware' => ['localeSessionRedirect', 'localizationRedirect', 'localeViewPath']
], function() {
Route::group(['namespace' => 'Site','middleware'=>'web'], function() {
Route::get('/','HomeController@home')->name('home') -> middleware('verifiedUser');
});
Route::group(['namespace' => 'Site', 'middleware' => ['auth', 'verifiedUser']], function() {//must be verify
Route::get('profile', function() {
return "you are auth";
})->name('profile');
});
Route::group(['namespace' => 'Auth', 'middleware' => 'auth'], function() {
Route::post('verifyUser', 'VerificationCodeController@verifyCode')->name('verifyCode');
Route::get('verify', 'VerificationCodeController@verify')->name('verify');
});
});
<file_sep><?php
return [
'logout' => 'تسجيل الخروج',
'lang'=>'اللغات'
];
<file_sep><?php
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use App\Http\Requests\AdminLoginValidation;
class LoginController extends Controller
{
public function loginView(){
return view('dashboard.auth.login');
}
public function login(AdminLoginValidation $req){
//validation
//chick in database
$remember_me = $req->has('remember_me') ? true : false;
if(auth()->guard('admin')->attempt(['email'=>$req->input('email'),'password'=>$req->input('password')])){
return redirect()->route('admin.dashboard');
}
else
return redirect()->back()->with(['error'=>'هذا الأدمن غير موجود']);
}
public function logout(){
$gaurd =$this ->getGaurd();
$gaurd->logout();
return redirect()->route('admin.login');
}
public function getGaurd(){
return auth('admin');
}
}
<file_sep><?php
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use App\Http\Enumeration\categoryType;
use App\Http\Requests\MainCategoriesRequest;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
class mainCatigoriesController extends Controller
{
//
public function index()
{
//$cat = Category::all();
//$cat->makeVisible('translations');
// $cat=Category::parent()->select('id','slug')->get();
$category = Category::parent()->paginate(PAGENATION_COUNT);
return view('dashboard.categories.index', compact('category'));
}
public function create()
{
//$main = Category::parent()->get();
$main = Category::get();
$arr = array();
$i=0;
foreach ($main as $m){
$arr[$i]=$m;
$j=0;
$arr[$i][$j]= Category::where('parent_id' , $m->id)->get();
$i++;
}
//return $arr;
return view('dashboard.categories.create',compact('main'));
}
public function store(MainCategoriesRequest $req)
{
//validation
if (!$req->has('is_active'))
$req->request->add(['is_active' => 0]);
else
$req->request->add(['is_active' => 1]);
// if($req->type == categoryType::mainCategory)
// $req->request->add(['parent_id'=>null]);
if(!$req->has('mainCat')||($req->mainCat ==0))
$req->request->add(['parent_id'=>null]);
else
$req->request->add(['parent_id'=>$req->mainCat]);
try {
DB::beginTransaction();
$cat = Category::create($req->all());
$cat->name = $req->name;
//$cat = Category::create($req->except('_token'));
$cat->save();
DB::commit();
return redirect()->route('admin.mainCategories')->with(['success' => 'تمت اضافة قسم جديد ']);
} catch (\Exception $ex) {
DB::rollBack();
return redirect()->back()->with(['error' => 'هنالك خطا ']);
}
}
public function edit($id)
{
//check if category is exist
$category = Category::find($id);
if (!$category) {
return redirect()->back()->with(['error' => 'هذا القسم غير موجود']);
} else {
return view('dashboard.categories.edit', compact('category'));
}
}
public function update($id, MainCategoriesRequest $req)
{
try {
if (!$req->has('is_active'))
$req->request->add(['is_active' => 0]);
else
$req->request->add(['is_active' => 1]);
$cat = Category::find($id);
if (!$cat) {
return redirect()->back()->with(['error' => 'هذا القسم غير موجود ']);
} else {
$cat->update(['slug' => $req->slug, 'is_active' => $req->is_active]);
$cat->name = $req->name;
$cat->save();
return redirect()->route('admin.mainCategories')->with(['success' => 'تمت العمليه بالنجاح ']);
}
} catch (\Exception $ex) {
}
}
public function delete($id)
{
try {
$cat = Category::find($id);
$action = $cat->delete();
if ($action == 1)
return redirect()->route('admin.mainCategories')->with(['success' => 'تمت العمليه بالنجاح ']);
else
return redirect()->route('admin.mainCategories')->with(['error' => 'هنالك خطاء']);
} catch (\Exception $ex) {
}
}
public function changeStatus()
{
}
}
<file_sep><?php
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use App\Http\Requests\MainCategoriesRequest;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class SubCatigoriesController extends Controller
{
public function index()
{
$category = Category::subcategory()->paginate(PAGENATION_COUNT);
return view('dashboard.subcategories.index', compact('category'));
}
public function create()
{
$category = Category::parent()->get();
return view('dashboard.subcategories.create', compact('category'));
}
public function store(MainCategoriesRequest $req)
{
if (!$req->has('is_active'))
$req->request->add(['is_active' => 0]);
else
$req->request->add(['is_active' => 1]);
try {
Db::beginTransaction();
$cat = Category::create($req->except('_token'));
$cat->name = $req->name;
$cat->save();
DB::commit();
return redirect()->route('admin.subCatigories')->with(['success' => 'done']);
} catch (\Exception $ex) {
DB::rollBack();
}
}
public function edit($id)
{
//check if category is exist
$category = Category::find($id);
if (!$category) {
return redirect()->back()->with(['error' => 'هذا القسم غير موجود']);
} else {
$main = Category::parent()->get();
return view('dashboard.subcategories.edit', compact('category','main'));
}
}
public function update($id, MainCategoriesRequest $req)
{
try {
if (!$req->has('is_active'))
$req->request->add(['is_active' => 0]);
else
$req->request->add(['is_active' => 1]);
$cat = Category::find($id);
if (!$cat) {
return redirect()->back()->with(['error' => 'هذا القسم غير موجود ']);
} else {
$cat->update(['slug' => $req->slug,'parent_id'=>$req->parent_id,'is_active' => $req->is_active]);
$cat->name = $req->name;
$cat->save();
return redirect()->route('admin.subCatigories')->with(['success' => 'تمت العمليه بالنجاح ']);
}
} catch (\Exception $ex) {
}
}
public function delete($id)
{
try {
$cat = Category::find($id);
$action = $cat->delete();
if ($action == 1)
return redirect()->route('admin.subCatigories')->with(['success' => 'تمت العمليه بالنجاح ']);
else
return redirect()->route('admin.subCatigories')->with(['error' => 'هنالك خطاء']);
} catch (\Exception $ex) {
}
}
public function changeStatus()
{
}
private function getMainCategory($parent_id)
{
$cat = Category::find($parent_id);
return $cat;
}
}
<file_sep><?php
return [
'settings' => 'Sittings',
'shipping-method'=>'Type Shipping',
'free-shipping'=>'Free-shipping',
'inner-shipping'=>'Inner-shipping',
'outer-shipping'=>'Outer-shipping',
'slider'=>"Slider",
];
<file_sep><?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\VerifiesEmails;
use App\Http\Requests\VerifyCodeRequest;
use App\Http\Services\VerificationServices;
use Illuminate\Support\Facades\Auth;
class VerificationCodeController extends Controller
{
/*
|--------------------------------------------------------------------------
| o
* mobile Verification Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling email verification for any
| user that recently registered with the application. Emails may also
| be re-sent if the user didn't receive the original email message.
|
*/
public $verifyServices;
public function __construct(VerificationServices $verificationServices)
{
$this->verifyServices = $verificationServices;
}
public function verifyCode(VerifyCodeRequest $req)
{
$check = $this->verifyServices->checkOTPCode($req->code);
if(!$check){//not correct Code
return redirect()->route('verify')->withErrors(['code'=>'not correct code']);//.Auth::id();
}else{ //not correct Code
$this->verifyServices->removeOTPCode($req->code);
return redirect()->route('profile');
}
}
public function verify(){
return view('auth.verification');
}
}
<file_sep><?php
return [
'Active' => 'مفعل',
'not Active'=>'غير مفعل',
'mainCategory'=>'وسائل التوصيل',
'add'=>'اضافه قسم جديد',
];
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Slider extends Model
{
protected $fillable = ['photo','is_active'];
public function scopeActive($query){
return $query->where('is_active',1);
}
public function getActive()
{
return $this->is_active == 1 ? 'Active' : 'not Active';
}
public function getPhotoAttribute($val){
return ($val !== null) ? asset('assets/images/sliders/'.$val) : "";
}
}
<file_sep><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ProfileRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'userName'=>'required',
'email'=>'required|email|unique:admins,email,'.$this->id,
//'email'=>'required|email',
'password'=>'<PASSWORD>',
'password_confirmation' => '<PASSWORD>|required_with:password|same:<PASSWORD>|<PASSWORD>'
];
}
public function messages()
{
return [
'userName.required'=>'يجب كتابة الأسم',
'email.required'=>'يجب كتابة الأيمل',
'email.email'=>'صيغةالأيمل غير صحيحه',
];
}
}
<file_sep><?php
namespace App\Models;
use Astrotomic\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model;
use phpDocumentor\Reflection\Types\Boolean;
class User_Verfication extends Model
{
protected $fillable =['user_id','code'];
public $table="user_verfication";
public function User(){
return $this->belongsTo(Product::class,'user_id');
}
}
<file_sep><?php
namespace App\Http\Controllers\Site;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Slider;
class HomeController extends Controller
{
public function home()
{
$data = [];
$data['sliders'] = Slider::select('id','photo')->get();
return view('front.home', compact('data'));
}
}
<file_sep><?php
namespace App\Http\Services;
use App\Models\User_Verfication;
class VerficatoinServices
{
/** set OTP code for mobile
* @param $data
*
* @return VerficationCode
*/
public function setVerficationCode($data){
$code = mt_rand(100000, 999999);
$data['code'] = $code;
User_Verfication::whereNotNull('user_id')->where(['user_id'=>$data['user_id']])->delete();
return User_Verfication::create($data);
}
}
<file_sep><?php
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use App\Http\Requests\ProductPriceRequest;
use App\Http\Requests\ProductStockRequest;
use App\Http\Requests\ProductImageRequest;
use App\Http\Requests\AttributeRequest;
use App\Models\Brand;
use App\Models\Category;
use App\Models\Product;
use App\Models\Tag;
use App\Models\Image;
use App\Models\Attribute;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ProductController extends Controller {
public function index() {
$products = Product::select('id', 'slug', 'price', 'is_active', 'created_at')->paginate(PAGENATION_COUNT);
return view('dashboard.products.general.index', compact('products'));
}
public function create() {
$data = [];
$data['brands'] = Brand::active()->select('id')->get();
$data['tags'] = Tag::select('id')->get();
$data['category'] = Category::active()->select('id')->get();
return view('dashboard.products.general.create', compact('data'));
}
public function store(ProductRequest $req) {
if (!$req->has('is_active'))
$req->request->add(['is_active' => 0]);
else
$req->request->add(['is_active' => 1]);
try {
DB::beginTransaction();
$prduct = Product::create([
'slug' => $req->slug,
'brand_id' => $req->brand,
'is_active' => $req->is_active,
]);
$prduct->name = $req->name;
$prduct->description = $req->description;
$prduct->short_description = $req->short_description;
$prduct->save();
$prduct->categories()->attach($req->categories);
$prduct->tags()->attach($req->tag);
DB::commit();
return redirect()->route('admin.products.general.create')->with(['success' => 'تمت اضافة منتج جديد ']);
} catch (\Exception $ex) {
DB::rollBack();
return redirect()->back()->with(['error' => 'هنالك خطا ']);
}
}
public function getPrice($id) {
return view('dashboard.products.price.create', compact('id'));
}
public function storePrice(ProductPriceRequest $req) {
try {
Product::whereId($req->product_id)->update($req->only(['price', 'special_price', 'special_price_type', 'special_price_start', 'special_price_end']));
return redirect()->route('admin.products')->with(['success' => 'تمت اضافة منتج جديد ']);
} catch (\Exception $e) {
}
}
public function getStock($id) {
// $product = Product::whereId($id)->select('sku','manage_stock','in_stock','qty')->get();
$product = Product::find($id);
return view('dashboard.products.Stock.create', compact('product'));
}
public function storeStock(ProductStockRequest $req) {
try {
//Product::whereId($req->product_id)->update($req->only(['sku','manage_stock','in_stock','qty']));
Product::whereId($req->product_id)->update($req->except(['_token', 'product_id']));
return redirect()->route('admin.products')->with(['success' => 'تمت اضافة منتج جديد ']);
} catch (\Exception $e) {
}
}
public function getImages($id) {
return view('dashboard.products.image.create2')->withId($id);
}
public function saveProductImages(Request $request ){
return $request;
$file = $request->file('dzfile');
$filename = uploadImage('products', $file);
return response()->json([
'name' => $filename,
'original_name' => $file->getClientOriginalName(),
]);
}
public function saveProductImagesDB(Request $req){
return $req;
// try {
DB::beginTransaction();
//save dropzone images to db
if ($req->has('document') && count($req->document) > 0) {
foreach ($req->document as $image) {
Image::create([
'product_id' => $req->product_id,
'photo' => $image,
]);
}
}
DB::commit();
return redirect()->route('admin.products')->with(['success' => 'updated successfully']);
// } catch (\Exception $ex) {
DB::rollBack();
return redirect()->route('admin.products')->with(['error' => 'هناك خطأ ما']);
//}
}
public function viewAttribute(){
$atrribute = Attribute::orderBy('id','DESC')->paginate(PAGENATION_COUNT);
return view('dashboard.products.attribute.index', compact('atrribute'));
}
public function createAttribute(){
return view("dashboard.products.attribute.create");
}
public function saveAttribute(AttributeRequest $req){
try{
DB::beginTransaction();
$attribute = Attribute::create();
$attribute ->name =$req->name;
$attribute->save();
DB::commit();
return redirect()->route('admin.products.attribute')->with(['success' => 'تمت اضافة خاصيه جديده ']);
}catch(\Exception $ex){
DB::rollback();
return redirect()->back()->with(['error' => 'هنالك خطا ']);
}
}
public function editAttribute($id){
$attribute = Attribute::find($id);
return view('dashboard.products.attribute.edit', compact('attribute'));
}
public function updateAttribute(AttributeRequest $req,$id){
try{
DB::beginTransaction();
$attribute = Attribute::find($id);
$attribute ->name =$req->name;
$attribute->save();
DB::commit();
return redirect()->route('admin.products.attribute')->with(['success' => 'تمت تعديل خاصيه جديده ']);
}catch(\Exception $ex){
DB::rollback();
return redirect()->back()->with(['error' => 'هنالك خطا ']);
}
}
public function deleteAttribute($id){
try{
DB::beginTransaction();
$attribute = Attribute::find($id);
$attribute->translations[0]->delete();
$attribute->delete();
DB::commit();
return redirect()->route('admin.products.attribute')->with(['success' => 'تمت حذف خاصيه ']);
}catch(\Exception $ex){
DB::rollback();
return redirect()->back()->with(['error' => 'هنالك خطا ']);
}
}
public function update(array $data, $id) {
}
public function delete($id) {
}
public function show($id) {
}
}
<file_sep><?php
namespace App\Repositories;
use \App\Http\Interfaces\RepositoryInerface;
class Repository implements RepositoryInerface
{
protected $model;
public function __construct(Model $model)
{
$this->model = $model;
}
public function all()
{
return $this->model->PAGENATION_COUNT();
}
public function crate(array $date)
{
// TODO: Implement crate() method.
return $this->model->create();
}
public function update(array $data, $id)
{
// TODO: Implement update() method.
$requerd = $this->find($id);
return $requerd->update($data);
}
public function delete($id)
{
// TODO: Implement delete() method.
return $this->model->destroy($id);
}
public function show($id)
{
// TODO: Implement show() method.
return $this->model->findOrFail($id);
}
}
<file_sep><?php
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use App\Http\Requests\BrandRequest;
use App\Http\Requests\TagsRequest;
use App\Models\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class TagsController extends Controller
{
public function index()
{
$tags = Tag::orderBy('id','DESC')->paginate(PAGENATION_COUNT);
return view('dashboard.tags.index',compact('tags'));
}
public function create()
{
return view('dashboard.tags.create');
}
public function store(TagsRequest $req)
{
try {
DB::beginTransaction();
$tag = Tag::create(['slug'=>$req->slug]);
$tag->name = $req->name;
$tag->save();
DB::commit();
return redirect()->route('admin.tags')->with(['success'=>'تمت العنليه بنجاح']);
}catch (\Exception $ex){
DB::rollBack();
}
}
public function edit($id)
{
$tag = Tag::find($id);
return view('dashboard.tags.edit',compact('tag'));
}
public function update($id, TagsRequest $req)
{
try {
$tag = Tag::find($id);
$tag->update(['slug'=>$req->slug]);
$tag->name = $req->name;
$tag->save();
return redirect()->route('admin.tags')->with(['success'=>'مت العمليه بالنجاح']);
}catch (\Exception $ex){
}
}
public function delete($id)
{
try {
$tag = Tag::find($id);
$action = $tag->delete();
if($action == 1 )
return redirect()->route('admin.tags')->with(['success'=>'تم حذف العنصر']);
else
return redirect()->route('admin.tags')->with(['error'=>'هنالك خطاء']);
}catch (\Exception $ex){
}
}
public function changeStatus()
{
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Admin Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['localeSessionRedirect', 'localizationRedirect', 'localeViewPath']
], function() {
//note : thers is prefix admin for all file rout
Route::group(['prefix' => 'admin', 'namespace' => 'Dashboard', 'middleware' => 'auth:admin'], function () {
Route::get('/', 'DashboardController@viewDashboard')->name('admin.dashboard');
Route::get('logout', 'LoginController@logout')->name('admin.logout');
Route::group(['prefix' => 'settings'], function () {
Route::get('shipping-methode/{type}', 'SittingsController@editShippingMethods')->name('edit.shipping.method');
Route::put('shipping-methode/{id}', 'SittingsController@updateShippingMethods')->name('update.shipping.method');
########################### begin Slider ###############################
Route::get('slider', 'SliderController@index')->name('admin.slider.index');
Route::get('slider-create', 'SliderController@create')->name('admin.slider.create');
Route::post('slider/upload', 'SliderController@upload')->name('slider.upload');
Route::get('slider/fetch', 'SliderController@fetch')->name('slider.fetch');
Route::get('sliderDelete/{id}', 'SliderController@delete')->name('slider.delete');
########################### End Slider ###############################
}); //end route settings
Route::group(['prefix' => 'profile'], function () {
Route::get('profile', 'ProfileController@editProfile')->name('admin.profile');
Route::put('updateprofile', 'ProfileController@updateProfile')->name('update.admin.profile');
}); //end route profile
########################### begin Categories #############################
Route::group(['prefix' => 'categories'], function() {
Route::get('/', 'mainCatigoriesController@index')->name('admin.mainCategories');
Route::get('create', 'mainCatigoriesController@create')->name('admin.mainCategories.create');
Route::post('store', 'mainCatigoriesController@store')->name('admin.mainCategories.store');
Route::get('edit/{id}', 'mainCatigoriesController@edit')->name('admin.maincategories.edit');
Route::post('update/{id}', 'mainCatigoriesController@update')->name('admin.maincategories.update');
Route::get('delete/{id}', 'mainCatigoriesController@delete')->name('admin.maincategories.delete');
Route::get('changeStatus/{id}', 'mainCatigoriesController@delete')->name('admin.maincategories.changeStatus');
});
########################### End Categories ###############################
########################### begin SubCategories ###############################
Route::group(['prefix' => 'subCategories'], function() {
Route::get('/', 'SubCatigoriesController@index')->name('admin.subCatigories');
Route::get('create', 'SubCatigoriesController@create')->name('admin.subCatigories.create');
Route::post('store', 'SubCatigoriesController@store')->name('admin.subCatigories.store');
Route::get('edit/{id}', 'SubCatigoriesController@edit')->name('admin.subCatigories.edit');
Route::post('update/{id}', 'SubCatigoriesController@update')->name('admin.subCatigories.update');
Route::get('delete/{id}', 'SubCatigoriesController@delete')->name('admin.subCatigories.delete');
Route::get('changeStatus/{id}', 'SubCatigoriesController@delete')->name('admin.subCatigories.changeStatus');
});
########################### End SubCategories ###############################
########################### begin Brand ###############################
Route::group(['prefix' => 'brands'], function() {
Route::get('/', 'BrandsController@index')->name('admin.brands');
Route::get('create', 'BrandsController@create')->name('admin.brands.create');
Route::post('store', 'BrandsController@store')->name('admin.brands.store');
Route::get('edit/{id}', 'BrandsController@edit')->name('admin.brands.edit');
Route::post('update/{id}', 'BrandsController@update')->name('admin.brands.update');
Route::get('delete/{id}', 'BrandsController@delete')->name('admin.brands.delete');
Route::get('changeStatus/{id}', 'BrandsController@delete')->name('admin.brands.changeStatus');
});
########################### End brand ###############################
########################### begin Tags ###############################
Route::group(['prefix' => 'tags'], function() {
Route::get('/', 'TagsController@index')->name('admin.tags');
Route::get('create', 'TagsController@create')->name('admin.tags.create');
Route::post('store', 'TagsController@store')->name('admin.tags.store');
Route::get('edit/{id}', 'TagsController@edit')->name('admin.tags.edit');
Route::post('update/{id}', 'TagsController@update')->name('admin.tags.update');
Route::get('delete/{id}', 'TagsController@delete')->name('admin.tags.delete');
Route::get('changeStatus/{id}', 'TagsController@delete')->name('admin.tags.changeStatus');
});
########################### End brand ###############################
########################### begin product ###############################
Route::group(['prefix' => 'product'], function() {
Route::get('/', 'ProductController@index')->name('admin.products');
Route::get('general-information', 'ProductController@create')->name('admin.products.general.create');
Route::post('store-general-information', 'ProductController@store')->name('admin.products.general.store');
Route::get('price/{id}', 'ProductController@getPrice')->name('admin.products.price.create');
Route::post('price', 'ProductController@storePrice')->name('admin.products.price.store');
Route::get('stock/{id}', 'ProductController@getStock')->name('admin.products.stock.create');
Route::post('stock', 'ProductController@storeStock')->name('admin.products.stock.store');
Route::get('image/{id}', 'ProductController@getImages')->name('admin.products.image.create');
Route::post('photo', 'ProductController@saveProductImages')->name('admin.products.images.store');
Route::post('photo/db', 'ProductController@saveProductImagesDB')->name('admin.products.images.store.db');
Route::get('attribute', 'ProductController@viewAttribute')->name('admin.products.attribute');
Route::get('create', 'ProductController@createAttribute')->name('admin.products.create.attribute');
Route::post('saveAttripute', 'ProductController@saveAttribute')->name('admin.products.save.attribute');
Route::get('editAttripute/{id}', 'ProductController@editAttribute')->name('admin.products.edit.attribute');
Route::post('updateAttripute/{id}', 'ProductController@updateAttribute')->name('admin.products.update.attribute');
Route::get('deleteAttripute/{id}', 'ProductController@deleteAttribute')->name('admin.products.delete.attribute');
Route::get('option', 'OptionController@viewOption')->name('admin.Option');
Route::get('createOption', 'OptionController@createOption')->name('admin.Option.create');
Route::post('saveOption', 'OptionController@saveOption')->name('admin.Option.save');
Route::get('editOption/{id}', 'OptionController@editOption')->name('admin.Option.edit');
Route::post('updateOption/{id}', 'OptionController@updateOption')->name('admin.Option.update');
Route::get('deleteOption/{id}', 'OptionController@deleteOption')->name('admin.Option.delete');
Route::get('dropzone/{id}', 'DropzoneController@index')->name('admin.products.dropzone.index');
Route::post('dropzone/upload', 'DropzoneController@upload')->name('dropzone.upload');
Route::get('dropzone/fetch', 'DropzoneController@fetch')->name('dropzone.fetch');
Route::get('dropzoneDelete/{id}', 'DropzoneController@delete')->name('dropzone.delete');
Route::get('edit/{id}', 'ProductController@edit')->name('admin.products.edit');
Route::post('update/{id}', 'ProductController@update')->name('admin.products.update');
Route::get('delete/{id}', 'ProductController@delete')->name('admin.products.delete');
Route::get('changeStatus/{id}', 'ProductController@changeStatus')->name('admin.products.changeStatus');
});
########################### End brand ###############################
});
Route::group(['namespace' => 'Dashboard', 'middleware' => 'guest:admin', 'prefix' => 'admin'], function() {
Route::get('login', 'LoginController@loginView')->name('admin.login');
Route::post('login', 'LoginController@login')->name('admin.post.login');
});
});
| 7923cc24a2eb013eddb291157cc798f80b5555f4 | [
"PHP"
] | 26 | PHP | medmjs/store-ecommerce | 897f5eeabc2bde6dea9a1ebad5e7bdd3d0e86bd0 | 25c1b7f87572b78381ed9b4e25a9eb702d61aa68 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.