branch_name
stringclasses 22
values | content
stringlengths 18
81.8M
| directory_id
stringlengths 40
40
| languages
listlengths 1
36
| num_files
int64 1
7.38k
| repo_language
stringclasses 151
values | repo_name
stringlengths 7
101
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep># matt-mac-man
matt-mac-man
|
6c035ed92cffb978971c6a48461c44777d29e617
|
[
"Markdown"
] | 1 |
Markdown
|
flashbladez/matt-mac-man
|
d3348828ded450a3b84b3f54ce9f4af91c733cba
|
8844172609d8e35b17cf6c147196e43f5cbed83e
|
refs/heads/master
|
<file_sep>package util;
import java.util.Map;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class AppConstants implements HttpSessionListener{
public AppConstants(){};
private static Map<String , Object> itemMap;
public static Map<String, Object> getItemMap() {
return itemMap;
}
public void setItemMap(Map<String, Object> itemMap) {
AppConstants.itemMap = itemMap;
}
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
}
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
}
}
<file_sep>package models;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PersistenceException;
import javax.persistence.SequenceGenerator;
import javax.persistence.Transient;
import org.apache.commons.codec.DecoderException;
import play.data.validation.Constraints.Email;
import play.data.validation.Constraints.MaxLength;
import play.data.validation.Constraints.MinLength;
import play.data.validation.Constraints.Required;
import play.db.ebean.Model;
import util.PasswordEncoder;
import util.PrepareModel;
import authtoken.validator.AuthenticityToken;
@Entity
@SequenceGenerator(name = "user_seq", sequenceName = "user_seq")
public class AppUser extends Model {
@Transient
@AuthenticityToken
public String authtoken;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
public Long userId;
@Required @MinLength(value=2) @MaxLength(value=15)
public String userFirstName;
@Required @MinLength(value=2) @MaxLength(value=15)
public String userSurname;
@Required @Email @Column(unique=true , updatable=false)
public String email;
@Required
public String hashedPassword;
public boolean isAdmin=true;
@OneToOne
public BusinessData businessData;
public Date registrationDate;
public AppUser(){};
public static Long createAppUser(AppUser user){
try{
user.registrationDate= new Date();
encodePassword(user);
PrepareModel.prepareAppUser(user);
user.save();
return user.userId;
}catch(PersistenceException ex){
return -1L;
}
}
public static Finder<Long,AppUser> finder = new Finder<Long,AppUser>(Long.class,AppUser.class);
public static String validate(AppUser user){
if(user.userFirstName==null){
return "A name is required";
}
return null;
}
private static void encodePassword(AppUser user){
PasswordEncoder encoder = PasswordEncoder.getInstance();
String maskedPassword;
try {
maskedPassword = encoder.encode(user.hashedPassword, user.registrationDate.toString());
user.hashedPassword= maskedPassword;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (DecoderException e) {
e.printStackTrace();
}
}
public static AppUser authenticate(String email , String password){
AppUser dbUser = finder.where().eq("email", email).findUnique();
if(dbUser ==null) return null;
AppUser authUser = new AppUser();
authUser.registrationDate=dbUser.registrationDate;
authUser.hashedPassword=<PASSWORD>;
encodePassword(authUser);
if(dbUser.hashedPassword.equals(authUser.hashedPassword)){
return dbUser;
}
else
{
return null;
}
}
public static boolean isEmailFree(String email){
boolean isEmpty=true;
AppUser result = finder.select("email").where().eq("email", email).findUnique();
if (result!=null) isEmpty=false;
return isEmpty;
}
public static AppUser getUserByEmail(String email){
return finder.where().eq("email", email).findUnique();
}
}
<file_sep>users:
- !!models.AppUser
userFirstName: test
userSurname: subject
email: <EMAIL>
hashedPassword: <PASSWORD>
registrationDate: 2007-08-05
- !!models.AppUser
userFirstName: uri
userSurname: naor
email: <EMAIL>
hashedPassword: <PASSWORD>
registrationDate: 2007-08-05<file_sep>entiendanet
===========
entiendanet<file_sep>package util;
import org.apache.commons.lang.WordUtils;
import models.AppUser;
public class PrepareModel {
public static void prepareAppUser(AppUser user){
try{
user.userFirstName=WordUtils.capitalize(user.userFirstName).trim();
user.userSurname= WordUtils.capitalize(user.userSurname).trim();
user.email=user.email.trim();
}
catch(NullPointerException ex){
ex.printStackTrace();
}
}
}
<file_sep>package models;
import java.util.Date;
import javax.annotation.Nonnull;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import play.data.validation.Constraints.MaxLength;
import play.data.validation.Constraints.MinLength;
import play.data.validation.Constraints.Required;
import play.db.ebean.Model;
@Entity
public class BusinessData extends Model {
@Id
@OneToOne
public Long businessId;
@Required
@Nonnull
public AppUser appUser;
@Required @MinLength(value=2) @MaxLength(value=15)
public String businessName;
@Required @MinLength(value=5) @MaxLength(value=30)
public String businessAddress;
@Required @MinLength(value=7) @MaxLength(value=30)
public Long businessPhone;
public Long businessFax;
public Long businessZipCode;
public String businessState;
@Required @MinLength(value=4) @MaxLength(value=30)
public String businessCountry;
protected BusinessData(){};
public BusinessData(AppUser user){
this.appUser=user;
}
}
<file_sep>package controllers;
import models.Client;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.*;
public class Clients extends Controller {
public static Result register(){
return ok(views.html.registration.registerV2.render(
Form.form(Client.class)));
}
public static Result saveClient(){
Form<Client> registrationForm = Form.form(Client.class).bindFromRequest();
if(registrationForm.hasErrors()){
return badRequest(views.html.registration.registerV2.render(registrationForm));
}
else{
Client client = registrationForm.bindFromRequest().get();
Long id = Client.saveClient(client);
return ok("hola " +id);
}
}
}
<file_sep># --- Created by Ebean DDL
# To stop Ebean DDL generation, remove this comment and start using Evolutions
# --- !Ups
create table app_user (
user_id bigint not null,
user_first_name varchar(255),
user_surname varchar(255),
email varchar(255),
hashed_password varchar(255),
is_admin boolean,
business_data_business_id bigint,
registration_date timestamp,
constraint uq_app_user_email unique (email),
constraint pk_app_user primary key (user_id))
;
create table business_data (
business_id bigint not null,
business_name varchar(255),
business_address varchar(255),
business_phone bigint,
business_fax bigint,
business_zip_code bigint,
business_state varchar(255),
business_country varchar(255),
constraint pk_business_data primary key (business_id))
;
create table client (
client_id bigint not null,
first_name varchar(255),
last_name varchar(255),
email varchar(255),
password varchar(255),
country varchar(255),
business varchar(255),
constraint uq_client_email unique (email),
constraint pk_client primary key (client_id))
;
create sequence user_seq;
create sequence business_data_seq;
create sequence client_seq;
alter table app_user add constraint fk_app_user_businessData_1 foreign key (business_data_business_id) references business_data (business_id) on delete restrict on update restrict;
create index ix_app_user_businessData_1 on app_user (business_data_business_id);
# --- !Downs
SET REFERENTIAL_INTEGRITY FALSE;
drop table if exists app_user;
drop table if exists business_data;
drop table if exists client;
SET REFERENTIAL_INTEGRITY TRUE;
drop sequence if exists user_seq;
drop sequence if exists business_data_seq;
drop sequence if exists client_seq;
|
af8292b1ae1eef5e1faf86e9aa011f5985d88976
|
[
"Java",
"Markdown",
"SQL",
"YAML"
] | 8 |
Java
|
unaor/entiendanet
|
e5d8e8257fac0f0e18ba0b48f36de8573162669f
|
93709c47763ba2359d380870006cb3a5a44df97e
|
refs/heads/master
|
<file_sep>import React from "react";
import { Redirect, Route, Switch } from "react-router-dom";
import Header from "./components/Header";
import LoginForm from "./components/LoginForm";
import PageNotFound from "./components/PageNotFound";
function App() {
return (
<div className="App">
<Header />
{/* Routes for the application */}
<Switch>
<Route exact path="/" render={() => <Redirect to="/login" />} />
<Route path="/login" component={LoginForm} />
<Route path="/dashboard" component={PageNotFound} />
<Route component={PageNotFound} />
</Switch>
</div>
);
}
export default App;
<file_sep>json-server --port 5000 db.json
|
ede7ff01da37f42c98effd17f30380f0922e0461
|
[
"Batchfile",
"JavaScript"
] | 2 |
Batchfile
|
shubhamnagota/SocialMediaExample
|
0dde86f1acbc8fd743144d197d2a804e07bf902d
|
ef0ea46cdd09193ba9815bbceff9168d6e6f2488
|
refs/heads/master
|
<file_sep># test1
Test progect1
|
445cee33e26bf329c08a6189e96c94caaf17e733
|
[
"Markdown"
] | 1 |
Markdown
|
ivan650/test1
|
cd97159556df17a3a245999a199c38e7aa3cc22a
|
9da4b7fec51c4e7d023dca01810d35146b454073
|
refs/heads/master
|
<file_sep>#!/bin/bash
# ignore-tidy-linelength
# Download and install MSYS2, needed primarily for the test suite (run-make) but
# also used by the MinGW toolchain for assembling things.
#
# FIXME: we should probe the default azure image and see if we can use the MSYS2
# toolchain there. (if there's even one there). For now though this gets the job
# done.
set -euo pipefail
IFS=$'\n\t'
source "$(cd "$(dirname "$0")" && pwd)/../shared.sh"
if isWindows; then
# FIXME(#65767): workaround msys bug, step 1
arch=i686
if [ "$MSYS_BITS" = "64" ]; then
arch=x86_64
fi
curl -O "${MIRRORS_BASE}/msys2-repo/mingw/$arch/mingw-w64-$arch-ca-certificates-20180409-1-any.pkg.tar.xz"
choco install msys2 --params="/InstallDir:${SYSTEM_WORKFOLDER}/msys2 /NoPath" -y --no-progress
mkdir -p "${SYSTEM_WORKFOLDER}/msys2/home/${USERNAME}"
ciCommandAddPath "${SYSTEM_WORKFOLDER}/msys2/usr/bin"
fi
|
6cbaf618f4e15a4f740a4120843f33f730bbb323
|
[
"Shell"
] | 1 |
Shell
|
braiins/rust
|
0b7e28a1610924a27471ffdb59a2885709b3b415
|
c73f40b615f823fffcfe8121cd8ba69c98689892
|
refs/heads/master
|
<repo_name>dycor/apiCinema<file_sep>/app/Models/Director.php
<?php
/**
* Created by Reliese Model.
* Date: Sat, 16 Jun 2018 20:19:59 +0000.
*/
namespace App\Models;
use Reliese\Database\Eloquent\Model as Eloquent;
/**
* Class Director
*
* @property int $id
* @property string $firstname
* @property string $lastname
* @property string $nationality
* @property \Carbon\Carbon $birthdate
* @property string $biography
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*
* @property \Illuminate\Database\Eloquent\Collection $films
*
* @package App\Models
*/
class Director extends Eloquent
{
protected $table = 'director';
protected $dates = [
'birthdate'
];
protected $fillable = [
'firstname',
'lastname',
'nationality',
'birthdate',
'biography'
];
public function films()
{
return $this->hasMany(\App\Models\Film::class, 'director');
}
}
<file_sep>/database/seeds/ActorsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use APICinema\Actor;
class ActorsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker\Factory::create();
for ($i = 0; $i < 50; $i++) {
$actor = new Actor;
$actor->lastName = $faker->lastName;
$actor->firstName = $faker->firstName;
$actor->nationality = 'Américain';
$actor->biography = $faker->paragraph($nbSentences = 2, $variableNbSentences = true);
$actor->birthdate = $faker->dateTimeThisCentury->format('Y-m-d');
$actor->save();
}
}
}
<file_sep>/resources/views/update-film.blade.php
Mettre à jour un film
<file_sep>/app/Http/Resources/Actor.php
<?php
namespace APICinema\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Actor extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'firstname' => $this->firstname,
'lastname' => $this->lastname,
'nationality' => $this->nationality,
'birthdate' => $this->birthdate,
'biography' => $this->biography
];
}
}
<file_sep>/app/Http/Controllers/FilmController.php
<?php
namespace APICinema\Http\Controllers;
use Illuminate\Http\Request;
use APICinema\Http\Resources\Film as FilmResource;
use APICinema\Http\Resources\Director as DirectorResource;
use APICinema\Film;
use APICinema\Director;
class FilmController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function search(Request $filters)
{
$films = (new Film)->newQuery();
if ($filters->has('title')) {
$films->where('title', 'LIKE','%'.$filters->input('title').'%');
}
if ($filters->has('releaseDate')) {
$films->where('releaseDate', $filters->input('releaseDate'));
}
if ($filters->has('category')) {
$films->join('category_film', 'film.id', '=', 'category_film.film');
$films->join('category', 'category.id', '=', 'category_film.category');
$films->where('categoryName', $filters->input('category'));
}
if ($filters->has('actorFirstname')) {
$films->join('film_actor', 'film.id', '=', 'film_actor.film');
$films->join('actor', 'actor.id', '=', 'film_actor.actor');
$films->where('firstname', 'LIKE','%'.$filters->input('actorFirstname').'%');
}
if ($filters->has('actorLastname')) {
$films->join('film_actor', 'film.id', '=', 'film_actor.film');
$films->join('actor', 'actor.id', '=', 'film_actor.actor');
$films->where('lastname', 'LIKE','%'.$filters->input('actorLastname').'%');
}
if ($filters->has('directorLastname')) {
$films->join('director', 'director.id', '=', 'film.director');
$films->where('lastname', 'LIKE','%'.$filters->input('directorLastname').'%');
}
if ($filters->has('directorFirstname')) {
$films->join('director', 'director.id', '=', 'film.director');
$films->where('firstname', 'LIKE','%'.$filters->input('directorFirstname').'%');
}
return FilmResource::collection($films->distinct()->get()) ;
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
$directors = Director::all();
$values = [];
foreach($directors as $director){
$values[$director->id] = $director->firstname.' '.$director->lastname;
}
//dd($values);
return view('forms.filmAdd',['values' =>$values]); //appel d'un helper dédié aux vues
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$film = new Film;
$film->title = $request->title;
$film->releaseDate = $request->releaseDate;
$film->duration = strtotime($request->duration);
$film->synopsis = $request->synopsis;
$film->director = $request->director;
$film->save();
return redirect()->route('front');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$film = Film::find($id) ;
$film->director_data = $film->director_fk->toArray();
return new FilmResource($film);
// dd($film);
// return $film;
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Request $request, Film $film)
{
$filmUpdate = Film::where('id', $film->id)
->update([
'title'=>$request->input('title'),
'releaseDate'=>$request->input('releaseDate'),
'duration'=>$request->input('duration'),
'synopsis'=>$request->input('synopsis'),
'director'=>$request->input('director')
]);
if ($filmUpdate){
return redirect()->route('home');
}
return back()->withInput();
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep>/database/seeds/CategoriesTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class CategoriesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
DB::table('category')->insert([
[
'id' => 1,
'categoryName' => 'Action'
],
[
'id' => 2,
'categoryName' => 'Comédie'
],
[
'id' => 3,
'categoryName' => 'Documentaires'
],
[
'id' => 4,
'categoryName' => 'Drame'
],
[
'id' => 5,
'categoryName' => 'Horreur'
],
[
'id' => 6,
'categoryName' => 'Comédies musicales'
],
[
'id' => 7,
'categoryName' => 'Policier'
],
[
'id' => 8,
'categoryName' => 'Romance'
],
[
'id' => 9,
'categoryName' => 'SF et fantastique'
],
[
'id' => 10,
'categoryName' => 'Thriller'
],
[
'id' => 11,
'categoryName' => 'Aventure'
]
]);
}
}
<file_sep>/database/seeds/CinemaTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class CinemaTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
//
DB::table('cinema')->insert([
/*[
'id' => 1,
'cinemaName' => 'UGC Les Halles',
'city' => 'Paris -Chatelet ',
'adress'=>'7 place De La Rotonde Forum Des Halles',
'postcode'=> '75001'
],*/
[
'id' => 2,
'cinemaName' => 'MK2 BIBLIOTHÈQUE',
'city' => 'Paris 13e arrondissement',
'adress'=>'162 avenue de France',
'postcode'=> '75013'
],
[
'id' => 3,
'cinemaName' => 'UGC Ciné Cité Bercy',
'city' => 'Paris 13e arrondissement',
'adress'=>'162 avenue de France',
'postcode'=> '75012 '
],
[
'id' => 4,
'cinemaName' => 'UGC Ciné Cité Bercy',
'city' => 'Paris 13e arrondissement',
'adress'=>'162 avenue de France',
'postcode'=> '75012 '
],
[
'id' => 5,
'cinemaName' => 'Le Grand Rex',
'city' => 'Paris 2eme arrondissement',
'adress'=>'1 Boulevard Poissonnière',
'postcode'=> '75002 '
],
[
'id' => 6,
'cinemaName' => 'UGC GEORGE V',
'city' => 'Paris 8e arrondissement',
'adress'=>'144-146, avenue des Champs-Elysées',
'postcode'=> '75008'
]]);
}
}
<file_sep>/app/Category.php
<?php
/**
* Created by Reliese Model.
* Date: Sat, 16 Jun 2018 20:19:59 +0000.
*/
namespace APICinema;
use Reliese\Database\Eloquent\Model as Eloquent;
/**
* Class Category
*
* @property int $id
* @property string $categoryName
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*
* @property \Illuminate\Database\Eloquent\Collection $films
*
* @package App\Models
*/
class Category extends Eloquent
{
protected $table = 'category';
protected $fillable = [
'categoryName'
];
public function films()
{
return $this->belongsToMany(\APICinema\Film::class, 'category_film', 'category', 'film')
->withPivot('id', 'category_film_name')
->withTimestamps();
}
}
<file_sep>/app/Http/Controllers/ShowingController.php
<?php
namespace APICinema\Http\Controllers;
use Illuminate\Http\Request;
use APICinema\Http\Resources\Showing as ShowingResource;
use APICinema\Showing;
class ShowingController extends Controller
{
public function search(Request $filters){
$showings = (new Showing)->newQuery();
//La version de la séance
if ($filters->has('language')) {
$showings->leftjoin('language','language.id', '=', 'showing.language_showing')
->where('language.languageName', 'LIKE','%'.$filters->input('language').'%')
->get();
}
//Le titre du film
if ($filters->has('title')) {
$showings->leftjoin('film','film.id', '=', 'showing.film')
->where('film.title', 'LIKE','%'.$filters->input('title').'%')
->get();
}
//Le nom du cinéma
if ($filters->has('cinemaName')) {
$showings->leftjoin('cinema','cinema.id', '=', 'showing.cinema')
->where('cinema.cinemaName', 'LIKE','%'.$filters->input('cinemaName').'%')
->get();
}
//Les horaires
if ($filters->has('schedule')) {
$showings
->where('showing.schedule', 'LIKE','%'.$filters->input('schedule').'%')
->get();
}
//La date
if ($filters->has('day')) {
$showings
->where('showing.day', 'LIKE','%'.$filters->input('day').'%')
->get();
}
return ShowingResource::collection($showings->distinct()->get()) ;
}
}
<file_sep>/app/Models/Language.php
<?php
/**
* Created by Reliese Model.
* Date: Sat, 16 Jun 2018 20:19:59 +0000.
*/
namespace App\Models;
use Reliese\Database\Eloquent\Model as Eloquent;
/**
* Class Language
*
* @property int $id
* @property string $languageName
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*
* @property \Illuminate\Database\Eloquent\Collection $showings
*
* @package App\Models
*/
class Language extends Eloquent
{
protected $table = 'language';
protected $fillable = [
'languageName'
];
public function showings()
{
return $this->hasMany(\App\Models\Showing::class, 'language_showing');
}
}
<file_sep>/app/Models/Film.php
<?php
/**
* Created by Reliese Model.
* Date: Sat, 16 Jun 2018 20:19:59 +0000.
*/
namespace App\Models;
use Reliese\Database\Eloquent\Model as Eloquent;
/**
* Class Film
*
* @property int $id
* @property string $title
* @property \Carbon\Carbon $releaseDate
* @property \Carbon\Carbon $duration
* @property string $synopsis
* @property int $director
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*
* @property \Illuminate\Database\Eloquent\Collection $categories
* @property \Illuminate\Database\Eloquent\Collection $actors
*
* @package App\Models
*/
class Film extends Eloquent
{
protected $table = 'film';
protected $casts = [
'director' => 'int'
];
protected $dates = [
'releaseDate',
'duration'
];
protected $fillable = [
'title',
'releaseDate',
'duration',
'synopsis',
'director'
];
public function director()
{
return $this->belongsTo(\App\Models\Director::class, 'director');
}
public function categories()
{
return $this->belongsToMany(\App\Models\Category::class, 'category_film', 'film', 'category')
->withPivot('id', 'category_film_name')
->withTimestamps();
}
public function actors()
{
return $this->belongsToMany(\App\Models\Actor::class, 'film_actor', 'film', 'actor')
->withPivot('id')
->withTimestamps();
}
}
<file_sep>/resources/views/showing-list.blade.php
@extends('single-film')
@section('content')
Les séances
<br><br>
<ul>
@foreach($showings as $showing)
{{ $showing->language_showing }}
@endforeach
</ul>
@endsection
<file_sep>/app/CategoryFilm.php
<?php
/**
* Created by Reliese Model.
* Date: Sat, 16 Jun 2018 20:19:59 +0000.
*/
namespace APICinema;
use Reliese\Database\Eloquent\Model as Eloquent;
/**
* Class CategoryFilm
*
* @property int $id
* @property string $category_film_name
* @property int $category
* @property int $film
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*
*
* @package App\Models
*/
class CategoryFilm extends Eloquent
{
protected $table = 'category_film';
protected $casts = [
'category' => 'int',
'film' => 'int'
];
protected $fillable = [
'category_film_name',
'category',
'film'
];
public function category()
{
return $this->belongsTo(\APICinema\Category::class, 'category');
}
public function film()
{
return $this->belongsTo(\APICinema\Film::class, 'film');
}
}
<file_sep>/app/FilmActor.php
<?php
/**
* Created by Reliese Model.
* Date: Sat, 16 Jun 2018 20:19:59 +0000.
*/
namespace APICinema;
use Reliese\Database\Eloquent\Model as Eloquent;
/**
* Class FilmActor
*
* @property int $id
* @property int $film
* @property int $actor
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*
*
* @package App\Models
*/
class FilmActor extends Eloquent
{
protected $table = 'film_actor';
protected $casts = [
'film' => 'int',
'actor' => 'int'
];
protected $fillable = [
'film',
'actor'
];
public function actor()
{
return $this->belongsTo(\APICinema\Actor::class, 'actor');
}
public function film()
{
return $this->belongsTo(\APICinema\Film::class, 'film');
}
}
<file_sep>/database/seeds/ActorFilmsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use APICinema\FilmActor;
class ActorFilmsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
for ($i = 1; $i <= 50; $i++) {
$filmActor = new FilmActor;
$filmActor->film = rand(1,6);
$filmActor->actor = $i;
$filmActor->save();
}
}
}
<file_sep>/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call(LanguageTableSeeder::class);
$this->call(DirectorsTableSeeder::class);
$this->call(CategoriesTableSeeder::class);
$this->call(FilmsTableSeeder::class);
$this->call(CategoryFilmsTableSeeder::class);
$this->call(ActorsTableSeeder::class);
$this->call(ActorFilmsTableSeeder::class);
}
}
<file_sep>/readme.md
# API Cinema
<img src="https://poser.pugx.org/laravel/framework/license.svg" alt="License"></a>
## About
This API made with Laravel framework allow you search existing showing of cinema. In an input , you can :
- Search showing of cinema in Paris
- Search information about director , actor or existing film in our data source
- Add yours own film
## Usage
A documentation has been done with Swagger editor. You can use the representation of the API in swagger.yaml file.
## Contributing
- <NAME>
- <NAME>
- <NAME>
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
<file_sep>/database/seeds/UserTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Models\Actor;
class UserTableSeeder extends Seeder {
public function run()
{
$faker = Faker\Factory::create('fr_FR');
for ($i = 0; $i < 10; $i++) {
$actor = new actor;
$actor->lastname = $faker->lastName;
$actor->firstname = $faker->firstName;
$actor->birthdate = $faker->dateTimeThisCentury->format('Y-m-d');
$actor->nationality = $faker->country;
$actor->save();
}
}
}<file_sep>/routes/api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
//
Route::apiResource('film', 'FilmController');
//Films routes
Route::get('/films/{id}','FilmController@show')->name('filmById');
Route::get('/films','FilmController@search')->name('films');
//Showing routes
Route::get('/showings/{param?}','ShowingController@search')->name('searchShowing');
//Actors routes
Route::get('/actors/{id}','ActorController@show')->name('actorBydId');
Route::get('/actors','ActorController@search')->name('actors');
//Directors routes
Route::get('/directors/{id}','DirectorController@show')->name('directorById');
Route::get('/directors','DirectorController@search')->name('directors');
<file_sep>/database/seeds/DirectorsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class DirectorsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('director')->insert([
[
'id' => 1,
'firstname' => 'Joss',
'lastname' => 'Whedon',
'nationality' => 'Américain',
'birthdate' => '1964-06-23',
'biography' => '<NAME> est un producteur, réalisateur et scénariste américain né le 23 juin 1964 à New York.'
],
[
'id' => 2,
'firstname' => 'David',
'lastname' => 'Leitch',
'nationality' => 'Américain',
'birthdate' => '1975-09-13',
'biography' => '<NAME> débute sa carrière de cascadeur au milieu des années 1990 dans des séries télévisées comme Sept à la maison, Ally McBeal ou encore Buffy contre les vampires.'
]
]);
}
}
<file_sep>/app/Http/Resources/Showing.php
<?php
namespace APICinema\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Carbon;
class Showing extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id'=> $this->id,
'language'=> $this->language_showing,
'schedule' => $this->getSchedule(),//Retourne le nom de l'attribut
//Impossible de retourner l'horaire
'day' => $this->day ,
'cinema' => $this->cinema,
'film'=> $this->film
];
}
}
<file_sep>/app/Http/Controllers/ActorController.php
<?php
namespace APICinema\Http\Controllers;
use Illuminate\Http\Request;
use APICinema\Actor;
use APICinema\Http\Resources\Actor as ActorResource;
class ActorController extends Controller
{
public function show($id)
{
$actor = Actor::find($id);
return new ActorResource($actor);
}
public function search(Request $filters)
{
$actors = (new Actor)->newQuery();
if ($filters->has('lastname')) {
$actors->where('lastname', 'LIKE','%'.$filters->input('lastname').'%');
}
if ($filters->has('firstname')) {
$actors->where('firstname', 'LIKE','%'.$filters->input('firstname').'%');
}
if ($filters->has('nationality')) {
$actors->where('nationality', 'LIKE','%'.$filters->input('nationality').'%');
}
if ($filters->has('birthdate')) {
$actors->where('birthdate', $filters->input('birthdate'));
}
return ActorResource::collection($actors->distinct()->get()) ;
}
}
<file_sep>/app/Models/Cinema.php
<?php
/**
* Created by Reliese Model.
* Date: Sat, 16 Jun 2018 20:19:59 +0000.
*/
namespace App\Models;
use Reliese\Database\Eloquent\Model as Eloquent;
/**
* Class Cinema
*
* @property int $id
* @property string $cinemaName
* @property string $city
* @property string $adress
* @property string $postcode
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*
* @property \Illuminate\Database\Eloquent\Collection $showings
*
* @package App\Models
*/
class Cinema extends Eloquent
{
protected $table = 'cinema';
protected $fillable = [
'cinemaName',
'city',
'adress',
'postcode'
];
public function showings()
{
return $this->hasMany(\App\Models\Showing::class, 'cinema');
}
}
<file_sep>/app/Showing.php
<?php
/**
* Created by Reliese Model.
* Date: Thu, 21 Jun 2018 12:58:33 +0000.
*/
//namespace App\Models;
namespace APICinema;
use Illuminate\Support\Carbon;
use Reliese\Database\Eloquent\Model as Eloquent;
/**
* Class Showing
*
* @property int $id
* @property int $language_showing
* @property \Carbon\Carbon $schedule
* @property \Carbon\Carbon $day
* @property int $cinema
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
* @property int $film
*
* @property \App\Models\Language $language
*
* @package App\Models
*/
class Showing extends Eloquent
{
protected $table = 'showing';
protected $casts = [
'language_showing' => 'int',
'cinema' => 'int',
'film' => 'int'
];
protected $dates = [
'schedule', //=> type time
'day'
];
protected $fillable = [
'language_showing',
'schedule',
'day',
'cinema',
'film'
];
//A utiliser pour retourner spécifiquement l'horaire de la séance
//car dans fillable 'schedule' n'est pas considéré comme une date mais
//comme une string
public function getSchedule(){
return $this->fillable[1];
}
public function cinema()
{
return $this->belongsTo(\App\Models\Cinema::class, 'cinema');
}
public function film()
{
return $this->belongsTo(\App\Models\Film::class, 'film');
}
public function language()
{
return $this->belongsTo(\App\Models\Language::class, 'language_showing');
}
}
<file_sep>/database/migrations/2018_06_01_092557_create_showing_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateShowingTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('showing', function (Blueprint $table) {
$table->increments('id');
$table->integer('language_showing')->unsigned();
$table->time('schedule');
$table->date('day');
$table->integer('cinema')->unsigned();
$table->timestamps();
$table->foreign('cinema')->references('id')->on('cinema');
$table->foreign('language_showing')->references('id')->on('language');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('showing');
}
}
<file_sep>/database/seeds/FilmsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use Carbon\Carbon;
class FilmsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('film')->insert([
[
'id' => 1,
'title' => 'Avengers',
'releaseDate' => '2018-05-24',
'duration' => '2:22:00',
'synopsis' => 'Les Avengers et leurs alliés devront être prêts à tout sacrifier pour neutraliser le redoutable Thanos avant que son attaque éclair ne conduise à la destruction complète de l’univers.',
'director' => 1,
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
],
[
'id' => 2,
'title' => 'DEADPOOL 2',
'releaseDate' => '2018-05-24',
'duration' => '1:59:00',
'synopsis' => 'L’insolent mercenaire de Marvel remet le masque !Plus grand, plus-mieux, et occasionnellement les fesses à l’air, il devra affronter un Super-Soldat dressé pour tuer, repenser l’amitié, la famille, et ce que signifie l’héroïsme – tout en bottant cinquante nuances de culs, car comme chacun sait, pour faire le Bien, il faut parfois se salir les doigts.',
'director' => 1,
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
],
[
'id' => 3,
'title' => 'Justice League',
'releaseDate' => '2017-11-15',
'duration' => '2:00:00',
'synopsis' => 'Après avoir retrouvé foi en l\'humanité, <NAME>, inspiré par l\'altruisme de Superman, sollicite l\'aide de sa nouvelle alliée, <NAME>, pour affronter un ennemi plus redoutable que jamais. Ensemble, Batman et Wonder Woman ne tardent pas à recruter une équipe de méta-humains pour faire face à cette menace inédite. Pourtant, malgré la force que représente cette ligue de héros sans précédent – Batman, Wonder Woman, Aquaman, Cyborg et Flash –, il est peut-être déjà trop tard pour sauver la planète d\'une attaque apocalyptique…',
'director' => 1,
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
],
[
'id' => 4,
'title' => 'Much Ado About Nothing',
'releaseDate' => '2014-01-29',
'duration' => '1:49:00',
'synopsis' => 'De retour de la guerre, <NAME> et ses fidèles compagnons d\'armes, Bénédict et Claudio, rendent visite au seigneur Léonato, gouverneur de Messine. Dans sa demeure, les hommes vont se livrer à une autre guerre. Celle de l\'amour, et notamment celle qui fait rage entre Béatrice et Bénédict, que leur entourage tente de réconcilier tout en essayant de déjouer les agissements malfaisants de <NAME>.',
'director' => 1,
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
],
[
'id' => 5,
'title' => '<NAME>',
'releaseDate' => '2014-10-29',
'duration' => '1:41:00',
'synopsis' => 'Depuis la mort de sa femme bien-aimée, <NAME> passe ses journées à retaper sa Ford Mustang de 1969, avec pour seule compagnie sa chienne Daisy. Il mène une vie sans histoire, jusqu\'à ce qu\'un malfrat sadique nommé <NAME> remarque sa voiture. John refuse de la lui vendre. Iosef n\'acceptant pas qu\'on lui résiste, s\'introduit chez John avec deux complices pour voler la Mustang, et tuer sauvagement Daisy.',
'director' => 2,
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
],
[
'id' => 6,
'title' => 'Atomic Blonde',
'releaseDate' => '2017-08-17',
'duration' => '1:55:00',
'synopsis' => 'L\'agent <NAME> est une des meilleures espionne du Service de renseignement de Sa Majesté ; à la fois sensuelle et sauvage et prête à déployer toutes ses compétences pour rester en vie durant sa mission impossible. Envoyée seule à Berlin dans le but de livrer un dossier de la plus haute importance dans cette ville au climat instable, elle s\'associe avec <NAME>, le chef de station local, et commence alors un jeu d\'espions des plus meurtriers',
'director' => 2,
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
]
]);
}
}
<file_sep>/swagger.yaml
swagger: "2.0"
info:
description: "This is the documentation of our API. We explain the existing routes you can use in your application. There is a description for Film , Showing , Actor and Director."
version: "1.0.0"
title: "API Cinema"
paths:
/films/{id}:
get:
tags:
- "film"
summary: "Return a film"
description: ""
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- name: "id"
in: "path"
description: "ID of film to return"
required: true
type: "integer"
format: "int64"
responses:
200:
description: "successful operation"
schema:
$ref: "#/definitions/Film"
/films/search:
get:
tags:
- "film"
summary: "Return a list of films"
description: ""
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- in: "body"
name: "filter research"
description: "filter request"
schema:
$ref: "#/definitions/FilmFilter"
responses:
200:
description: "successful operation"
schema:
type: "array"
items:
$ref: "#/definitions/Film"
/directors/{id}:
get:
tags:
- "directors"
summary: "Return informations about a director"
description: ""
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- name: "id"
in: "path"
description: "ID of director"
required: true
type: "integer"
format: "int64"
responses:
200:
description: "successful operation"
schema:
$ref: "#/definitions/Director"
/directors:
get:
tags:
- "directors"
summary: "Return list of director"
description: ""
consumes:
- "application/json"
produces:
- "application/json"
responses:
200:
description: "successful operation"
schema:
$ref: "#/definitions/Director"
/actors/{id}:
get:
tags:
- "actors"
summary: "Return informations about a actor"
description: ""
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- name: "id"
in: "path"
description: "ID of director"
required: true
type: "integer"
format: "int64"
responses:
200:
description: "successful operation"
schema:
$ref: "#/definitions/Actor"
/actors:
get:
tags:
- "actors"
summary: "Return list of actor"
description: ""
consumes:
- "application/json"
produces:
- "application/json"
responses:
200:
description: "successful operation"
schema:
$ref: "#/definitions/Actor"
/showings/search/{param}:
get:
tags:
- "showings"
summary: "Return informations about a showing"
description: ""
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- name: "param"
in: "path"
description: "ID of film to return"
required: true
type: "integer"
format: "int64"
responses:
200:
description: "successful operation"
schema:
$ref: "#/definitions/Showing"
definitions:
Film:
type: "object"
properties:
id:
type: "integer"
format: "int64"
title:
type: "string"
format: "string"
releaseDate:
$ref: "#/definitions/Date"
synopsis:
type: "string"
format: "string"
director:
type: "integer"
format: "int64"
created_at:
$ref: "#/definitions/Date"
updated_at:
$ref: "#/definitions/Date"
director_data:
type: "object"
format: "array"
Date:
properties:
date:
type: "string"
format: "date-time"
timezone_type:
type: "integer"
format: "int"
timezone:
type: "string"
format: "string"
FilmFilter:
properties:
title:
type: "string"
format: "string"
releaseDate:
type: "string"
format: "date"
category:
type: "string"
format: "string"
actorFirstname:
type: "string"
format: "string"
actorLastname:
type: "string"
format: "string"
directorLastname:
type: "string"
format: "string"
directorFirstname:
type: "string"
format: "string"
Category:
type: "object"
properties:
id:
type: "integer"
format: "int64"
name:
type: "string"
xml:
name: "Category"
Director:
type: "object"
properties:
id:
type: "integer"
format: "int64"
firstname:
type: "string"
format: "string"
lastname:
type: "string"
format: "string"
nationality:
type: "string"
format: "string"
birthday:
$ref: "#/definitions/Date"
biography:
type: "string"
format: "string"
xml:
name: "Director"
Actor:
type: "object"
properties:
id:
type: "integer"
format: "int64"
firstname:
type: "string"
format: "string"
lastname:
type: "string"
format: "string"
nationality:
type: "string"
format: "string"
birthday:
$ref: "#/definitions/Date"
biography:
type: "string"
format: "string"
xml:
name: "Actor"
Showing:
type: "object"
properties:
id:
type: "integer"
format: "int64"
language_showing:
type: "integer"
format: "int64"
schedule:
$ref: "#/definitions/Time"
day:
$ref: "#/definitions/Date"
cinema:
type: "integer"
format: "int64"
created_at:
$ref: "#/definitions/Date"
updated_at:
$ref: "#/definitions/Date"
Time:
type: "object"
properties:
hour:
type: "string"
format: "int64"
minutes:
type: "string"
format: "int64"
second:
type: "string"
format: "int64"
ApiResponse:
type: "object"
properties:
code:
type: "integer"
format: "int32"
type:
type: "string"
message:
type: "string"
<file_sep>/resources/views/single-film.blade.php
@section('title')
Séance d'un film
@endsection
<div class="title m-b-md">Les séances de vos films<br><br></div>
@foreach($showings as $showing)
{{$showing->title}}
<br>
{{$showing->languageName}}
<br>
{{$showing->schedule}}
<br>
{{$showing->day}}
<br>
{{$showing->cinemaName}}
@endforeach
<file_sep>/app/Http/Controllers/DirectorController.php
<?php
namespace APICinema\Http\Controllers;
use Illuminate\Http\Request;
use APICinema\Director;
use APICinema\Http\Resources\Director as DirectorResource;
class DirectorController extends Controller
{
public function show($id)
{
$director = Director::find($id) ;
return new DirectorResource($director);
}
public function search(Request $filters)
{
$directors = (new Director)->newQuery();
if ($filters->has('lastname')) {
$directors->where('lastname', 'LIKE','%'.$filters->input('lastname').'%');
}
if ($filters->has('firstname')) {
$directors->where('firstname', 'LIKE','%'.$filters->input('firstname').'%');
}
if ($filters->has('nationality')) {
$directors->where('nationality', 'LIKE','%'.$filters->input('nationality').'%');
}
if ($filters->has('birthdate')) {
$directors->where('birthdate',$filters->input('birthdate'));
}
return DirectorResource::collection($directors->distinct()->get()) ;
}
}
|
dc2b222b55bb1d01f7a78f825cae1fed39f5f2d6
|
[
"Markdown",
"YAML",
"Blade",
"PHP"
] | 29 |
Markdown
|
dycor/apiCinema
|
e942ad1d2819a2d660e8c7dca48af07911c04f27
|
d11210c549bf3f8d5bb27fb53ff89bf16a494443
|
refs/heads/master
|
<file_sep>package com.example.aufgabe1;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView option1 = (TextView)findViewById(R.id.option1);
TextView option2 = (TextView)findViewById(R.id.option2);
TextView option3 = (TextView)findViewById(R.id.option3);
TextView option4 = (TextView)findViewById(R.id.option4);
//Console Ausgabe bei Click auf die jeweilige Option
option1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("MainActivity", "Option 1 geklickt");
}
});
option2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("MainActivity", "Option 2 geklickt");
}
});
option3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("MainActivity", "Option 3 geklickt");
}
});
option4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("MainActivity", "Option 4 geklickt");
}
});
}
}<file_sep>package com.example.woche1aufgabe3;
import androidx.appcompat.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.TextView;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
EditText text_eingabe;
TextView text_ausgabe;
Button toFahrenheit;
Button toCelsius;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Eingabe und Ausgabe Feld wird im Code iniziiert (zum späteren Auslesen/Überschreiben
text_eingabe = (EditText)findViewById(R.id.text_eingabe);
text_ausgabe = (TextView)findViewById(R.id.text_ausgabe);
// Buttons werden für Code iniziiert
toFahrenheit = (Button)findViewById(R.id.button_to_fahrenheit);
toCelsius = (Button)findViewById(R.id.button_to_celsius);
// Event/Clicklistener wird für Fahrenheitberechnung hinzugefügt
// bei Click -> Auslesen des Eingabefelds und Berechnung, Ausgabefeld wird mit ergebnis gefüllt
toFahrenheit.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String eingabe = text_eingabe.getText().toString();
int result = (Integer.parseInt(eingabe) - 32) * 5/9;
String final_result = String.valueOf(result);
text_ausgabe.setText(final_result);
}
});
// Event/Clicklistener wird für Celsiusberechnung hinzugefügt
// bei Click -> Auslesen des Eingabefelds und Berechnung, Ausgabefeld wird mit ergebnis gefüllt
toCelsius.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String eingabe = text_eingabe.getText().toString();
int result = (Integer.parseInt(eingabe) * 9/5) + 32;
String final_result = String.valueOf(result);
text_ausgabe.setText(final_result);
}
});
}
}<file_sep>package com.example.travelquest.fragments;
import androidx.lifecycle.ViewModel;
public class F3_Netflix_ViewModel extends ViewModel {
// TODO: Implement the ViewModel
}<file_sep>package com.example.hoehenmesser;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SyncStatusObserver;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.content.SharedPreferences;
public class MainActivity extends AppCompatActivity {
private TextView textPressure;
private TextView textHeight;
private TextView textSeek;
private SensorManager sensorManager;
private Sensor druckSensor;
Button button;
SeekBar seekBar;
double sensorValue;
double slideValue;
boolean sensorChanged;
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor sharedPreferencesEditor;
private SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float[]sensorValues = sensorEvent.values;
if (!sensorChanged) sensorValue = sensorValues[0];
textPressure.setText(String.format("Druck: %s", String.valueOf(sensorValue)));
System.out.println("In SENSORCHANGED()");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onDestroy() {
super.onDestroy();
System.out.println("In ONDESTROY()");
// SHARED PREF
saveValue();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Shared Preference Initialization
sharedPreferences = this.getSharedPreferences("storedValues", MODE_PRIVATE);
sensorChanged = false;
textPressure = (TextView) findViewById(R.id.textPressure);
textHeight = (TextView)findViewById(R.id.textHeight);
textSeek = (TextView)findViewById(R.id.textSeek);
seekBar = (SeekBar)findViewById(R.id.seekBar);
button = (Button)findViewById(R.id.button);
sensorManager = (SensorManager) getSystemService((SENSOR_SERVICE));
druckSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
// shared Preference - get the values and set seekbar accordingly
setValue();
System.out.println(slideValue);
seekBar.setMin(-100);
seekBar.setMax(100);
seekBar.setProgress(0);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
sensorChanged = true;
double prog = seekBar.getProgress();
slideValue = prog/10;
textSeek.setText(String.valueOf(slideValue));
sensorValue = 1013.25 + slideValue;
textPressure.setText(String.format("Druck: %s", String.valueOf(sensorValue)));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
double prog = seekBar.getProgress();
slideValue = prog/10;
textSeek.setText(String.valueOf(slideValue));
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
double prog = seekBar.getProgress();
slideValue = prog/10;
textSeek.setText(String.valueOf(slideValue));
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println(sensorValue + " | " + slideValue);
double hoehe = (288.15 / 0.0065 ) * ( 1 - Math.pow((sensorValue/1013.25), 1.0/5.255));
textHeight.setText(String.format("Höhe: %s", (String.valueOf(hoehe)).toString()));
}
});
}
void setValue () {
// SHARED PREFERENCE
slideValue = sharedPreferences.getFloat("slideVal", 3.125f);
System.out.println("did set Value of slider to " + slideValue);
}
void saveValue () {
System.out.println("in saveValue() -- sensorValue saved = " + sensorValue);
sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putFloat("slideVal",(float)sensorValue);
sharedPreferencesEditor.apply();
System.out.println("saved Value");
}
@Override
protected void onPause() {
super.onPause();
// SHARED PREF
saveValue();
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, druckSensor, SensorManager.SENSOR_DELAY_UI);
// SHARED PREF
setValue();
}
}<file_sep>include ':app'
rootProject.name = "GPSReceiver_v2"<file_sep>package com.example.myrouteplam.ui.neue_route;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import com.example.myrouteplam.MainActivity;
import com.example.myrouteplam.R;
import com.example.myrouteplam.entities.Route;
import java.io.File;
import java.sql.Timestamp;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class NeueRouteFragment extends Fragment implements LocationListener {
private static final String TAG = "";
boolean routeBegin;
Timestamp timeStart;
Timestamp timeStop;
String longLatStart;
String longLatStop;
Button btn_startStop;
TextView text;
boolean startStop;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
LocationManager locationManager;
double longitude;
double latitude;
Context c;
String timestampNow;
List<String[]> dataPointList;
byte[] gpxFile;
private NeueRouteViewModel neueRouteViewModel;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
neueRouteViewModel = new ViewModelProvider(this).get(NeueRouteViewModel.class);
View root = inflater.inflate(R.layout.neue_route, container, false);
final TextView textView = root.findViewById(R.id.txtView_neue_route);
Button btn_startRoute = root.findViewById(R.id.btn_neue_route);
init();
/**
* Methode zeichnet nach Betätigung die Route auf.
* Die einzelnen Daten werden ausgelesen und dem Routen Objekt für die Datenbank übergeben.
*/
btn_startRoute.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Aufnahme der Route
if (!startStop) {
startStop = true;
btn_startRoute.setText("Stop");
textView.setText("I'm tracking your steps.");
initLocationTracking();
} else {
logDataEnde();
startStop = false;
btn_startRoute.setText("Start");
textView.setText("");
generateGPX(dataPointList);
Route routeObj = new Route();
routeObj.setBeginn(longLatStart);
routeObj.setBezeichnung("Route " + routeObj.getId());
routeObj.setDauer((double) getDateDiff(timeStart, timeStop));
routeObj.setEnde(longLatStop);
routeObj.setGpxData(gpxFile);
//routeObj.setPois();
//Obj der Datenbank hinzufügen/pushen
MainActivity.routeDB.routeDao().addRoute(routeObj);
Toast.makeText(getActivity(), "Route hinzugefügt", Toast.LENGTH_SHORT).show();
clearData();
}
}
});
neueRouteViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
}
});
return root;
}
/**
* Methode initialisiert die Vorgänge damit eine Route aufgezeichnet wird
*/
void init() {
startStop = false;
c = getActivity();
locationManager = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
routeBegin = true;
dataPointList = new ArrayList<String[]>();
}
/**
* Methode setzt Variablen auf Initialwerte.
*/
void clearData() {
routeBegin = true;
dataPointList = new ArrayList<String[]>();
startStop = false;
}
/**
* Die Methode ruft Geodaten per Location Manager ab.
* Es wird je nach Verfügung GPS oder das Netzwerk verwendet.
*/
void initLocationTracking() {
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled)
getGPS();
else
getGPSNetwork();
}
@Override
public void onLocationChanged(@NonNull Location location) {
this.longitude = location.getLongitude();
this.latitude = location.getLatitude();
logData();
}
//Case: GPS Daten über Netzwerk abrufen
private void getGPSNetwork() {
if (ActivityCompat.checkSelfPermission(c, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(c, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) this);
}
//Case: GPS Daten über Satellit abrufen
private void getGPS() {
if (ActivityCompat.checkSelfPermission(c, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(c, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
}
/**
* In der Methode werden die Daten (Koordinaten und Timestamp) vorbereitet und
* Startwerte für die Datenbank werden extrahiert.
*/
void logData() {
this.timestampNow = String.valueOf(new Timestamp(System.currentTimeMillis()));
String[] data = new String[4];
data[0] = "" + this.timestampNow;
data[1] = "" + this.longitude;
data[2] = "" + this.latitude;
dataPointList.add(data);
if (routeBegin) {
longLatStart = longitude + " " + latitude;
timeStart = new Timestamp(System.currentTimeMillis());
routeBegin = false;
}
}
/**
* In dieser Methode werden Endwerte nach dem loggen der Route extrahiert
*/
public void logDataEnde() {
this.timestampNow = String.valueOf(new Timestamp(System.currentTimeMillis()));
String[] data = new String[4];
data[0] = "" + this.timestampNow;
data[1] = "" + this.longitude;
data[2] = "" + this.latitude;
dataPointList.add(data);
longLatStop = longitude + " " + latitude;
timeStop = new Timestamp(System.currentTimeMillis());
}
/**
* Methode erstellt eine GPX Datei aus den getrackten Daten und loggt zeilenwise die Route.
*/
void generateGPX(List<String[]> list) {
String track_name = getRandomName();
String filename = "tracked_data_" + track_name + ".gpx";
String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?><gpx version=\"1.1\" creator=\"gruppe-kilian-anna\">";
String name = "<name>" + "track" + track_name + "</name><trk><trkseg>\n";
String segments = "";
for (String[] arr : list) {
segments += "<trkpt lat=\"" + arr[1] + "\" lon=\"" + arr[2] + "\"><time>" + arr[0] + "</time></trkpt>\n";
}
String footer = "</trkseg></trk></gpx>";
String finalString = header + name + segments + footer;
gpxFile = finalString.getBytes();
}
/**
* Methode erzeugt IDs/Namen für die GPX getrackten Routen
*
* @return Filename
*/
String getRandomName() {
Random a = new Random();
String f = "" + a.nextDouble();
return f;
}
/**
* Die Methode berechnet die Differenz der Start- und Endwerte der getrackten Route.
*
* @param oldTs Startwerte der Timestamp
* @param newTs Endwerte der Timestamp
* @return
*/
public static long getDateDiff(Timestamp oldTs, Timestamp newTs) {
long diffInMS = newTs.getTime() - oldTs.getTime();
return TimeUnit.MINUTES.convert(diffInMS, TimeUnit.SECONDS);
}
}<file_sep>package com.example.abgabe_4.fragments;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.abgabe_4.R;
import com.example.abgabe_4.activities.RouteView;
import com.example.abgabe_4.adapters.RouteListAdapter;
import com.example.abgabe_4.database.entities.Route;
import com.example.abgabe_4.database.util.ObjectHandler;
import java.util.ArrayList;
import java.util.List;
public class Route_List extends Fragment implements RouteListAdapter.OnRouteListener {
private static final String TAG = "";
Context c;
private RouteListViewModel alleRoutenViewModel;
ArrayList<Route> routenListeArr = new ArrayList<>();
//Variable beinhaltet Recyclerview aus xml layout
private RecyclerView mRecyclerView;
//Adapter ist die Brücke zwischen Data (ArrayList) und dem RecyclerView --> Adapter sorgt für Performance (so viele Items wie gebraucht werden, werden dargestellt)
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private RouteListViewModel mViewModel;
public static Route_List newInstance() {
return new Route_List();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
alleRoutenViewModel =
new ViewModelProvider(this).get(RouteListViewModel.class);
View root = inflater.inflate(R.layout.route__list_fragment, container, false);
alleRoutenViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
//Items für die Listendarstellung
routenListeArr = (ArrayList<Route>) ObjectHandler.INSTANCE.getRouteDao().getRouten();
// ArrayList<Route> routenListeArr = new ArrayList<>();
mRecyclerView = root.findViewById(R.id.liste_routen);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(c);
mAdapter = new RouteListAdapter(routenListeArr, Route_List.this::onRouteClick);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
});
return root;
}
@Override
public void onRouteClick(int position) {
// id of the item to hand to intent (single route)
Route route = routenListeArr.get(position);
Intent intent = new Intent(getActivity(), RouteView.class);
Bundle b = new Bundle();
b.putString("route_bezeichnung", route.getBezeichnung());
intent.putExtras(b);
getActivity().startActivity(intent);
}
}<file_sep>include ':app'
rootProject.name = "Aufgabe 1"<file_sep>package com.example.abgabe_4.database.util;
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public enum Generator {
INSTANCE;
public String getRandomNumberAsString() {
Random random = new Random();
return "" + random.nextInt();
}
@RequiresApi(api = Build.VERSION_CODES.O)
public String getDateAsString(){
return "" + LocalDateTime.now();
}
// returns a list of sorted koordinates (lat_smallest + long_smallest) ++ ...
public List<Koordinate> getSortedKoordinateList(List<Koordinate>koordinateList){
List<Koordinate>sortedKoordinateList = new ArrayList<Koordinate>();
double [] lat_values = new double[koordinateList.size()];
double [] long_values = new double[koordinateList.size()];
for ( int i = 0; i < koordinateList.size(); i++) {
lat_values[i] = koordinateList.get(i).getLatitude();
long_values[i] = koordinateList.get(i).getLongitude();
}
Arrays.sort(lat_values);
Arrays.sort(long_values);
for (int j = 0; j < koordinateList.size(); j ++) {
sortedKoordinateList.add(new Koordinate(lat_values[j], long_values[j]));
}
return sortedKoordinateList;
}
}
<file_sep>package com.example.abgabe_4.database.dao;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.TypeConverters;
import com.example.abgabe_4.database.entities.Route;
import com.example.abgabe_4.database.util.Converters;
import java.util.List;
@Dao
@TypeConverters({Converters.class})
public interface RouteDao {
// ADD EINE ROUTE
@Insert
public void addRoute(Route route);
// GET ALL ROUTEN
@Query("SELECT * FROM route")
List<Route> getRouten();
// GET EINE ROUTE
@Query("SELECT * FROM route WHERE bezeichnung = :bezeichnung")
Route getRoute(String bezeichnung);
}
<file_sep>package com.example.abgabe_4.models;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class RouteData extends AppCompatActivity {
//
}
<file_sep>package com.example.myrouteplam.entities;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import java.io.File;
@Entity(tableName = "routen")
public class Poi {
@PrimaryKey
public int id;
@ColumnInfo(name = "daten")
private String daten;
@ColumnInfo(name = "foto")
private File foto;
public Poi(String daten, File foto) {
this.daten = daten;
this.foto = foto;
}
}
<file_sep>package com.example.abgabe_4.activities;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.example.abgabe_4.R;
public class CameraIntent extends AppCompatActivity {
/**
* Quelle für Kamera Intent Tutorial: https://www.geeksforgeeks.org/android-how-to-open-camera-through-intent-and-display-captured-image/
*/
private static final int pic_id = 123;
Button openCamera;
ImageView cameraImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_intent);
openCamera = findViewById(R.id.btn_camera);
cameraImage = findViewById(R.id.camera_image);
openCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// open the camera
Intent cameraIntent
= new Intent(MediaStore
.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, pic_id);
}
});
}
@SuppressLint("MissingSuperCall")
protected void onActivityResult(int requestCode,
int resultCode,
Intent data) {
if (requestCode == pic_id) {
Bitmap photo = (Bitmap) data.getExtras()
.get("data");
cameraImage.setImageBitmap(photo);
}
}
}
|
cae48cd676934436754e440f26cb0193f8b69d16
|
[
"Java",
"Gradle"
] | 13 |
Java
|
Gelantine-Ritter/Mobile-Anwendungsentwicklung-Android-Studi
|
c81141a27fec2e6fa6335e357d4c516acf3895bc
|
b44771b958a74195d919cc0ad04f7dd64ca6defb
|
refs/heads/main
|
<repo_name>Prathap-13/process<file_sep>/README.md
# process
This is my assignment file repository
I created diffrent two files for HTML and CSS
it will give the hole picture of the webpage and diffrent views of webpages
|
6507be98d0fc27699461f54b191d7c5e7f84d0ff
|
[
"Markdown"
] | 1 |
Markdown
|
Prathap-13/process
|
a05be54a3caaad0260588cfd8f820fa6ef2c8568
|
00bdd577d847f78f2690f778e1d6d9fd078d366f
|
refs/heads/main
|
<repo_name>remimestdagh/iOS-whatsnext<file_sep>/WhatsNext/Controllers/FilmFavouritesViewController.swift
//
// FilmFavouritesViewController.swift
// WhatsNext
//
// Created by <NAME> on 10/11/2020.
//
import UIKit
/// minimalist tableview to display already watched films
class FilmFavouritesViewController: UITableViewController {
@IBOutlet weak var logOutButton: UIBarButtonItem!
var films: [Film] = []
var currentFilm: Film?
let loadingIndicator = UIActivityIndicatorView(style: .large)
/// logout button, returns to login screen
/// - Parameter sender: the logout button
@IBAction func didPressLogoutButton(_ sender: Any) {
UserDefaults.standard.set(false, forKey: "isLoggedIn")
UserDefaults.standard.synchronize()
let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
let mySceneDelegate: SceneDelegate = self.view.window?.windowScene?.delegate as! SceneDelegate
mySceneDelegate.window?.rootViewController = loginVC
}
override func viewDidLoad() {
super.viewDidLoad()
loadingIndicator.center = view.center
view.addSubview(loadingIndicator)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.fetchFilms()
}
/// fetches films from api, includes loading animation
func fetchFilms() {
loadingIndicator.startAnimating()
Network.shared.getFavouriteFilms { [self] films in
self.films = films
loadingIndicator.stopAnimating()
tableView.reloadData()
}
}
/// method to render a cell of a tableview
/// - Parameters:
/// - tableView: the tableview
/// - indexPath: index of the cell in the tableview
/// - Returns: the cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FilmCell", for: indexPath)
cell.textLabel?.text = films[indexPath.row].titel
cell.detailTextLabel?.text = films[indexPath.row].regisseur
return cell
}
}
extension FilmFavouritesViewController {
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
currentFilm = films[indexPath.row]
return indexPath
}
}
extension FilmFavouritesViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return films.count
}
}
<file_sep>/WhatsNext/Model/AuthToken.swift
//
// AuthToken.swift
// WhatsNext
//
// Created by <NAME> on 14/11/2020.
//
import Foundation
struct AuthToken: Decodable {
let accessToken: String
let tokenType: String
enum CodingKeys: String, CodingKey {
case accessToken = "access_token"
case tokenType = "token_type"
}
}
<file_sep>/WhatsNext/SecureStore/SecureStoreError.swift
import Foundation
/// predefines frequent keychain errors
enum SecureStoreError: Error {
case stringToDataConversionError
case dataToStringConversionError
case unhandledError(message: String)
}
extension SecureStoreError: LocalizedError {
var errorDescription: String? {
switch self {
case .stringToDataConversionError:
return NSLocalizedString("String to Data conversion error", comment: "")
case .dataToStringConversionError:
return NSLocalizedString("Data to String conversion error", comment: "")
case .unhandledError(let message):
return NSLocalizedString(message, comment: "")
}
}
}
<file_sep>/WhatsNext/Validation.swift
import Foundation
/// enum contraining frequent errors
enum EvaluateError: Error {
case isEmpty
case isNotValidEmailAddress
case isNotValidEmailLength
case invalidCharacter
case tooLong
case tooShort
case passwordMismatch
case passwordNotStrong
}
extension EvaluateError: LocalizedError {
var errorDescription: String? {
switch self {
case .tooShort:
return NSLocalizedString(
"Your name needs to be at least 2 characters long",
comment: ""
)
case .tooLong:
return NSLocalizedString(
"Your name can't be longer than 14 characters",
comment: ""
)
case .invalidCharacter:
return NSLocalizedString(
"Your name can only contain letters",
comment: ""
)
case .isEmpty:
return NSLocalizedString(
"Please fill in every field",
comment: ""
)
case .isNotValidEmailAddress:
return NSLocalizedString(
"Email is not valid",
comment: ""
)
case .isNotValidEmailLength:
return NSLocalizedString(
"Email is not valid",
comment: ""
)
case .passwordMismatch:
return NSLocalizedString("Passwords don't match!", comment: "")
case .passwordNotStrong:
return NSLocalizedString("Password must contain a special character,a lowercase letter, a capital, a number and must be at least 8 characters long", comment: "")
}
}
}
/// validations for register functionality
struct Validations {
static func validate(username: String) throws {
guard username.count > 1 else {
throw EvaluateError.tooShort
}
guard username.count < 15 else {
throw EvaluateError.tooLong
}
for character in username {
guard character.isLetter else {
throw EvaluateError.invalidCharacter
}
}
}
static func validatePassword(password: String, password2: String) throws {
guard password == password2 else {
throw EvaluateError.passwordMismatch
}
if isValid(input: password, regEx: passwordRegex, predicateFormat: "SELF MATCHES[c] %@") == false {
throw EvaluateError.passwordNotStrong
}
}
private static let passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[d$@$!%*?&#])[A-Za-z\\dd$@$!%*?&#]{8,}"
private static let emailRegEx = "(?:[a-zA-Z0-9!#$%\\&‘*+/=?\\^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%\\&'*+/=?\\^_`{|}"
+ "~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
+ "x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
+ "z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
+ "]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
+ "9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
+ "-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"
static func email(_ string: String) throws {
if string.isEmpty == true {
throw EvaluateError.isEmpty
}
if isValid(input: string,
regEx: emailRegEx,
predicateFormat: "SELF MATCHES[c] %@") == false {
throw EvaluateError.isNotValidEmailAddress
}
if maxLength(emailAddress: string) == false {
throw EvaluateError.isNotValidEmailLength
}
}
// MARK: - Private
private static func isValid(input: String, regEx: String, predicateFormat: String) -> Bool {
return NSPredicate(format: predicateFormat, regEx).evaluate(with: input)
}
private static func maxLength(emailAddress: String) -> Bool {
// 64 chars before domain and total 80. '@' key is part of the domain.
guard emailAddress.count <= 80 else {
return false
}
guard let domainKey = emailAddress.firstIndex(of: "@") else { return false }
return emailAddress[..<domainKey].count <= 64
}
}
<file_sep>/WhatsNext/Model/NetworkRouter.swift
//
// NetworkRouter.swift
// WhatsNext
//
// Created by <NAME> on 10/11/2020.
//
import Foundation
import Alamofire
/// network router to predefine api calls, ensures expandablity
enum NetworkRouter {
case fetchFavourites
case login(login: Login)
case getNextFilms(String)
case addToWatchlist(String)
case addToWatched(String)
case register(register: Register)
case fetchWatchlist
var baseURL: String { return "http://192.168.1.37:45455/api/" }
var path: String {
switch self {
case .fetchFavourites:
return "Films/GetFavourites"
case .login:
return "Account"
case .register:
return "Account/Register"
case .getNextFilms:
return "Films/GetNextFilms"
case .addToWatchlist(let id):
return "Films/AddToWatchlist/\(id)"
case .addToWatched(let id):
return "Films/AddToWatched/\(id)"
case .fetchWatchlist:
return "Films/GetWatchlist"
}
}
var method: HTTPMethod {
switch self {
case .fetchFavourites:
return .get
case .login:
return .post
case .getNextFilms:
return .get
case .addToWatched:
return .post
case .addToWatchlist:
return .post
case .register:
return .post
case .fetchWatchlist:
return .get
}
}
var parameters: [String: String]? {
switch self {
case .fetchFavourites:
return nil
case .login(let login):
return [
"email": login.email,
"password": login.password
]
case .register(let register):
return [
"email": register.email,
"password": <PASSWORD>,
"passwordConfirmation": <PASSWORD>,
"lastName": register.lastName,
"firstName": register.firstName
]
case .getNextFilms(let skip):
return ["skip": skip]
case .addToWatched:
return nil
case .addToWatchlist(let id):
return ["id": id]
case .fetchWatchlist:
return nil
}
}
}
extension NetworkRouter: URLRequestConvertible {
func asURLRequest() throws -> URLRequest {
let newUrl = try baseURL.asURL().appendingPathComponent(path)
var request = URLRequest(url: newUrl)
request.method = method
if method == .get {
request = try URLEncodedFormParameterEncoder()
.encode(parameters, into: request)
} else if method == .post {
request = try JSONParameterEncoder().encode(parameters, into: request)
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
}
return request
}
}
<file_sep>/WhatsNext/Model/Register.swift
//
// Register.swift
// WhatsNext
//
// Created by <NAME> on 29/11/2020.
//
import Foundation
/// struct to pass paramters to register method
struct Register: Encodable {
let email: String
let password: String
let passwordConfirmation: String
let firstName: String
let lastName: String
}
<file_sep>/WhatsNext/AuthRequestInterceptor.swift
//
// AuthRequestInterceptor.swift
// WhatsNext
//
// Created by <NAME> on 07/11/2020.
import Alamofire
/// interceptor for api, inserts auth token
class AuthRequestInterceptor: RequestInterceptor {
let retryLimit = 5
let retryDelay: TimeInterval = 10
/// inserts token when calling api
/// - Parameters:
/// - urlRequest: url of request
/// - session: current session
/// - completion: indicates success
func adapt(
_ urlRequest: URLRequest,
for session: Session,
completion: @escaping (Result<URLRequest, Error>) -> Void
) {
var urlRequest = urlRequest
if let token = TokenManager.shared.fetchAccessToken() {
urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
completion(.success(urlRequest))
}
/// retries request when error == server error
/// - Parameters:
/// - request: request
/// - session: current session
/// - error: thrown error by server
/// - completion: success or not
func retry(
_ request: Alamofire.Request,
for session: Session,
dueTo error: Error,
completion: @escaping (RetryResult) -> Void
) {
let response = request.task?.response as? HTTPURLResponse
if
let statusCode = response?.statusCode,
(500...599).contains(statusCode),
request.retryCount < retryLimit {
completion(.retryWithDelay(retryDelay))
} else {
return completion(.doNotRetry)
}
}
}
<file_sep>/WhatsNext/Controllers/FilmDetailViewController.swift
//
// FilmDetailViewController.swift
// WhatsNext
//
// Created by <NAME> on 25/12/2020.
//
import Foundation
import UIKit
/// View that's shown after a film is selected from the tableview
class FilmDetailViewController: UIViewController {
var film: Film!
@IBOutlet weak var filmPoster: UIImageView!
@IBOutlet weak var filmScore: UILabel!
@IBOutlet weak var filmYear: UILabel!
@IBOutlet weak var filmName: UILabel!
@IBOutlet weak var mainStackView: UIStackView!
@IBOutlet weak var filmDirector: UILabel!
@IBOutlet weak var filmDescription: UITextView!
@IBOutlet weak var filmRuntime: UILabel!
override func viewWillAppear(_ animated: Bool) {
mainStackView.layer.cornerRadius = 15
mainStackView.layer.cornerCurve = .continuous
}
override func viewDidLoad() {
super.viewDidLoad()
setImage(from: self.film!.titleImage)
filmName.text = self.film!.titel
filmDirector.text = "Director: \(self.film!.regisseur)"
filmDescription.text = self.film!.description
filmYear.text = "Release date: \(self.film!.year)"
filmScore.text = "Score: \(self.film!.score)"
filmRuntime.text = "Runtime: \(self.film!.runtime) minutes"
}
/// sets image from url
/// - Parameter url: url of image
func setImage(from url: String) {
guard let imageURL = URL(string: url) else { return }
DispatchQueue.global().async {
guard let imageData = try? Data(contentsOf: imageURL) else { return }
let image = UIImage(data: imageData)
DispatchQueue.main.async {
self.filmPoster.image = image
}
}
}
}
<file_sep>/WhatsNext/Controllers/FilmCardViewController.swift
//
// FilmCardViewController.swift
// WhatsNext
//
// Created by <NAME> on 21/11/2020.
//
import Foundation
import UIKit
class FilmCardViewController: UIViewController {
//attributes
@IBOutlet weak var IVPoster: UIImageView!
@IBOutlet weak var LBLFilmTitle: UILabel!
@IBOutlet weak var LBLScore: UILabel!
@IBOutlet weak var mainStackView: UIStackView!
@IBOutlet weak var IVMessage: UIImageView!
@IBOutlet weak var LBLDescription: UITextView!
@IBOutlet weak var SwipeView: UIView!
var currentIndex: Int = 0
var films: [Film] = []
var currentFilm: Film?
let defaultSkip: Int = 0
//methods
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.getNextFilms(skip: defaultSkip)
mainStackView.layer.cornerRadius = 15
mainStackView.layer.cornerCurve = .continuous
}
func getNextFilms(skip: Int) {
Network.shared.getNextFilms(skip: skip) { [self] films in
self.films = films
if !films.isEmpty {
self.currentFilm = films[0]
setImage(from: self.currentFilm!.titleImage)
LBLFilmTitle.text=self.currentFilm?.titel
LBLScore.text = self.currentFilm?.regisseur
LBLDescription.text = self.currentFilm?.description
}
}
}
func setImage(from url: String) {
guard let imageURL = URL(string: url) else { return }
DispatchQueue.global().async {
guard let imageData = try? Data(contentsOf: imageURL) else { return }
let image = UIImage(data: imageData)
DispatchQueue.main.async {
self.IVPoster.image = image
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
let swipeGesture = UIPanGestureRecognizer(target: self, action: #selector(swipeGesture(gestureRecognizer: )))
self.SwipeView.addGestureRecognizer(swipeGesture)
}
@objc func swipeGesture(gestureRecognizer: UIPanGestureRecognizer) { let labelPoint =
gestureRecognizer.translation(in: view)
SwipeView.center = CGPoint(x: view.bounds.width/2 + labelPoint.x, y: view.bounds.height/2 + labelPoint.y)
let xFromCenter = view.bounds.width / 2 - SwipeView.center.x
var rotation = CGAffineTransform(rotationAngle: xFromCenter/200)
let scale = min(100/abs(xFromCenter), 1)
var scaleAndRotated = rotation.scaledBy(x: scale, y: scale)
SwipeView.transform = scaleAndRotated
if gestureRecognizer.state == .ended {
if SwipeView.center.x < (view.bounds.width / 2 - 100) {
self.IVMessage.isHidden = false
self.IVMessage.image = UIImage(named: "NopeSign")
nextFilm()
}
if SwipeView.center.x > (view.bounds.width / 2 + 100) {
self.IVMessage.isHidden = false
self.IVMessage.image = UIImage(named: "LikeSign")
Network.shared.addToWatchlist(id: String.init(currentFilm!.id)) { isSuccess in
if isSuccess {
self.nextFilm()
}
}
}
if SwipeView.center.y > (view.bounds.height / 2 + 200) {
self.IVMessage.isHidden = false
self.IVMessage.image = UIImage(named: "SeenSign")
Network.shared.addToWatched(id: String.init(currentFilm!.id)) { isSuccess in
if isSuccess {
self.nextFilm()
}
}
}
rotation = CGAffineTransform(rotationAngle: 0)
scaleAndRotated = rotation.scaledBy(x: 1, y: 1)
SwipeView.transform = scaleAndRotated
SwipeView.center = CGPoint(x: view.bounds.width/2, y: view.bounds.height/2)
}
}
///called after swipe, prepares view for next film
func nextFilm() {
hideImageAfterTime(time: 2, imageView: self.IVMessage)
self.currentIndex+=1
self.IVMessage.isHidden = false
if self.currentIndex == self.films.endIndex {
getNextFilms(skip: defaultSkip)
self.currentIndex = 0
}
self.currentFilm = self.films[self.currentIndex]
self.LBLFilmTitle.text = self.currentFilm?.titel
self.LBLScore.text = self.currentFilm?.regisseur
self.LBLDescription.text = self.currentFilm?.description
setImage(from: self.currentFilm!.titleImage)
}
///hides message image after indicated time in seconds
func hideImageAfterTime(time: CFTimeInterval, imageView: UIImageView) {
DispatchQueue.main.asyncAfter(deadline: .now() + time) {
imageView.isHidden = true
}
}
}
<file_sep>/WhatsNext/Model/Films.swift
//
// Films.swift
// WhatsNext
//
// Created by <NAME> on 22/11/2020.
//
/// struct to decode api calls into array of film
struct Films: Decodable {
let items: [Film]
}
<file_sep>/WhatsNext/NetworkLogger.swift
//
// NetworkLogger.swift
// WhatsNext
//
// Created by <NAME> on 08/11/2020.
//
import Foundation
import Alamofire
/// provides logging functionality to api, prints objects in console
class NetworkLogger: EventMonitor {
func requestDidFinish(_ request: Request) {
print(request.description)
}
func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value, AFError>) {
guard let data = response.data else {
return
}
if let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) {
print(json)
}
}
}
<file_sep>/WhatsNext/SecureStore/SecureStoreQueryable.swift
import Foundation
/// defines a query in dictionary form to browse the securestore
protocol SecureStoreQueryable {
var query: [String: Any] { get }
}
struct GenericPasswordQueryable {
let service: String
let accessGroup: String?
init(service: String, accessGroup: String? = nil) {
self.service = service
self.accessGroup = accessGroup
}
}
extension GenericPasswordQueryable: SecureStoreQueryable {
var query: [String: Any] {
var query: [String: Any] = [:]
query[String(kSecClass)] = kSecClassGenericPassword
query[String(kSecAttrService)] = service
#if !targetEnvironment(simulator)
if let accessGroup = accessGroup {
query[String(kSecAttrAccessGroup)] = accessGroup
}
#endif
return query
}
}
<file_sep>/WhatsNext/Controllers/FilmWatchlistViewController.swift
//
// FilmWatchlistViewController.swift
// WhatsNext
//
// Created by <NAME> on 29/11/2020.
//
import Foundation
import UIKit
/// Custom cell for tableview of watchlist
class FilmCell: UITableViewCell {
@IBOutlet weak var posterImg: UIImageView!
@IBOutlet weak var titleLbl: UILabel!
@IBOutlet weak var yearLbl: UILabel!
}
/// View controller of watchlist
class FilmWatchlistViewController: UITableViewController, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
var films: [Film] = []
var filteredFilms: [Film]!
var currentFilm: Film?
let loadingIndicator = UIActivityIndicatorView(style: .large)
override func viewDidLoad() {
super.viewDidLoad()
loadingIndicator.center = view.center
view.addSubview(loadingIndicator)
searchBar.delegate = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let filmDetailViewController = segue.destination as! FilmDetailViewController
let indexPath = tableView.indexPathForSelectedRow
filmDetailViewController.film = self.filteredFilms[indexPath!.row]
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.fetchFilms()
filteredFilms = films
}
/// enables the use of a cancel button in the searchbar to close the keyboard and empty the filter
/// - Parameter searchBar: <#searchBar description#>
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = ""
searchBar.showsCancelButton = false
searchBar.endEditing(true)
filteredFilms = films
tableView.reloadData()
}
/// filter function for the search bar
/// - Parameters:
/// - searchBar: the searchbar
/// - searchText: the filter string
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchBar.showsCancelButton = true
if searchText == "" {
filteredFilms = films
tableView.reloadData()
return
}
filteredFilms = films.filter { (film: Film) -> Bool in
return film.titel.lowercased().contains(searchText.lowercased())
}
tableView.reloadData()
}
/// fetches films from api
func fetchFilms() {
loadingIndicator.startAnimating()
Network.shared.getWatchlist { [self] films in
self.films = films
self.filteredFilms = films
loadingIndicator.stopAnimating()
tableView.reloadData()
}
}
/// Renders a tablecell
/// - Parameters:
/// - tableView: the tableview
/// - indexPath: index in tableview
/// - Returns: The cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FilmCell", for: indexPath) as! FilmCell
let imageURL = URL(string: filteredFilms[indexPath.row].titleImage)!
DispatchQueue.global().async {
guard let imageData = try? Data(contentsOf: imageURL) else { return }
let image = UIImage(data: imageData)
DispatchQueue.main.async {
cell.posterImg.image = image
}
}
cell.titleLbl.text = filteredFilms[indexPath.row].titel
cell.yearLbl.text = String(filteredFilms[indexPath.row].year)
return cell
}
}
extension FilmWatchlistViewController {
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
currentFilm = filteredFilms[indexPath.row]
return indexPath
}
}
extension FilmWatchlistViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredFilms.count
}
}
<file_sep>/WhatsNext/Model/Network.swift
//
// AccountController.swift
// WhatsNext
//
// Created by <NAME> on 07/11/2020.
//
import Foundation
import Alamofire
/// incorperates networkrouter, logger, interceptor to provide api functionality
class Network {
let sessionManager: Session = {
let configuration = URLSessionConfiguration.af.default
configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
let responseCacher = ResponseCacher(behavior: .modify { _, response in
let userInfo = ["date": Date()]
return CachedURLResponse(
response: response.response,
data: response.data,
userInfo: userInfo,
storagePolicy: .notAllowed
)
})
let networkLogger = NetworkLogger()
let interceptor = AuthRequestInterceptor()
return Session(
configuration: configuration,
interceptor: interceptor,
cachedResponseHandler: responseCacher,
eventMonitors: [networkLogger])
}()
static let shared = Network()
let baseURL = URL(string: "http://192.168.1.37:45455/api/")!
func login(login: Login, completion: @escaping (Bool) -> Void) {
AF.request("http://192.168.1.37:45455/api/Account",
method: .post,
parameters: login,
encoder: JSONParameterEncoder.default).validate().responseString { [self] response in
switch response.result {
case .success(let data):
UserDefaults.standard.set(true, forKey: "isLoggedIn")
self.saveAccessCode(accessCode: data)
completion(true)
case .failure:
UserDefaults.standard.set(false, forKey: "isLoggedIn")
completion(false)
}
}
}
func register(register: Register, completion: @escaping (Bool) -> Void) {
AF.request("http://192.168.1.37:45455/api/Account/Register",
method: .post,
parameters: register,
encoder: JSONParameterEncoder.default).validate().responseString { [self] response in
switch response.result {
case .success(let data):
UserDefaults.standard.set(true, forKey: "isLoggedIn")
self.saveAccessCode(accessCode: data)
completion(true)
case .failure:
UserDefaults.standard.set(false, forKey: "isLoggedIn")
completion(false)
}
}
}
func saveAccessCode(accessCode: String) {
TokenManager.shared.saveAccessToken(authToken: accessCode)
}
func getFavouriteFilms(completion: @escaping ([Film]) -> Void) {
sessionManager.request(
NetworkRouter.fetchFavourites as URLRequestConvertible).validate().responseDecodable(of: [Film].self) { response in
guard let films = response.value
else {
return completion([])
}
completion(films)
}
}
func getWatchlist(completion: @escaping ([Film]) -> Void) {
sessionManager.request(
NetworkRouter.fetchWatchlist as
URLRequestConvertible).validate().responseDecodable(of: [Film].self) { response in
guard let films = response.value
else {
return completion([])
}
completion(films)
}
}
func getNextFilms(skip: Int, completion: @escaping ([Film]) -> Void) {
sessionManager.request(
NetworkRouter.getNextFilms(String(skip)) as
URLRequestConvertible).validate().responseDecodable(of: [Film].self) { response in
guard let films = response.value
else {
return completion([])
}
completion(films)
}
}
func addToWatchlist(id: String, completion: @escaping (Bool) -> Void) {
sessionManager.request(NetworkRouter.addToWatchlist(id) as URLRequestConvertible
).validate().response { response in
let result = response.result
switch result {
case .success:
completion(true)
case .failure:
completion(false)
}
}
}
func addToWatched(id: String, completion: @escaping (Bool) -> Void) {
sessionManager.request(NetworkRouter.addToWatched(id) as URLRequestConvertible
).validate().response { response in
let result = response.result
switch result {
case .success:
completion(true)
case .failure:
completion(false)
}
}
}
}
<file_sep>/Podfile
# Uncomment the next line to define a global platform for your project
platform :ios, '12.0'
target 'WhatsNext' do
use_frameworks!
pod 'Alamofire', '~> 5.2'
pod 'SwiftLint'
pod 'RAMAnimatedTabBarController'
target 'WhatsNextTests' do
inherit! :search_paths
# Pods for testing
end
target 'WhatsNextUITests' do
# Pods for testing
end
end
<file_sep>/WhatsNext/Model/Login.swift
//
// Login.swift
// WhatsNext
//
// Created by <NAME> on 07/11/2020.
//
import Foundation
/// struct to pass to login
struct Login: Encodable {
let email: String
let password: String
}
<file_sep>/WhatsNext/Model/Film.swift
//
// Film.swift
// WhatsNext
//
// Created by <NAME> on 07/11/2020.
//
import Foundation
/// struct for film
struct Film {
var id: Int
var titel: String
var regisseur: String
var year: Int
var score: Int
var titleImage: String
var runtime: Int
var description: String
enum CodingKeys: String, CodingKey {
case id
case titel
case regisseur
case year
case score
case titleImage
case runtime
case description
}
}
extension Film: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
titel = try container.decode(String.self, forKey: .titel)
regisseur = try container.decode(String.self, forKey: .regisseur)
year = try container.decode(Int.self, forKey: .year)
score = try container.decode(Int.self, forKey: .score)
titleImage = try container.decode(String.self, forKey: .titleImage)
runtime = try container.decode(Int.self, forKey: .runtime)
description = try container.decode(String.self, forKey: .description)
}
}
<file_sep>/README.md
# iOS WhatsNext app
### Movie recommentation app
## Table of contents
* [General info](#general-info)
* [Technologies](#technologies)
* [Setup](#setup)
* [Credentials for testing](#credentials)
### General info
This project was made for HoGent.
Native apps 2: iOS
### Technologies
Project is created with cacao
used pods:
* Alamofire
* SwiftLint
* RAMAnimatedTabBarController
### Setup
To run this project, clone project and:
```
$ cd ../iOS-whatsnext
$ pod install
```
Backend is at: https://github.com/remimestdagh/Movierecommendations-BE
### Credentials
- <EMAIL>
- <PASSWORD>
### Created & maintained by
<NAME>
<file_sep>/WhatsNext/Model/User.swift
//
// User.swift
// WhatsNext
//
// Created by <NAME> on 07/11/2020.
//
import Foundation
/// struct to store user information
struct User {
var username: String?
var password: String?
var token: String?
init(username: String?, password: String?, token: String? = nil) {
self.username = username
self.password = <PASSWORD>
self.token = token
}
}
<file_sep>/WhatsNext/Model/TokenManager.swift
import Foundation
class TokenManager {
let userAccount = "accessToken"
static let shared = TokenManager()
let secureStore: SecureStore = {
let accessTokenQueryable = GenericPasswordQueryable(service: "WhatsNext")
return SecureStore(secureStoreQueryable: accessTokenQueryable)
}()
/// saves accesstoken
/// - Parameter authToken: the token
func saveAccessToken(authToken: String) {
if authToken=="" {
UserDefaults.standard.set(false, forKey: "isLoggedIn")
} else {
UserDefaults.standard.set(true, forKey: "isLoggedIn")
}
do {
try secureStore.setValue(authToken, for: userAccount)
} catch let exception {
print("Error saving access token: \(exception)")
}
}
/// fetches accesstoken from storage
/// - Returns: the token
func fetchAccessToken() -> String? {
do {
return try secureStore.getValue(for: userAccount)
} catch let exception {
print("Error fetching access token: \(exception)")
}
return nil
}
/// removes access token
func clearAccessToken() {
do {
return try secureStore.removeValue(for: userAccount)
} catch let exception {
print("Error clearing access token: \(exception)")
}
}
}
<file_sep>/WhatsNext/Controllers/LoginViewController.swift
//
// LoginViewController.swift
// WhatsNext
//
// Created by <NAME> on 07/11/2020.
//
import UIKit
import Foundation
/// view controller for the login view
class LoginViewController: UIViewController, UITextFieldDelegate {
var registerActive: Bool = false
var labelActive: Bool = false
@IBOutlet weak var errorLabel: UILabel!
@IBOutlet weak var userNameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var needAccountButton: UIButton!
@IBOutlet weak var registerButton: UIButton!
@IBOutlet weak var confirmPasswordField: UITextField!
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
/// Provides network functionality
private var network: Network = Network()
override func viewDidLoad() {
super.viewDidLoad()
self.userNameField.delegate = self
self.passwordField.delegate = self
self.confirmPasswordField.delegate = self
self.firstNameTextField.delegate = self
self.lastNameTextField.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
registerButton.isHidden = true
confirmPasswordField.isHidden = true
firstNameTextField.isHidden = true
lastNameTextField.isHidden = true
errorLabel.isHidden = true
}
/// Listener to make sure keyboard closes when return is pressed on the keyboard
/// - Parameter textField: the textfield
/// - Returns: false
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
/// Listener for want to register button, shows more textfields when users need to register
/// - Parameter sender: sender
@IBAction func didTapNeedAccountButton(_ sender: Any) {
if registerActive {
registerButton.isHidden = true
confirmPasswordField.isHidden = true
firstNameTextField.isHidden = true
lastNameTextField.isHidden = true
loginButton.isHidden = false
registerActive = false
needAccountButton.setTitle("Need an account?", for: .normal)
} else {
registerButton.isHidden = false
confirmPasswordField.isHidden = false
firstNameTextField.isHidden = false
lastNameTextField.isHidden = false
loginButton.isHidden = true
registerActive = true
needAccountButton.setTitle("Already have an account?", for: .normal)
}
}
/// Listener for register button
/// - Parameter sender: sender
@IBAction func didTapRegisterButton(_ sender: Any) {
do {
try Validations.validate(username: firstNameTextField.text!)
try Validations.email(userNameField.text!)
try Validations.validate(username: lastNameTextField.text!)
try Validations.validatePassword(password: <PASSWORD>Field.text!, password2: <PASSWORD>PasswordField.text!)
} catch {
errorLabel.isHidden = false
errorLabel.text = error.localizedDescription
showPopup(isSuccess: false, optionalMessage: error.localizedDescription)
return
}
let register: Register = Register(email: userNameField.text!,
password: <PASSWORD>!, passwordConfirmation: <PASSWORD>.text!,
firstName: firstNameTextField.text!, lastName: lastNameTextField.text!
)
Network.shared.register(register: register) { isSuccess in
let loggedin = UserDefaults.standard.bool(forKey: "isLoggedIn")
if !loggedin {
self.showPopup(isSuccess: loggedin)
} else {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainTabBarController = storyboard.instantiateViewController(identifier: "MainTabBarController")
// This is to get the SceneDelegate object from your view controller
// then call the change root view controller function to change to main tab bar
(UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.changeRootViewController(mainTabBarController)
}
}
}
/// Listener for login button
/// - Parameter sender: object that sent it
@IBAction func didTapSignInButton(_ sender: Any) {
let login: Login = Login(email: userNameField.text!, password: <PASSWORD>!)
var loggedin = false
Network.shared.login(login: login) { isSuccess in
loggedin = UserDefaults.standard.bool(forKey: "isLoggedIn")
if !loggedin {
self.showPopup(isSuccess: loggedin, optionalMessage: login.email)
} else {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainTabBarController = storyboard.instantiateViewController(identifier: "MainTabBarController")
// This is to get the SceneDelegate object from your view controller
// then call the change root view controller function to change to main tab bar
(UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.changeRootViewController(mainTabBarController)
}
}
}
/// Shows popup message when something goes wrong during login
/// - Parameters:
/// - isSuccess: indicated whether the message will be an error or success message
/// - optionalMessage: custom message content
func showPopup(isSuccess: Bool, optionalMessage: String = "") {
let successMessage = "Congratulations! You logged in successully. Welcome, "+optionalMessage
let errorMessage = "Something went wrong. Please try again. "+optionalMessage
let alert = UIAlertController(title: isSuccess ? "Success": "Error",
message: isSuccess ? successMessage: errorMessage, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Done", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
<file_sep>/WhatsNext/Controllers/FilmTableViewController.swift
//
// FilmViewController.swift
// WhatsNext
//
// Created by <NAME> on 08/11/2020.
//
import Foundation
import UIKit
class FilmViewController: UITableViewController {
}
|
ffcc0598e43b0da986bba78836456028862bcd07
|
[
"Swift",
"Markdown",
"Ruby"
] | 22 |
Swift
|
remimestdagh/iOS-whatsnext
|
03bedafc5f2f1004fbd81c4e024441a58c3bc454
|
4c9a4151af9bff05e3d488c599b8d7705c71d342
|
refs/heads/master
|
<repo_name>gentleShark/MobileApp_SuiteCRM<file_sep>/android/settings.gradle
rootProject.name = 'CRM_Prospect'
include ':app'
<file_sep>/app/components/ProspectEditScreen/styles.js
import { StyleSheet } from 'react-native';
export const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "white",
},
headerWrapper: {
flex: 0.05,
justifyContent: 'center',
alignItems: 'center',
padding: 5,
},
bodyWrapper: {
flex: 0.6,
padding: 10,
},
buttonWrapper: {
flex: 0.05,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
paddingVertical: 20,
paddingHorizontal: 5,
},
input: {
flex: 1,
},
scroll: {
borderBottomWidth: 1,
borderTopWidth: 1,
borderColor: '#CCCC',
},
icon: {
height: 30,
width: 30,
backgroundColor: "#1F94B7",
},
});<file_sep>/app/layout/styles.js
import { StyleSheet } from 'react-native';
export const styles = StyleSheet.create({
mainStyle: {
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
padding: 10,
},
navigator: {
backgroundColor: '#1F94B7',
borderBottomWidth: 1,
},
fontNavBar: {
color: 'white',
fontSize: 20,
fontWeight: 'bold',
backgroundColor: "rgba(0,0,0,0)",
},
fontBasicDefault: {
color: 'black',
fontSize: 12,
backgroundColor: "white",
},
fontBasicMedium: {
color: 'black',
fontWeight: 'bold',
fontSize: 15,
backgroundColor: "white",
},
fontBasicBig: {
color: 'black',
fontSize: 20,
//fontWeight: 'bold',
backgroundColor: "white",
},
fontBasicNote: {
color: 'grey',
fontSize: 15,
backgroundColor: "white",
},
fontBasicError: {
color: 'red',
fontSize: 15,
backgroundColor: "white",
},
});<file_sep>/__tests__/components/ProspectListScreen/test.ProspectListScreen.jsx
import { ActivityIndicator, View } from 'react-native';
import React from 'react';
import { shallow } from 'enzyme';
import { ProspectListScreen } from '../../../app/components/ProspectListScreen/ProspectListScreen'
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
/* Mock for the default props of the component. */
var arg = {
state: {
params:{
item:null,
}
}
}
var prospectListMock = require('./prospectListMock.json');
var prospectUpdateMock = require('./prospectUpdateMock.json');
var newProspectMock = require('./newProspectMock.json');
var findProspectById = (prospect, idToMatch) => {
return prospect.name_value_list.id.value == idToMatch;
}
afterEach(() => {
// Reload the default configuration after each test.
prospectUpdateMock = require('./prospectUpdateMock.json');
});
describe('ProspectListScreen', () => {
it('renders without crashing', () => {
const tree = renderer.create(
<ProspectListScreen jest={{list: prospectListMock}} navigation={arg}/>
);
});
it('display the search list with the correct values', () => {
const tree = renderer.create(
<ProspectListScreen jest={{list: prospectListMock}} navigation={arg}/>
);
const instance = tree.getInstance();
const patternToSearch = "jean";
instance.setSearching(true);
instance.handleSearch(patternToSearch);
// Ensure that the prospectSearchList only contains the prospect with the word "jean" in their first_name/last_name.
expect(instance.state.prospectSearch.length).toBe(2);
expect(instance.state.prospectSearch[0].name_value_list.last_name.value + " " +
instance.state.prospectSearch[0].name_value_list.first_name.value).toBe("prospect 6 jean");
expect(instance.state.prospectSearch[1].name_value_list.last_name.value + " " +
instance.state.prospectSearch[1].name_value_list.first_name.value).toBe("<NAME> ");
});
it('update a prospect from the list', () => {
const tree = renderer.create(
<ProspectListScreen jest={{list: prospectListMock}} navigation={arg}/>
);
const instance = tree.getInstance();
instance.updateProspectList(prospectUpdateMock);
var updatedProspectIndex = instance.state.prospectList.findIndex((item) => findProspectById(item, prospectUpdateMock.id.value));
var updatedProspect = instance.state.prospectList[updatedProspectIndex].name_value_list;
// Ensure that the prospectList is updated with the corrects values.
for(key in prospectUpdateMock){
expect(prospectUpdateMock[key]).toEqual(updatedProspect[key])
}
});
it('add a prospect to the list', () => {
const tree = renderer.create(
<ProspectListScreen jest={{list: prospectListMock}} navigation={arg}/>
);
const instance = tree.getInstance();
var listSize = instance.state.prospectList.length;
instance.updateProspectList(newProspectMock);
// Ensure that the prospectList size has increased by one.
expect(instance.state.prospectList.length).toBe(listSize + 1);
var updatedProspectIndex = instance.state.prospectList.findIndex((item) => findProspectById(item, newProspectMock.id.value));
var updatedProspect = instance.state.prospectList[updatedProspectIndex].name_value_list;
// Ensure that the prospectList is updated with the corrects values.
for(key in newProspectMock){
expect(newProspectMock[key]).toEqual(updatedProspect[key])
}
});
it('delete a prospect from the list', () => {
const tree = renderer.create(
<ProspectListScreen jest={{list: prospectListMock}} navigation={arg}/>
);
const instance = tree.getInstance();
var listSize = instance.state.prospectList.length;
// Set the deletion flag.
prospectUpdateMock.deleted.value = 1;
instance.updateProspectList(prospectUpdateMock);
var updatedProspectIndex = instance.state.prospectList.findIndex((item) => findProspectById(item, prospectUpdateMock.id.value));
// Ensure that the prospectList is updated with the corrects values.
expect(instance.state.prospectList.length).toBe(listSize - 1);
expect(updatedProspectIndex).toBe(-1);
});
xit('Display an ActivityIndicator on fetching', () => {
const wrapper = shallow(
<ProspectListScreen jest={{list: prospectListMock}} navigation={arg}/>
);
const wrapperTmp = wrapper.setState({isFecthing: true});
wrapperTmp.instance().render();
const wrapperToTest = wrapperTmp.update();
console.log("HERE!!!!");
for(idx in wrapperToTest.nodes){
console.log(wrapperToTest.nodes[idx].type);
}
expect(wrapperTmp.contains(ActivityIndicator)).toBe(true);
});
});
describe('Snapshot testing', () => {
it('renders correctly', () => {
const tree = renderer.create(
<ProspectListScreen jest={{list: prospectListMock}} navigation={arg}/>
).toJSON();
expect(tree).toMatchSnapshot();
});
});
<file_sep>/__tests__/components/ProspectEditScreen/test.ProspectEditScreen.jsx
import 'react-native';
import React from 'react';
import { ProspectEditScreen } from '../../../app/components/ProspectEditScreen/ProspectEditScreen'
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
/* Mock for the default props of the component. */
var arg = {
state: {
params:{
item:null,
}
}
}
var prospectMock = require('./prospectMock.json');
afterEach(() => {
// Reload the default configuration after each test.
arg = {
state: {
params:{
item:null,
}
}
}
});
describe('ProspectEditScreen', () => {
it('renders without crashing', () => {
const tree = renderer.create(
<ProspectEditScreen navigation={arg}/>
);
});
it('renders without prospect infos', () => {
const tree = renderer.create(
<ProspectEditScreen navigation={arg}/>
);
const instance = tree.getInstance();
// Because the arg passed to the component doesn't have any item,
// we expect the state[key] of the instance to be set to null.
for (key in prospectMock.name_value_list) {
expect(instance.state[key]).toBeNull();
}
});
it('renders with prospect info', () => {
arg.state.params.item = prospectMock;
const tree = renderer.create(
<ProspectEditScreen navigation={arg}/>
);
const instance = tree.getInstance();
for (key in prospectMock.name_value_list) {
// If the value is set then we expect to find it in the component state.
if(prospectMock.name_value_list[key].value){
expect(instance.state[key]).toBe(prospectMock.name_value_list[key].value);
}
// Otherwise, the value should be set to null.
else {
expect(instance.state[key]).toBeNull();
}
}
});
it('is editable by default on creation of prospect', () => {
const tree = renderer.create(
<ProspectEditScreen navigation={arg}/>
);
const instance = tree.getInstance();
expect(instance.state.isEditable).toBeTruthy();
});
it('is not editable by default on consultation of prospect', () => {
arg.state.params.item = prospectMock;
const tree = renderer.create(
<ProspectEditScreen navigation={arg}/>
);
const instance = tree.getInstance();
expect(instance.state.isEditable).toBeFalsy();
});
});
describe('Snapshot testing', () => {
it('renders correctly', () => {
const tree = renderer.create(
<ProspectEditScreen navigation={arg}/>
).toJSON();
expect(tree).toMatchSnapshot();
});
});<file_sep>/app/components/LoginScreen/LoginScreen.js
import React, { Component } from 'react';
import { StackNavigator } from 'react-navigation';
import { Text, TextInput, Image, View, ScrollView, Button, ActivityIndicator, AsyncStorage, Keyboard } from 'react-native';
import { default as Icon } from 'react-native-vector-icons/MaterialCommunityIcons';
import { ThemeProvider, Checkbox } from 'react-native-material-ui';
import { styles as defaultStyles } from '../../layout/styles.js'
import { styles, images } from './index.js'
import * as constants from '../../config/const.js'
import { restCall } from '../../core/rest_api.js'
var DEBUG = false;
var MD5 = require("crypto-js/md5");
/**
* Author: <NAME> OUKEM
*
* Description: This is a React Native component which gives an UI to connect to a CRM server.
* It can give a feedback on a connection failure and it can remember the user login and the server IP
* accross application life cycle.
*
*/
export class LoginScreen extends Component {
constructor(props) {
super(props);
this.navigate = this.navigate.bind(this);
this.state={
status: '',
session: null,
isFetching: false,
ip: null,
login: null,
password: <PASSWORD>,
isChecked: false,
isKeyboardOpen: false,
};
}
navigate(screen){
var params = {
session: this.state.session,
ip: this.state.ip,
};
// Navigate to the given screen.
this.props.navigation.navigate(screen, params);
}
connect(){
this.setInfo(this.state.isChecked);
this.authentify(this.state.ip, this.state.login, MD5(this.state.password));
if(DEBUG){
console.log("(LoginScreen) parameters: ");
console.log("ip = " + this.state.ip);
console.log("login = " + this.state.login);
console.log("passwd = " + this.state.password);
console.log("(LoginScreen) credential (MD5): ");
console.log(MD5(this.state.password));
}
}
authentify(ip, login, password){
var credential = {"user_auth":{"user_name": login, "password": <PASSWORD>() }};
this.setState({isFetching: true});
var onSuccess = function(responseData){
// We received a response from the server.
this.setState({isFetching: false, session: responseData.id});
// Got a session.
if(this.state.session){
fc = this.navigate.bind(this);
fc(constants.listScreen);
}
// Wrong credential.
else {
this.setState({status: 'Mauvais identifiants', session: null});
}
}
var onFailure = function(error){
// No response from the server or an error.
this.setState({isFetching: false, status: "Serveur injoignable", session: null});
}
restCall("login", credential, this.state.ip, onSuccess.bind(this), onFailure.bind(this));
}
onCheckboxCheck(checked, value){
this.setState({isChecked: checked})
this.setInfo(checked);
}
/**
* Store/Delete the login and the server IP.
* If isSaving is true then the data are saved otherwise it is removed.
**/
async setInfo(isSaving){
try {
if(isSaving){
await AsyncStorage.setItem('ip', this.state.ip);
await AsyncStorage.setItem('login', this.state.login);
} else {
await AsyncStorage.removeItem('ip');
await AsyncStorage.removeItem('login');
}
} catch (error) {
console.log("AsyncStorage error: "+ error);
}
}
// Get the stored values of the server IP and login if there is any.
async getInfo(key){
try {
var value = await AsyncStorage.getItem(key);
return value;
} catch (error) {
console.log("AsyncStorage error: "+ error);
return null;
}
}
async componentWillMount(){
// Auto fill the input field if the user has checked the remind info checkbox.
var ip = await this.getInfo("ip");
var login = await this.getInfo("login");
this.setState({ip: ip ? ip : '', login: login ? login : '', isChecked: (ip || login) ? true : false});
// Add keyboard listener to hide the logo on show up.
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));
}
componentWillUnmount(){
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow(){
this.setState({isKeyboardOpen: true});
}
_keyboardDidHide(){
this.setState({isKeyboardOpen: false});
}
render() {
return (
<ThemeProvider uiTheme={constants.uiTheme}>
<View style={styles.container}>
{!this.state.isKeyboardOpen && // We dont display the logo when the keyboard is open
<View style={styles.logoWrapper}>
<Image source={images.logoExelcia} style={styles.logo} resizeMode="contain" />
</View>
}
<View style={styles.inputWrapper}>
<ScrollView>
{/* Server field*/}
<InputLabelRow icon='server-network' value={this.state.ip} placeholder="IP du serveur" isSecure={false}
onChangeText={(text) => this.setState({ip: text})} keyboardType='numeric'/>
{/* Login field*/}
<InputLabelRow icon='account-outline' value={this.state.login} placeholder="Nom d'utilisateur" isSecure={false}
onChangeText={(text) => this.setState({login: text})} />
{/* Password field*/}
<InputLabelRow icon='lock-outline' value={this.state.password} placeholder="<PASSWORD>" isSecure={true}
onChangeText={(text) => this.setState({password: text})} onSubmitEditing={() =>this.connect()}/>
<Checkbox style={{height:40}}value="ok" checked={this.state.isChecked} onCheck={this.onCheckboxCheck.bind(this)} label="Retenir le login et l'adresse du serveur" />
</ScrollView>
</View>
<View style={styles.statusWrapper}>
{this.state.isFetching &&
<ActivityIndicator style={styles.statusWrapper} size="large" /> ||
<Text style={defaultStyles.fontBasicError}> { this.state.status } </Text>
}
</View>
<View style={styles.buttonWrapper}>
<Button
onPress={() => this.connect()}
title="Connexion"
color={constants.uiTheme.palette.primaryColor}
disabled={this.state.isFetching}
/>
</View>
</View>
</ThemeProvider>
);
}
}
var InputLabelRow = React.createClass({
render() {
return (
<View style={styles.inputLineWrap}>
<View style={styles.iconWrap}>
<Icon name={this.props.icon} size={30}/>
</View>
<TextInput
keyboardType={this.props.keyboardType ? this.props.keyboardType : 'default'}
secureTextEntry={this.props.isSecure}
onChangeText={this.props.onChangeText}
onSubmitEditing={this.props.onSubmitEditing}
value={this.props.value}
placeholder={this.props.placeholder}
placeholderTextColor="#CCC"
style={styles.input}
/>
</View>
);
}
});<file_sep>/app/config/const.js
/**
* The default UI theme for the all application. It is used by most application components.
**/
export const uiTheme = {
palette: {
primaryColor: '#1F94B7', //'#1F94B7',
accentColor: '#07589A',
},
toolbar: {
container: {
height: 50,
},
},
};
/**
* This is the key for the navigation screens.
**/
export const loginScreen = "ProspectLoginScreen";
export const listScreen = "ProspectlistScreen";
export const editScreen = "ProspectEditScreen";
/**
* These keys must match the returned key from SuiteCRM REST API.
**/
export const id_key = "id";
export const last_name_key = "last_name";
export const first_name_key = "first_name";
export const title_key = "title";
export const department_key = "department";
export const account_name_key = "account_name";
export const work_phone_number_key = "phone_work";
export const mobile_phone_number_key = "phone_mobile";
export const website_key = "website";
export const email_key = "email1";
export const country_key = "primary_address_country";
export const street_key = "primary_address_street";
export const city_key = "primary_address_city";
export const postalcode_key = "primary_address_postalcode";
export const description_key = "description";
export const deleted_key = "deleted";
/**
* The palette of colors for the ProspectListScreen avatars.
**/
export var avatarColors = ["#e8d725", "#38579e", "#f9b6bf", "#ef64d8", "#c10f6e",
"#e57074", "#f9d1c0", "#2c55a3", "#611296", "#f22bcd", "#4a97ad", "#85f702",
"#f7a5a7", "#e4f7a0", "#81ef93", "#1cddb7", "#ea6267", "#91b7ff", "#91d613",
"#eac715", "#fcd292", "#a40bc6", "#ed38e4", "#605df7", "#c6008b", "#e0477d",
"#27dd95", "#d64f02", "#fc7bcf", "#f79283"];<file_sep>/app/components/ProspectListScreen/styles.js
import { StyleSheet } from 'react-native';
export const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "white",
},
headerWrapper: {
flex: 0.04,
justifyContent: 'center',
alignItems: 'flex-start',
padding: 10,
},
searchWrapper: {
flex: 1,
justifyContent: 'center',
alignItems: 'flex-start',
},
bodyWrapper: {
flex: 0.5,
paddingHorizontal: 5,
paddingVertical: 20,
},
activityIndicator: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
},
buttonWrapper: {
flex: 0.05,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
paddingHorizontal: 20,
paddingBottom: 20,
//backgroundColor: 'black',
},
scroll: {
borderBottomWidth: 2,
borderTopWidth: 2,
borderColor: '#CCCC',
},
icon: {
height: 30,
width: 30,
backgroundColor: "#1F94B7",
},
});<file_sep>/__tests__/components/LoginScreen/test.LoginScreen.jsx
import 'react-native';
import React from 'react';
import { LoginScreen } from '../../../app/components/LoginScreen/LoginScreen'
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
describe('LoginScreen', () => {
it('renders without crashing', () => {
const tree = renderer.create(
<LoginScreen />
);
});
});
describe('Snapshot testing', () => {
it('renders correctly', () => {
const tree = renderer.create(
<LoginScreen />
).toJSON();
expect(tree).toMatchSnapshot();
});
});<file_sep>/app/components/ProspectListScreen/ProspectListScreen.js
import React, { Component } from 'react';
import { Text, ScrollView, View, Button, FlatList, TouchableHighlight, ActivityIndicator } from 'react-native';
import { ThemeProvider, Toolbar, IconToggle, Avatar} from 'react-native-material-ui';
import { styles as defaultStyles } from '../../layout/styles.js'
import { styles, images } from './index.js'
import * as constants from '../../config/const.js'
import { restCall } from '../../core/rest_api.js'
var DEBUG = false;
/**
* Author: <NAME>
*
* Description: This is a React Native component which gives an UI to visualize a list of prospect
* fetched from a CRM server.
* It can give a feedback on a connection failure and it can remember the user login and the server IP
* accross application life cycle.
*
*/
export class ProspectListScreen extends Component {
// Hide the navigation bar since we use a Toolbar on this component.
static navigationOptions = {
header: null,
};
constructor(props) {
super(props);
this.state = { error: false, isFetching: false, flatListNeedUpdate: 1, isSearching: false, prospectList: [], prospectSearch: []};
this.navigate = this.navigate.bind(this);
this.reload = this.reload.bind(this);
this.logout = this.logout.bind(this);
this.setSearching = this.setSearching.bind(this);
}
/**
* Navigate to the given screen.
* item if set it is the prospect to consult/edit. Otherwise it mean it is a prospect creation (which it is by default).
**/
navigate(screen, item=null){
var params = {
session: this.props.navigation.state.params.session,
ip: this.props.navigation.state.params.ip,
item: item,
// This is the function that will be called on EditScreen before going back to this screen.
callback: this.updateProspectList.bind(this),
};
this.props.navigation.navigate(screen, params);
}
/**
* Use the info returned by the EditScreen to update the prospectList without refetching the database.
*/
updateProspectList(entry_list){
// Return the index in the list of the item to be updated.
var returnedItemID = entry_list["id"].value;
var itemIndex = this.state.prospectList.findIndex((obj) => {return obj.name_value_list.id.value == returnedItemID});
var item;
// It was a prospect creation since it doesn't exist in the list.
if(itemIndex === -1){
item = new Object();
item.name_value_list = new Object();
item.id = returnedItemID;
item.module_name = "Leads";
this.state.prospectList.push(item);
}
// It was a prospect update.
else {
item = this.state.prospectList[itemIndex];
}
// If the prospect has been deleted. It is removed from the list.
if(entry_list.deleted.value === 1 && itemIndex !== -1){
this.state.prospectList.splice(itemIndex, 1);
}
// Else we update the prospect data.
else {
for(key in entry_list){
if(DEBUG){
console.log("item.name_value_list["+key+"]="+item.name_value_list[key]);
}
item.name_value_list[key] = entry_list[key];
}
}
if(DEBUG){
console.log("List length = "+this.state.prospectList.length);
}
// If we are in search mode we need to redo the search since an item has changed.
if(this.state.isSearching){
this.handleSearch(this.toolbar.state.searchValue);
}
// Resort the list in case a name has changed.
this.state.prospectList.sort(this.alphabeticalSort);
// Usefull to re-render the flatList because it is a PureComponent.
this.setState({flatListNeedUpdate: (-this.state.flatListNeedUpdate)});
}
logout(){
var ip = this.props.navigation.state.params.ip;
var session = this.props.navigation.state.params.session;
var param = {session: session};
var paramJSON = JSON.stringify(param);
restCall("logout", paramJSON, ip, null, null);
this.props.navigation.goBack();
}
goToEdit(item){
this.navigate(constants.editScreen, item);
}
reload(){
this.fetchProspectList();
}
componentDidMount(){
// Usefull for jest test as we don't want to fetch data in Jest. TODO: find a way to mock the fetch function.
if(this.props.jest){
this.setState({prospectList: this.props.jest.list.entry_list});
} else {
this.fetchProspectList();
}
}
fetchProspectList(){
var ip = this.props.navigation.state.params.ip;
var session = this.props.navigation.state.params.session;
if(DEBUG){
console.log("(ListScreen) Session id received = " + session);
}
// Api request.
var params = {"session":session, "module_name":"Leads", "query":"", "order_by":"", "offset":0, "select_fields":
[constants.id_key, constants.last_name_key, constants.first_name_key, constants.title_key, constants.department_key, constants.account_name_key,
constants.email_key, constants.work_phone_number_key, constants.mobile_phone_number_key, constants.website_key, constants.country_key, constants.street_key,
constants.city_key, constants.postalcode_key, constants.description_key]
,"link_name_to_fields_array":[], "max_results":1000};
this.setState({isFetching: true});
var onSuccess = function(responseData){
// Set the state manually to sort before rendering.
this.state.prospectList = responseData.entry_list;
this.state.prospectList.sort(this.alphabeticalSort);
this.setState({isFetching: false});
}
var onFailure = function(error){
this.setState({isFetching: false, error: true});
}
restCall("get_entry_list", params, ip, onSuccess.bind(this), onFailure.bind(this));
}
alphabeticalSort(itemA, itemB){
if(!itemA.name_value_list[constants.last_name_key] || !itemB.name_value_list[constants.last_name_key]) return 0;
if(itemA.name_value_list[constants.last_name_key].value.toLowerCase() < itemB.name_value_list[constants.last_name_key].value.toLowerCase()) return -1;
if(itemA.name_value_list[constants.last_name_key].value.toLowerCase() > itemB.name_value_list[constants.last_name_key].value.toLowerCase()) return 1;
return 0;
}
handleSearch(pattern){
var results = new Array();
for(idx in this.state.prospectList){
var last_name = this.state.prospectList[idx].name_value_list[constants.last_name_key].value;
var first_name;
if(this.state.prospectList[idx].name_value_list[constants.first_name_key]){
first_name = this.state.prospectList[idx].name_value_list[constants.first_name_key].value;
}
// Add to the searchList items which includes in their last_name/first_name the searchPattern.
if(last_name.includes(pattern) || (first_name ? first_name.includes(pattern) : false)){
results.push(this.state.prospectList[idx]);
}
}
this.setState({flatListNeedUpdate: (-this.state.flatListNeedUpdate), prospectSearch: results});
}
setSearching(bool){
this.setState({isSearching: bool, prospectSearch: null});
}
render() {
return (
<ThemeProvider uiTheme={constants.uiTheme}>
<View style={styles.container}>
<Toolbar
ref={toolbarComponent => this.toolbar = toolbarComponent}
key="toolbar"
leftElement="exit-to-app"
onLeftElementPress={this.logout}
rightElement={<IconToggle name="cloud-download" color="white" onPress={this.reload} disabled={this.state.isFetching}/>}
centerElement="Liste des prospects"
searchable={{ autoFocus: true,
placeholder: 'Rechercher dans la liste',
onSearchPressed: () => this.setSearching(true),
onSearchClosed: () => this.setSearching(false),
onChangeText: (text) => this.handleSearch(text),
}}
/>
{/*Header Part*/}
<View style={styles.headerWrapper}>
{this.state.error &&
<Text style={defaultStyles.fontBasicError}>Erreur de réseau</Text> ||
<Text style={defaultStyles.fontBasicNote}>Selectionnez un prospect pour le modifier</Text>
}
</View>
{/*Body Part*/}
<View style={styles.bodyWrapper}>
{this.state.isFetching &&
<ActivityIndicator style={styles.activityIndicator} size="large" /> ||
<ScrollView style={styles.scroll}>
<FlatList
data={this.state.isSearching ? this.state.prospectSearch : this.state.prospectList}
keyExtractor={(item, index) => item.name_value_list.id.value}
extraData={this.state.flatListNeedUpdate}
renderItem={({item, index}) =>
<TouchableHighlight onPress={() => this.goToEdit(item)}>
<View style={{flexDirection: 'row', backgroundColor:(index % 2) ? '#f1f2f4' : '#e2e6e9', alignItems: 'center'}}>
<View style={{width: 50, padding: 5}}>
<Avatar
style={{container:{backgroundColor:constants.avatarColors[index%constants.avatarColors.length]}}}
text={item.name_value_list[constants.last_name_key].value.charAt(0).toUpperCase()}
size={40}
/>
</View>
<View>
<Text style={[defaultStyles.fontBasicBig, {backgroundColor:'rgba(0,0,0,0)'}]}>
{item.name_value_list[constants.last_name_key].value} {item.name_value_list[constants.first_name_key] ?
item.name_value_list[constants.first_name_key].value : ''}
</Text>
{item.name_value_list[constants.email_key] &&
<Text style={[defaultStyles.fontBasic, {backgroundColor:'rgba(0,0,0,0)'}]}>
{item.name_value_list[constants.email_key].value}
</Text>
}
</View>
</View>
</TouchableHighlight>
}
/>
</ScrollView>
}
</View>
{/*Button Part*/}
<View style={styles.buttonWrapper}>
<Button
onPress={() => this.navigate(constants.editScreen)}
title="Créer un nouveau prospect"
color={constants.uiTheme.palette.primaryColor}
disabled={this.state.isFetching}
/>
</View>
</View>
</ThemeProvider>
);
}
}
<file_sep>/README.md
# MobileApp_SuiteCRM
A cross plateform, mobile application used to connect to a SuiteCRM server and consult/modify/add/delete the Leads (Prospect in French).
It uses the React Native Framework for the logic/UI and Jest for the tests.
## Installation guide
First of all you will have to install NPM and React Native on your computer. Follow the instructions on [React Native official website](https://facebook.github.io/react-native/docs/getting-started.html).
Then you will have to clone the repository and download the dependencies of the project:
```
$ git clone http://github.com/jhoukem/MobileApp_SuiteCRM
$ cd MobileApp_SuiteCRM
$ npm update
```
Finally just run the app on your phone with this command:
`$ react-native run-android` (Android devices)
Refers to React Native documentation for iOS devices.
Of course in order to be used, this application need to connect to a [SuiteCRM server](https://suitecrm.com "SuiteCRM official website").
## Demo
<img src="https://cloud.githubusercontent.com/assets/9862039/26598392/18a7c14e-4543-11e7-9784-6564a3f21176.png" alt="Demo 1" height="512"/>
<img src="https://cloud.githubusercontent.com/assets/9862039/26405082/2b2a1dde-4062-11e7-8be7-89ea7c28cc96.png" alt="Demo 2" height="512"/>
<file_sep>/app/core/rest_api.js
const DEBUG = false;
export var restCall = function(method, parameters, url, functionOnSuccess, functionOnFailure){
var arg = 'method='+ method +'&input_type=JSON&response_type=JSON&rest_data=';
var dataToSend = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: arg.concat(JSON.stringify(parameters)),
}
if(DEBUG){
console.log("URL="+ url);
console.log("Data to send: ");
console.log(dataToSend);
}
// For production you may want to remove 'SuiteCRM' from the path.
// Here it is set because I use a Wampserver and you can have multiple website with wamp
// so you have to specify the folder.
fetch('http://'+ url +'/SuiteCRM/service/v3_1/rest.php', dataToSend)
.then((response) => response.json())
.then((responseData) => {
if(functionOnSuccess){
functionOnSuccess(responseData);
}
if(DEBUG){
console.log(responseData);
}
})
.catch((error) => {
if(functionOnFailure){
functionOnFailure(error);
}
console.log("Fetch error: " + error);
});
} <file_sep>/App.js
import React, { Component } from 'react';
import { StackNavigator } from 'react-navigation';
import { AppRegistry } from 'react-native';
import { LoginScreen } from './app/components/LoginScreen/LoginScreen.js'
import { ProspectListScreen } from './app/components/ProspectListScreen/ProspectListScreen.js'
import { ProspectEditScreen } from './app/components/ProspectEditScreen/ProspectEditScreen.js'
import * as constants from './app/config/const.js'
// The style options for the navigation Bar.
const options = {
navigationOptions: {
title: constants.applicationTitle,
headerStyle: {
backgroundColor: constants.uiTheme.palette.primaryColor,
height: constants.uiTheme.toolbar.container.height,
},
headerTitleStyle: {
color: 'white',
alignSelf: 'center',
},
}
};
// The object used to navigate in the App. Here we register all our screens.
const Navigator = StackNavigator({
[constants.loginScreen]: { screen: LoginScreen },
[constants.listScreen]: { screen: ProspectListScreen },
[constants.editScreen]: { screen: ProspectEditScreen },
},
options
);
class App extends Component {
render(){
return (
// Here the props set to null is to avoid logging navigation infos on screen transitions.
<Navigator onNavigationStateChange={null}/>
);
}
}
AppRegistry.registerComponent('CRM_Prospect', () => App);
|
b0ddc8f68128fb569a40919eeeb23fcd4924ed18
|
[
"Markdown",
"Gradle",
"JavaScript"
] | 13 |
Markdown
|
gentleShark/MobileApp_SuiteCRM
|
c4921c2be23ee9cb07c5178c11df27ca4b6afaa0
|
84a7353f0960b413c803ac080a1c6a73cc194dc2
|
refs/heads/main
|
<file_sep># VideoToText
This code is used to transcribe video data into txt file using speech recognition.
|
2f1c019e35099a0656b702cb84256baa6e01ab08
|
[
"Markdown"
] | 1 |
Markdown
|
SohamPatel712/VideoToText
|
9227f04afb6583c0f33f8d6b7e9401f78704cc54
|
bd9ce2a6f37a7de13763e3d2da0450e0985d2c85
|
refs/heads/master
|
<repo_name>DDSloan96/DroneIYFirmware<file_sep>/README.md
# DroneIYFirmware
Firmware/microcontroller component for DroneIY
|
b09a2b77f08a6642c63a2a822c8f1cd22a6ff8e8
|
[
"Markdown"
] | 1 |
Markdown
|
DDSloan96/DroneIYFirmware
|
b1251a82dbe5c9d97462dca3b7955aca64b06e5e
|
1afc3b0accca076123dbab7e0f93bd51c22116ed
|
refs/heads/master
|
<repo_name>vsk-coding/junkfiles<file_sep>/anchore.sh
docker-compose exec api anchore-cli image vuln vulnerables/phpldapadmin-remote-dump all > 1.log
docker-compose exec api anchore-cli image vuln vulnerables/web-owasp all > 2.log
docker-compose exec api anchore-cli image vuln vulnerables/web-dvwa all > 3.log
docker-compose exec api anchore-cli image vuln vulnerables/metasploit-vulnerability-emulator all > 4.log
docker-compose exec api anchore-cli image vuln vulnerables/web-owasp-railsgoat all > 5.log
docker-compose exec api anchore-cli image vuln vulnerables/cve-2017-7494 all > 6.log
docker-compose exec api anchore-cli image vuln vulnerables/mail-haraka-2.8.9-rce all > 7.log
docker-compose exec api anchore-cli image vuln vulnerables/cve-2014-6271 all > 8.log
docker-compose exec api anchore-cli image vuln vulnerables/cve-2014-0160 all > 9.log
docker-compose exec api anchore-cli image vuln vulnerables/cve-2016-6515 all > 10.log
docker-compose exec api anchore-cli image vuln vulnerables/cve-2016-4977 all > 11.log
docker-compose exec api anchore-cli image vuln vulnerables/cve-2016-10033 all > 12.log
docker-compose exec api anchore-cli image vuln vulnerables/web-roundcube-1.2.2-rce all > 13.log
docker-compose exec api anchore-cli image vuln vulnerables/cve-2016-7434 all > 14.log
docker-compose exec api anchore-cli image vuln vulnerables/web-owasp-phpgoat all > 15.log
docker-compose exec api anchore-cli image vuln vulnerables/web-owasp-nodegoat all > 16.log
docker-compose exec api anchore-cli image vuln vulnerables/web-owasp-mutillidae2 all > 17.log
docker-compose exec api anchore-cli image vuln vulnerables/web-bwapp all > 18.log
|
6fa1df29267a5d628da0690e6a35da93bf68b817
|
[
"Shell"
] | 1 |
Shell
|
vsk-coding/junkfiles
|
ad90cd473bc7da49419f5c89f944b637dd4bdcdb
|
6629dde57dbd5a175a10df479dd669b6c270b498
|
refs/heads/master
|
<repo_name>ecapital1/puppetcode<file_sep>/test/Puppetfile
mod "base",
:git => 'git://github.com:ecapital1/puppetcode.git'
<file_sep>/test/modules/base/init.pp
class base {
include base::snmp
}
<file_sep>/test/modules/base/snmp.pp
class base::snmp {
class { '::snmp':
agentaddress => ['udp:161'],
ro_community => hiera('snmp:community'),
}
}
|
c1e5d69b4154647c59a9a827e24c981a34e41c27
|
[
"Puppet",
"Ruby"
] | 3 |
Puppet
|
ecapital1/puppetcode
|
d85a8bbe3a5c4dbc937532e4f3447b48ccd2ae93
|
b654d92f78b1c58bb287b78e2c4cd52024bbe81c
|
refs/heads/master
|
<repo_name>MMarciante/Dense-Plasma-Data-Repo<file_sep>/README.md
# Dense-Plasma-Data-Repo
This repo contains various forms of data that characterize the physical properties of dense plasmas. The data source is either computational or experimental. The current data was obtained from published results, digitized and stored in CSV files.
Each file includes a header that describes its content and source.
We are also developing a Jupyter notebook for easy viewing of the database. An example Jupyter notebook is included here, but it is only here as a test; please don't try to use it!
|
695728a62d7a6b013c753aec67c1c660cc28a606
|
[
"Markdown"
] | 1 |
Markdown
|
MMarciante/Dense-Plasma-Data-Repo
|
79b45bf8aabc6b8ae57263b09b4a5d483bd3b02c
|
d9f6d4cb82d4bfbaadd3cf2cab8c69015db0e120
|
refs/heads/master
|
<repo_name>Hebertla/CST-100<file_sep>/README.md
# CST-100
Introduction to Java PRogramming
|
5821c69350cc3f334997cff5d2afa54cc6c74f56
|
[
"Markdown"
] | 1 |
Markdown
|
Hebertla/CST-100
|
c2d6393b90ec28ffeaded91dd9f851a45b2d95b1
|
f5e58b87d0ca33d61f99dac0bc839d592b9f815f
|
refs/heads/main
|
<repo_name>dthms/buoy<file_sep>/src/App.js
import React, { useState, useEffect } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { request } from 'graphql-request';
import Navigation from './components/Navigation';
import Footer from './components/Footer';
import Banner from './components/Banner'
import Home from './pages/Home';
import Changelog from './pages/Changelog';
import Docs from './pages/Docs';
import Document from './pages/Document';
function App() {
const [docs, setDocs] = useState(null);
// Get all docs
useEffect(() => {
const fetchDocs = async () => {
const { docs } = await request(
'https://api-eu-central-1.graphcms.com/v2/ckkvhq1szma5p01z090ux67pg/master',
`
{
docs {
id
shortDescription
documentTitle
article {
html
}
slug
}
}
`
)
setDocs(docs)
// console.log(docs)
}
fetchDocs()
}, []);
return (
<div className="antialiased">
<Banner />
<div className="max-w-container px-5 m-auto lg:px-10">
<BrowserRouter>
<Navigation />
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/changelog' component={Changelog} />
<Route exact path='/docs' component={Docs} />
{!docs ? ( 'Loading' ) : (
<Route path='/docs/:slug'>
<Document docs={docs} />
</Route>
)}
</Switch>
<Footer />
</BrowserRouter>
</div>
</div>
);
}
export default App;
<file_sep>/src/components/TitleSection.js
import React from "react"
import Wiggle from "../wiggle.svg";
function TitleSection(props) {
return (
<section className="mt-12 lg:mt-20 lg:px-20 relative">
<h1 className="w-3/5">{props.title}</h1>
<p className="xl mt-7 text-gray-600">{props.subtitle}</p>
<div className="w-full lg:w-36 mt-12 lg:mt-16 relative">
<div className="absolute py-1 -right-3 lg:-right-1 -top-3 rotate-12 transform px-2 bg-green-100 rounded-lg text-body-xs font-bold text-green-800 border border-green-300 shadow-sm">Save 50%</div>
<a href="https://onkickoff.myshopify.com/cart/37414900334755:1?channel=buy_button" target="_blank" className="py-3 px-8 text-center block text-white text-base font-semibold bg-purple-600 rounded-md lg:inline-block">{props.buttonOne}</a>
<a href="#">{props.buttonTwo}</a>
</div>
<img src={Wiggle} className="z-0 absolute -top-240 -right-176" />
</section>
)
}
export default TitleSection<file_sep>/src/pages/Home.js
import React, { Component } from 'react';
import TitleSection from "../components/TitleSection";
import Article from "../components/Article";
import Buy from "../components/Buy";
import Test from "../test.mp4"
class Home extends Component {
render() {
return (
<div className="space-y-20 lg:space-y-28">
<TitleSection
title="Utility first design system"
subtitle="A comprehensive design system built with implemention in mind. Buoy is an extremely scalable system built in Figma using Auto Layout V3 and Variants."
buttonOne="Buy Now"
/>
<div className="p-8 lg:p-20 rounded-lg text-center relative bg-gradient-to-r from-purple-400 via-red-300 to-alt-600">
<video autoplay="autoplay" loop muted className="rounded-md shadow-lg">
<source src={Test} type="video/mp4" />
</video>
</div>
<Article />
<Buy />
</div>
);
}
}
export default Home;<file_sep>/src/pages/Docs.js
import React from 'react';
import Navigation from '../components/NavigationDocs';
function Documents() {
return (
<div className="flex flex-row lg:px-20 lg:space-x-12">
<Navigation />
<div className="flex flex-grow w-full flex-col space-y-12">
<div className="space-y-4">
<h2>Getting started with Buoy</h2>
<p className="lg">Stop reinventing the wheel with Buoy - a comprehensive design system optimized for scalability, accessibility, and developers. Built in Figma using Auto Layout 3.0 and Variants.</p>
</div>
<h4>What's new</h4>
</div>
</div>
)
}
export default Documents;<file_sep>/src/components/Banner.js
import React from "react"
function Banner() {
return (
<section className="w-full bg-purple-200 py-4 space-x-3 text-purple-700 font-medium text-center text-sm relative z-10">
<span className="py-1 px-1.5 border border-green-300 shadow-sm bg-green-100 text-green-800 text-body-xs font-bold rounded-md">50% OFF</span>
<p className="inline-block">Become one of our first 100 early access adopters</p>
<a href="#scroll" className="text-body text-purple-600">Learn more</a>
</section>
)
}
export default Banner<file_sep>/src/pages/Changelog.js
import React, { Component } from 'react';
class Changelog extends Component {
render() {
return (
<div>
<h2>Changelog</h2>
</div>
);
}
}
export default Changelog;<file_sep>/src/components/Article.js
import React from "react"
import Dan from "../dan.png";
export default function Article() {
return (
<section id="scroll" className="lg:px-20 space-y-10">
<p className="lg">
I’m in the process of building Buoy. I’ve opened up
early access so you can help support the project and
gain access to the growing system. This is my progress
so far...
</p>
<p className="lg">
Version 1.0.0 will contain all of the above and likely more.
Every component will have comprehesive documention on this
website and in Figma. Finally, I’ll also be building live
previews of each component in React, these will be used
in the documention to help illustrate how states work etc.
</p>
<p className="lg">
The current version is 0.0.1, you can view my release
plan on the changelog page.
</p>
<p className="lg">
Thanks for checking in,
</p>
<img className="inline w-1/3 lg:w-1/5" src={Dan} />
</section>
)
}<file_sep>/src/pages/Document.js
import React from 'react';
import { useParams } from 'react-router-dom';
import "../styles/doc.css";
import Navigation from '../components/NavigationDocs';
function Document({ docs }) {
let { slug } = useParams();
const item = docs.find((item) => item.slug === slug)
console.log(item)
return (
<div className="flex flex-row lg:px-20 lg:space-x-12">
<Navigation />
<div className="flex flex-grow w-full flex-col">
<div className="space-y-4">
<h2>{item.documentTitle}</h2>
<p className="lg">{item.shortDescription}</p>
</div>
{!item ? ( 'Loading' ) : (
<div className="doc" dangerouslySetInnerHTML={{ __html: item.article.html }}></div>
)}
</div>
</div>
)
}
export default Document;
|
b07a5157a0fdb95e8b1e4da0957e05bfe8d268e8
|
[
"JavaScript"
] | 8 |
JavaScript
|
dthms/buoy
|
1935128eacc1ece65addabc1ef0c56518bb618a1
|
7e6d298b46aeb6e77bcb574d816b727e3a9f099f
|
refs/heads/master
|
<repo_name>Financehub/FinRepo<file_sep>/financehub/src/main/webapp/js/clickatell.js
/*
* 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.
*/
function changeCase(element)
{
var oldValue = element.value;
var newValue = oldValue.charAt(0).toUpperCase() + oldValue.substring(1);
element.value = newValue;
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://platform.clickatell.com/messages/http/send?apiKey=<KEY>&to=27787579660&content=", true);
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4 && xhr.status === 200)
{
console.log('success')
}
};
xhr.send();
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/entity/AmountBracket.java
package za.co.obeytrix.financehub.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "AmountBracket")
public class AmountBracket {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int amountBracketId;
private String amountBracketString;
public AmountBracket() {
}
public AmountBracket(int amountBracketId, String amountBracketString) {
this.amountBracketId = amountBracketId;
this.amountBracketString = amountBracketString;
}
public int getAmountBracketId() {
return amountBracketId;
}
public void setAmountBracketId(int amountBracketId) {
this.amountBracketId = amountBracketId;
}
public String getAmountBracketString() {
return amountBracketString;
}
public void setAmountBracketString(String amountBracketString) {
this.amountBracketString = amountBracketString;
}
@Override
public String toString() {
return "AmountBracket [amountBracketId=" + amountBracketId + ", amountBracketString=" + amountBracketString
+ "]";
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/fianancehub/utility/ProvinceNames.java
package za.co.obeytrix.fianancehub.utility;
public enum ProvinceNames {
EASTERN_CAPE("Eastern Cape"),
FREE_STATE("Free State"),
GAUTENG("Gauteng"),
KZN("KZN"),
LIMPOPO("Limpopo"),
MPUMALANGA("Mpumalanga"),
NORTH_WEST("North West"),
NORTHERN_CAPE("Northern Cape"),
WESTERN_PROVINCE("Western Cape");
private String name;
public String getName() {
return name;
}
ProvinceNames(String name) {
this.name = name;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/persistence/maps/PurposeForFinanceHolder.java
package za.co.obeytrix.financehub.persistence.maps;
public class PurposeForFinanceHolder {
private String purpose_for_finance_id;
private String purpose_description;
public String getPurpose_for_finance_id() {
return purpose_for_finance_id;
}
public void setPurpose_for_finance_id(String purpose_for_finance_id) {
this.purpose_for_finance_id = purpose_for_finance_id;
}
public String getPurpose_description() {
return purpose_description;
}
public void setPurpose_description(String purpose_description) {
this.purpose_description = purpose_description;
}
@Override
public String toString() {
return "PurposeForFinanceHolder{" + "purpose_for_finance_id=" + purpose_for_finance_id + ", purpose_description=" + purpose_description + '}';
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/persistence/maps/ProvincialScopeHolder.java
package za.co.obeytrix.financehub.persistence.maps;
public class ProvincialScopeHolder {
private String provincial_scope_id;
private String provinces;
public String getProvincial_scope_id() {
return provincial_scope_id;
}
public void setProvincial_scope_id(String provincial_scope_id) {
this.provincial_scope_id = provincial_scope_id;
}
public String getProvinces() {
return provinces;
}
public void setProvinces(String provinces) {
this.provinces = provinces;
}
@Override
public String toString() {
return "ProvincialScopeHolder [provincial_scope_id=" + provincial_scope_id + ", provinces=" + provinces + "]";
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrixsa/web/navigation/UserTypeValueChangeListener.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrixsa.web.navigation;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;
import za.co.obeytrixsa.web.views.RegistrationView;
/**
*
* @author Kobedi.Makgabutlane
*/
public class UserTypeValueChangeListener implements ValueChangeListener
{
private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(RegistrationView.class);
@Override
public void processValueChange(ValueChangeEvent event) throws AbortProcessingException
{
LOGGER.info("onselect " + event.getNewValue().toString() );
RegistrationView reg = (RegistrationView) FacesContext.getCurrentInstance().
getExternalContext().getSessionMap().get("registrationFormView");
reg.setUserType(event.getNewValue().toString());
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/beans/Registration.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.beans;
/**
*
* @author kobedi.makgabutlane
*/
public class Registration {
private Integer businessId;
private String businessName;
private String businessOwner;
private String businessRegistrationNumber;
private String businessRegistationDate;
private String operationDuration;
private String businessType;
private String createDate;
private String turnOver;
public Registration(Integer businessId,String businessName, String businessOwner, String businessRegistrationNumber, String operationDuration) {
this.businessId = businessId;
this.businessName = businessName;
this.businessOwner = businessOwner;
this.businessRegistrationNumber = businessRegistrationNumber;
this.operationDuration = operationDuration;
}
public Registration(Integer businessId, String businessName, String businessRegistrationNumber, String businessType) {
this.businessId = businessId;
this.businessName = businessName;
this.businessRegistrationNumber = businessRegistrationNumber;
this.businessType = businessType;
}
public Registration(Integer businessId, String businessName, String businessRegistrationNumber, String businessType, String createDate, String turnOver) {
this.businessId = businessId;
this.businessName = businessName;
this.businessRegistrationNumber = businessRegistrationNumber;
this.businessType = businessType;
this.createDate = createDate;
this.turnOver = turnOver;
}
public String getTurnOver() {
return turnOver;
}
public void setTurnOver(String turnOver) {
this.turnOver = turnOver;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
public String getBusinessType() {
return businessType;
}
public void setBusinessType(String businessType) {
this.businessType = businessType;
}
public Registration(){}
public Integer getBusinessId() {
return businessId;
}
public void setBusinessId(Integer businessId) {
this.businessId = businessId;
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public String getBusinessOwner() {
return businessOwner;
}
public void setBusinessOwner(String businessOwner) {
this.businessOwner = businessOwner;
}
public String getBusinessRegistrationNumber() {
return businessRegistrationNumber;
}
public void setBusinessRegistrationNumber(String businessRegistrationNumber) {
this.businessRegistrationNumber = businessRegistrationNumber;
}
public String getBusinessRegistationDate() {
return businessRegistationDate;
}
public void setBusinessRegistationDate(String businessRegistationDate) {
this.businessRegistationDate = businessRegistationDate;
}
public String getOperationDuration() {
return operationDuration;
}
public void setOperationDuration(String operationDuration) {
this.operationDuration = operationDuration;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrixsa/collection/persistence/application/initialization/CollectionApplicationContextListener.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrixsa.collection.persistence.application.initialization;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import za.co.obeytrix.financehub.dao.ApplicationDAO;
import za.co.obeytrix.financehub.dao.TableCreator;
import za.co.obeytrix.financehub.domain.ModalParameterCollection;
import za.co.obeytrix.financehub.entity.Funding;
import za.co.obeytrix.financehub.entity.Registration;
import za.co.obeytrix.financehub.entity.Role;
import za.co.obeytrix.financehub.persistence.maps.FunderHolder;
import za.co.obeytrix.financehub.persistence.maps.FunderMap;
import za.co.obeytrix.financehub.persistence.maps.TransactionalUser;
import za.co.obeytrixsa.web.views.RegistrationView;
/**
*
* @author Kobedi.Makgabutlane
*/
public class CollectionApplicationContextListener implements ServletContextListener {
private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(CollectionApplicationContextListener.class);
public static int DATA_SOURCE = -1;
private boolean isCollectionPersistenceEnabled(ServletContext sc)
{
String persistenceType;
persistenceType = sc.getInitParameter("PersistenceTypeEnabled");
return persistenceType!=null && persistenceType.equalsIgnoreCase("true");
}
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
boolean isCollectionTypePersistence = isCollectionPersistenceEnabled(sc);
ConcurrentMap<String, Funding> appliedProductsMap = new ConcurrentHashMap<String, Funding>();
ConcurrentMap< String, TransactionalUser> registrationData = new ConcurrentHashMap<String, TransactionalUser>();
if(isCollectionTypePersistence)
{
FunderMap instance = FunderMap.getInstance();
if(instance!=null)
{
ConcurrentMap<String, FunderHolder> fundingHolderMap = FunderMap.getFundingHolderMap();
System.out.println("Pushing referen to context application");
sc.setAttribute("FunderMapInstance", instance);
sc.setAttribute("appliedForProducts", appliedProductsMap);
sc.setAttribute("isCollectionTypePersistence", isCollectionTypePersistence);
sc.setAttribute("registrationData", registrationData);
}
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
sc.setAttribute("FunderMapInstance", null);
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/entity/FinanceAmount.java
package za.co.obeytrix.financehub.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class FinanceAmount {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int amountId;
private String amount;
public FinanceAmount() {
}
public int getAmountId() {
return amountId;
}
public void setAmountId(int amountId) {
this.amountId = amountId;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
@Override
public String toString() {
return "FinanceAmount [amountId=" + amountId + ", amount=" + amount + "]";
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/dao/ProductDao.java
package za.co.obeytrix.financehub.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import org.apache.log4j.Logger;
import za.co.obeytrix.financehub.entity.Address;
import za.co.obeytrix.financehub.entity.BusinessSector;
import za.co.obeytrix.financehub.entity.BusinessSectors;
import za.co.obeytrix.financehub.entity.ContactDetails;
import za.co.obeytrix.financehub.entity.EnterpriseOwnership;
import za.co.obeytrix.financehub.entity.FinanceProduct;
import za.co.obeytrix.financehub.entity.Funder;
import za.co.obeytrix.financehub.entity.FunderType;
import za.co.obeytrix.financehub.entity.ProductScope;
import za.co.obeytrix.financehub.entity.PurposeForFinance;
import za.co.obeytrix.financehub.entity.TurnoverBracket;
public class ProductDao {
private static Logger logger = Logger.getLogger(ProductDao.class);
private static EntityManager em;
public ProductDao() {
setUpEntityManager();
}
public ProductDao(boolean noDBConnection) {
if(noDBConnection)
setUpEntityManager();
}
private void setUpEntityManager() {
try {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("FinancehubPU");
em = emf.createEntityManager();
} catch (Exception e) {
logger.error("Entity manager setup in ProductDao failed due to : " + e);
e.printStackTrace();
}
}
public int persistAddress(Address address) {
em.getTransaction().begin();
em.persist(address);
em.getTransaction().commit();
return address.getAddressId();
}
public void persistProduct(FinanceProduct product) {
em.getTransaction().begin();
em.persist(product);
em.getTransaction().commit();
}
public void persistFunder(Funder funder) {
em.getTransaction().begin();
em.persist(funder);
em.getTransaction().commit();
}
public List<FinanceProduct> getAllProducts() {
TypedQuery<FinanceProduct> query = em.createQuery("SELECT p FROM Product p ORDER BY p.name", FinanceProduct.class);
return query.getResultList();
}
public FinanceProduct getProductByName(String productName) {
TypedQuery<FinanceProduct> query = em.createQuery("SELECT p FROM FinanceProduct p WHERE p.productName = '" + productName + "'", FinanceProduct.class);
if (query.getResultList().size() != 0) {
return query.getResultList().get(0);
} else {
return null;
}
}
public FinanceProduct getProductByNameAndFunder(String productName, String funderName) {
if(getFunderByName(funderName) == null) {
return null;
} else {
Funder funder = getFunderByName(funderName);
TypedQuery<FinanceProduct> query = em.createQuery("SELECT p FROM FinanceProduct p WHERE p.productName = '" + productName
+ "' AND p.funder.funderId = " + funder.getFunderId() , FinanceProduct.class);
if (query.getResultList().size() != 0) {
return query.getResultList().get(0);
} else {
return null;
}
}
}
/* public List<FinanceProduct> getProductsByPreliminarySearch(PreliminarySearch preliminarySearch) {
TypedQuery<FinanceProduct> query = em.createQuery("SELECT p FROM FinanceProduct p WHERE "
+ "JSON_SEARCH(searchString, 'all', '" + preliminarySearch.getFinanceAmount() + "') IS NOT NULL"
+ " AND JSON_SEARCH(searchString, 'all', '" + preliminarySearch.getAnnualTurnover() + "') IS NOT NULL"
+ " AND JSON_SEARCH(searchString, 'all', '" + (preliminarySearch.getBusinessSector().equals("Other") ? "No sector specified" : preliminarySearch.getBusinessSector()) + "') IS NOT NULL"
+ " AND JSON_SEARCH(searchString, 'all', '" + (preliminarySearch.getEnterpriseOwnership().equals("Other") ? "No ownership specified" : preliminarySearch.getEnterpriseOwnership()) + "') IS NOT NULL"
+ " AND JSON_SEARCH(searchString, 'all', '" + (preliminarySearch.getEnterpriseSize().equals("Other") ? "No size specified" : preliminarySearch.getEnterpriseSize()) + "') IS NOT NULL"
+ " AND JSON_SEARCH(searchString, 'all', '" + (preliminarySearch.getFinancePurpose().equals("Other") ? "No purpose specified" : preliminarySearch.getFinancePurpose()) + "') IS NOT NULL", FinanceProduct.class);
return query.getResultList();
}*/
public List<FunderType> getAllFunderTypes() {
TypedQuery<FunderType> query = em.createQuery("SELECT f FROM FunderType f ORDER BY f.funderTypeName",
FunderType.class);
return query.getResultList();
}
public List<ProductScope> getAllProductScopes() {
TypedQuery<ProductScope> query = em.createQuery("SELECT p FROM ProductScope p ORDER BY p.productScope",
ProductScope.class);
return query.getResultList();
}
public Funder getFunderByName(String name) {
TypedQuery<Funder> query = em.createQuery("SELECT f FROM Funder f WHERE f.funderName = '" + name + "'",
Funder.class);
if (query.getResultList().size() != 0) {
return query.getResultList().get(0);
} else {
return null;
}
}
public FunderType getFunderTypeByName(String name) {
TypedQuery<FunderType> query = em
.createQuery("SELECT t FROM FunderType t WHERE t.funderTypeName = '" + name + "'", FunderType.class);
if (query.getResultList().size() != 0) {
return query.getResultList().get(0);
} else {
return null;
}
}
public ProductScope getScopeByName(String prodScope) {
TypedQuery<ProductScope> query = em.createQuery("SELECT s FROM ProductScope s WHERE s.productScope = '" + prodScope + "'", ProductScope.class);
if (query.getResultList().size() != 0) {
return query.getResultList().get(0);
} else {
return null;
}
}
public Address getAddressById(int id) {
TypedQuery<Address> query = em.createQuery("SELECT a FROM Address a WHERE a.addressId = " + id + "", Address.class);
if (query.getResultList().size() != 0) {
return query.getResultList().get(0);
} else {
return null;
}
}
public ContactDetails getContactDetailsById(int id) {
TypedQuery<ContactDetails> query = em.createQuery("SELECT c FROM ContactDetails c WHERE c.contactDetailsId = " + id + "", ContactDetails.class);
if (query.getResultList().size() != 0) {
return query.getResultList().get(0);
} else {
return null;
}
}
/*
public List<AmountBracket> getAllFinanceAmountCatagories() {
TypedQuery<AmountBracket> query = em.createQuery("SELECT a FROM AmountBracket a ORDER BY a.amountBracketId", AmountBracket.class);
return query.getResultList();
}
*/
public List<EnterpriseOwnership> getAllEnterpriseOwnershipCatagories() {
TypedQuery<EnterpriseOwnership> query = em.createQuery("SELECT e FROM EnterpriseOwnership e ORDER BY e.enterpriseOwnershipId", EnterpriseOwnership.class);
return query.getResultList();
}
public List<PurposeForFinance> getFinancePurposes() {
TypedQuery<PurposeForFinance> query = em.createQuery("SELECT p FROM PurposeForFinance p ORDER BY p.financePurposeId", PurposeForFinance.class);
return query.getResultList();
}
public List<TurnoverBracket> getTurnoverCategories() {
TypedQuery<TurnoverBracket> query = em.createQuery("SELECT t FROM TurnoverBracket t ORDER BY t.turnOverBracketId", TurnoverBracket.class);
return query.getResultList();
}
/* public List<EnterpriseSize> getEnterpriseSizeCategories() {
TypedQuery<EnterpriseSize> query = em.createQuery("SELECT e FROM EnterpriseSize e ORDER BY e.enterpriseSizeId", EnterpriseSize.class);
return query.getResultList();
}
*/
public List<BusinessSectors> getAllBusinessSectors() {
TypedQuery<BusinessSectors> query = em.createQuery("SELECT bs FROM BusinessSectors bs ", BusinessSectors.class);
return query.getResultList();
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/dao/ApplicationDAO.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.dao;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.apache.log4j.Logger;
import za.co.obeytrix.financehub.entity.Address;
import za.co.obeytrix.financehub.entity.BusinessOwner;
import za.co.obeytrix.financehub.entity.FinanceApplication;
import za.co.obeytrix.financehub.entity.FinanceProduct;
import za.co.obeytrix.financehub.entity.FinancehubApplication;
import za.co.obeytrix.financehub.entity.FinancehubBusinessOwner;
import za.co.obeytrix.financehub.entity.FinancehubProductApplication;
import za.co.obeytrix.financehub.entity.FinancehubRole;
import za.co.obeytrix.financehub.entity.FinancehubUser;
import za.co.obeytrix.financehub.entity.Funding;
import za.co.obeytrix.financehub.entity.Registration;
import za.co.obeytrix.financehub.entity.User;
import za.co.obeytrix.financehub.entity.Role;
/**
*
* @author Kobedi.Makgabutlane
*/
public class ApplicationDAO {
private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(ApplicationDAO.class);
private static Logger logger = Logger.getLogger(ProductDao.class);
private static EntityManager em;
private static String peristenceUnitName;
public static ApplicationDAO appDAO = new ApplicationDAO();
public static ApplicationDAO getInstance() {
return appDAO;
}
private ApplicationDAO() {
}
public static EntityManager getEm() {
return em;
}
public static void setEm(EntityManager em) {
ApplicationDAO.em = em;
}
public int persistFinanceApplicationProduct(FinancehubProductApplication fappProduct) {
em.getTransaction().begin();
em.persist(fappProduct);
em.getTransaction().commit();
return fappProduct.getFinanceApplicationId();
}
public int persistFHRole(FinancehubRole role) {
em.getTransaction().begin();
em.persist(role);
em.getTransaction().commit();
return role.getRoleId();
}
public int persistFHUser(FinancehubUser user) {
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();
return user.getUserId();
}
public FinancehubUser getFinancehubUser(String email) {
TypedQuery<FinancehubUser> query = em.createQuery("FROM FinancehubUser u where u.email=:email", FinancehubUser.class);
query.setParameter("email", email);
return query.getSingleResult();
}
public int persistRegistration(Registration registration) {
em.getTransaction().begin();
em.persist(registration);
em.getTransaction().commit();
return registration.getRegId();
}
public int persistUser(User user) {
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();
return user.getUserId();
}
public int persistFinanceApplication(FinanceApplication fa) {
em.getTransaction().begin();
em.persist(fa);
em.getTransaction().commit();
return fa.getFinanceApplicationId();
}
public int persistRole(Role role) {
em.getTransaction().begin();
em.persist(role);
em.getTransaction().commit();
return role.getRoleId();
}
public List<Address> getAllAddress() {
TypedQuery<Address> query = em.createQuery("SELECT p FROM Address p", Address.class);
return query.getResultList();
}
public List<FinancehubProductApplication> getAllFinProductApplications(Integer userId) {
TypedQuery<FinancehubProductApplication> query = em.createQuery("FROM FinancehubProductApplication p "
+ "where p.user=:userId", FinancehubProductApplication.class);
query.setParameter("userId", userId);
return query.getResultList();
}
public List<FinancehubProductApplication> getAllFinProductApplications() {
TypedQuery<FinancehubProductApplication> query = em.createQuery("SELECT p FROM FinancehubProductApplication p", FinancehubProductApplication.class);
return query.getResultList();
}
public List<FinanceApplication> getAllFinApplications() {
TypedQuery<FinanceApplication> query = em.createQuery("SELECT p FROM FinanceApplication p", FinanceApplication.class);
return query.getResultList();
}
public Integer processApplication(Integer id)
{
int result=-1;
Query query = em.createQuery("UPDATE FinancehubApplication p set p.processed='Processed',p.applicationStatus='Processed'"
+ " where p.financeApplicationId=:id");
query.setParameter("id", id);
em.getTransaction().begin();
result = query.executeUpdate();
em.getTransaction().commit();
return result;
}
public List<FinanceApplication> getAllUserFinApplications(Integer regId) {
TypedQuery<FinanceApplication> query = em.createQuery("FROM FinanceApplication p where p.regId=:regId", FinanceApplication.class);
query.setParameter("regId", regId);
return query.getResultList();
}
public List<FinancehubApplication> getUserFinApplicationsByUserId(Integer userId) {
TypedQuery<FinancehubApplication> query = em.createQuery("FROM FinancehubApplication p where p.userId=:userId", FinancehubApplication.class);
query.setParameter("userId", userId);
return query.getResultList();
}
public List<FinancehubApplication> getUserFinApplicationsByOrgId(Integer orgId) {
TypedQuery<FinancehubApplication> query = em.createQuery("FROM FinancehubApplication p where p.instId=:orgId", FinancehubApplication.class);
query.setParameter("orgId", orgId);
return query.getResultList();
}
public List<FinancehubApplication> getUserProcessedFinApplicationsByOrgId(Integer orgId) {
TypedQuery<FinancehubApplication> query = em.createQuery("FROM FinancehubApplication p where p.processed=:processed and p.instId=:orgId", FinancehubApplication.class);
query.setParameter("orgId", orgId);
query.setParameter("processed", "Processed");
return query.getResultList();
}
public User getRegistrationIdForUser(Integer id) {
TypedQuery<User> query = em.createQuery("FROM User u where u.userId=:id", User.class);
query.setParameter("id", id);
return query.getSingleResult();
}
public Integer getUserRegistrationNumber(Integer id) {
int registrationId = -1;
User user = getRegistrationIdForUser(id);
if (user != null) {
return user.getRegId();
}
return registrationId;
}
public List<BusinessOwner> getAllBusinessOwners() {
TypedQuery<BusinessOwner> query = em.createQuery("SELECT p FROM BusinessOwner p", BusinessOwner.class);
return query.getResultList();
}
public List<Registration> getAllRegistrations() {
TypedQuery<Registration> query = em.createQuery("SELECT p FROM Registration p", Registration.class);
return query.getResultList();
}
public List<User> getAllUsers() {
TypedQuery<User> query = em.createQuery("SELECT p FROM User p", User.class);
return query.getResultList();
}
public List<Role> getAllRoles() {
TypedQuery<Role> query = em.createQuery("SELECT p FROM Role p", Role.class);
return query.getResultList();
}
public List<Object> getAllATables() {
TypedQuery<Object> query = em.createQuery("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE()", Object.class);
return query.getResultList();
}
public List<Funding> getAllFunding() {
TypedQuery<Funding> query = em.createQuery("SELECT p FROM Funding p", Funding.class);
return query.getResultList();
}
public void populateRoleTable(List<Role> roles) {
em.getTransaction().begin();
for (Role role : roles) {
em.persist(role);
}
em.getTransaction().commit();
}
public static void main(String[] arg) {
String pu = "FinancehubPU";
ApplicationDAO dao = getInstance();
EntityManager ems = dao.createEM(pu);
ApplicationDAO.setEm(ems);
List<Role> roles = new ArrayList<>();
Role role1 = new Role();
role1.setRoleName("FhubUser");
role1.setRoleDescription("Financehub User");
roles.add(role1);
Role role2 = new Role();
role2.setRoleName("FinAdmin");
role2.setRoleDescription("Finance Institution Officer");
roles.add(role2);
Role role3 = new Role();
role3.setRoleName("RegAdmin");
role3.setRoleDescription("Regulator Administration");
roles.add(role3);
Role role4 = new Role();
role4.setRoleName("DataCapturerAdmin");
role4.setRoleDescription("BASA Data Capture Admin");
roles.add(role4);
//dao.populateRoleTable(roles);
//User user = new User();
//user.setRoleId(1);//Set to System Administrator
//dao.persistUser(user);
//Role role = new Role();
//role.setRoleName("WebAdmin");
//role.setRoleDescription("Content Web Master");
//dao.persistRole(role);
//Registration reg = new Registration();
//BusinessOwner bwoner = new BusinessOwner();
//bwoner.setAge("35 and under");
//bwoner.setBusinessAddress("82 Street \n Complex A \n Estate D\n 0081");
//bwoner.setBusinessName("Accessories Sorted");
//bwoner.setCellPhone("0787579660");
//bwoner.setBusinessType("Pty");
//bwoner.setIdNumber("80051058");
//bwoner.setGender('F');
//bwoner.setRace('B');
//bwoner.setNationality("Province");
//bwoner.setPassport("TEWQ784554211");
// bwoner.setWebsite("www.financehub.co.za");
//reg.setEmail("<EMAIL>");
//reg.setFirstName("TestUser");
//reg.setLastName("TestUser LastName");
//reg.setOtpKey("00000");
//reg.setPassword("<PASSWORD>$#");
//reg.setBusinessOwner(bwoner);
//int registration = dao.persistRegistration(reg);
//user.setRegId(registration);
//dao.persistUser(user);
//System.out.println(registration);
FinancehubRole fbrole = new FinancehubRole();
fbrole.setRoleName("Business Owner");
fbrole.setRoleDescription("Business Owner");
//dao.persistFHRole(fbrole);
FinancehubUser user = new FinancehubUser();
user = createFbUser(2, 1,user);
user.setCellphone("0614211331");
user.setEmail("<EMAIL>");
user.setFirstName("Business Banker 2");
user.setOrgId(200);
user.setLastName("BB2");
user.setPasssword("<PASSWORD>");
//Integer userId = dao.persistFHUser(user);
// System.out.println(userId);
//
FinancehubBusinessOwner fbo = new FinancehubBusinessOwner();
FinancehubProductApplication fpApp = new FinancehubProductApplication();
fpApp.setUser(2);
fpApp.setInstId(14);
fpApp.setProductName("Absa Women Empowerment");
fpApp.setBusinesOwner(fbo);
fbo.setGender('F');
fbo.setRace('B');
fbo.setAge("42");
fbo.setFinanceProductApplication(fpApp);
//int appId = dao.persistFinanceApplicationProduct(fpApp);
//System.out.println(appId);
//FinancehubUser storedUser = dao.getFinancehubUser("<EMAIL>");
//System.out.println(storedUser);
//List<FinancehubApplication> apps = dao.getUserProcessedFinApplicationsByOrgId(200);
List<FinancehubApplication> apps = dao.getUserFinApplicationsByUserId(2);
//Integer update = dao.processApplication(6);
System.out.println(apps);
}
public static FinancehubUser createFbUser(int userType, int status, FinancehubUser user) {
if (userType == 1) {
user.setRoleId(1);
user.setStatus(status);
}
if (userType == 2) {
user.setRoleId(2);
user.setStatus(status);
}
if (userType == 3) {
user.setRoleId(3);
user.setStatus(status);
}
if (userType == 4) {
user.setRoleId(4);
user.setStatus(status);
}
if (userType == 5) {
user.setRoleId(5);
user.setStatus(status);
}
return user;
}
//FinancehubPU
public static EntityManager createEM(String persistenceUnitName) {
EntityManager ems = null;
try {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
ems = emf.createEntityManager();
} catch (Exception e) {
LOGGER.error("Entity manager setup in ApplicationContextListener failed due to : " + e);
e.printStackTrace();
}
return ems;
}
public List<Funding> createFunding(ApplicationDAO dao) {
String pu = "FinancehubPU";
if (dao == null) {
dao = getInstance();
EntityManager ems = dao.createEM(pu);
ApplicationDAO.setEm(ems);
}
return dao.getAllFunding();
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/fianancehub/utility/ContactJsonUtil.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.fianancehub.utility;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
*
* @author Kobedi.Makgabutlane
*/
public class ContactJsonUtil {
private static final ObjectMapper MAPPER = new ObjectMapper();
public static String contactToJson(Contact contact) throws JsonProcessingException
{
return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(contact);
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/beans/CaptureFinanceProductMB.java
package za.co.obeytrix.financehub.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import za.co.obeytrix.fianancehub.utility.ProductPersistingUtility;
@ManagedBean
@SessionScoped
public class CaptureFinanceProductMB implements Serializable {
private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory.getLogger(CaptureFinanceProductMB.class);
public final static ResourceBundle bundle = ResourceBundle.getBundle("za.co.obeytrix.financehub.product.form");
private ProductPersistingUtility persistingUtility;
private List<String> provincialFocusList;
private List<String> purposeForFinanceList;
private List<String> businessSectorList;
private Map<String, String> financeAmountMap = new HashMap<String, String>();
public CaptureFinanceProductMB() {
}
@PostConstruct
public void init() {
logger.info("Managed bean: CaptureFinanceProductMB has been constructed.");
try {
String provincialFocusString = bundle.getString("provincial.focus");
logger.info("provincialFocusString: " + provincialFocusString );
provincialFocusList = new ArrayList<String>(Arrays.asList(provincialFocusString.split(",")));
logger.info("provincialFocus list size: " + provincialFocusList.size() );
String financeTypeString = bundle.getString("finance.types");
purposeForFinanceList = new ArrayList<String>(Arrays.asList(financeTypeString.split(",")));
String targetSectorString = bundle.getString("target.sectors");
businessSectorList = new ArrayList<String>(Arrays.asList(targetSectorString.split(",")));
String financeAmountString = bundle.getString("finance.amount");
List<String>financeAmountList = new ArrayList<String>(Arrays.asList(financeAmountString.split(",")));
for(String financeAmount : financeAmountList) {
financeAmountMap.put(financeAmount, financeAmount);
}
persistingUtility = new ProductPersistingUtility();
} catch (Exception e) {
logger.error("Error in loading Rendering properties for capture finance form.");
e.printStackTrace();
}
}
public void actionListener(ActionEvent actionEvent) {
logger.info("Processing Product capture action event.");
try {
persistingUtility.captureFunding();
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.redirect(ec.getRequestContextPath() + "/capturedProduct.xhtml");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void actionListenerRecapture(ActionEvent actionEvent) {
logger.info("Processing Product recapture action event.");
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.redirect(ec.getRequestContextPath() + "/captureProduct.xhtml");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ProductPersistingUtility getPersistingUtility() {
return persistingUtility;
}
public void setPersistingUtility(ProductPersistingUtility persistingUtility) {
this.persistingUtility = persistingUtility;
}
public List<String> getProvincialFocusList() {
return provincialFocusList;
}
public void setProvincialFocusList(List<String> provincialFocusList) {
this.provincialFocusList = provincialFocusList;
}
public List<String> getPurposeForFinanceList() {
return purposeForFinanceList;
}
public void setPurposeForFinanceList(List<String> purposeForFinanceList) {
this.purposeForFinanceList = purposeForFinanceList;
}
public List<String> getBusinessSectorList() {
return businessSectorList;
}
public void setBusinessSectorList(List<String> businessSectorList) {
this.businessSectorList = businessSectorList;
}
public Map<String, String> getFinanceAmountMap() {
return financeAmountMap;
}
public void setFinanceAmountMap(Map<String, String> financeAmountMap) {
this.financeAmountMap = financeAmountMap;
}
}
<file_sep>/financehub/src/main/java/za/co/financehub/context/initialization/loader/ApplicationContextListener.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.financehub.context.initialization.loader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import za.co.obeytrix.financehub.dao.ApplicationDAO;
import za.co.obeytrix.financehub.dao.TableCreator;
import za.co.obeytrix.financehub.domain.ModalParameterCollection;
import za.co.obeytrix.financehub.entity.Registration;
import za.co.obeytrix.financehub.entity.Role;
import za.co.obeytrixsa.web.views.RegistrationView;
/**
*
* @author Kobedi.Makgabutlane
*/
public class ApplicationContextListener implements ServletContextListener {
private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(ApplicationContextListener.class);
public static int DATA_SOURCE = -1;
@Override
public void contextInitialized(ServletContextEvent sce) {
// String persistenceUnitName;
//// System.out.println("Sending test email");
//// sendTestEmail();
// ServletContext sc = sce.getServletContext();
// persistenceUnitName = sc.getInitParameter("PersistenceUnitName");
// LOGGER.info("PersistenceUnitName " + persistenceUnitName);
// if (persistenceUnitName != null && persistenceUnitName.length() > 0) {
// EntityManager em = createEM(persistenceUnitName, sc);
// LOGGER.info("EntityManager successfully created");
// if (em != null) {
// ApplicationDAO dao = ApplicationDAO.getInstance();
// ApplicationDAO.setEm(em);
// try {
// //TableCreator.init();
// //LOGGER.info("Address data " + TableCreator.createfinancehub_business_ownerTable());
// //TableCreator.createFinancehub_UserTable();
//
// //TableCreator.createFinancehub_User_RoleTable();
// //TableCreator.createFinancehub_RegistrationTable();
// List<Role> roles = new ArrayList<>();
//
// Role role1 = new Role();
// role1.setRoleName("FhubUser");
// role1.setRoleDescription("Financehub User");
//
// roles.add(role1);
//
// Role role2 = new Role();
// role2.setRoleName("FinAdmin");
// role2.setRoleDescription("Finance Institution Officer");
//
// roles.add(role2);
//
// Role role3 = new Role();
// role3.setRoleName("RegAdmin");
// role3.setRoleDescription("Regulator Administration");
//
// roles.add(role3);
//
// Role role4 = new Role();
// role4.setRoleName("DataCapturerAdmin");
// role4.setRoleDescription("BASA Data Capture Admin");
//
// roles.add(role4);
// //dao.populateRoleTable(roles);
// //LOGGER.info("Populate Roles " + dao.getAllRoles());
// // LOGGER.info("Users " + dao.getAllUsers());
// //LOGGER.info("Registrations " + dao.getAllRegistrations());
// sc.setAttribute("AppDAORef", dao);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// System.out.println("Sending test email");
// sendTestEmail();
}
private void initializeConcurrentMap(ServletContext sc) {
final ConcurrentMap< String, Registration> registrationData = new ConcurrentHashMap< String, Registration>();
sc.setAttribute("registrationMap", registrationData);
sc.setAttribute("modalParameterCollection", ModalParameterCollection.getInstance());
}
public EntityManager createOutOfContextEM(String persistenceUnitName) {
EntityManager em = null;
try {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
LOGGER.info("EMF Instance " + emf);
em = emf.createEntityManager();
DATA_SOURCE = 1;
} catch (Exception e) {
LOGGER.error("Entity manager setup in ApplicationContextListener failed due to : " + e);
DATA_SOURCE = 2;
e.printStackTrace();
} finally {
// if(DATA_SOURCE==1 || DATA_SOURCE==2)
// {
// initializeConcurrentMap(sc);
// }
}
return em;
}
private EntityManager createEM(String persistenceUnitName, ServletContext sc) {
EntityManager em = null;
try {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("FinancehubPU");
LOGGER.info("EMF Instance " + emf);
em = emf.createEntityManager();
DATA_SOURCE = 1;
} catch (Exception e) {
LOGGER.error("Entity manager setup in ApplicationContextListener failed due to : " + e);
DATA_SOURCE = 2;
e.printStackTrace();
} finally {
if (DATA_SOURCE == 1 || DATA_SOURCE == 2) {
initializeConcurrentMap(sc);
}
}
return em;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrixsa/web/views/PortalRegView.java
///*
// * To change this license header, choose License Headers in Project Properties.
// * To change this template file, choose Tools | Templates
// * and open the template in the editor.
// */
//package za.co.obeytrixsa.web.views;
//
//import java.io.IOException;
//import java.io.Serializable;
//import java.util.LinkedHashMap;
//import java.util.Map;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.concurrent.ConcurrentMap;
//import javax.annotation.PostConstruct;
//import javax.faces.application.FacesMessage;
//import javax.faces.bean.ManagedBean;
//import javax.faces.bean.ManagedProperty;
//import javax.faces.bean.SessionScoped;
//import javax.faces.context.FacesContext;
//import javax.faces.event.ValueChangeEvent;
//import javax.servlet.ServletContext;
//import javax.servlet.http.HttpSession;
//import osaemail.OsaEmail;
//import static osaemail.OsaEmail.OTP;
//import static osaemail.OsaEmail.determinMessasge;
//import za.co.obeytrix.financehub.entity.Registration;
//
///**
// *
// * @author Kobedi.Makgabutlane
// */
//@ManagedBean(name = "portalRegView", eager = true)
//@SessionScoped
//public class PortalRegView implements Serializable {
//
// private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(RegistrationView.class);
//
// private String firstName;
// private String lastName;
// private String cellNumber;
// private String email;
// private String password;
// private String confirmPassword;
// private String userType;
// private int number;
// private String otp;
//
// @ManagedProperty("#{appFormView}")
// private ApplicationView appView;
//
// private String userTypeHolder;
// private Map<String, Object> userTypeValue;
//
// public int getNumber() {
// return number;
// }
//
// public void increment() {
// number++;
// }
//
// public String getUserType() {
// return userType;
// }
//
// public void setUserType(String userType) {
// this.userType = userType;
// }
//
// public String getUserTypeHolder() {
// return userTypeHolder;
// }
//
// public void setUserTypeHolder(String userTypeHolder) {
// this.userTypeHolder = userTypeHolder;
// }
//
// public Map<String, Object> getUserTypeValue() {
// return userTypeValue;
// }
//
// public void setUserTypeValue(Map<String, Object> userTypeValue) {
// this.userTypeValue = userTypeValue;
// }
//
// public String getFirstName() {
// return firstName;
// }
//
// public void setFirstName(String firstName) {
// this.firstName = firstName;
// }
//
// public String getLastName() {
// return lastName;
// }
//
// public void setLastName(String lastName) {
// this.lastName = lastName;
// }
//
// public String getCellNumber() {
// return cellNumber;
// }
//
// public void setCellNumber(String cellNumber) {
// this.cellNumber = cellNumber;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = <PASSWORD>;
// }
//
// public String getConfirmPassword() {
// return confirmPassword;
// }
//
// public void setConfirmPassword(String confirmPassword) {
// this.confirmPassword = <PASSWORD>Password;
// }
//
// public void setAppView(ApplicationView appView) {
// this.appView = appView;
// }
//
// public String getOtp() {
// return otp;
// }
//
// public void setOtp(String otp) {
// this.otp = otp;
// }
//
// @PostConstruct
// public void initialize() {
// userTypeValue = new LinkedHashMap<String, Object>();
// userTypeValue.put("Please choose your role", "-1"); //label, value
// userTypeValue.put("Business Banker", "2"); //label, value
// userTypeValue.put("Analytics Specialist", "3"); //label, value
// userTypeValue.put("Data Capture Officer", "4"); //label, value
// }
//
// public void onSelect(ValueChangeEvent e) {
// int atinital = -1;
// ++atinital;
// LOGGER.info("onselect " + e.getNewValue().toString());
// String selectedUserType = e.getNewValue().toString();
// if (selectedUserType.equalsIgnoreCase("-1") && atinital >= 0) {
// info();
// }
// }
//
// public void info() {
// FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Info", "Please select a valid Role below."));
// }
//
// public void duplicateEmail(String email) {
// FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Email address " + email + " has already been used."));
// }
//
// public String directAppFlow(String selectedUserType) {
//
// return null;
//
// }
//
// public void navigate() throws IOException {
// FacesContext context = FacesContext.getCurrentInstance();
// ServletContext sc = (ServletContext) context.getExternalContext().getContext();
// HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
// String sessionId = session.getId();
// LOGGER.info("session id. " + sessionId);
// ConcurrentMap< String, Registration> registrationData = (ConcurrentMap< String, Registration>) sc.getAttribute("registrationMap");
// Registration registration = new Registration();
// registration.setFirstName(this.firstName);
// registration.setLastName(this.lastName);
// registration.setEmail(this.email);
// registration.setPassword(<PASSWORD>);
// registration.setCellPhone(this.cellNumber);
// Object record = registrationData.putIfAbsent(sessionId, registration);
// if (record != null) {
// duplicateEmail(this.email);
// } else {
// appView.setEmail(this.email);
// appView.setFirstName(this.firstName);
// appView.setLastName(this.lastName);
// appView.setCellNumber(this.cellNumber);
// sc.setAttribute("registInProgress", registration);
// sc.setAttribute("regEntity", "PartnerReg");
// context.getExternalContext().redirect("validateEmailAddress.xhtml");
// }
//
// }
//
// public void createAccount() throws IOException {
// FacesContext context = FacesContext.getCurrentInstance();
// ServletContext sc = (ServletContext) context.getExternalContext().getContext();
// String usrType = this.userTypeHolder;
// this.otp = new String(OTP());
// String message = OsaEmail.determinMessasge(0, null, null, this.otp);
// OsaEmail.EmailMessage(this.email, message);
// sc.setAttribute("sentOTP", this.otp);
// navigate();
// }
//
// private boolean emailIsNotKnown(String email) {
// // Do a database check to make sure is not
// if (email != null) {
// return true;
// }
//
// return false;
// }
//
// public void signIn() throws IOException {
// FacesContext context = FacesContext.getCurrentInstance();
// context.getExternalContext().redirect("login.xhtml");
// }
//
// public void logout() throws IOException {
// FacesContext context = FacesContext.getCurrentInstance();
// context.getExternalContext().redirect("index.html");
// }
//
//}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/persistence/maps/FunderMap.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.persistence.maps;
import za.co.obeytrix.financehub.entity.Funding;
import java.io.Reader;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.io.InputStreamReader;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import java.util.ArrayList;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import za.co.obeytrix.financehub.entity.BusinessSectors;
import za.co.obeytrix.financehub.entity.ContactDetails;
import za.co.obeytrix.financehub.entity.ProvincialScope;
import za.co.obeytrix.financehub.entity.QualificationCriteria;
import za.co.obeytrix.financehub.entity.RequiredDocumentation;
import za.co.obeytrixsa.preliminary.search.modal.ModalParameter;
/**
*
* @author Kobedi.Makgabutlane
*/
public class FunderMap {
private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(FunderMap.class);
private static FunderMap funderMap;
private static ConcurrentMap<String, Funding> fundingMap;
private static ConcurrentMap<String, FunderHolder> fundingHolderMap;
public static FunderMap getInstance() {
if (funderMap == null) {
funderMap = new FunderMap();
}
return funderMap;
}
private FunderMap() {
populateFundingMap();
}
public static ConcurrentMap<String, FunderHolder> getFundingHolderMap() {
if(fundingHolderMap!=null)
{
LOGGER.info("maintaining consistent clear and size for holder object");
fundingHolderMap.clear();
fundingHolderMap = populateFundingMap();
}
return fundingHolderMap;
}
public static ConcurrentMap<String, Funding> getFundingMap() {
return fundingMap;
}
private static ConcurrentMap<String, FunderHolder> populateFundingMap() {
InputStreamReader isReader = new InputStreamReader(FunderMap.class.getResourceAsStream("/META-INF/funding.csv"));
Reader readers = isReader;
com.opencsv.CSVReader reader = new com.opencsv.CSVReader(readers, ';');
ColumnPositionMappingStrategy<FunderHolder> beanStrategy = new ColumnPositionMappingStrategy<FunderHolder>();
beanStrategy.setType(FunderHolder.class);
beanStrategy.setColumnMapping(new String[]{"fundingId", "fundingInstitution", "productName", "minFinanceAmount",
"maxFinanceAmount", "description", "contactId", "provincialScopeId", "financePurposeId", "businessSectorId", "criteriaId", "documentationId",
"funding_pool", "minAmount", "maxAmount"});
com.opencsv.bean.CsvToBean<FunderHolder> csvToBean = new com.opencsv.bean.CsvToBean<FunderHolder>();
List<FunderHolder> funderHolderList = csvToBean.parse(beanStrategy, reader);
if (funderHolderList != null && funderHolderList.size() > 0) {
fundingHolderMap = new ConcurrentHashMap<>();
for (int i = 0; i < funderHolderList.size(); i++) {
FunderHolder fholder = funderHolderList.get(i);
if (i > 0) {
fundingHolderMap.putIfAbsent(Integer.toString(new Integer(fholder.getFundingId())), fholder);
}
}
}
return fundingHolderMap;
}
public static void main(String[] arg) {
populateFundingMap();
}
public static List<Funding> generateFundingEntitiesFromHolderMap(ConcurrentMap<String, FunderHolder> fundingHolderMap,ModalParameter modalParameterModalParameter) {
Funding funding;
List<Funding> result = new ArrayList();
int amount = new Integer(modalParameterModalParameter.getAmountStringValue());
String businessSectory = modalParameterModalParameter.getBusinessSector();
String provincialScope = modalParameterModalParameter.getBusinessOperationProvice();
String financePuprpose = modalParameterModalParameter.getTypeOfFinance();
LOGGER.info("Modal Params " + modalParameterModalParameter);
int min, max;
Set<String> keys = fundingHolderMap.keySet();
FunderHolder holder;
for (String key : keys) {
holder = fundingHolderMap.get(key);
min = new Integer(holder.getMinAmount());
max = new Integer(holder.getMaxAmount());
if (amount >= min && amount <= max) {
LOGGER.info("Building products for amount " + amount);
funding = new Funding();
funding.setBusinessSectors(new BusinessSectors());
funding.setContact(new ContactDetails());
funding.setCriteria(new QualificationCriteria());
funding.setDescription(holder.getDescription());
funding.setFinancePurpose(null);
funding.setFundingId(new Integer(holder.getFundingId()));
funding.setFundingInstitution(holder.getFundingInstitution());
funding.setFundingPool(holder.getFunding_pool());
funding.setMaxFinanceAmount(holder.getMaxFinanceAmount());
funding.setMinFinanceAmount(holder.getMinFinanceAmount());
funding.setProductName(holder.getProductName());
funding.setProvincialScope(new ProvincialScope());
funding.setRequiredDocumentation(new RequiredDocumentation());
result.add(funding);
}
}
return result;
}
public static List<Funding> generateFundingEntitiesFromHolderMap(ConcurrentMap<String, FunderHolder> fundingHolderMap) {
Funding funding;
List<Funding> result = new ArrayList();
int min = 0, max = 0;
Set<String> keys = fundingHolderMap.keySet();
FunderHolder holder;
for (String key : keys) {
holder = fundingHolderMap.get(key);
funding = new Funding();
funding.setBusinessSectors(new BusinessSectors());
funding.setContact(new ContactDetails());
funding.setCriteria(new QualificationCriteria());
funding.setDescription(holder.getDescription());
funding.setFinancePurpose(null);
funding.setFundingId(new Integer(holder.getFundingId()));
funding.setFundingInstitution(holder.getFundingInstitution());
funding.setFundingPool(holder.getFunding_pool());
funding.setMaxFinanceAmount(holder.getMaxFinanceAmount());
funding.setMinFinanceAmount(holder.getMinFinanceAmount());
funding.setProductName(holder.getProductName());
funding.setProvincialScope(new ProvincialScope());
funding.setRequiredDocumentation(new RequiredDocumentation());
result.add(funding);
}
return result;
}
}
<file_sep>/financehub/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>za.org.osa.banking.financehub</groupId>
<artifactId>financehub</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>financehub</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jsf.version>2.2.8</jsf.version>
<servlet.version>3.1.0</servlet.version>
<spring.version>4.3.1.RELEASE</spring.version>
</properties>
<dependencies>
<!-- <dependency>
<groupId>hibernate</groupId>
<artifactId>hibernate3</artifactId>
<version>3.2.3.GA</version>
</dependency>
<dependency>
<groupId>hibernate-annotations</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.0.GA</version>
</dependency>
<dependency>
<groupId>hibernate-commons-annotations</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.0.0.GA</version>
</dependency> -->
<!-- <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency> -->
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.ibatis</groupId>
<artifactId>ibatis2-common</artifactId>
<version>2.3.0.677</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/ibatis-2.3.0.677.jar</systemPath>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.8.Final</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-ses</artifactId>
<version>1.11.271</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>6.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- Making MyAQL Production Ready-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.4</version>
</dependency>
<!-- <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.3.Final</version>
</dependency> -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- JSF -->
<!-- https://mvnrepository.com/artifact/com.sun.faces/jsf-api -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>${jsf.version}</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>${jsf.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.ibatis</groupId>
<artifactId>ibatis-sqlmap</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>net.sf.uadetector</groupId>
<artifactId>uadetector-resources</artifactId>
<version>2014.10</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-spanner</artifactId>
<version>0.47.0-beta</version>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.com/maven2/</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.8</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project><file_sep>/financehub/src/main/java/za/co/obeytrixsa/clickatel/api/sms/message/ClickatellUtility.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrixsa.clickatel.api.sms.message;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Kobedi.Makgabutlane
*/
public class ClickatellUtility {
public static void main(String[] arg)
{
try {
ClickatellRest clickRest = new ClickatellRest("ZTqHPn8iQgmHYPYWUYZ3tg==&");
ClickatellRest.Message response = clickRest.sendMessage("27787579660", "Hello, this is a test message!");
} catch (Exception ex) {
Logger.getLogger(ClickatellUtility.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/dao/RunSqlScript.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.dao;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.ibatis.common.jdbc.ScriptRunner;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
/**
*
* @author Kobedi.Makgabutlane
*/
public class RunSqlScript {
private InputStream getReource()
{
InputStream input = this.getClass().getClassLoader().getResourceAsStream("META-INF/addressImport.sql");
return input;
}
private Connection createConnection() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://192.168.127.12:3306/BASA_schema", "tomcatLiferay", "LRTomKati");
return con;
}
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
RunSqlScript rs = new RunSqlScript();
String aSQLScriptFilePath = "/financehub/src/main/resources/META-INF/addressImport.sql";
// Create MySql Connection
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/BASA_schema", "tomcatLiferay", "LRTomKati");
Statement stmt = null;
try {
String result = IOUtils.toString(rs.getReource(), StandardCharsets.US_ASCII);
// Initialize object for ScripRunner
ScriptRunner sr = new ScriptRunner(con, false, false);
// Give the input file to Reader
Reader reader;
reader = new BufferedReader(
new FileReader(aSQLScriptFilePath));
// Exctute script
sr.runScript(reader);
reader.close();
} catch (Exception e) {
System.err.println("Failed to Execute" + aSQLScriptFilePath
+ " The error is " + e.getMessage());
e.printStackTrace();
}
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/entity/FinanceProduct.java
package za.co.obeytrix.financehub.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "FinanceProduct")
public class FinanceProduct implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int productId;
@Column(name="productName")
private String productName;
@Column(name="productDescription")
private String productDescription;
@Column(name="targetMarket")
private String targetMarket;
@Column(name="partnerShips")
private String partnerShips;
@Column(name="searchString")
private String searchString;
@ManyToOne
@JoinColumn(name="productScope")
private ProductScope productScope;
@ManyToOne
@JoinColumn(name="funderId")
private Funder funder;
@ManyToOne
@JoinColumn(name="contactDetailsId")
private ContactDetails contactDetails;
@ManyToOne
@JoinColumn(name="addressId")
private Address address;
public FinanceProduct() {
}
public FinanceProduct(String productName, String productDescription, String targetMarket, String partnerShips,
ProductScope productScope, Funder funder, ContactDetails contactDetails, Address address, String searchString) {
this.productName = productName;
this.productDescription = productDescription;
this.targetMarket = targetMarket;
this.partnerShips = partnerShips;
this.productScope = productScope;
this.funder = funder;
this.contactDetails = contactDetails;
this.address = address;
this.searchString = searchString;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public String getTargetMarket() {
return targetMarket;
}
public void setTargetMarket(String targetMarket) {
this.targetMarket = targetMarket;
}
public String getPartnerShips() {
return partnerShips;
}
public void setPartnerShips(String partnerShips) {
this.partnerShips = partnerShips;
}
public ProductScope getProductScope() {
return productScope;
}
public void setProductScope(ProductScope productScope) {
this.productScope = productScope;
}
public Funder getFunder() {
return funder;
}
public void setFunder(Funder funder) {
this.funder = funder;
}
public ContactDetails getContactDetails() {
return contactDetails;
}
public void setContactDetails(ContactDetails contactDetails) {
this.contactDetails = contactDetails;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
@Override
public String toString() {
return "FinanceProduct [productId=" + productId + ", productName=" + productName + ", productDescription="
+ productDescription + ", targetMarket=" + targetMarket + ", partnerShips=" + partnerShips
+ ", searchString=" + searchString + ", productScope=" + productScope + ", funder=" + funder
+ ", contactDetails=" + contactDetails + ", address=" + address + "]";
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/beans/ApplicationSource.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.beans;
import java.io.Serializable;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import za.co.obeytrix.financehub.dao.ApplicationDAO;
/**
*
* @author Kobedi.Makgabutlane
*/
@ManagedBean
@ApplicationScoped
public class ApplicationSource implements Serializable {
private ApplicationDAO applicationDAO;
public ApplicationDAO getApplicationDAO() {
return applicationDAO;
}
public void setApplicationDAO(ApplicationDAO applicationDAO) {
this.applicationDAO = applicationDAO;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/persistence/maps/UserMap.java
package za.co.obeytrix.financehub.persistence.maps;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import za.co.obeytrix.financehub.entity.User;
public class UserMap {
private ConcurrentMap<String, User> users;
private ConcurrentMap<String, User> userRoles;
private void populateUserMap() {
users = new ConcurrentHashMap<String, User>();
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrixsa/web/views/CollectionResultsView.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrixsa.web.views;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletContext;
import za.co.obeytrix.financehub.entity.Funding;
/**
*
* @author Kobedi.Makgabutlane
*/
@ManagedBean(name = "collectionResultsView", eager = true)
@SessionScoped
public class CollectionResultsView implements Serializable {
private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(CollectionResultsView.class);
private List<Funding> products = new ArrayList<>();
private Funding selectedProduct;
@ManagedProperty("#{viewService}")
private ViewService service;
public void loadApplication() {
System.out.println("Check if products were loaded:: " + products);
}
public void countSelection(ActionEvent actionEvent) throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
System.out.println("Target product " + selectedProduct);
if (selectedProduct != null) {
ServletContext sc = (ServletContext) context.getExternalContext().getContext();
sc.setAttribute("selectedProduct", null);
sc.setAttribute("selectedProduct", selectedProduct);
//appliedForProducts
ConcurrentMap<String, Funding> appliedProductsMap = (ConcurrentMap<String, Funding>) sc.getAttribute("appliedForProducts");
//Add applied for products if not already added for statistics.
if (appliedProductsMap != null) {
appliedProductsMap.putIfAbsent(Integer.toString(selectedProduct.getFundingId()), selectedProduct);
}
context.getExternalContext().redirect("registration.xhtml");
}
}
public void searchAgain() throws IOException {
//Save all the data in here.
FacesContext context = FacesContext.getCurrentInstance();
context.getExternalContext().redirect("index.html");
}
public Funding getSelectedProduct() {
return selectedProduct;
}
public void setSelectedProduct(Funding selectedProduct) {
this.selectedProduct = selectedProduct;
}
public void setService(ViewService service) {
this.service = service;
}
public List<Funding> getProducts() {
return products;
}
public void setProducts(List<Funding> products) {
this.products = products;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrixsa/persistence/PersistenceUtil.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrixsa.persistence;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import za.co.obeytrix.financehub.entity.Registration;
/**
*
* @author Kobedi.Makgabutlane
*/
public class PersistenceUtil {
public static SqlMapClient smcinstance;
public static SqlMapClient getInstance()
{
return smcinstance;
}
public static void initialazeSource()
{
try {
ClassLoader classloader = PersistenceUtil.class.getClassLoader();
InputStream is = classloader.getResourceAsStream("SqlMapConfig.xml");
smcinstance = SqlMapClientBuilder.buildSqlMapClient(is);
} catch (Exception e) {
System.out.println("Check H2 Connection or check if its started.");
e.printStackTrace();
}
}
public static List<Registration> getAllRegs()
{
List<Registration> list = new ArrayList<>();
List<Registration> preparedList = new ArrayList<>();
if (smcinstance != null) {
try {
list = smcinstance.queryForList("PersistenceUtil.getAllRegs");
} catch (SQLException ex) {
Logger.getLogger(za.co.obeytrix.financehub.entity.Registration.class.getName()).log(Level.SEVERE, null, ex);
}
}
return list;
}
public static List<Registration> searchByEmail(Registration reg)
{
List<Registration> list = new ArrayList<>();
Registration seachObject;
List<Registration> preparedList = new ArrayList<>();
if (smcinstance != null) {
try {
seachObject = (Registration) smcinstance.queryForObject("PersistenceUtil.singleItemByEmail",reg);
list.add(seachObject);
} catch (SQLException ex) {
Logger.getLogger(za.co.obeytrix.financehub.entity.Registration.class.getName()).log(Level.SEVERE, null, ex);
}
}
return list;
}
public static void main(String[] arg)
{
PersistenceUtil.initialazeSource();
//List<Registration> rglist = getAllRegs();
Registration reg = new Registration();
reg.setEmail("<EMAIL>");
//System.out.println(rglist);
List<Registration> rglist = searchByEmail(reg);
System.out.println(rglist);
System.out.println(UUID.randomUUID());
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/entity/Funding.java
package za.co.obeytrix.financehub.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "funding")
public class Funding implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int fundingId;
private String fundingInstitution;
private String productName;
private String minFinanceAmount;
private String maxFinanceAmount;
private String description;
//private boolean isSelected;
@ManyToOne
@JoinColumn(name = "contactId")
private ContactDetails contact;
@ManyToOne
@JoinColumn(name = "provincialScopeId")
private ProvincialScope provincialScope;
@ManyToOne
@JoinColumn(name = "financePurposeId")
private PurposeForFinance financePurpose;
@ManyToOne
@JoinColumn(name = "businessSectorId")
private BusinessSectors businessSectors;
@ManyToOne
@JoinColumn(name = "criteriaId")
private QualificationCriteria criteria;
@ManyToOne
@JoinColumn(name = "documentationId")
private RequiredDocumentation requiredDocumentation;
@Column(name = "funding_pool")
private String fundingPool;
//private String searchString;
public Funding() {
}
public Funding(int fundingId, String fundingInstitution, String productName, String minFinanceAmount,
String maxFinanceAmount, String description, String fundingPool, ContactDetails contact,
ProvincialScope provincialScope, PurposeForFinance financePurpose, BusinessSectors businessSectors,
QualificationCriteria criteria, RequiredDocumentation requiredDocumentation) {
super();
this.fundingId = fundingId;
this.fundingInstitution = fundingInstitution;
this.productName = productName;
this.minFinanceAmount = minFinanceAmount;
this.maxFinanceAmount = maxFinanceAmount;
this.description = description;
this.fundingPool = fundingPool;
this.contact = contact;
this.provincialScope = provincialScope;
this.financePurpose = financePurpose;
this.businessSectors = businessSectors;
this.criteria = criteria;
this.requiredDocumentation = requiredDocumentation;
//this.searchString = searchString;
}
public int getFundingId() {
return fundingId;
}
public void setFundingId(int fundingId) {
this.fundingId = fundingId;
}
public String getFundingInstitution() {
return fundingInstitution;
}
public void setFundingInstitution(String fundingInstitution) {
this.fundingInstitution = fundingInstitution;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
// public boolean isIsSelected() {
// return isSelected;
// }
//
// public void setIsSelected(boolean isSelected) {
// this.isSelected = isSelected;
// }
public String getMinFinanceAmount() {
return minFinanceAmount;
}
public void setMinFinanceAmount(String minFinanceAmount) {
this.minFinanceAmount = minFinanceAmount;
}
public String getMaxFinanceAmount() {
return maxFinanceAmount;
}
public void setMaxFinanceAmount(String maxFinanceAmount) {
this.maxFinanceAmount = maxFinanceAmount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ContactDetails getContact() {
return contact;
}
public void setContact(ContactDetails contact) {
this.contact = contact;
}
public QualificationCriteria getCriteria() {
return criteria;
}
public void setCriteria(QualificationCriteria criteria) {
this.criteria = criteria;
}
public RequiredDocumentation getRequiredDocumentation() {
return requiredDocumentation;
}
public void setRequiredDocumentation(RequiredDocumentation requiredDocumentation) {
this.requiredDocumentation = requiredDocumentation;
}
// public String getSearchString() {
// return searchString;
// }
//
// public void setSearchString(String searchString) {
// this.searchString = searchString;
// }
public ProvincialScope getProvincialScope() {
return provincialScope;
}
public void setProvincialScope(ProvincialScope provincialScope) {
this.provincialScope = provincialScope;
}
public PurposeForFinance getFinancePurpose() {
return financePurpose;
}
public void setFinancePurpose(PurposeForFinance financePurpose) {
this.financePurpose = financePurpose;
}
public BusinessSectors getBusinessSectors() {
return businessSectors;
}
public void setBusinessSectors(BusinessSectors businessSectors) {
this.businessSectors = businessSectors;
}
public String getFundingPool() {
return fundingPool;
}
public void setFundingPool(String fundingPool) {
this.fundingPool = fundingPool;
}
@Override
public String toString() {
return "Funding [fundingId=" + fundingId + ", fundingInstitution=" + fundingInstitution + ", productName="
+ productName + ", minFinanceAmount=" + minFinanceAmount + ", maxFinanceAmount=" + maxFinanceAmount
+ ", description=" + description + ", fundingPool=" + fundingPool + ", contact=" + contact
+ ", provincialScope=" + provincialScope + ", financePurpose=" + financePurpose + ", businessSectors="
+ businessSectors + ", criteria=" + criteria + ", requiredDocumentation=" + requiredDocumentation
+ ", searchString=" + "" + "]";
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/beans/EditProductMB.java
package za.co.obeytrix.financehub.beans;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import za.co.obeytrix.financehub.entity.Funding;
@ManagedBean
@SessionScoped
public class EditProductMB implements Serializable {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(EditProductMB.class);
private Funding selectedProduct;
private String contactNames;
private String phoneNumbers;
public EditProductMB() {
}
@PostConstruct
public void init() {
selectedProduct = (Funding) FacesContext.getCurrentInstance().getAttributes().get("selectedProduct");
Object json = selectedProduct.getContact().getContact();
JSONObject contactDetailsJson = (JSONObject) json;
phoneNumbers = (String) contactDetailsJson.get("phoneNumbers");
contactNames = (String) contactDetailsJson.get("contactNames");
}
public Funding getSelectedProduct() {
return selectedProduct;
}
public void setSelectedProduct(Funding selectedProduct) {
this.selectedProduct = selectedProduct;
}
public String getContactNames() {
return contactNames;
}
public void setContactNames(String contactNames) {
this.contactNames = contactNames;
}
public String getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(String phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrixsa/financehub/capture/CaptureProduct.java
package za.co.obeytrixsa.financehub.capture;
import java.io.Serializable;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CaptureProduct implements Serializable {
private static final long serialVersionUID = 1L;
Logger logger = LoggerFactory.getLogger(CaptureProduct.class);
private List<String> businessSectorList;
private List<String> purposeForFinanceList;
private List<String> provincialFocusList;
public CaptureProduct() {
}
public List<String> getBusinessSectorList() {
return businessSectorList;
}
public void setBusinessSectorList(List<String> businessSectorList) {
this.businessSectorList = businessSectorList;
}
public List<String> getPurposeForFinanceList() {
return purposeForFinanceList;
}
public void setPurposeForFinanceList(List<String> purposeForFinanceList) {
this.purposeForFinanceList = purposeForFinanceList;
}
public List<String> getProvincialFocusList() {
return provincialFocusList;
}
public void setProvincialFocusList(List<String> provincialFocusList) {
this.provincialFocusList = provincialFocusList;
}
@Override
public String toString() {
return "CaptureProduct [businessSectorList=" + businessSectorList + ", purposeForFinanceList="
+ purposeForFinanceList + ", provincialFocusList=" + provincialFocusList + "]";
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/dao/TableCreator.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Kobedi.Makgabutlane
*/
public class TableCreator {
private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(TableCreator.class);
private static Connection connection;
public TableCreator() throws Exception {
init();
}
private static Connection getConnection() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://172.16.31.10:3306/BASA_schema", "tomcatLiferay", "LRTomKati");
return con;
}
public static void init() {
try {
connection = getConnection();
LOGGER.info("Connection created.");
} catch (Exception ex) {
Logger.getLogger(TableCreator.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static Integer createfinancehub_business_ownerTable() {
init();
String tableDropQuery = "DROP TABLE IF EXISTS financehub_business_owner";
String tableCreateQuery = "CREATE TABLE `financehub_business_owner` (\n"
+ " `BUZZ_ID` int(11) NOT NULL AUTO_INCREMENT,\n"
+ " `FK_REG_ID` int(11) NOT NULL DEFAULT '-1',\n"
+ " `GENDER` char(1) NOT NULL,\n"
+ " `RACE` char(1) NOT NULL,\n"
+ " `AGE` varchar(50) NOT NULL,\n"
+ " `CELL_PHONE` varchar(50) NOT NULL,\n"
+ " `WORK_PHONE` varchar(50) DEFAULT NULL,\n"
+ " `NATIONALITY` varchar(20) DEFAULT NULL,\n"
+ " `PASSPORT_NUMBER` varchar(25) DEFAULT NULL,\n"
+ " `ID_NUMBER` varchar(13) DEFAULT NULL,\n"
+ " `BUSINESS_NAME` varchar(100) DEFAULT NULL,\n"
+ " `BUSINESS_TYPE` varchar(50) DEFAULT NULL,\n"
+ " `FK_PROVINCE_ID` int(11) DEFAULT '-1',\n"
+ " `WEB_SITE` varchar(100) DEFAULT NULL,\n"
+ " `BUSINESS_ADDRESS` varchar(255) DEFAULT NULL,\n"
+ " `CREATE_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n"
+ " `MODIFIED_DATE` timestamp NULL DEFAULT NULL,\n"
+ " `MODIFIED_BY` int(11) DEFAULT '1000',\n"
+ " PRIMARY KEY (`BUZZ_ID`)\n"
+ ");";
return execute(tableDropQuery, tableCreateQuery, "financehub_business_owner");
}
public static Integer createFinancehub_RegistrationTable() {
init();
String tableDropQuery = "DROP TABLE IF EXISTS financehub_registration";
String tableCreateQuery = "CREATE TABLE `financehub_registration` (\n"
+ " `REG_ID` int(11) NOT NULL AUTO_INCREMENT,\n"
+ " `FIRST_NAME` varchar(50) DEFAULT NULL,\n"
+ " `LAST_NAME` varchar(100) DEFAULT NULL,\n"
+ " `EMAIL` varchar(100) DEFAULT NULL,\n"
+ " `PASSWORD` varchar(200) DEFAULT NULL,\n"
+ " `OTP_KEY` varchar(10) DEFAULT '0000',\n"
+ " `CREATE_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n"
+ " `MODIFIED_DATE` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
+ " `MODIFIED_BY` int(11) DEFAULT '1000',\n"
+ " PRIMARY KEY (`REG_ID`));";
return execute(tableDropQuery, tableCreateQuery, "financehub_registration");
}
public static Integer createFinancehub_User_RoleTable() {
init();
String tableDropQuery = "DROP TABLE IF EXISTS financehub_user_role";
String tableCreateQuery = "CREATE TABLE `financehub_user` (\n"
+ " `USER_ID` int(11) NOT NULL AUTO_INCREMENT,\n"
+ " `FK_REG_ID` int(11) DEFAULT '1',\n"
+ " `FK_ROLE_ID` int(11) DEFAULT '1',\n"
+ " `STATUS` int(11) DEFAULT '0',\n"
+ " `CREATE_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n"
+ " `MODIFIED_DATE` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
+ " `MODIFIED_BY` int(11) DEFAULT '1000',\n"
+ " PRIMARY KEY (`USER_ID`));";
return execute(tableDropQuery, tableCreateQuery, "financehub_user_role");
}
public static Integer createFinancehub_UserTable() {
init();
String tableDropQuery = "DROP TABLE IF EXISTS financehub_user";
String tableCreateQuery = "CREATE TABLE `financehub_user` (\n"
+ " `USER_ID` int(11) NOT NULL AUTO_INCREMENT,\n"
+ " `FK_REG_ID` int(11) DEFAULT '1',\n"
+ " `FK_ROLE_ID` int(11) DEFAULT '1',\n"
+ " `STATUS` int(11) DEFAULT '0',\n"
+ " `CREATE_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n"
+ " `MODIFIED_DATE` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
+ " `MODIFIED_BY` int(11) DEFAULT '1000',\n"
+ " PRIMARY KEY (`USER_ID`));";
return execute(tableDropQuery, tableCreateQuery, "financehub_user");
}
private static int execute(String preStatement, String statement, String tableName) {
Statement stmt = null;
Connection conn = null;
int result = 0;
try {
//conn = getConnection();
stmt = connection.createStatement();
stmt.executeUpdate(preStatement);
result = stmt.executeUpdate(statement);
if (result == 0) {
System.out.println("Table " + tableName + " created successfully!");
} else {
System.out.println("Table creation failed!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
Logger.getLogger(TableCreator.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(TableCreator.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return 0;
}
public static void main(String[] arg) throws SQLException {
createfinancehub_business_ownerTable();
createFinancehub_RegistrationTable();
createFinancehub_UserTable();
createFinancehub_User_RoleTable();
// String tableDropQuery = "DROP TABLE IF EXISTS addressZ";
// String tableCreateQuery = "CREATE TABLE `addressZ` (\n"
// + " `addressId` int(11) NOT NULL AUTO_INCREMENT,\n"
// + " `addressString` varchar(100) NOT NULL,\n"
// + " `city` varchar(45) NOT NULL,\n"
// + " PRIMARY KEY (`addressId`));";
// Statement stmt = null;
// Connection conn = null;
//
// try {
// conn = getConnection();
// stmt = conn.createStatement();
// stmt.executeUpdate(tableDropQuery);
// int result = stmt.executeUpdate(tableCreateQuery);
// if (result == 0) {
// System.out.println("Table created successfully!");
// } else {
// System.out.println("Oops!");
// }
//
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// if (stmt != null) {
// try {
// stmt.close();
// } catch (SQLException ex) {
// Logger.getLogger(TableCreator.class.getName()).log(Level.SEVERE, null, ex);
// }
// }
// if (conn != null) {
// conn.close();
// }
// }
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/fianancehub/utility/ProductPersistingUtility.java
package za.co.obeytrix.fianancehub.utility;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import za.co.obeytrix.fianancehub.utility.CapturedProductData;
import za.co.obeytrix.financehub.dao.CaptureFundingDAO;
import za.co.obeytrix.financehub.entity.BusinessSectors;
import za.co.obeytrix.financehub.entity.ContactDetails;
import za.co.obeytrix.financehub.entity.FinancePurpose;
import za.co.obeytrix.financehub.entity.Funding;
import za.co.obeytrix.financehub.entity.ProvincialScope;
import za.co.obeytrix.financehub.entity.PurposeForFinance;
import za.co.obeytrix.financehub.entity.QualificationCriteria;
import za.co.obeytrix.financehub.entity.RequiredDocumentation;
public class ProductPersistingUtility {
Logger logger = LoggerFactory.getLogger(ProductPersistingUtility.class);
private CapturedProductData capturedProductData;
public ProductPersistingUtility() {
capturedProductData = new CapturedProductData();
}
public CapturedProductData getCapturedProductData() {
return capturedProductData;
}
public void setCapturedProductData(CapturedProductData capturedProductData) {
this.capturedProductData = capturedProductData;
}
public int captureFunding() throws Exception {
Funding funding = new Funding();
funding.setFundingInstitution(capturedProductData.getFunderName());
funding.setProductName(capturedProductData.getProductName());
//funding.setMinAmount(capturedProductData.getMinAmount());
//funding.setMaxAmount(capturedProductData.getMaxAmount());
funding.setDescription(capturedProductData.getProductDescription());
ContactDetails contactDetails = createContactDetails(capturedProductData.getContactName(),
capturedProductData.getPhoneNumbers(),
capturedProductData.getEmailAddresses(),
capturedProductData.getWebsite());
CaptureFundingDAO.getInstance().persistContactDetails(contactDetails);
funding.setContact(contactDetails);
BusinessSectors businessSectors = createBusinessSectors();
int sectorId = CaptureFundingDAO.getInstance().persistBusinessSectors(businessSectors);
logger.info("Captured sectors with ID: " + sectorId );
funding.setBusinessSectors(businessSectors);
PurposeForFinance financePurpose = createFinancePurpose();
int financePurposeId = CaptureFundingDAO.getInstance().persistFinancePurpose(createFinancePurpose());
logger.info("Captured finance purpose with ID: " + financePurposeId);
financePurpose.setFinancePurposeId(financePurposeId);
funding.setFinancePurpose(financePurpose);
ProvincialScope provincialScope = createProvincialScope();
CaptureFundingDAO.getInstance().persistProvincialScope(provincialScope);
funding.setProvincialScope(provincialScope);
QualificationCriteria qualificationCriteria = createQualificationCriteria();
CaptureFundingDAO.getInstance().persistQualificationCriteria(qualificationCriteria);
funding.setCriteria(qualificationCriteria);
RequiredDocumentation requiredDocumentation = createRequiredDocumentation();
CaptureFundingDAO.getInstance().persistRequiredDocumetation(requiredDocumentation);
funding.setRequiredDocumentation(requiredDocumentation);
funding.setFundingPool(capturedProductData.getFundingPool());
int capturedFundingId = CaptureFundingDAO.getInstance().persistFunding(funding);
return capturedFundingId;
}
private ContactDetails createContactDetails(String contactNames, String phoneNumbers, String emailAddresses, String website) {
List<String> contactNamesList = new ArrayList<String>(Arrays.asList(contactNames.split(",")));
List<String> phoneNumbersList = new ArrayList<String>(Arrays.asList(phoneNumbers.split(",")));
List<String> emailAddressesList = new ArrayList<String>(Arrays.asList(emailAddresses.split(",")));
List<String> websiteList = new ArrayList<String>(Arrays.asList(website.split(",")));
Contact contact = new Contact(contactNamesList, phoneNumbersList, emailAddressesList, websiteList);
ContactDetails contactDetails = new ContactDetails();
ObjectMapper mapper = new ObjectMapper();
try {
String contactDetailsJsonString = mapper.writeValueAsString(contact);
contactDetails.setContact(contactDetailsJsonString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return contactDetails;
}
private PurposeForFinance createFinancePurpose() throws Exception {
String [] financePurposeArray = capturedProductData.getSelectedPurposes();
List<String> financePurposeList = new ArrayList<>();
for (String purpose : financePurposeArray ) {
financePurposeList.add(purpose);
}
PurposeForFinance financePurpose = new PurposeForFinance();
ObjectMapper mapper = new ObjectMapper();
String purposeJsonString = mapper.writeValueAsString(financePurposeList);
financePurpose.setPurposeDescription(purposeJsonString);
return financePurpose;
}
private ProvincialScope createProvincialScope() throws Exception {
String [] provincialScopeArray = capturedProductData.getSelectedProvinces();
List<String> scopeList = new ArrayList<>();
for (String province : provincialScopeArray ) {
scopeList.add(province);
}
ProvincialScope provincialScope = new ProvincialScope();
ObjectMapper mapper = new ObjectMapper();
String scopeJsonString = mapper.writeValueAsString(scopeList);
provincialScope.setProvince(scopeJsonString);
return provincialScope;
}
private BusinessSectors createBusinessSectors() throws Exception {
String [] sectorsArray = capturedProductData.getSelectedSectors();
List<String> sectorsList = new ArrayList<>();
for (String sector : sectorsArray) {
sectorsList.add(sector);
}
BusinessSectors businessSectors = new BusinessSectors();
ObjectMapper mapper = new ObjectMapper();
String sectorJsonString = mapper.writeValueAsString(sectorsList);
businessSectors.setBusinesssector(sectorJsonString);
return businessSectors;
}
private QualificationCriteria createQualificationCriteria() throws Exception {
List<String> criteriaList = new ArrayList<>();
criteriaList.add(capturedProductData.getQualificationCriteria1());
criteriaList.add(capturedProductData.getQualificationCriteria2());
criteriaList.add(capturedProductData.getQualificationCriteria3());
criteriaList.add(capturedProductData.getQualificationCriteria4());
criteriaList.add(capturedProductData.getQualificationCriteria5());
ObjectMapper mapper = new ObjectMapper();
String criteriaString = mapper.writeValueAsString(criteriaList);
QualificationCriteria criteria = new QualificationCriteria();
criteria.setCriteria(criteriaString);
return criteria;
}
private RequiredDocumentation createRequiredDocumentation() throws Exception {
List<String> documentationList = new ArrayList<>();
documentationList.add(capturedProductData.getRequiredDocumentation1());
documentationList.add(capturedProductData.getRequiredDocumentation2());
documentationList.add(capturedProductData.getRequiredDocumentation3());
documentationList.add(capturedProductData.getRequiredDocumentation4());
documentationList.add(capturedProductData.getRequiredDocumentation5());
ObjectMapper mapper = new ObjectMapper();
String documentationString = mapper.writeValueAsString(documentationList);
RequiredDocumentation requiredDocumentation = new RequiredDocumentation();
requiredDocumentation.setDocumentation(documentationString);
return requiredDocumentation;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrixsa/user/interaction/comms/EmailComms.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrixsa.user.interaction.comms;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
/**
*
* @author Kobedi.Makgabutlane
*/
public class EmailComms {
private static String FROM_FIELD = "<EMAIL>";
private final static String BCC_FIELD = "<EMAIL>";//financehubinfo
private final static String USER_NAME = "<EMAIL>";
private final static String PASSWORD = "<PASSWORD>";
private final static int OTP_SIZE = 5;
private final static int PASSWORD_SIZE = 10;
private static int indicator = 0;
private String securityToken;
private static String rightSubject;
private static String assesmentCandiates = "Dear Client"
+ "\n\nYou have successfully registered for your organization's Architectural Assessment. Please use this token " + "#####" + " to complete your assessment."
+ " Use the link here " + "www.obeytrixsa.co.za to begin your assessment.\n\n"
+ "Please note you only have 3 attempts in which to complete your assessment. After that you will be forced to send an email to request for another chance.\n\n"
+ "\n\n Regards \n\n Enterprise Architecture Administration.";
//indicator =2;
private static String financehubInfo = "Dear Client"
+ "\n\nYou have successfully registered as a Financehub partner. To apply for finance and manage your applications, go to our website on http://www.financehub.co.za\n\n"
+ "Financehub also allows you to see your application status changes as administered by the relevant admin officer on your application."
+ "\n\nRegards \n\nFinancehub Administration.\n"
+ "<EMAIL>";
//indicator =1;
private static String financehubpsswordReset = "Dear Client"
+ "\n\nYou have successfully registered as Financehub partner. Your username and password is " + "username=$$$$$$$, password=#######" + ".You may access financehub on http://www.financehub.co.za to see"
+ " your profile. Now you can start applying for finance.\n"
+ "Financehub also allows you to see your application status changes as administered by the relevant admin officer on your application.."
+ "\n\nRegards\n\nFinancehub Administration.\n"
+ "<EMAIL>";
//indicator =0;
private static String financehubOTP = "Dear Client"
+ "\n\nYou are receiving this email from Financehub. Your email validation code is " + "#######" + ".\n"
+ "Please type the code on the displayed input box to confirm your email address."
+ "\n\nRegards\n\nFinancehub Administration.\n"
+ "<EMAIL>";
private static String licenseCanditate = "Dear Client"
+ "\n\nYour license has been successfully generated for your organization. Please use this token " + "#####" + " to activate your product."
+ " Use the link here " + "www.krysznatec.com to see videos on how to activate your license.\n\n"
+ "Please note you only have 24 hrs to complete your activation. After that you will be forced to send an email to request for another chance.\n\n"
+ "\n\n Regards \n\n Subware License Activation.";
private String toField;
public String getToField() {
return toField;
}
public void setToField(String toField) {
this.toField = toField;
}
public String getSecurityToken() {
return securityToken;
}
public void setSecurityToken(String securityToken) {
this.securityToken = securityToken;
}
public EmailComms() {
}
//String securityToken,String toField,String subject,int indicator,String from
public EmailComms(String securityToken, String toField, String subject, int indicator, String from) {
try {
EmailComms.FROM_FIELD = from;
EmailComms.indicator = indicator;
licenseCanditate = licenseCanditate.replace("#####", securityToken);
EmailComms(toField, subject);
} catch (Exception e) {
System.out.println("error while sending email to assessment candidate. " + e);
}
}
/**
* Constructor to create an instance that send an email to
*
* @param securityToken securityToken.
* @param toField toField.
* @param subject subject field.
*/
public EmailComms(String securityToken, String toField, String subject) {
try {
assesmentCandiates = assesmentCandiates.replace("#####", securityToken);
EmailComms(toField, subject);
} catch (Exception e) {
System.out.println("error while sending email to assessment candidate. " + e);
}
}
public static void main(String[] args) {
// TODO code application logic here
String secToken = <PASSWORD>";
String message, otp;
message = determinMessasge(0, null, null, new String(OTP()));
message = determinMessasge(1, "name.surname", new String(Password()), new String(OTP()));
message = determinMessasge(2, "name.surname", new String(Password()), new String(OTP()));
//EmailMessage("<EMAIL>", message);
EmailComms("<EMAIL>", message);
//
// ////String securityToken,String toField,String subject,int indicator,String from
// new OsaEmail(secToken, "<EMAIL>", "Financehub Registration",1,"<EMAIL>");
//
}
public static char[] Password() {
System.out.println("Generating password using random() : ");
System.out.print("Your new password is : ");
// A strong password has Cap_chars, Lower_chars,
// numeric value and symbols. So we are using all of
// them to generate our password
String Capital_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String Small_chars = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
String symbols = "!@#$%^&*_=+-/.?<>)";
String values = Capital_chars + Small_chars
+ numbers + symbols;
// Using random method
Random rndm_method = new Random();
char[] password = new char[PASSWORD_SIZE];
for (int i = 0; i < PASSWORD_SIZE; i++) {
// Use of charAt() method : to get character value
// Use of nextInt() as it is scanning the value as int
password[i]
= values.charAt(rndm_method.nextInt(values.length()));
}
return password;
}
public static char[] OTP() {
System.out.println("Generating OTP using random() : ");
System.out.print("You OTP is : ");
// Using numeric values
String numbers = "0123456789";
// Using random method
Random rndm_method = new Random();
char[] otp = new char[OTP_SIZE];
for (int i = 0; i < OTP_SIZE; i++) {
// Use of charAt() method : to get character value
// Use of nextInt() as it is scanning the value as int
otp[i]
= numbers.charAt(rndm_method.nextInt(numbers.length()));
}
return otp;
}
public static String determinMessasge(int indicator, String userName, String passsword, String otp) {
switch (indicator) {
case 0:
rightSubject = "Financehub Registration";
return financehubOTP.replace("#######", otp);
case 1:
rightSubject = "Financehub Information";
return financehubpsswordReset.replace("$$$$$$$", userName).replace("#######", passsword); //$$$$$$$, #######
case 2:
rightSubject = "Financehub Information";
return financehubInfo;
default:
rightSubject = "Financehub Information";
return financehubInfo;
}
}
public static void sendAWSMail(String toField, String financehubMessage, String indicator) {
final String username = "<EMAIL>", password = "<PASSWORD>";
String to = toField;
String from = FROM_FIELD;
Properties props = new Properties();
props.put("mail.smtp.host", "cp05.cphost.co.za");
//props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from, "Finance Hub"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setRecipients(Message.RecipientType.BCC,
InternetAddress.parse(BCC_FIELD));
message.setSubject(rightSubject);
BodyPart messageBodyPart = new MimeBodyPart();
message.setText(financehubMessage);
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(EmailComms.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void EmailComms(String toField, String financehubMessage) {
final String username = "<EMAIL>", password = "<PASSWORD>";
String to = toField;
String from = FROM_FIELD;
Properties props = new Properties();
props.put("mail.smtp.host", "cp05.cphost.co.za");
//props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setRecipients(Message.RecipientType.BCC,
InternetAddress.parse(BCC_FIELD));
message.setSubject(rightSubject);
BodyPart messageBodyPart = new MimeBodyPart();
message.setText(financehubMessage);
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/beans/MyInboxData.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.beans;
/**
*
* @author kobedi.makgabutlane
*/
public class MyInboxData {
private Integer financeId;
private Integer institutionId;
private String financeApplicationDate;
private String productName;
private Double financeAmount;
private String financeStatus;
public MyInboxData(Integer financeId, Integer institutionId, String financeApplicationDate, String productName, Double financeAmount, String financeStatus) {
this.financeId = financeId;
this.institutionId = institutionId;
this.financeApplicationDate = financeApplicationDate;
this.productName = productName;
this.financeAmount = financeAmount;
this.financeStatus = financeStatus;
}
public MyInboxData(Integer financeId, Integer institutionId, String financeApplicationDate, String productName, String financeStatus) {
this.financeId = financeId;
this.institutionId = institutionId;
this.financeApplicationDate = financeApplicationDate;
this.productName = productName;
this.financeStatus = financeStatus;
}
public Integer getFinanceId() {
return financeId;
}
public void setFinanceId(Integer financeId) {
this.financeId = financeId;
}
public Integer getInstitutionId() {
return institutionId;
}
public void setInstitutionId(Integer institutionId) {
this.institutionId = institutionId;
}
public String getFinanceApplicationDate() {
return financeApplicationDate;
}
public void setFinanceApplicationDate(String financeApplicationDate) {
this.financeApplicationDate = financeApplicationDate;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Double getFinanceAmount() {
return financeAmount;
}
public void setFinanceAmount(Double financeAmount) {
this.financeAmount = financeAmount;
}
public String getFinanceStatus() {
return financeStatus;
}
public void setFinanceStatus(String financeStatus) {
this.financeStatus = financeStatus;
}
@Override
public String toString() {
return "MyInboxData{" + "financeId=" + financeId + ", institutionId=" + institutionId + ", financeApplicationDate=" + financeApplicationDate + ", productName=" + productName + ", financeAmount=" + financeAmount + ", financeStatus=" + financeStatus + '}';
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrixsa/collection/data/source/CollectionInitialization.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrixsa.collection.data.source;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
*
* @author Kobedi.Makgabutlane
*/
public class CollectionInitialization {
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/entity/FinancePurpose.java
package za.co.obeytrix.financehub.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class FinancePurpose {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int purposeId;
private String purpose;
public FinancePurpose() {
}
public FinancePurpose(int purposeId, String purpose) {
this.purposeId = purposeId;
this.purpose = purpose;
}
public int getPurposeId() {
return purposeId;
}
public void setPurposeId(int purposeId) {
this.purposeId = purposeId;
}
public String getPurpose() {
return purpose;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
@Override
public String toString() {
return "FinancePurpose [purposeId=" + purposeId + ", purpose=" + purpose + "]";
}
}
<file_sep>/financehub/src/test/java/za/co/obeytrix/financehub/dao/test/ApplicationDAOTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.dao.test;
import java.util.List;
import javax.persistence.EntityManager;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import za.co.obeytrix.financehub.dao.ApplicationDAO;
import za.co.obeytrix.financehub.entity.FinanceApplication;
import za.co.obeytrix.financehub.entity.User;
/**
*
* @author Kobedi.Makgabutlane
*/
@Ignore
public class ApplicationDAOTest {
private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(ApplicationDAOTest.class);
@Before
public void init()
{
EntityManager ems = ApplicationDAO.createEM("FinancehubPU");
ApplicationDAO.setEm(ems);
}
@Test
public void testappDAOGetAllFinApplications()
{
ApplicationDAO appDao = ApplicationDAO.getInstance();
assertNotNull(appDao.getAllFinApplications());
}
@Test
public void testappDAOGetAllFinApplicationsForSingleUser()
{
ApplicationDAO appDao = ApplicationDAO.getInstance();
Integer id = appDao.getUserRegistrationNumber(10);
LOGGER.info("id " + id);
List<FinanceApplication> apps = appDao.getAllUserFinApplications(id);
LOGGER.info("Apps " + apps);
assertNotNull(apps);
}
@Test
public void testGetAppsForSingleUser()
{
ApplicationDAO appDao = ApplicationDAO.getInstance();
User user = appDao.getRegistrationIdForUser(10);
LOGGER.info("User " + user);
assertNotNull(user);
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/fianancehub/utility/ApplicationDaoUtils.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.fianancehub.utility;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import za.co.obeytrix.financehub.dao.ApplicationDAO;
/**
*
* @author Kobedi.Makgabutlane
*/
public class ApplicationDaoUtils {
private static final Logger LOGGER = Logger.getLogger(ApplicationDaoUtils.class);
public static EntityManager getEM(ServletContext sc) {
EntityManager em = null;
if (sc != null) {
ApplicationDAO appDao = (ApplicationDAO) sc.getAttribute("AppDAORef");
if (appDao != null) {
em = ApplicationDAO.getInstance().getEm();
}
}
return em;
}
public static EntityManager createEM(String persistenceUnitName) {
EntityManager ems = null;
try {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
ems = emf.createEntityManager();
} catch (Exception e) {
LOGGER.error("Entity manager setup in ApplicationContextListener failed due to : " + e);
e.printStackTrace();
}
return ems;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/entity/FinancehubRole.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author Kobedi.Makgabutlane
*/
@Entity
@Table(name="fh_user_role")
public class FinancehubRole implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ROLE_ID")
private int roleId;
@Column(name="ROLE_NAME")
private String roleName;
@Column(name="ROLE_DESCRIPTION")
private String roleDescription;
@Column(name="CREATE_DATE", insertable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDescription() {
return roleDescription;
}
public void setRoleDescription(String roleDescription) {
this.roleDescription = roleDescription;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/entity/ProvincialScope.java
package za.co.obeytrix.financehub.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "provincial_scope")
public class ProvincialScope {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "provincial_scope_id")
private int provinceId;
private String provinces;
public ProvincialScope() {
}
public ProvincialScope(int provinceId, String province) {
this.provinceId = provinceId;
this.provinces = province;
}
public int getProvinceId() {
return provinceId;
}
public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
public String getProvince() {
return provinces;
}
public void setProvince(String province) {
this.provinces = province;
}
@Override
public String toString() {
return "ProvincialScope [provinceId=" + provinceId + ", province=" + provinces + "]";
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/domain/FinancehubRole.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.domain;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author Kobedi.Makgabutlane
*/
public class FinancehubRole {
private Integer roleId;
private String roleName;
private String roleDescription;
private String roleCreationDate;
private Date createDate;
private SimpleDateFormat sdf = new SimpleDateFormat("");
public FinancehubRole(){}
public FinancehubRole(Integer roleId, String roleName, String roleDescription, String roleCreationDate, Date createDate) {
this.roleId = roleId;
this.roleName = roleName;
this.roleDescription = roleDescription;
this.roleCreationDate = roleCreationDate;
this.createDate = createDate;
}
public FinancehubRole(Integer roleId, String roleName, String roleDescription, String roleCreationDate) {
this.roleId = roleId;
this.roleName = roleName;
this.roleDescription = roleDescription;
this.roleCreationDate = roleCreationDate;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDescription() {
return roleDescription;
}
public void setRoleDescription(String roleDescription) {
this.roleDescription = roleDescription;
}
public String getRoleCreationDate() {
return roleCreationDate;
}
public void setRoleCreationDate(String roleCreationDate) {
this.roleCreationDate = roleCreationDate;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/dao/ContactDetailsDAO.java
package za.co.obeytrix.financehub.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;
import za.co.obeytrix.fianancehub.utility.FinancehubEntityManagerFactory;
import za.co.obeytrix.financehub.entity.ContactDetails;
public class ContactDetailsDAO {
private static Logger logger = Logger.getLogger(ContactDetailsDAO.class);
private static ContactDetailsDAO contactDetailsDAO;
private ContactDetailsDAO() {
}
public static ContactDetailsDAO getInstance() {
if (contactDetailsDAO == null) {
contactDetailsDAO = new ContactDetailsDAO();
}
return contactDetailsDAO;
}
public int persistContactDetails(ContactDetails contactDetails) {
EntityManager em = FinancehubEntityManagerFactory.getEntityManager();
em.getTransaction().begin();
em.persist(contactDetails);
em.getTransaction().commit();
return contactDetails.getContactId();
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/funder/basket/manage/FunderBasket.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.funder.basket.manage;
/**
*
* @author Kobedi.Makgabutlane
*/
public class FunderBasket {
private FinanceApplications financeApplications;
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/entity/RequiredDocumentation.java
package za.co.obeytrix.financehub.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "required_documentation")
public class RequiredDocumentation {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "required_documentation_id")
private int documentationId;
private String documentation;
public RequiredDocumentation() {
}
public int getDocumentationId() {
return documentationId;
}
public void setDocumentationId(int documentationId) {
this.documentationId = documentationId;
}
public String getDocumentation() {
return documentation;
}
public void setDocumentation(String documentation) {
this.documentation = documentation;
}
@Override
public String toString() {
return "RequiredDocumentation [documentationId=" + documentationId + ", documentation=" + documentation + "]";
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/entity/FinancehubApplication.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author Kobedi.Makgabutlane
*/
@Entity
@Table(name = "fh_finance_applications")
public class FinancehubApplication implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "FINAPP_ID")
private int financeApplicationId;
@Column(name = "FK_INST_ID")
private int instId;
@Column(name = "FK_USER_ID")
private int userId;
@Column(name = "PRODUCT_NAME")
private String productName;
@Column(name = "FUNDER")
private String funder;
@Column(name = "TARGET_MARKET")
private String targetMarket;
@Column(name = "APPLICATION_STATUS")
private String applicationStatus;
@Column(name = "PROCESSED")
private String processed;
@Column(name = "CREATE_DATE", insertable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date createDate;
@Column(name = "MODIFIED_DATE", insertable = true, updatable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date modifiedDate;
@Column(name="MODIFIED_BY")
private int modifiedById;
public FinancehubApplication(){}
public FinancehubApplication(int financeApplicationId, int instId, String productName, String funder, String targetMarket, String applicationStatus, String processed, Date createDate) {
this.financeApplicationId = financeApplicationId;
this.instId = instId;
this.productName = productName;
this.funder = funder;
this.targetMarket = targetMarket;
this.applicationStatus = applicationStatus;
this.processed = processed;
this.createDate = createDate;
}
public int getFinanceApplicationId() {
return financeApplicationId;
}
public void setFinanceApplicationId(int financeApplicationId) {
this.financeApplicationId = financeApplicationId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getInstId() {
return instId;
}
public void setInstId(int instId) {
this.instId = instId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getFunder() {
return funder;
}
public void setFunder(String funder) {
this.funder = funder;
}
public String getTargetMarket() {
return targetMarket;
}
public void setTargetMarket(String targetMarket) {
this.targetMarket = targetMarket;
}
public String getApplicationStatus() {
return applicationStatus;
}
public void setApplicationStatus(String applicationStatus) {
this.applicationStatus = applicationStatus;
}
public String getProcessed() {
return processed;
}
public void setProcessed(String processed) {
this.processed = processed;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public int getModifiedById() {
return modifiedById;
}
public void setModifiedById(int modifiedById) {
this.modifiedById = modifiedById;
}
@Override
public String toString() {
return "FinanceApplication{" + "financeApplicationId=" + financeApplicationId + ", + , instId=" + instId + ", productName=" + productName + ", funder=" + funder + ", product=" + "" + ", targetMarket=" + targetMarket + ", applicationStatus=" + applicationStatus + ", processed=" + processed + ", createDate=" + createDate + ", modifiedDate=" + modifiedDate + ", modifiedById=" + modifiedById + '}';
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/fianancehub/utility/QualificationCriteria.java
package za.co.obeytrix.fianancehub.utility;
import java.util.ArrayList;
import java.util.List;
public class QualificationCriteria {
private String qualificationCriteria1;
private String qualificationCriteria2;
private String qualificationCriteria3;
private String qualificationCriteria4;
private String qualificationCriteria5;
private List<String> criteriaList = new ArrayList<String>();
public QualificationCriteria() {
}
public QualificationCriteria(String qualificationCriteria1, String qualificationCriteria2,
String qualificationCriteria3, String qualificationCriteria4, String qualificationCriteria5) {
this.qualificationCriteria1 = qualificationCriteria1;
this.qualificationCriteria2 = qualificationCriteria2;
this.qualificationCriteria3 = qualificationCriteria3;
this.qualificationCriteria4 = qualificationCriteria4;
this.qualificationCriteria5 = qualificationCriteria5;
criteriaList.add(qualificationCriteria1);
criteriaList.add(qualificationCriteria2);
criteriaList.add(qualificationCriteria3);
criteriaList.add(qualificationCriteria4);
criteriaList.add(qualificationCriteria5);
}
public String getQualificationCriteria1() {
return qualificationCriteria1;
}
public void setQualificationCriteria(String qualificationCriteria1) {
this.qualificationCriteria1 = qualificationCriteria1;
}
public String getQualificationCriteria2() {
return qualificationCriteria2;
}
public void setQualificationCriteria2(String qualificationCriteria2) {
this.qualificationCriteria2 = qualificationCriteria2;
}
public String getQualificationCriteria3() {
return qualificationCriteria3;
}
public void setQualificationCriteria3(String qualificationCriteria3) {
this.qualificationCriteria3 = qualificationCriteria3;
}
public String getQualificationCriteria4() {
return qualificationCriteria4;
}
public void setQualificationCriteria4(String qualificationCriteria4) {
this.qualificationCriteria4 = qualificationCriteria4;
}
public String getQualificationCriteria5() {
return qualificationCriteria5;
}
public void setQualificationCriteria5(String qualificationCriteria5) {
this.qualificationCriteria5 = qualificationCriteria5;
}
public List<String> getCriteriaList() {
return criteriaList;
}
public void setCriteriaList(List<String> criteriaList) {
this.criteriaList = criteriaList;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/domain/FinancehubCollection.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import za.co.obeytrix.financehub.notifications.NotifyActivity;
/**
*
* @author Kobedi.Makgabutlane
*/
public abstract class FinancehubCollection implements NotifyActivity,Serializable {
protected Collection<Object> collection = new ArrayList<>();
final protected ConcurrentMap< String, Object > objectData = new ConcurrentHashMap<String, Object >();
final protected ConcurrentMap< String, Object > purposeOfFinanceCallection = new ConcurrentHashMap<String, Object >();
final protected ConcurrentMap< String, Object > businessSectorCallection = new ConcurrentHashMap<String, Object >();
final protected ConcurrentMap< String, Object > provincialScopeCallection = new ConcurrentHashMap<String, Object >();
public Collection<Object> getCollection() {
return collection;
}
public void setCollection(Collection<Object> collection) {
this.collection = collection;
}
protected boolean addObjectLisst(Collection<Object> list)
{
return collection.add(list);
}
protected Collection<Object> getObjectList()
{
return getCollection();
}
protected Object saveObject(String key, Object value)
{
return objectData.putIfAbsent(key, value);
}
protected Object retrieveObject(String key)
{
return objectData.get(key);
}
protected Object removeObject(String key)
{
return objectData.remove(key);
}
protected Object retriveBusinessSector(String key)
{
return businessSectorCallection.get(key);
}
protected Object saveBusinessSector(String key, Object value)
{
return businessSectorCallection.putIfAbsent(key, value);
}
protected Object retriveFinancePurpose(String key)
{
return purposeOfFinanceCallection.get(key);
}
protected Object saveFinancePurpose(String key, Object value)
{
return purposeOfFinanceCallection.putIfAbsent(key, value);
}
protected Object retriveProvincialScope(String key)
{
return provincialScopeCallection.get(key);
}
protected Object saveProvincialScope(String key, Object value)
{
return provincialScopeCallection.putIfAbsent(key, value);
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrixsa/web/views/ApplicationView.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrixsa.web.views;
import java.io.IOException;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import za.co.obeytrix.financehub.dao.ApplicationDAO;
import za.co.obeytrix.financehub.entity.BusinessOwner;
import za.co.obeytrix.financehub.entity.FinanceApplication;
import za.co.obeytrix.financehub.entity.Funding;
import za.co.obeytrix.financehub.entity.Registration;
import za.co.obeytrix.financehub.entity.User;
import za.co.obeytrix.financehub.persistence.maps.TransactionalUser;
/**
*
* @author kobedi.makgabutlane
*/
@ManagedBean(name = "appFormView", eager = true)
@SessionScoped
public class ApplicationView implements Serializable {
private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(ApplicationView.class);
@ManagedProperty("#{loginFormView}")
private LoginView loginView;
private Map<String, Object> genderValue;
private String genderHolder;
private Map<String, Object> raceValue;
private String raceHolder;
private Map<String, Object> ageValue;
private String ageHolder;
private String firstName;
private String lastName;
private String email;
private String officeNumber;
private String nationalityHolder;
private Map<String, Object> nationalityValue;
private String provinceHolder;
private Map<String, Object> provinceValue;
private String passportNumber;
private String idNumber;
private String website;
private String physicalAddress;
private String cellNumber;
private String companyRegistrationTypeIdHolder;
private Map<String, Object> companyRegistrationTypeIdValue;
private String turnOverHolder;
private Map<String, Object> turnOverValue;
private String numberOfEmployeesHolder;
private Map<String, Object> numberOfEmployeeValue;
private String beeLevelHolder;
private Map<String, Object> beeLevelValue;
private String registrationNumber;
private String numberOfDirectors;
private String businessStartDate;
private String businessName;
@PostConstruct
public void init() {
initialize();
}
public void setLoginView(LoginView loginView) {
this.loginView = loginView;
}
private void initialize() {
genderValue = new LinkedHashMap<String, Object>();
genderValue.put("Please select your gender", "Please select your gender"); //label, value
genderValue.put("Female", "Female"); //label, value
genderValue.put("Male", "Male");
raceValue = new LinkedHashMap<String, Object>();
raceValue.put("Please your ethnic group", "Please your ethnic group"); //label, value
raceValue.put("Black", "Black"); //label, value
raceValue.put("White", "White");
raceValue.put("Coloured", "Coloured");
raceValue.put("Indian", "Indian");
ageValue = new LinkedHashMap<String, Object>();
ageValue.put("Please select your age group", "Please select your age group"); //label, value
ageValue.put("35 and under", "35 and under"); //label, value
ageValue.put("36 and above", "36 and above");
provinceValue = new LinkedHashMap<String, Object>();
provinceValue.put("Please select your provice", "Please select your provice"); //label, value
provinceValue.put("Eastern Cape", "Eastern Cape"); //label, value
provinceValue.put("Free State", "Free State"); //label, value
provinceValue.put("Gauteng", "Gauteng"); //label, value
provinceValue.put("Kwa-Zulu Natal", "Kwa-Zulu Natal"); //label, value
provinceValue.put("Limpopo", "Limpopo"); //label, value
provinceValue.put("North West", "North West");
provinceValue.put("Northern Cape", "Northern Cape");
provinceValue.put("Western Cape", "Western Cape");
companyRegistrationTypeIdValue = new LinkedHashMap<String, Object>();
companyRegistrationTypeIdValue.put("Please select company type", "Please select company type"); //label, value
companyRegistrationTypeIdValue.put("(Pty) Ltd", "(Pty) Ltd");
companyRegistrationTypeIdValue.put("Close Corporation(CC)", "Close Corporation(CC)");
companyRegistrationTypeIdValue.put("Government Entities", "Government Entities");
companyRegistrationTypeIdValue.put("Not for Profit Organisation (NPO)", "Not for Profit Organisation (NPO)");
companyRegistrationTypeIdValue.put("(Pty) Ltd", "(Pty) Ltd");
companyRegistrationTypeIdValue.put("Close Corporation(CC)", "Close Corporation(CC)");
companyRegistrationTypeIdValue.put("Co - operative", "Co - operative");
companyRegistrationTypeIdValue.put("Government Entities", "Government Entities");
companyRegistrationTypeIdValue.put("Non - Government Organisation(NGO)", "Non - Government Organisation(NGO)");
companyRegistrationTypeIdValue.put("Not for Profit Organisation (NPO)", "Not for Profit Organisation (NPO)");
companyRegistrationTypeIdValue.put("Partnership", "Partnership");
companyRegistrationTypeIdValue.put("Public Benefit Organisation", "Public Benefit Organisation");
companyRegistrationTypeIdValue.put("Public Company", "Public Company");
companyRegistrationTypeIdValue.put("Section 21", "Section 21");
companyRegistrationTypeIdValue.put("Sole Proprietor", "Sole Proprietor");
companyRegistrationTypeIdValue.put("Trust", "Trust");
turnOverValue = new LinkedHashMap<String, Object>();
turnOverValue.put("Please select your your turn over", "Please select your your turn over"); //label, value
turnOverValue.put("Less than R 1 million", "Less than R 1 million"); //label, value
turnOverValue.put("Between R 1 million and R 5 million", "Between R 1 million and R 5 million"); //label, value
turnOverValue.put("Between R 5 million and R 10 million", "Between R 5 million and R 10 million"); //label, value
turnOverValue.put("Over R 10 Million", "Over R 10 Million"); //label, value
numberOfEmployeeValue = new LinkedHashMap<String, Object>();
numberOfEmployeeValue.put("Please select number of employees", "Please select number of employees"); //label, value
numberOfEmployeeValue.put("1 - 10", "1 - 10"); //label, value
numberOfEmployeeValue.put("10 - 50", "10 - 50"); //label, value
numberOfEmployeeValue.put("50 - 100", "50 - 100"); //label, value
numberOfEmployeeValue.put("100 and above", "100 and above"); //label, value
beeLevelValue = new LinkedHashMap<String, Object>();
beeLevelValue.put("Please select BEE Level", "Please select BEE Level"); //label, value
beeLevelValue.put("1", "100 or above"); //label, value
beeLevelValue.put("2", "85 to 99.99");
beeLevelValue.put("3", "75 to 84.99");
beeLevelValue.put("4", "65 to 74.99"); //label, value
beeLevelValue.put("5", "55 to 64.99");
beeLevelValue.put("6", "45 to 54.99"); //label, value
beeLevelValue.put("7", "40 to 44.99");
beeLevelValue.put("8", "30 to 39.99");
beeLevelValue.put("Non Compliant", "< 30");
populateNationality();
}
private void populateNationality() {
nationalityValue = new LinkedHashMap<String, Object>();
nationalityValue.put("Please select your nationality", "Please select your nationality"); //label, value
nationalityValue.put("South Africa", "South Africa");
nationalityValue.put("Afghanistan", "Afghanistan");
nationalityValue.put("Albania", "Albania");
nationalityValue.put("Algeria", "Algeria");
nationalityValue.put("American Samoa", "American Samoa");
nationalityValue.put("Andorra", "Andorra");
nationalityValue.put("Angola", "Angola");
nationalityValue.put("Anguilla", "Anguilla");
nationalityValue.put("Antarctica", "Antarctica");
nationalityValue.put("Antigua and Barbuda", "Antigua and Barbuda");
nationalityValue.put("Argentina", "Argentina");
nationalityValue.put("Armenia", "Armenia");
nationalityValue.put("Aruba", "Aruba");
nationalityValue.put("Australia", "Australia");
nationalityValue.put("Austria", "Austria");
nationalityValue.put("Azerbaijan", "Azerbaijan");
nationalityValue.put("Bahamas", "Bahamas");
nationalityValue.put("Bahrain", "Bahrain");
nationalityValue.put("Bangladesh", "Bangladesh");
nationalityValue.put("Barbados", "Barbados");
nationalityValue.put("Belarus", "Belarus");
nationalityValue.put("Belgium", "Belgium");
nationalityValue.put("Benin", "Benin");
nationalityValue.put("Bermuda", "Bermuda");
nationalityValue.put("Bhutan", "Bhutan");
nationalityValue.put("Belgium", "Belgium");
nationalityValue.put("Zambia", "Zambia");
nationalityValue.put("Zimbabwe", "Zimbabwe");
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public String getBusinessStartDate() {
return businessStartDate;
}
public void setBusinessStartDate(String businessStartDate) {
this.businessStartDate = businessStartDate;
}
public String getNumberOfDirectors() {
return numberOfDirectors;
}
public void setNumberOfDirectors(String numberOfDirectors) {
this.numberOfDirectors = numberOfDirectors;
}
public String getBeeLevelHolder() {
return beeLevelHolder;
}
public void setBeeLevelHolder(String beeLevelHolder) {
this.beeLevelHolder = beeLevelHolder;
}
public Map<String, Object> getBeeLevelValue() {
return beeLevelValue;
}
public void setBeeLevelValue(Map<String, Object> beeLevelValue) {
this.beeLevelValue = beeLevelValue;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getNumberOfEmployeesHolder() {
return numberOfEmployeesHolder;
}
public void setNumberOfEmployeesHolder(String numberOfEmployeesHolder) {
this.numberOfEmployeesHolder = numberOfEmployeesHolder;
}
public Map<String, Object> getNumberOfEmployeeValue() {
return numberOfEmployeeValue;
}
public void setNumberOfEmployeeValue(Map<String, Object> numberOfEmployeeValue) {
this.numberOfEmployeeValue = numberOfEmployeeValue;
}
public String getTurnOverHolder() {
return turnOverHolder;
}
public void setTurnOverHolder(String turnOverHolder) {
this.turnOverHolder = turnOverHolder;
}
public Map<String, Object> getTurnOverValue() {
return turnOverValue;
}
public void setTurnOverValue(Map<String, Object> turnOverValue) {
this.turnOverValue = turnOverValue;
}
public String getCellNumber() {
return cellNumber;
}
public void setCellNumber(String cellNumber) {
this.cellNumber = cellNumber;
}
public String getCompanyRegistrationTypeIdHolder() {
return companyRegistrationTypeIdHolder;
}
public void setCompanyRegistrationTypeIdHolder(String companyRegistrationTypeIdHolder) {
this.companyRegistrationTypeIdHolder = companyRegistrationTypeIdHolder;
}
public Map<String, Object> getCompanyRegistrationTypeIdValue() {
return companyRegistrationTypeIdValue;
}
public void setCompanyRegistrationTypeIdValue(Map<String, Object> companyRegistrationTypeIdValue) {
this.companyRegistrationTypeIdValue = companyRegistrationTypeIdValue;
}
public String getPhysicalAddress() {
return physicalAddress;
}
public void setPhysicalAddress(String physicalAddress) {
this.physicalAddress = physicalAddress;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getProvinceHolder() {
return provinceHolder;
}
public void setProvinceHolder(String provinceHolder) {
this.provinceHolder = provinceHolder;
}
public Map<String, Object> getProvinceValue() {
return provinceValue;
}
public void setProvinceValue(Map<String, Object> provinceValue) {
this.provinceValue = provinceValue;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
public String getPassportNumber() {
return passportNumber;
}
public void setPassportNumber(String passportNumber) {
this.passportNumber = passportNumber;
}
public Map<String, Object> getNationalityValue() {
return nationalityValue;
}
public void setNationalityValue(Map<String, Object> nationalityValue) {
this.nationalityValue = nationalityValue;
}
public String getNationalityHolder() {
return nationalityHolder;
}
public void setNationalityHolder(String nationalityHolder) {
this.nationalityHolder = nationalityHolder;
}
public String getOfficeNumber() {
return officeNumber;
}
public void setOfficeNumber(String officeNumber) {
this.officeNumber = officeNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Map<String, Object> getAgeValue() {
return ageValue;
}
public void setAgeValue(Map<String, Object> ageValue) {
this.ageValue = ageValue;
}
public String getAgeHolder() {
return ageHolder;
}
public void setAgeHolder(String ageHolder) {
this.ageHolder = ageHolder;
}
public Map<String, Object> getRaceValue() {
return raceValue;
}
public void setRaceValue(Map<String, Object> raceValue) {
this.raceValue = raceValue;
}
public String getRaceHolder() {
return raceHolder;
}
public void setRaceHolder(String raceHolder) {
this.raceHolder = raceHolder;
}
public Map<String, Object> getGenderValue() {
return genderValue;
}
public void setGenderValue(Map<String, Object> genderValue) {
this.genderValue = genderValue;
}
public String getGenderHolder() {
return genderHolder;
}
public void setGenderHolder(String genderHolder) {
this.genderHolder = genderHolder;
}
public void previous() throws IOException
{
FacesContext context = FacesContext.getCurrentInstance();
context.getExternalContext().redirect("registration.xhtml");
}
private char determinRace(String race)
{
char selectedRace='U';
switch(race)
{
case "Black":
selectedRace = 'B';
break;
case "White":
selectedRace = 'W';
break;
case "Coloured":
selectedRace = 'C';
break;
case "Indian":
selectedRace = 'I';
break;
}
return selectedRace;
}
private char determinGender(String race)
{
char selectedGender='M';
switch(race)
{
case "Female":
selectedGender = 'F';
break;
case "Male":
selectedGender = 'M';
break;
}
return selectedGender;
}
public void finalizeApp() throws IOException
{
FacesContext context = FacesContext.getCurrentInstance();
Registration reg;
BusinessOwner businessO = new BusinessOwner(true);
businessO.setAge(this.ageHolder);
businessO.setBusinessName(this.businessName);
businessO.setBusinessType(this.companyRegistrationTypeIdHolder);
businessO.setWorkPhone(this.officeNumber);
businessO.setGender(determinGender(this.genderHolder));
businessO.setIdNumber(this.idNumber);
businessO.setBusinessName(this.businessName);
businessO.setBusinessAddress(this.physicalAddress);
businessO.setNationality(this.nationalityHolder);
businessO.setRace(determinRace(this.raceHolder));
businessO.setRegistrationNumber(this.registrationNumber);
businessO.setTradeTenure(this.businessStartDate);
businessO.setAnnualTurnOver(this.turnOverHolder);
businessO.setNumberOfEmployees(this.numberOfEmployeesHolder);
FinanceApplication financeApp = new FinanceApplication();
ServletContext sc = (ServletContext) context.getExternalContext().getContext();
reg = (Registration) sc.getAttribute("registInProgress");
Funding funding = (Funding) sc.getAttribute("selectedProduct");
if(reg!=null && funding!=null)
{
System.out.println("Persistint Application Info");
financeApp.setApplicationStatus("Pending");
financeApp.setFunder(funding.getFundingInstitution());
financeApp.setProcessed("No");
financeApp.setInstId(funding.getFundingId());
financeApp.setProductName(funding.getProductName());
financeApp.setTargetMarket(funding.getDescription());
reg.setBusinessOwner(businessO);
ApplicationDAO appDao = (ApplicationDAO) sc.getAttribute("AppDAORef");
boolean isCollectionPersistenceEnabled = (boolean) sc.getAttribute("isCollectionTypePersistence");
if(appDao!=null && !isCollectionPersistenceEnabled)
{
System.out.println("Doing it now ");
int persist = appDao.persistRegistration(reg);
businessO.setRegId(persist);
financeApp.setRegId(persist);
User user = new User();
user.setRegId(persist);
user.setRoleId(1);
System.out.println(" "+ appDao.persistUser(user));
System.out.println(" " + appDao.persistFinanceApplication(financeApp));
sc.setAttribute("registInProgress", null);
sc.setAttribute("selectedProduct", null);
}
if(isCollectionPersistenceEnabled)
{
ConcurrentMap< String, TransactionalUser> registrationData = (ConcurrentMap< String, TransactionalUser>) sc.getAttribute("registrationData");
TransactionalUser user = (TransactionalUser) sc.getAttribute("tranxUser");
user.setRegistration(reg);
user.getAppliedProducts().add(funding);
LOGGER.info("Adding reg " + reg + " to registration data collection");
if(registrationData!=null)
registrationData.putIfAbsent(Integer.toString(user.getUserId()), user);
}
}
System.out.println("Test Application Processed");
try {
sc.setAttribute("registInProgress",null);
sc.setAttribute("selectedProduct",null);
sc.setAttribute("tranxUser",null);
success();
Thread.currentThread().sleep(1000*10);
} catch (InterruptedException ex) {
Logger.getLogger(ApplicationView.class.getName()).log(Level.SEVERE, null, ex);
}
loginView.setUserName("");
loginView.setPassword("");
context.getExternalContext().redirect("login.xhtml");
}
public void success() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "You have completed your registration.Redirecting to login page in few seconds.\n"));
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/entity/ProductScope.java
package za.co.obeytrix.financehub.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="ProductScope")
public class ProductScope {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int scopeId;
@Column(name="productScope")
private String productScope;
public ProductScope() {
}
public ProductScope(int scopeId, String productScope) {
this.scopeId = scopeId;
this.productScope = productScope;
}
public int getScopeId() {
return scopeId;
}
public void setScopeId(int scopeId) {
this.scopeId = scopeId;
}
public String getProductScope() {
return productScope;
}
public void setProductScope(String productScope) {
this.productScope = productScope;
}
@Override
public String toString() {
return "ProductScope [scopeId=" + scopeId + ", productScope=" + productScope + "]";
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/entity/FinancehubBusinessOwner.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author Kobedi.Makgabutlane
*/
@Entity
@Table(name = "fh_business_owner")
public class FinancehubBusinessOwner implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "BUZZ_ID")
private int buzzId;
@OneToOne(mappedBy = "businesOwner")
private FinancehubProductApplication financeProductApplication;
@Column(name = "GENDER")
private char gender;
@Column(name = "RACE")
private char race;
@Column(name = "AGE")
private String age;
@Column(name = "WORK_PHONE")
private String workPhone;
@Column(name = "NATIONALITY")
private String nationality;
@Column(name = "ID_NUMBER")
private String idNumber;
@Column(name = "BUSINESS_NAME")
private String businessName;
@Column(name = "NUM_DIRECTORS")
private int numDirectors;
@Column(name = "COMPANY_TYPE")
private String businessType;
@Column(name = "BEE_LEVEL")
private String beeLevel;
@Column(name = "REGISTRTION_NUM")
private String registrationNumber;
@Column(name = "TRADE_TENURE")
private String tradeTenure;
@Column(name = "ANNUAL_TURNOVER")
private String annualTurnOver;
@Column(name = "NUM_EMPLOYEES")
private String numberOfEmployees;
@Column(name = "BUSINESS_ADDRESS")
private String businessAddress;
@Column(name = "CREATE_DATE", insertable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date createDate;
@Column(name = "MODIFIED_DATE", insertable = true, updatable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date modifiedDate;
@Column(name = "MODIFIED_BY")
private int modifiedById;
public FinancehubProductApplication getFinanceProductApplication() {
return financeProductApplication;
}
public void setFinanceProductApplication(FinancehubProductApplication financeProductApplication) {
this.financeProductApplication = financeProductApplication;
}
public String getNumberOfEmployees() {
return numberOfEmployees;
}
public void setNumberOfEmployees(String numberOfEmployees) {
this.numberOfEmployees = numberOfEmployees;
}
public String getAnnualTurnOver() {
return annualTurnOver;
}
public void setAnnualTurnOver(String annualTurnOver) {
this.annualTurnOver = annualTurnOver;
}
public String getTradeTenure() {
return tradeTenure;
}
public void setTradeTenure(String tradeTenure) {
this.tradeTenure = tradeTenure;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getBeeLevel() {
return beeLevel;
}
public void setBeeLevel(String beeLevel) {
this.beeLevel = beeLevel;
}
public int getNumDirectors() {
return numDirectors;
}
public void setNumDirectors(int numDirectors) {
this.numDirectors = numDirectors;
}
public int getBuzzId() {
return buzzId;
}
public void setBuzzId(int buzzId) {
this.buzzId = buzzId;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public char getRace() {
return race;
}
public void setRace(char race) {
this.race = race;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getWorkPhone() {
return workPhone;
}
public void setWorkPhone(String workPhone) {
this.workPhone = workPhone;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public String getBusinessType() {
return businessType;
}
public void setBusinessType(String businessType) {
this.businessType = businessType;
}
public String getBusinessAddress() {
return businessAddress;
}
public void setBusinessAddress(String businessAddress) {
this.businessAddress = businessAddress;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public int getModifiedById() {
return modifiedById;
}
public void setModifiedById(int modifiedById) {
this.modifiedById = modifiedById;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/persistence/maps/UserHolder.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.persistence.maps;
/**
*
* @author Kobedi.Makgabutlane
*/
public class UserHolder {
private String USER_ID;
private String FK_ROLE_ID;
private String FK_ORG_ID;
private String STATUS;
private String FIRST_NAME;
private String LAST_NAME;
private String CELL_PHONE;
private String EMAIL;
private String PASSWORD;
private String CREATE_DATE;
private String MODIFIED_DATE;
private String MODIFIED_BY;
public String getUSER_ID() {
return USER_ID;
}
public void setUSER_ID(String USER_ID) {
this.USER_ID = USER_ID;
}
public String getFK_ROLE_ID() {
return FK_ROLE_ID;
}
public void setFK_ROLE_ID(String FK_ROLE_ID) {
this.FK_ROLE_ID = FK_ROLE_ID;
}
public String getFK_ORG_ID() {
return FK_ORG_ID;
}
public void setFK_ORG_ID(String FK_ORG_ID) {
this.FK_ORG_ID = FK_ORG_ID;
}
public String getSTATUS() {
return STATUS;
}
public void setSTATUS(String STATUS) {
this.STATUS = STATUS;
}
public String getFIRST_NAME() {
return FIRST_NAME;
}
public void setFIRST_NAME(String FIRST_NAME) {
this.FIRST_NAME = FIRST_NAME;
}
public String getLAST_NAME() {
return LAST_NAME;
}
public void setLAST_NAME(String LAST_NAME) {
this.LAST_NAME = LAST_NAME;
}
public String getCELL_PHONE() {
return CELL_PHONE;
}
public void setCELL_PHONE(String CELL_PHONE) {
this.CELL_PHONE = CELL_PHONE;
}
public String getEMAIL() {
return EMAIL;
}
public void setEMAIL(String EMAIL) {
this.EMAIL = EMAIL;
}
public String getPASSWORD() {
return PASSWORD;
}
public void setPASSWORD(String PASSWORD) {
this.PASSWORD = <PASSWORD>;
}
public String getCREATE_DATE() {
return CREATE_DATE;
}
public void setCREATE_DATE(String CREATE_DATE) {
this.CREATE_DATE = CREATE_DATE;
}
public String getMODIFIED_DATE() {
return MODIFIED_DATE;
}
public void setMODIFIED_DATE(String MODIFIED_DATE) {
this.MODIFIED_DATE = MODIFIED_DATE;
}
public String getMODIFIED_BY() {
return MODIFIED_BY;
}
public void setMODIFIED_BY(String MODIFIED_BY) {
this.MODIFIED_BY = MODIFIED_BY;
}
@Override
public String toString() {
return "UserHolder{" + "USER_ID=" + USER_ID + ", FK_ROLE_ID=" + FK_ROLE_ID + ", FK_ORG_ID=" + FK_ORG_ID + ", STATUS=" + STATUS + ", FIRST_NAME=" + FIRST_NAME + ", LAST_NAME=" + LAST_NAME + ", CELL_PHONE=" + CELL_PHONE + ", EMAIL=" + EMAIL + ", PASSWORD=" + <PASSWORD> + ", CREATE_DATE=" + CREATE_DATE + ", MODIFIED_DATE=" + MODIFIED_DATE + ", MODIFIED_BY=" + MODIFIED_BY + '}';
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/domain/ModalParameterCollection.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.domain;
import java.util.*;
import za.co.obeytrix.financehub.entity.BusinessSectors;
import za.co.obeytrix.financehub.entity.ProvincialScope;
import za.co.obeytrix.financehub.entity.PurposeForFinance;
/**
*
* @author Kobedi.Makgabutlane
*/
public class ModalParameterCollection extends FinancehubCollection {
private static ModalParameterCollection instance = new ModalParameterCollection();
public static ModalParameterCollection getInstance()
{
return instance;
}
private ModalParameterCollection()
{
init();
}
public final void init()
{
createFinancePurposeCollection();
createProvincialScopeCollection();
createBusinessSectorCollection();
}
private void createFinancePurposeCollection()
{
String []financePurpuse = {"Asset Based Finance", "Expansion Capital", "Credit Guarantee",
"Acquisition Finance", "Equity Instruments", "Grant", " Asset Finance", "Export", "Trade Finance", "Working Capital","Other"};
int ii=1000;
for(String key : financePurpuse)
{
PurposeForFinance value = new PurposeForFinance(ii, key);
super.saveBusinessSector(key, value);
++ii;
}
}
public List<? extends Collection> getFinancePurposeCollection(String key)
{
if(key.equalsIgnoreCase("all"))
return new ArrayList(super.purposeOfFinanceCallection.values());
return (List<? extends Collection>) super.purposeOfFinanceCallection.get(key);
}
private void createProvincialScopeCollection()
{
String []provincialScope = {"Eastern Cape", "Free State", "Gauteng", "KZN", "Limpopo", "Mpumalanga", "North West", "Northern Cape", "Western Cape","All"};
int ii=2000;
for(String key : provincialScope)
{
ProvincialScope value = new ProvincialScope(ii, key);
super.saveProvincialScope(key, value);
++ii;
}
}
public List<? extends Collection> getProvincialScopeCollection(String key)
{
if(key.equalsIgnoreCase("all"))
return new ArrayList(super.provincialScopeCallection.values());
return (List<? extends Collection>) super.retriveProvincialScope(key);
}
private void createBusinessSectorCollection()
{
String []businessSector = {"Agriculture", "Communication", "Construction", "Energy", "Finance & Services", "Manufacturing", "Mining", "Tourism", "Transport", "Wholesale & Retail"};
int ii=3000;
for(String key : businessSector)
{
BusinessSectors value = new BusinessSectors(ii, key);
super.saveBusinessSector(key, value);
++ii;
}
}
public List<? extends Collection> getBusinessSectorCollection(String key)
{
if(key.equalsIgnoreCase("all"))
return new ArrayList(super.businessSectorCallection.values());
return (List<? extends Collection>) super.retriveBusinessSector(key);
}
@Override
public void objectActityNotify(Object object) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/domain/FinancehubUprocessed.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.domain;
import java.util.Collection;
/**
*
* @author Kobedi.Makgabutlane
*/
public class FinancehubUprocessed extends FinancehubCollection {
@Override
protected boolean addObjectLisst(Collection<Object> list)
{
return super.collection.add(list);
}
@Override
protected Collection<Object> getObjectList()
{
return super.getCollection();
}
@Override
protected Object saveObject(String key, Object value)
{
return super.objectData.putIfAbsent(key, value);
}
@Override
protected Object retrieveObject(String key)
{
return super.objectData.get(key);
}
@Override
protected Object removeObject(String key)
{
return super.objectData.remove(key);
}
@Override
public void objectActityNotify(Object object)
{
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrixsa/web/views/EmailValidationView.java
///*
// * To change this license header, choose License Headers in Project Properties.
// * To change this template file, choose Tools | Templates
// * and open the template in the editor.
// */
package za.co.obeytrixsa.web.views;
import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import za.co.obeytrix.financehub.entity.Registration;
import za.co.obeytrixsa.user.interaction.comms.EmailComms;
import static za.co.obeytrixsa.user.interaction.comms.EmailComms.EmailComms;
/**
*
* @author Kobedi.Makgabutlane
*/
@ManagedBean(name = "emailValidate", eager = true)
@SessionScoped
public class EmailValidationView implements Serializable {
private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(RegistrationView.class);
private int number;
private String otp;
public String getOtp() {
return otp;
}
public void setOtp(String otp) {
this.otp = otp;
}
public int getNumber() {
return number;
}
public void increment() {
number++;
}
public void success() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "Your email has been confirmed, please proceed.\n"
+ "Redirecting to login page details in few seconds"));
}
public void successBO() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "Your email has been confirmed, please proceed to more details.\n"
+ "Redirecting to more details in few seconds"));
}
public void resendMessage() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "A new otp code has sent to your email, please check."));
}
public void failure() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "The provided OTP does not match the emailed OTP,sorry."));
}
public void systemError() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "A system error occured,please register again."));
}
public void proceed() throws IOException {
String mailedOtp = this.otp;
FacesContext context = FacesContext.getCurrentInstance();
ServletContext sc = (ServletContext) context.getExternalContext().getContext();
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
Registration reg = (Registration) sc.getAttribute("registInProgress");
if (reg != null) {
String sentOTP = (String) sc.getAttribute("sentOTP");
LOGGER.info("Sent OTP code " + sentOTP);
if (sentOTP.equalsIgnoreCase(this.otp)) {
String message = EmailComms.determinMessasge(1,reg.getEmail(), reg.getPassword(), sentOTP);// EmailComms.determinMessasge(1, reg.getEmail(), reg.getPassword(), sentOTP);
EmailComms(reg.getEmail(), message);
message = EmailComms.determinMessasge(2, null, null, null);
EmailComms(reg.getEmail(), message);
String regEntity = (String)sc.getAttribute("regEntity");
if(regEntity!=null && regEntity.equalsIgnoreCase("BOReg"))
{
successBO();
LOGGER.info("BO Registration");
sc.setAttribute("regEntity",null);
try {
Thread.currentThread().sleep(1000*9);
context.getExternalContext().redirect("application.xhtml");
} catch (InterruptedException ex) {
Logger.getLogger(EmailValidationView.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
success();
LOGGER.info("NonBo Registration");
sc.setAttribute("regEntity",null);
try {
Thread.currentThread().sleep(1000*9);
context.getExternalContext().redirect("login.xhtml");
} catch (InterruptedException ex) {
Logger.getLogger(EmailValidationView.class.getName()).log(Level.SEVERE, null, ex);
}
}
sc.setAttribute("sentOTP",null);
} else {
failure();
}
}
else
systemError();
}
public void resend() {
String mailedOtp = this.otp;
FacesContext context = FacesContext.getCurrentInstance();
ServletContext sc = (ServletContext) context.getExternalContext().getContext();
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
Registration reg = (Registration) sc.getAttribute("registInProgress");
if (reg != null) {
this.otp = new String(EmailComms.OTP());
sc.setAttribute("sentOTP",null);
sc.setAttribute("sentOTP", this.otp);
String message = EmailComms.determinMessasge(0, null, null, this.otp);
EmailComms(reg.getEmail(), message);
resendMessage();
}
}
}<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/entity/FinancehubUser.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author Kobedi.Makgabutlane
*/
@Entity
@Table(name = "fh_user")
public class FinancehubUser implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "USER_ID")
private int userId;
@Column(name = "STATUS")
private int status;
@Column(name = "FK_ROLE_ID")
private int roleId;
@Column(name = "FK_ORG_ID")
private int orgId;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
@Column(name = "CELL_PHONE")
private String cellphone;
@Column(name = "EMAIL")
private String email;
@Column(name = "PASSWORD")
private String passsword;
@Column(name = "CREATE_DATE", insertable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date createDate;
@Column(name = "MODIFIED_DATE", insertable = true, updatable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date modifiedDate;
@Column(name = "MODIFIED_BY")
private int modifiedBy;
public int getOrgId() {
return orgId;
}
public void setOrgId(int orgId) {
this.orgId = orgId;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPasssword() {
return passsword;
}
public void setPasssword(String passsword) {
this.passsword = passsword;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public int getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(int modifiedBy) {
this.modifiedBy = modifiedBy;
}
@Override
public String toString() {
return "FinancehubUser{" + "userId=" + userId + ", status=" + status + ", roleId=" + roleId + ", firstName=" + firstName + ", lastName=" + lastName + ", cellphone=" + cellphone + ", email=" + email + ", passsword=" + passsword + ", createDate=" + createDate + ", modifiedDate=" + modifiedDate + ", modifiedBy=" + modifiedBy + '}';
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/beans/Application.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrix.financehub.beans;
import za.co.obeytrix.financehub.entity.FinancehubApplication;
/**
*
* @author kobedi.makgabutlane
*/
public class Application {
private Integer applicantId;
private Integer institutionId;
private String applicantName;
private String productName;
private String applicationStatus;
private String applicationDate;
private Application selectedApplication;
private String funder;
private boolean isAccepted;
public Application(Integer applicantId, Integer institutionId, String applicantName, String productName, String applicationStatus, String applicationDate) {
this.applicantId = applicantId;
this.institutionId = institutionId;
this.applicantName = applicantName;
this.productName = productName;
this.applicationStatus = applicationStatus;
this.applicationDate = applicationDate;
}
public Application(Integer applicantId, Integer institutionId, String funder, String productName, String applicationStatus, String applicationDate,boolean accepted) {
this.applicantId = applicantId;
this.institutionId = institutionId;
this.funder = funder;
this.productName = productName;
this.applicationStatus = applicationStatus;
this.applicationDate = applicationDate;
this.isAccepted = accepted;
}
public String getFunder() {
return funder;
}
public void setFunder(String funder) {
this.funder = funder;
}
public boolean isIsAccepted() {
return isAccepted;
}
public void setIsAccepted(boolean isAccepted) {
this.isAccepted = isAccepted;
}
public Application getSelectedApplication() {
return selectedApplication;
}
public void setSelectedApplication(Application selectedApplication) {
System.out.println("Application : set:: " + this.selectedApplication);
this.selectedApplication = selectedApplication;
}
public Integer getApplicantId() {
return applicantId;
}
public void setApplicantId(Integer applicantId) {
this.applicantId = applicantId;
}
public Integer getInstitutionId() {
return institutionId;
}
public void setInstitutionId(Integer institutionId) {
this.institutionId = institutionId;
}
public String getApplicantName() {
return applicantName;
}
public void setApplicantName(String applicantName) {
this.applicantName = applicantName;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getApplicationStatus() {
return applicationStatus;
}
public void setApplicationStatus(String applicationStatus) {
this.applicationStatus = applicationStatus;
}
public String getApplicationDate() {
return applicationDate;
}
public void setApplicationDate(String applicationDate) {
this.applicationDate = applicationDate;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/fianancehub/utility/CaptureProductFormRenderingUtility.java
package za.co.obeytrix.fianancehub.utility;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import za.co.obeytrix.financehub.dao.BusinessSectorDAO;
import za.co.obeytrix.financehub.dao.FinanceAmountDAO;
import za.co.obeytrix.financehub.dao.ProvincialScopeDAO;
import za.co.obeytrix.financehub.dao.PurposeForFinanceDAO;
import za.co.obeytrix.financehub.entity.BusinessSector;
import za.co.obeytrix.financehub.entity.FinanceAmount;
import za.co.obeytrix.financehub.entity.ProvincialScope;
import za.co.obeytrix.financehub.entity.PurposeForFinance;
public class CaptureProductFormRenderingUtility {
Logger logger = LoggerFactory.getLogger(CaptureProductFormRenderingUtility.class);
private BusinessSectorDAO businessSectorDAO;
private PurposeForFinanceDAO purposeForFinanceDAO;
private ProvincialScopeDAO provincialScopeDAO;
private FinanceAmountDAO financeAmountDAO;
private RequiredDocumentation requiredDocumentation;
private QualificationCriteria qualificationCriteria;
private List<String> businessSectorList = new ArrayList<String>();
private List<String> purposeForFinanceList = new ArrayList<String>();
private List<String> provincialScopeList = new ArrayList<String>();
private Map<String, String> financeAmountMap = new HashMap<String, String>();
public CaptureProductFormRenderingUtility() {
businessSectorDAO = new BusinessSectorDAO();
populateBusinessSectors();
purposeForFinanceDAO = new PurposeForFinanceDAO();
populatePurposeForFinance();
provincialScopeDAO = new ProvincialScopeDAO();
populateProvincialScopeList();
financeAmountDAO = new FinanceAmountDAO();
populateFinanceAmountMap();
}
private void populateBusinessSectors() {
List<BusinessSector> bslist = businessSectorDAO.getAllBusinessSectors();
logger.info("Number of business sectors found: " + bslist.size());
for (BusinessSector bs : bslist ) {
businessSectorList.add(bs.getBusinessSector());
}
}
private void populatePurposeForFinance() {
List<PurposeForFinance> purposeList = purposeForFinanceDAO.getAllPurposesForFinance();
for (PurposeForFinance fp : purposeList) {
purposeForFinanceList.add(fp.getPurposeDescription());
}
}
private void populateProvincialScopeList() {
List<ProvincialScope> scopeList = provincialScopeDAO.getAllProvincialScopes();
for (ProvincialScope ps : scopeList) {
provincialScopeList.add(ps.getProvince());
}
}
private void populateFinanceAmountMap() {
List<FinanceAmount> financeAmountList = financeAmountDAO.getAllFinanceAmounts();
for (FinanceAmount fa : financeAmountList) {
financeAmountMap.put(fa.getAmount(), fa.getAmount());
}
}
public RequiredDocumentation getRequiredDocumentation() {
return requiredDocumentation;
}
public void setRequiredDocumentation(RequiredDocumentation requiredDocumentation) {
this.requiredDocumentation = requiredDocumentation;
}
public QualificationCriteria getQualificationCriteria() {
return qualificationCriteria;
}
public void setQualificationCriteria(QualificationCriteria qualificationCriteria) {
this.qualificationCriteria = qualificationCriteria;
}
public List<String> getBusinessSectorList() {
return businessSectorList;
}
public void setBusinessSectorList(List<String> businessSectorList) {
this.businessSectorList = businessSectorList;
}
public List<String> getPurposeForFinanceList() {
return purposeForFinanceList;
}
public void setPurposeForFinanceList(List<String> purposeForFinanceList) {
this.purposeForFinanceList = purposeForFinanceList;
}
public List<String> getProvincialScopeList() {
return provincialScopeList;
}
public void setProvincialScopeList(List<String> provincialScopeList) {
this.provincialScopeList = provincialScopeList;
}
public Map<String, String> getFinanceAmountMap() {
return financeAmountMap;
}
public void setFinanceAmountMap(Map<String, String> financeAmountMap) {
this.financeAmountMap = financeAmountMap;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/financehub/beans/AllProductsMB.java
package za.co.obeytrix.financehub.beans;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.apache.log4j.Logger;
import za.co.obeytrix.financehub.entity.Funding;
import za.co.obeytrixsa.search.engine.PreliminarySearchUtility;
@ManagedBean
@SessionScoped
public class AllProductsMB implements Serializable {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(AllProductsMB.class);
private PreliminarySearchUtility utility;
private Funding selectedProduct;
public AllProductsMB() {
}
@PostConstruct
public void init() {
utility = new PreliminarySearchUtility();
utility.doPreliminarySearch();
}
public void editProductListener(ActionEvent actionEvent) {
logger.info("Processing action event for redirecting to apply page.");
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getAttributes().put("selectedProduct", selectedProduct);
try {
ec.redirect(ec.getRequestContextPath() + "/editProduct.xhtml");
} catch (IOException e) {
e.printStackTrace();
}
}
public PreliminarySearchUtility getUtility() {
return utility;
}
public void setUtility(PreliminarySearchUtility utility) {
this.utility = utility;
}
public Funding getSelectedProduct() {
return selectedProduct;
}
public void setSelectedProduct(Funding selectedProduct) {
this.selectedProduct = selectedProduct;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrixsa/web/views/MyInboxView.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package za.co.obeytrixsa.web.views;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import za.co.obeytrix.financehub.beans.MyInboxData;
/**
*
* @author kobedi.makgabutlane
*/
@ManagedBean(name = "myInboxFormView", eager = true)
@SessionScoped
public class MyInboxView implements Serializable {
private List<MyInboxData> myInboxList;
@ManagedProperty("#{viewService}")
private ViewService service;
@PostConstruct
public void generateInboxInfo()
{
if(service!=null)
{
// myInboxList = service.getMyInboxList();
// myInboxList = service.getMyInboxDataFromDB();
}
else
{
System.out.println("Service was not injected");
}
}
public List<MyInboxData> getMyInboxList() {
return myInboxList;
}
public void setService(ViewService service) {
this.service = service;
}
}
<file_sep>/financehub/src/main/java/za/co/obeytrix/fianancehub/utility/ProductReportUtility.java
package za.co.obeytrix.fianancehub.utility;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.PostConstruct;
import javax.persistence.Tuple;
import org.primefaces.model.chart.Axis;
import org.primefaces.model.chart.AxisType;
import org.primefaces.model.chart.BarChartModel;
import org.primefaces.model.chart.ChartSeries;
import org.primefaces.model.chart.HorizontalBarChartModel;
import org.primefaces.model.chart.PieChartModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import za.co.obeytrix.financehub.dao.ProductReportDAO;
import za.co.obeytrix.financehub.entity.BusinessSectors;
import za.co.obeytrix.financehub.entity.Funding;
import za.co.obeytrix.financehub.entity.ProvincialScope;
import za.co.obeytrix.financehub.entity.PurposeForFinance;
import za.co.obeytrix.financehub.persistence.maps.BusinessSectorHolder;
import za.co.obeytrix.financehub.persistence.maps.BusinessSectorMap;
import za.co.obeytrix.financehub.persistence.maps.FunderHolder;
import za.co.obeytrix.financehub.persistence.maps.FunderMap;
import za.co.obeytrix.financehub.persistence.maps.ProvincialScopeHolder;
import za.co.obeytrix.financehub.persistence.maps.ProvincialScopeMap;
import za.co.obeytrix.financehub.persistence.maps.PurposeForFinanceHolder;
import za.co.obeytrix.financehub.persistence.maps.PurposeForFinanceMap;
public class ProductReportUtility implements Serializable {
private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory.getLogger(ProductReportUtility.class);
//private PieChartModel sectorPieChart;
private PieChartModel sectorPieChartFromMap;
//private PieChartModel provincePieChart;
private PieChartModel provincePieChartFromMap;
//private PieChartModel financeTypePieChart;
private PieChartModel financeTypePieChartFromMap;
//private BarChartModel amountBarChart;
private BarChartModel amountBarChartFromMap;
private String productReportString = "Product report utility is fine";
//private List<Funding> allProducts = new ArrayList<Funding>();
private List<FunderHolder> allProductsFromMap = new ArrayList<FunderHolder>();
public ProductReportUtility() {
logger.info("Constructing ProductReportUtility");
//sectorPieChart = new PieChartModel();
//populateSectorPie();
sectorPieChartFromMap = new PieChartModel();
populateSectorPieFromMap();
//financeTypePieChart = new PieChartModel();
//populateFinanceTypePie();
financeTypePieChartFromMap = new PieChartModel();
populateFinanceTypePieFromMap();
//provincePieChart = new PieChartModel();
//populateProvincePie();
provincePieChartFromMap = new PieChartModel();
populateProvincePieFromMap();
//amountBarChart = new BarChartModel();
//populateAmountBarChart();
//allProducts = populateAllProducts();
allProductsFromMap = populateAllProductsFromMap();
amountBarChartFromMap = new BarChartModel();
populateAmountBarChartFromMap();
}
/*private List<Funding> populateAllProducts() {
return ProductReportDAO.getInstance().getAllProducts();
}*/
private List<FunderHolder> populateAllProductsFromMap() {
List<FunderHolder> allProductsList = new ArrayList<>();
ConcurrentMap<String, FunderHolder> fundingMap = FunderMap.getInstance().getFundingHolderMap();
System.out.println("FunderMap: " + fundingMap);
Set<String> keys = fundingMap.keySet();
FunderHolder funding;
for(String key : keys) {
funding = fundingMap.get(key);
allProductsList.add(funding);
}
System.out.println("All product list: " + allProductsList);
return allProductsList;
}
private void populateAmountBarChartFromMap() {
int cat1Count = 0;
int cat2Count = 0;
int cat3Count = 0;
int cat4Count = 0;
int cat5Count = 0;
ConcurrentMap<String, FunderHolder> fundingMap = FunderMap.getInstance().getFundingHolderMap();
Set<String> keys = fundingMap.keySet();
for(String key : keys) {
if (!fundingMap.get(key).toString().isEmpty()) {
if (categoryIsInRangeForMaps(fundingMap.get(key), BarChartBoundaryValues.R1K.getValue(), BarChartBoundaryValues.R50K.getValue())) {
cat1Count++;
}
if (categoryIsInRangeForMaps(fundingMap.get(key), BarChartBoundaryValues.R50K.getValue(), BarChartBoundaryValues.R500K.getValue())) {
cat2Count++;
}
if (categoryIsInRangeForMaps(fundingMap.get(key), BarChartBoundaryValues.R500K.getValue(), BarChartBoundaryValues.R1M.getValue())) {
cat3Count++;
}
if (categoryIsInRangeForMaps(fundingMap.get(key), BarChartBoundaryValues.R1M.getValue(), BarChartBoundaryValues.R10M.getValue())) {
cat4Count++;
}
if (categoryIsInRangeForMaps(fundingMap.get(key), BarChartBoundaryValues.R10M.getValue(), 49000000)) {
cat5Count++;
}
}
}
ChartSeries series = new ChartSeries();
amountBarChartFromMap.setTitle("Funding Amounts");
amountBarChartFromMap.setLegendPosition("ne");
series.setLabel("Funders");
series.set(BarChartBoundaryValues.R1K + "-" +BarChartBoundaryValues.R50K , cat1Count);
series.set(">" + BarChartBoundaryValues.R50K + "-" +BarChartBoundaryValues.R500K , cat2Count);
series.set(">" + BarChartBoundaryValues.R500K + "-" +BarChartBoundaryValues.R1M , cat3Count);
series.set(">" + BarChartBoundaryValues.R1M + "-" +BarChartBoundaryValues.R10M , cat4Count);
series.set(">" + BarChartBoundaryValues.R10M + "-" +BarChartBoundaryValues.R50M , cat5Count);
amountBarChartFromMap.addSeries(series);
Axis xAxis = amountBarChartFromMap.getAxis(AxisType.X);
xAxis.setLabel("Finance Amount");
Axis yAxis = amountBarChartFromMap.getAxis(AxisType.Y);
yAxis.setLabel("Funders");
yAxis.setTickInterval("5");
yAxis.setMin(0);
yAxis.setMax(20);
}
/*private void populateAmountBarChart() {
List<Tuple> amountsTuple = ProductReportDAO.getInstance().getAllMinAndMaxAmounts();
int cat1Count = 0;
int cat2Count = 0;
int cat3Count = 0;
int cat4Count = 0;
int cat5Count = 0;
for (Tuple tuple : amountsTuple) {
if (categoryIsInRange(tuple, BarChartBoundaryValues.R1K.getValue(), BarChartBoundaryValues.R50K.getValue())) {
cat1Count++;
}
if (categoryIsInRange(tuple, BarChartBoundaryValues.R50K.getValue(), BarChartBoundaryValues.R500K.getValue())) {
cat2Count++;
}
if (categoryIsInRange(tuple, BarChartBoundaryValues.R500K.getValue(), BarChartBoundaryValues.R1M.getValue())) {
cat3Count++;
}
if (categoryIsInRange(tuple, BarChartBoundaryValues.R1M.getValue(), BarChartBoundaryValues.R10M.getValue())) {
cat4Count++;
}
if (categoryIsInRange(tuple, BarChartBoundaryValues.R10M.getValue(), 49000000)) {
cat5Count++;
}
}
ChartSeries series = new ChartSeries();
amountBarChart.setTitle("Funding Amounts");
amountBarChart.setLegendPosition("ne");
series.setLabel("Funders");
series.set(BarChartBoundaryValues.R1K + "-" +BarChartBoundaryValues.R50K , cat1Count);
series.set(">" + BarChartBoundaryValues.R50K + "-" +BarChartBoundaryValues.R500K , cat2Count);
series.set(">" + BarChartBoundaryValues.R500K + "-" +BarChartBoundaryValues.R1M , cat3Count);
series.set(">" + BarChartBoundaryValues.R1M + "-" +BarChartBoundaryValues.R10M , cat4Count);
series.set(">" + BarChartBoundaryValues.R10M + "-" +BarChartBoundaryValues.R50M , cat5Count);
amountBarChart.addSeries(series);
Axis xAxis = amountBarChart.getAxis(AxisType.X);
xAxis.setLabel("Finance Amount");
Axis yAxis = amountBarChart.getAxis(AxisType.Y);
yAxis.setLabel("Funders");
yAxis.setTickInterval("5");
yAxis.setMin(0);
yAxis.setMax(20);
}*/
private boolean categoryIsInRange(Tuple tuple, Integer categoryLowerBound, Integer categoryUpperBound) {
if ((tuple.get("minFinanceAmount") != null)
& (tuple.get("maxFinanceAmount") != null)) {
Integer min = BarChartBoundaryValues.valueOf(tuple.get("minFinanceAmount").toString()).getValue();
Integer max = BarChartBoundaryValues.valueOf(tuple.get("maxFinanceAmount").toString()).getValue();
if ((categoryLowerBound >= min )
& (categoryUpperBound < max)) {
return true;
}
}
return false;
}
private boolean categoryIsInRangeForMaps(FunderHolder funding, Integer categoryLowerBound, Integer categoryUpperBound) {
if (((funding.getMaxFinanceAmount() != null) && (!funding.getMaxFinanceAmount().isEmpty()))
&& ((funding.getMinFinanceAmount() != null) && (!funding.getMinFinanceAmount().isEmpty()))) {
System.out.println("Min amount: " + funding.getMinFinanceAmount().toString());
System.out.println("Mix amount: " + funding.getMaxFinanceAmount().toString());
Integer min = BarChartBoundaryValues.valueOf(funding.getMinFinanceAmount().toString()).getValue();
Integer max = BarChartBoundaryValues.valueOf(funding.getMaxFinanceAmount().toString()).getValue();
if ((categoryLowerBound >= min )
& (categoryUpperBound < max)) {
return true;
}
}
return false;
}
/*private void populateFinanceTypePie() {
financeTypePieChart.set(FinanceTypeNames.ASSET_BASED_FINANCE.getName(), countFinanceTypeValues(FinanceTypeNames.ASSET_BASED_FINANCE.getName()));
financeTypePieChart.set(FinanceTypeNames.EXPANSION_CAPITAL.getName(), countFinanceTypeValues(FinanceTypeNames.EXPANSION_CAPITAL.getName()));
financeTypePieChart.set(FinanceTypeNames.CREDIT_GUARANTEE.getName(), countFinanceTypeValues(FinanceTypeNames.CREDIT_GUARANTEE.getName()));
financeTypePieChart.set(FinanceTypeNames.ACQUISION_FINANCE.getName(), countFinanceTypeValues(FinanceTypeNames.ACQUISION_FINANCE.getName()));
financeTypePieChart.set(FinanceTypeNames.GRANT.getName(), countFinanceTypeValues(FinanceTypeNames.GRANT.getName()));
financeTypePieChart.set(FinanceTypeNames.EQUITY_INSTRUMENTS.getName(), countFinanceTypeValues(FinanceTypeNames.EQUITY_INSTRUMENTS.getName()));
financeTypePieChart.set(FinanceTypeNames.ASSET_FINANCE.getName(), countFinanceTypeValues(FinanceTypeNames.ASSET_FINANCE.getName()));
financeTypePieChart.set(FinanceTypeNames.EXPORT.getName(), countFinanceTypeValues(FinanceTypeNames.EXPORT.getName()));
financeTypePieChart.set(FinanceTypeNames.TRADE_FINANCE.getName(), countFinanceTypeValues(FinanceTypeNames.TRADE_FINANCE.getName()));
financeTypePieChart.set(FinanceTypeNames.WORKING_CAPITAL.getName(), countFinanceTypeValues(FinanceTypeNames.WORKING_CAPITAL.getName()));
financeTypePieChart.set(FinanceTypeNames.OTHER.getName(), countFinanceTypeValues(FinanceTypeNames.OTHER.getName()));
financeTypePieChart.setTitle("Finance Type Availability");
financeTypePieChart.setLegendPosition("W");
financeTypePieChart.setShowDataLabels(true);
}*/
private void populateFinanceTypePieFromMap() {
financeTypePieChartFromMap.set(FinanceTypeNames.ASSET_BASED_FINANCE.getName(), countFinanceTypeValuesFromMap(FinanceTypeNames.ASSET_BASED_FINANCE.getName()));
financeTypePieChartFromMap.set(FinanceTypeNames.EXPANSION_CAPITAL.getName(), countFinanceTypeValuesFromMap(FinanceTypeNames.EXPANSION_CAPITAL.getName()));
financeTypePieChartFromMap.set(FinanceTypeNames.CREDIT_GUARANTEE.getName(), countFinanceTypeValuesFromMap(FinanceTypeNames.CREDIT_GUARANTEE.getName()));
financeTypePieChartFromMap.set(FinanceTypeNames.ACQUISION_FINANCE.getName(), countFinanceTypeValuesFromMap(FinanceTypeNames.ACQUISION_FINANCE.getName()));
financeTypePieChartFromMap.set(FinanceTypeNames.GRANT.getName(), countFinanceTypeValuesFromMap(FinanceTypeNames.GRANT.getName()));
financeTypePieChartFromMap.set(FinanceTypeNames.EQUITY_INSTRUMENTS.getName(), countFinanceTypeValuesFromMap(FinanceTypeNames.EQUITY_INSTRUMENTS.getName()));
financeTypePieChartFromMap.set(FinanceTypeNames.ASSET_FINANCE.getName(), countFinanceTypeValuesFromMap(FinanceTypeNames.ASSET_FINANCE.getName()));
financeTypePieChartFromMap.set(FinanceTypeNames.EXPORT.getName(), countFinanceTypeValuesFromMap(FinanceTypeNames.EXPORT.getName()));
financeTypePieChartFromMap.set(FinanceTypeNames.TRADE_FINANCE.getName(), countFinanceTypeValuesFromMap(FinanceTypeNames.TRADE_FINANCE.getName()));
financeTypePieChartFromMap.set(FinanceTypeNames.WORKING_CAPITAL.getName(), countFinanceTypeValuesFromMap(FinanceTypeNames.WORKING_CAPITAL.getName()));
financeTypePieChartFromMap.set(FinanceTypeNames.OTHER.getName(), countFinanceTypeValuesFromMap(FinanceTypeNames.OTHER.getName()));
financeTypePieChartFromMap.setTitle("Finance Type Availability");
financeTypePieChartFromMap.setLegendPosition("W");
financeTypePieChartFromMap.setShowDataLabels(true);
}
/*private void populateProvincePie() {
provincePieChart.set(ProvinceNames.EASTERN_CAPE.getName(), countProvinceValues(ProvinceNames.EASTERN_CAPE.getName()));
provincePieChart.set(ProvinceNames.FREE_STATE.getName(), countProvinceValues(ProvinceNames.FREE_STATE.getName()));
provincePieChart.set(ProvinceNames.GAUTENG.getName(), countProvinceValues(ProvinceNames.GAUTENG.getName()));
provincePieChart.set(ProvinceNames.KZN.getName(), countProvinceValues(ProvinceNames.KZN.getName()));
provincePieChart.set(ProvinceNames.LIMPOPO.getName(), countProvinceValues(ProvinceNames.LIMPOPO.getName()));
provincePieChart.set(ProvinceNames.MPUMALANGA.getName(), countProvinceValues(ProvinceNames.MPUMALANGA.getName()));
provincePieChart.set(ProvinceNames.NORTH_WEST.getName(), countProvinceValues(ProvinceNames.NORTH_WEST.getName()));
provincePieChart.set(ProvinceNames.NORTHERN_CAPE.getName(), countProvinceValues(ProvinceNames.NORTHERN_CAPE.getName()));
provincePieChart.set(ProvinceNames.WESTERN_PROVINCE.getName(), countProvinceValues(ProvinceNames.WESTERN_PROVINCE.getName()));
provincePieChart.setTitle("Finance Products Provincial Scope");
provincePieChart.setLegendPosition("W");
provincePieChart.setShowDataLabels(true);
}*/
private void populateProvincePieFromMap() {
provincePieChartFromMap.set(ProvinceNames.EASTERN_CAPE.getName(), countProvinceValuesFromMap(ProvinceNames.EASTERN_CAPE.getName()));
provincePieChartFromMap.set(ProvinceNames.FREE_STATE.getName(), countProvinceValuesFromMap(ProvinceNames.FREE_STATE.getName()));
provincePieChartFromMap.set(ProvinceNames.GAUTENG.getName(), countProvinceValuesFromMap(ProvinceNames.GAUTENG.getName()));
provincePieChartFromMap.set(ProvinceNames.KZN.getName(), countProvinceValuesFromMap(ProvinceNames.KZN.getName()));
provincePieChartFromMap.set(ProvinceNames.LIMPOPO.getName(), countProvinceValuesFromMap(ProvinceNames.LIMPOPO.getName()));
provincePieChartFromMap.set(ProvinceNames.MPUMALANGA.getName(), countProvinceValuesFromMap(ProvinceNames.MPUMALANGA.getName()));
provincePieChartFromMap.set(ProvinceNames.NORTH_WEST.getName(), countProvinceValuesFromMap(ProvinceNames.NORTH_WEST.getName()));
provincePieChartFromMap.set(ProvinceNames.NORTHERN_CAPE.getName(), countProvinceValuesFromMap(ProvinceNames.NORTHERN_CAPE.getName()));
provincePieChartFromMap.set(ProvinceNames.WESTERN_PROVINCE.getName(), countProvinceValuesFromMap(ProvinceNames.WESTERN_PROVINCE.getName()));
provincePieChartFromMap.setTitle("Finance Products Provincial Scope");
provincePieChartFromMap.setLegendPosition("W");
provincePieChartFromMap.setShowDataLabels(true);
}
/*private void populateSectorPie() {
sectorPieChart.set(SectorNames.MINING.getName(), countBusinessSectorsValues(SectorNames.MINING.getName()));
sectorPieChart.set(SectorNames.AGRICULTURE.getName(), countBusinessSectorsValues(SectorNames.AGRICULTURE.getName()));
sectorPieChart.set(SectorNames.COMMUNICATION.getName(), countBusinessSectorsValues(SectorNames.COMMUNICATION.getName()));
sectorPieChart.set(SectorNames.CONSTRUCTION.getName(), countBusinessSectorsValues(SectorNames.CONSTRUCTION.getName()));
sectorPieChart.set(SectorNames.ENERGY.getName(), countBusinessSectorsValues(SectorNames.ENERGY.getName()));
sectorPieChart.set(SectorNames.FINANCE_SERVICES.getName(), countBusinessSectorsValues(SectorNames.FINANCE_SERVICES.getName()));
sectorPieChart.set(SectorNames.MANUFACTURING.getName(), countBusinessSectorsValues(SectorNames.MANUFACTURING.getName()));
sectorPieChart.set(SectorNames.TOURSISM.getName(), countBusinessSectorsValues(SectorNames.TOURSISM.getName()));
sectorPieChart.set(SectorNames.TRANSPORT.getName(), countBusinessSectorsValues(SectorNames.TRANSPORT.getName()));
sectorPieChart.set(SectorNames.WHOLESALE.getName(), countBusinessSectorsValues(SectorNames.WHOLESALE.getName()));
sectorPieChart.setTitle("Business Sector Coverage");
sectorPieChart.setLegendPosition("W");
sectorPieChart.setShowDataLabels(true);
}*/
private void populateSectorPieFromMap() {
sectorPieChartFromMap.set(SectorNames.MINING.getName(), countBusinessSectorsValuesFromMap(SectorNames.MINING.getName()));
sectorPieChartFromMap.set(SectorNames.AGRICULTURE.getName(), countBusinessSectorsValuesFromMap(SectorNames.AGRICULTURE.getName()));
sectorPieChartFromMap.set(SectorNames.COMMUNICATION.getName(), countBusinessSectorsValuesFromMap(SectorNames.COMMUNICATION.getName()));
sectorPieChartFromMap.set(SectorNames.CONSTRUCTION.getName(), countBusinessSectorsValuesFromMap(SectorNames.CONSTRUCTION.getName()));
sectorPieChartFromMap.set(SectorNames.ENERGY.getName(), countBusinessSectorsValuesFromMap(SectorNames.ENERGY.getName()));
sectorPieChartFromMap.set(SectorNames.FINANCE_SERVICES.getName(), countBusinessSectorsValuesFromMap(SectorNames.FINANCE_SERVICES.getName()));
sectorPieChartFromMap.set(SectorNames.MANUFACTURING.getName(), countBusinessSectorsValuesFromMap(SectorNames.MANUFACTURING.getName()));
sectorPieChartFromMap.set(SectorNames.TOURSISM.getName(), countBusinessSectorsValuesFromMap(SectorNames.TOURSISM.getName()));
sectorPieChartFromMap.set(SectorNames.TRANSPORT.getName(), countBusinessSectorsValuesFromMap(SectorNames.TRANSPORT.getName()));
sectorPieChartFromMap.set(SectorNames.WHOLESALE.getName(), countBusinessSectorsValuesFromMap(SectorNames.WHOLESALE.getName()));
sectorPieChartFromMap.setTitle("Business Sector Coverage");
sectorPieChartFromMap.setLegendPosition("W");
sectorPieChartFromMap.setShowDataLabels(true);
}
private Number countProvinceValues(String provinceNameValue) {
int count = 0;
List<ProvincialScope> provinceList = ProductReportDAO.getInstance().getAllProvincialScopes();
logger.info("Provincial scopes found for report: " + provinceList.size());
for (ProvincialScope scope : provinceList) {
if (scope.getProvince().contains(provinceNameValue)) {
count++;
}
}
return count;
}
private Number countProvinceValuesFromMap(String provinceNameValue) {
int count = 0;
ConcurrentMap<String, ProvincialScopeHolder> scopeMap = ProvincialScopeMap.getInstance().getProvincialScopeHolderMap();
logger.info("Provincial scopes found for report: " + scopeMap.size());
Set<String> keys = scopeMap.keySet();
for(String key : keys) {
if (scopeMap.get(key).toString().contains(provinceNameValue)) {
count++;
}
}
return count;
}
private int countFinanceTypeValues(String financeTypeValue) {
int count = 0;
List<PurposeForFinance> financeTypeList = ProductReportDAO.getInstance().getAllFinanceTypes();
logger.info("Finance types found for report: " + financeTypeList.size());
for (PurposeForFinance purpose : financeTypeList) {
if (purpose.getPurposeDescription().contains(financeTypeValue)) {
count++;
}
}
return count;
}
private int countFinanceTypeValuesFromMap(String financeTypeValue) {
int count = 0;
ConcurrentMap<String, PurposeForFinanceHolder> financePurposeMap = PurposeForFinanceMap.getInstance().getPurposeForFinanceHolderMap();
logger.info("Finance types found for report: " + financePurposeMap.size());
Set<String> keys = financePurposeMap.keySet();
for(String key : keys) {
if (financePurposeMap.get(key).toString().contains(financeTypeValue)) {
count++;
}
}
return count;
}
private int countBusinessSectorsValues(String businessSectorValue) {
int count = 0;
List<BusinessSectors> businessSectorsList = ProductReportDAO.getInstance().getAllBusinessSectors();
logger.info("Business sectors found for report: " + businessSectorsList.size());
for (BusinessSectors sector : businessSectorsList) {
if (sector.getBusinesssector().contains(businessSectorValue)) {
count++;
}
}
return count;
}
private int countBusinessSectorsValuesFromMap(String businessSectorValue) {
int count = 0;
ConcurrentMap<String, BusinessSectorHolder> businessSectorsMap = BusinessSectorMap.getInstance().getBusinessSectorHolderMap();
logger.info("Business sectors found for report in map: " + businessSectorsMap.size());
Set<String> keys = businessSectorsMap.keySet();
for(String key : keys) {
if (businessSectorsMap.get(key).toString().contains(businessSectorValue)) {
count++;
}
}
return count;
}
/*public PieChartModel getSectorPieChart() {
return sectorPieChart;
}
public void setSectorPieChart(PieChartModel sectorPieChart) {
this.sectorPieChart = sectorPieChart;
} */
public PieChartModel getSectorPieChartFromMap() {
return sectorPieChartFromMap;
}
public void setSectorPieChartFromMap(PieChartModel sectorPieChartFromMap) {
this.sectorPieChartFromMap = sectorPieChartFromMap;
}
/*public PieChartModel getProvincePieChart() {
return provincePieChart;
}
public void setProvincePieChart(PieChartModel provincePieChart) {
this.provincePieChart = provincePieChart;
}*/
/*public PieChartModel getFinanceTypePieChart() {
return financeTypePieChart;
}
public void setFinanceTypePieChart(PieChartModel financeTypePieChart) {
this.financeTypePieChart = financeTypePieChart;
}
public PieChartModel getFinanceTypePieChartFromMap() {
return financeTypePieChartFromMap;
}*/
public void setFinanceTypePieChartFromMap(PieChartModel financeTypePieChartFromMap) {
this.financeTypePieChartFromMap = financeTypePieChartFromMap;
}
/*public BarChartModel getAmountBarChart() {
return amountBarChart;
}
public void setAmountBarChart(BarChartModel amountBarChart) {
this.amountBarChart = amountBarChart;
} */
public BarChartModel getAmountBarChartFromMap() {
return amountBarChartFromMap;
}
public void setAmountBarChartFromMap(BarChartModel amountBarChartFromMap) {
this.amountBarChartFromMap = amountBarChartFromMap;
}
public String getProductReportString() {
return productReportString;
}
public void setProductReportString(String productReportString) {
this.productReportString = productReportString;
}
/*public List<Funding> getAllProducts() {
return allProducts;
}*/
public List<FunderHolder> getAllProductsFromMap() {
return allProductsFromMap;
}
public PieChartModel getProvincePieChartFromMap() {
return provincePieChartFromMap;
}
public void setProvincePieChartFromMap(PieChartModel provincePieChartFromMap) {
this.provincePieChartFromMap = provincePieChartFromMap;
}
public PieChartModel getFinanceTypePieChartFromMap() {
return financeTypePieChartFromMap;
}
}
|
cec3d2bcf8b354e580a7dfea09cbd4a29412d235
|
[
"Java",
"JavaScript",
"Maven POM"
] | 57 |
Java
|
Financehub/FinRepo
|
a68d61bc2d5a7f288bf3dec6d0ca0420e57385ca
|
a91f0d7aec912d67966c8aef8c7cd7ac0a4dcc91
|
refs/heads/master
|
<file_sep>import java.util.Scanner;
class sum{
public static void main(String[] args) {
int number[] = new int[100];
int sum = 0;
int l;
Scanner input = new Scanner(System.in);
System.out.println("Enter the length of the array.");
l = input.nextInt();
System.out.println("Enter an array:");
for(int i=0; i<l; i++){
number[i] = input.nextInt();
}
System.out.println("The array is:");
for(int i=0; i<l; i++){
System.out.print(number[i]+" ");
}
System.out.println();
for(int i = 0; i<number.length; i++){
sum = sum + number[i];
}
System.out.println("The sum is: " + sum);
}
}<file_sep>import java.util.Scanner;
class calc{
public static void main(String args[]){
Scanner cal = new Scanner(System.in);
double a, b, c;
System.out.println("Enter the numbers: ");
a = cal.nextDouble();
b = cal.nextDouble();
c = a + b;
System.out.println(c);
}
}<file_sep>import java.util.Scanner;
class trans{
public static void main(String[] args) {
Scanner mult = new Scanner(System.in);
int a[][] = new int[10][10];
int t[][] = new int[10][10];
int r, c, i, j;
System.out.println("Enter the no. of rows & columns: ");
r = mult.nextInt();
c = mult.nextInt();
System.out.println("Enter elements of a");
for(i=0; i<r; i++){
for(j=0; j<c; j++){
a[i][j] = mult.nextInt();
}
}
System.out.println("The entered matrix is: ");
for(i=0; i<r; i++){
for(j=0; j<c; j++){
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
for(i=0; i<r; i++){
for(j=0; j<c; j++){
t[j][i] = a[i][j];
}
}
System.out.println("The transposed matrix is: ");
for(i=0; i<r; i++){
for(j=0; j<c; j++){
System.out.print(t[i][j]+"\t");
}
System.out.println();
}
}
}
|
059657523d42560478e5ec16bd9e9cedccfb9561
|
[
"Java"
] | 3 |
Java
|
rekib0023/JAVA
|
954bd3e480f2a507a52c2ca3cb31f300e6eb4e97
|
2bfeab286b86b87b546ef5ecc97b71a69b6cfc6e
|
refs/heads/master
|
<repo_name>sudhanshu-soni/HP-World-Store<file_sep>/app/src/main/res/values/strings.xml
<resources>
<string name="app_name">HP World</string>
<string name="logo">logo</string>
<string name="description">Description</string>
<string name="descriptionContent">
<![CDATA[As the world’s leading Technology Company, HP impacts the lives of millions of people around the world. We create new possibilities with technology to have a meaningful impact on people, businesses, governments & society and make technology work for our customers. HP aims to deliver the best experience to customers every single time - at home, at work and on the go. An experience that is differentiated and customized. HP India is the No. 1 PC and Printer brand in India.]]>
</string>
<string name="address">Address</string>
<string name="addressContent">S 34 B, 2nd Flr, Dainik Bhaskar Mall, Electronic Market Hoshangabad Road Bhopal - 462039</string>
<string name="contactTextView">Contact</string>
<string name="mobileNumber">+918657568728</string>
<string name="business_hours">Business Hours</string>
<string name="mon">Mon : 11:30 AM - 09:30 PM</string>
<string name="tue">Tue : 11:30 AM - 09:30 PM</string>
<string name="wed">Wed : 11:30 AM - 09:30 PM</string>
<string name="thu">Thu : 11:30 AM - 09:30 PM</string>
<string name="fri">Fri : 11:30 AM - 09:30 PM</string>
<string name="sat">Sat : 11:30 AM - 09:30 PM</string>
<string name="sun">Sun : 11:30 AM - 09:30 PM</string>
<string name="business_name">Business Name</string>
<string name="hp_world_store">HP World Store</string>
</resources><file_sep>/settings.gradle
include ':app'
rootProject.name='HP World Store'
|
17b249a652c348655bc5fe5bfaea237fe0a5d2e7
|
[
"XML",
"Gradle"
] | 2 |
XML
|
sudhanshu-soni/HP-World-Store
|
29b916802860385c00044f6260272e50d087d4d6
|
a6aae313403bf69425117bf15360c54fddc7c78e
|
refs/heads/master
|
<file_sep>#!/bin/bash
yum install httpd
service httpd start
#checking the status of the httpd
service httpd status
|
526cb49465031195ba45afb108b068a355255d59
|
[
"Shell"
] | 1 |
Shell
|
santhoshrao450/sample
|
c8ed51fbc996cdb775bdc2e61ba6d7973dfdd131
|
dac412f7c4eaffe489f3556399058d0008c8ae0d
|
refs/heads/main
|
<file_sep>from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
from server.organizations.models import SchoolActivityGroup
from server.users.models import Consumer
from server.utils.model_fields import random_slug
class Event(models.Model):
slug = models.CharField(max_length=40, default=random_slug, unique=True)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
consumers = models.ManyToManyField(
Consumer,
blank=True,
)
school_group = models.ForeignKey(
SchoolActivityGroup,
on_delete=models.SET_NULL,
null=True,
)
locations_name = models.CharField(
max_length=250,
null=True,
blank=True,
)
has_summary = models.BooleanField(default=False)
summary_general_notes = models.CharField(
max_length=400,
null=True,
blank=True,
)
summary_general_rating = models.IntegerField(
validators=[
MinValueValidator(0),
MaxValueValidator(10),
],
null=True,
blank=True,
)
summary_children_behavior = models.IntegerField(
validators=[
MinValueValidator(0),
MaxValueValidator(10),
],
null=True,
blank=True,
)
def clean(self):
if self.start_time > self.end_time:
raise ValidationError(
{"end_time": _("end time must occur after start time")}
)
def __str__(self):
return f"{self.school_group} : {self.start_time} : {self.slug}"
class ConsumerEventFeedback(models.Model):
class Meta:
constraints = [
models.UniqueConstraint(
fields=["consumer", "event"], name="unique consumer feedback"
)
]
slug = models.CharField(max_length=40, default=random_slug, unique=True)
event = models.ForeignKey(
Event,
on_delete=models.CASCADE,
)
consumer = models.ForeignKey(
Consumer,
on_delete=models.SET_NULL,
null=True,
blank=False,
)
general_notes = models.CharField(
max_length=400,
blank=True,
)
secondary_notes = models.CharField(
max_length=400,
blank=True,
)
general_rating = models.IntegerField(
validators=[
MinValueValidator(0),
MaxValueValidator(10),
],
null=True,
blank=True,
)
secondary_rating = models.IntegerField(
validators=[
MinValueValidator(0),
MaxValueValidator(10),
],
null=True,
blank=True,
)
<file_sep><template>
<div>
<navbar user-type="vendor" />
<v-row no-gutters>
<v-col class="mt-16 px-6 mx-auto" md="9" xl="8">
<router-view />
</v-col>
</v-row>
</div>
</template>
<script>
import Navbar from "../components/Navbar/Navbar"
export default {
components: {
Navbar,
},
}
</script>
<file_sep>from os import path
from allauth.account.forms import (
EmailAwarePasswordResetTokenGenerator,
ResetPasswordForm,
)
from allauth.account.utils import user_pk_to_url_str
from django.conf import settings
from django.contrib.auth import forms as admin_forms
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.translation import gettext_lazy as _
User = get_user_model()
class UserChangeForm(admin_forms.UserChangeForm):
class Meta(admin_forms.UserChangeForm.Meta):
model = User
class UserCreationForm(admin_forms.UserCreationForm):
class Meta(admin_forms.UserCreationForm.Meta):
model = User
error_messages = {
"username": {"unique": _("This username has already been taken.")}
}
class SendInviteForm(ResetPasswordForm):
"""
used to send an invitation to onboard the platform and reset the password
"""
default_token_generator = EmailAwarePasswordResetTokenGenerator()
def send_email_invite(self, email, uri, uid, token):
context = {
"uri": uri,
"uid": uid,
"token": token,
}
msg_plain = render_to_string("users/invite_with_password_reset.txt", context)
msg_html = render_to_string("users/invite_with_password_reset.html", context)
send_mail(
"Welcome To Connective!",
msg_plain,
None,
[email],
html_message=msg_html,
)
def save(self, request, **kwargs):
email = self.cleaned_data["email"]
token_generator = kwargs.get("token_generator", self.default_token_generator)
for user in self.users:
temp_key = token_generator.make_token(user)
uri = path.join(settings.CLIENT_BASE_URL, "he/welcome/reset-password")
self.send_email_invite(email, uri, user_pk_to_url_str(user), temp_key)
return self.cleaned_data["email"]
<file_sep># Generated by Django 3.1.11 on 2021-07-27 13:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('posts', '0002_auto_20210727_1319'),
]
operations = [
migrations.RenameField(
model_name='post',
old_name='creation_time',
new_name='created',
),
]
<file_sep><template>
<div>
<pagination-select-table
v-if="pagination"
v-bind="$props"
@paginate="$emit('paginate')"
:value="selectedRows"
@input="e => $emit('input', e)"
/>
<select-table
v-else
v-bind="$props"
:value="selectedRows"
@input="e => $emit('input', e)"
/>
<chip-container :labels="getChipLabels()" icon="mdi-account-circle">{{
$t("general.chosen")
}}</chip-container>
</div>
</template>
<script>
// wrapper for the select table (add rows to chips bucket)
import SelectTable from "./SelectTable"
import PaginationSelectTable from "./PaginationSelectTable"
import ChipContainer from "./ChipContainer"
export default {
components: {
SelectTable,
PaginationSelectTable,
ChipContainer,
},
model: {
prop: "selectedRows",
},
props: {
headers: {
// v-data-table headers. e.g., [ { text: 'Calories', value: 'calories' }, ... ]
type: Array,
required: true,
},
items: {
// v-data-table items (i.e., table rows)
type: Array,
required: true,
},
selectedRows: {
type: Array,
required: true
},
pagination: {
type: Boolean,
default: false,
},
totalServerItems: {
// received from server via count field (relevant in pagination mode only)
type: Number,
required: false,
},
loading: {
type: Boolean,
default: false,
},
chipsLabelHeader: {
// headers keys to display on chip
type: [String, Array],
required: true,
},
},
methods: {
getChipLabels() {
return this.selectedRows.map(row => this.getLabel(row))
},
getLabel(row) {
if (!Array.isArray(this.chipsLabelHeader)) {
return row[this.chipsLabelHeader]
}
let label = ""
for (const header of this.chipsLabelHeader) {
label += row[header] + " "
}
return label
},
},
}
</script>
<style lang="scss" scoped>
.chips-container {
width: 650px;
height: 300px;
overflow-y: auto;
}
</style>
<file_sep># Generated by Django 3.1.11 on 2021-07-25 11:42
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('organizations', '0022_importedactivity'),
]
operations = [
migrations.RenameField(
model_name='importedactivity',
old_name='proffesion',
new_name='profession',
),
migrations.RemoveField(
model_name='importedactivity',
name='domain',
),
migrations.RemoveField(
model_name='importedactivity',
name='logo',
),
migrations.RemoveField(
model_name='importedactivity',
name='originization',
),
migrations.RemoveField(
model_name='importedactivity',
name='tags',
),
]
<file_sep>import { action } from "@storybook/addon-actions"
import RadioGroup from "../components/RadioGroup.vue"
export default {
title: "RadioGroup",
component: RadioGroup,
}
const Template = args => ({
components: { RadioGroup },
methods: { action },
data: () => ({ args }),
template: `
<radio-group
class="mx-auto"
style="width: 800px;"
v-model="args.selectedItem"
:title="args.title"
:choices="args.choices"
@input="action('input')()"
/>
`,
})
export const Primary = Template.bind({})
Primary.args = {
title: "בחרו את הפוקימון האהוב עליכם",
selectedItem: "",
choices: [
{
label: "פיקאצ'ו",
value: "pikachu",
},
{
label: "צ'אריזרד",
value: "charizard",
},
{
label: "בולבזאור",
value: "bulbasaur",
},
{
label: "סנורלאקס",
value: "snorlax",
},
],
}
<file_sep>from factory import Faker, SubFactory
from factory.django import DjangoModelFactory
from server.organizations.models import (
Activity,
Organization,
SchoolActivityGroup,
SchoolActivityOrder,
)
from server.schools.tests.factories import SchoolFactory
class OrganizationFactory(DjangoModelFactory):
email = Faker("email")
description = "description"
website_url = "https://org.com"
name = "Organization Name"
goal = "Goal"
year_founded = "2005"
status = "status"
target_audience = [1, 2, 3, 4, 5, 6]
number_of_employees = 100
number_of_members = 200
number_of_volunteers = 30
location_lon = 32.109333
location_lat = 34.855499
address_city = "city"
address_street = "addr"
address_house_num = "13"
address_zipcode = "550202"
cities = {}
districts = {}
union_type = "union type"
class Meta:
model = Organization
class ActivityFactory(DjangoModelFactory):
name = "Activity Name"
target_audience = [1, 2, 3]
domain = "Domain"
originization = SubFactory(OrganizationFactory)
description = "Activity Description"
contact_name = "<NAME>"
logo = None
phone_number = "0521234567"
class Meta:
model = Activity
class SchoolActivityOrderFactory(DjangoModelFactory):
activity = SubFactory(ActivityFactory)
school = SubFactory(SchoolFactory)
class Meta:
model = SchoolActivityOrder
class SchoolActivityGroupFactory(DjangoModelFactory):
activity_order = SubFactory(SchoolActivityOrderFactory)
name = "Group 1"
description = "Group 1"
class Meta:
model = SchoolActivityGroup
<file_sep><template>
<div class="note primary lighten-2">
<p class="text-center">
<slot></slot>
</p>
</div>
</template>
<style scoped lang="scss">
.note {
position: relative;
width: 300px;
min-height: 100px;
margin: 25px auto;
padding: 45px 15px 15px 15px;
-webkit-box-shadow: 0 2px 12px rgba(0, 0, 0, 0.7);
-moz-box-shadow: 0 2px 12px rgba(0, 0, 0, 0.7);
box-shadow: 0 1px 2px #000;
// background: #fff url(https://our.fogbugz.com/images/tbKiwiLogo.gif) no-repeat
// 4px 8px;
}
.note p {
font-size: 36px;
overflow: hidden;
}
.note::before {
content: " ";
display: block;
position: absolute;
left: 115px;
top: -15px;
width: 75px;
height: 25px;
z-index: 2;
background-color: rgba(243, 245, 228, 0.5);
border: 2px solid rgba(255, 255, 255, 0.5);
-webkit-box-shadow: 0 0 5px #888;
-moz-box-shadow: 0 0 5px #888;
box-shadow: 2px 2px 2px #000;
-webkit-transform: rotate(6deg);
-moz-transform: rotate(6deg);
-o-transform: rotate(6deg);
}
</style>
<file_sep># Generated by Django 3.1.11 on 2021-06-13 12:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organizations', '0006_auto_20210613_1101'),
]
operations = [
migrations.AddField(
model_name='schoolactivitygroup',
name='activity_email',
field=models.EmailField(blank=True, max_length=254, null=True),
),
migrations.AddField(
model_name='schoolactivitygroup',
name='activity_website_url',
field=models.URLField(blank=True, null=True),
),
migrations.AlterField(
model_name='schoolactivitygroup',
name='description',
field=models.CharField(max_length=550, verbose_name='description'),
),
]
<file_sep><template>
<v-card
class="my-15 mx-auto px-sm-10 py-sm-10"
max-width="1000"
:min-height="$vuetify.breakpoint.mobile ? 350 : 500"
:elevation="$vuetify.breakpoint.mobile ? 0 : 3"
>
<v-card-title class="text-sm-h4" v-text="$t('events.eventsFeedback')" />
<v-card-subtitle
class="text-md-h6 pt-3"
v-text="$t('events.clickAnEventToGiveFeedbackSoWeCanImproveTogether!')"
/>
<click-list
v-if="formattedEvents.length"
v-model="selected"
class="my-12"
:title="$t('events.eventsToSummarize')"
:items="formattedEvents"
@input="onEventClick"
/>
<div
v-else
class="text-center text-md-h6 absolute-center text-body-1"
v-text="$t('events.eventsToFeedbackWereNotFound')"
/>
</v-card>
</template>
<script>
import store from "../vuex/store"
import moment from "moment"
import ClickList from "../components/ClickList"
export default {
components: { ClickList },
async beforeRouteEnter(to, from, next) {
const events = await store.dispatch("consumerEvent/getPastEvents", 60)
next(vm => (vm.eventsToFeedback = events.filter(e => !e.hasFeedback)))
},
data() {
return {
selected: [],
isEventClicked: false,
eventsToFeedback: null,
}
},
computed: {
formattedEvents() {
if (!this.eventsToFeedback) return []
return this.eventsToFeedback.map(event => ({
action: moment(event.startTime).format("DD.MM.YYYY"),
subtitle: event.activityName,
title: event.schoolGroupName,
}))
},
},
methods: {
onEventClick(e) {
// extract event slug & route to event summary
if (this.isEventClicked) return
this.isEventClicked = true
const eventPos = e[0]
this.$router.push({
name: "ConsumerEventFeedback",
params: { slug: this.eventsToFeedback[eventPos].slug },
})
},
},
}
</script>
<file_sep>const imagemin = require("imagemin")
const imageminWebp = require("imagemin-webp")
const imagesFolder = "src/assets/img/"
imagemin([`${imagesFolder}/original/small/*`], {
destination: `${imagesFolder}/optimized`,
plugins: [imageminWebp({ quality: 100 })],
}).then(() => {
console.log("+ Small Images Optimization: Success!")
})
imagemin([`${imagesFolder}/original/big/*`], {
destination: `${imagesFolder}/optimized`,
plugins: [imageminWebp({ quality: 50 })],
}).then(() => {
console.log("+ Big Images Optimization: Success!")
})
<file_sep><template>
<div>
<div class="d-lg-flex justify-space-between">
<div class="mx-auto">
<h1 v-text="$t('program.programCreation')" class="mb-5" />
<h2
v-text="$t('program.fillInTheDetailsAndCreateNewProgram')"
class="mb-8"
/>
<form-card
v-model="fields"
elevation="0"
class="w-lg-75 mx-auto mx-lg-0"
@valid="isFormValid = true"
@invalid="isFormValid = false"
/>
</div>
<picture-input
class="my-10 mx-auto align-self-center mx-lg-16"
:placeholderPicUrl="CAMERA_ROUNDED_DRAWING"
@fileUpload="setLogo"
/>
</div>
<div class="text-center text-lg-start mt-16 mb-8">
<v-btn
data-testid="save-btn"
large
v-text="$t('userActions.save')"
class="white--text primary"
:disabled="!(isFormValid && logo)"
@click="onSubmit"
/>
<v-btn
class="mx-3 white--text"
color="primary"
outlined
large
v-text="$t('userActions.back')"
@click="$router.go(-1)"
/>
</div>
</div>
</template>
<script>
import cloneDeep from "lodash/cloneDeep"
import { mapActions } from "vuex"
import Api from "../api"
import Utils from "../helpers/utils"
import { VENDOR_PROGRAM_FIELDS } from "../helpers/constants/constants"
import { CAMERA_ROUNDED_DRAWING } from "../helpers/constants/images"
import FormCard from "../components/FormCard"
import PictureInput from "../components/PictureInput"
export default {
components: { FormCard, PictureInput },
data() {
return {
CAMERA_ROUNDED_DRAWING,
fields: cloneDeep(VENDOR_PROGRAM_FIELDS),
isFormValid: false,
logo: null,
}
},
methods: {
...mapActions("vendorProgram", ["createProgram"]),
...mapActions("snackbar", ["showMessage"]),
async onSubmit() {
const data = this.fields.reduce(
(accum, f) => ({ ...accum, [f.name]: f.value }),
{ tags: [], logo: this.logo }
)
try {
const program = await this.createProgram(
Utils.objectToFormData(data)
)
this.showMessage(this.$t("success.programCreatedSuccessfully"))
this.$router.push({
name: "VendorProgramMediaUpload",
params: { programSlug: program.slug },
})
} catch (err) {
const message = Api.utils.parseResponseError(err)
this.showMessage(message)
}
},
setLogo(e) {
this.logo = e
},
},
}
</script>
<file_sep><template>
<v-row no-gutters>
<v-col class="secondary relative" cols="12" lg="5">
<router-view />
</v-col>
<v-col class="relative d-none d-lg-block overflow-hidden" lg="7">
<video width="800" :src="video" autoplay playsinline loop muted class="absolute-center" />
</v-col>
</v-row>
</template>
<script>
import { BACKGROUNDS } from "../helpers/constants/images"
export default {
data() {
return {
video: BACKGROUNDS.welcome,
}
},
}
</script>
<file_sep><template>
<div>
<v-card class="absolute-center py-12 px-7" width="320" elevation="16">
<v-card-title
class="text-h4 justify-center mb-6"
v-text="$t('auth.detailsCompletion')"
/>
<v-card-subtitle
class="text-h6 text-center mb-8"
v-text="$t('general.personalInfo')"
/>
<validation-observer
ref="observer"
tag="form"
v-slot="{ invalid }"
@submit.prevent="submit"
>
<validation-provider v-slot="{ errors }" name="name" rules="required">
<v-text-field
class="mt-5"
v-model="registrationInfo.name"
:error-messages="errors"
:label="$t('general.name')"
required
/>
</validation-provider>
<validation-provider
v-slot="{ errors }"
name="phone"
rules="required|numeric|phoneNumberIsrael"
>
<v-text-field
class="mt-5"
v-model="registrationInfo.phone"
:error-messages="errors"
:label="$t('general.phoneNumber')"
required
/>
</validation-provider>
<div class="mx-auto d-flex justify-center mt-12">
<v-btn
class="ml-3 white--text"
type="submit"
color="primary"
elevation="3"
v-text="$t('auth.detailsConfirmation')"
:disabled="invalid"
/>
<v-btn
class="mr-3"
type="button"
color="primary"
elevation="3"
outlined
v-text="$t('userActions.toHomepage')"
@click="logout"
/>
</div>
</validation-observer>
</v-card>
<modal
:redirectComponentName="modalRedirectComponentName"
v-show="popupMsg !== ''"
@close="popupMsg = ''"
>
{{ popupMsg }}
</modal>
</div>
</template>
<script>
import { mapActions } from "vuex"
import debounce from "lodash/debounce"
import { ValidationObserver, ValidationProvider } from "vee-validate"
import store from "../../vuex/store"
import Modal from "../../components/Modal"
import Api from "../../api"
export default {
components: {
ValidationProvider,
ValidationObserver,
Modal,
},
data() {
return {
modalRedirectComponentName: "",
slug: null,
popupMsg: "",
registrationInfo: {
name: "",
phone: "",
},
}
},
async mounted() {
let userDetails = await store.dispatch("user/getUserDetails")
this.slug = userDetails.slug
},
methods: {
...mapActions("user", ["updateUserDetails"]),
...mapActions("vendor", ["updateProfile"]),
...mapActions("snackbar", ["showMessage"]),
...mapActions("auth", ["logout"]),
submit: debounce(
async function () {
try {
await Promise.all[
(this.updateProfile({
slug: this.slug,
profile: { phoneNumber: this.registrationInfo.phone },
}),
this.updateUserDetails({
slug: this.slug,
userDetails: { name: this.registrationInfo.name },
}))
]
this.modalRedirectComponentName = "VendorProfile"
this.popupMsg = this.$t("general.detailsSuccessfullyUpdated")
} catch (err) {
const message = Api.utils.parseResponseError(err)
this.showMessage(message)
}
},
500,
{ leading: true, trailing: false }
),
},
}
</script>
<style lang="scss" scoped>
.v-card__subtitle,
.v-card__text,
.v-card__title {
padding: 0;
}
</style>
<file_sep><template>
<hover-button @click="isDialogOpen = true" circle :shadow="false">
<avataaars v-bind="avataaarsOptions" />
<form-dialog
:title="$t('auth.profilePicture')"
v-model="isDialogOpen"
:inputFields="dialogOptions"
@save="saveAvatarOptions"
/>
</hover-button>
</template>
<script>
import Avataaars from "vuejs-avataaars"
import FormDialog from "../FormDialog"
import HoverButton from "../HoverButton"
import { getDialogOptions, defaultAvatarOptions } from "./helpers"
export default {
components: {
Avataaars,
FormDialog,
HoverButton,
},
model: {
prop: "avatarOptions",
},
props: {
avatarOptions: {
type: Object,
required: true,
},
},
data() {
return {
isDialogOpen: false,
defaultAvatarOptions,
}
},
methods: {
saveAvatarOptions(options) {
this.$emit("input", options)
},
},
computed: {
avataaarsOptions() {
if (Object.keys(this.avatarOptions).length) {
return this.avatarOptions
}
return this.defaultAvatarOptions
},
dialogOptions() {
return getDialogOptions(this.avataaarsOptions)
},
},
}
</script>
<file_sep><template>
<div
data-testid="input-drawer"
class="drawer white-bg pt-3"
@click="openDrawer"
v-click-outside="{
handler: closeDrawer,
include: clickOutsideInclude,
}"
>
<v-row dense justify="space-between">
<v-col cols="2" sm="2">
<h3 class="text-subtitle-2 text-lg-subtitle-1">
{{ label }}
</h3>
</v-col>
<v-col cols="7" class="overflow-hidden">
<validation-observer slim>
<validation-provider
immediate
vid="uniqueName"
v-slot="{ errors }"
:name="uniqueName"
:rules="rules"
>
<v-text-field
v-if="type === 'text'"
v-show="isDrawerOpen()"
class="mt-5"
:data-testid="uniqueName"
:value="value"
:error-messages="errors"
@input="$emit('input', $event)"
>
</v-text-field>
<v-select
v-if="type === 'select'"
v-show="isDrawerOpen()"
chips
deletable-chips
class="mt-5"
:data-testid="uniqueName"
:value="value"
:error-messages="errors"
:items="choices"
:multiple="multiselect"
@input="$emit('input', $event)"
/>
<strong
v-show="!isDrawerOpen()"
class="text-subtitle-2 text-lg-subtitle-1"
:class="{ 'red--text': errors[0] }"
>
{{ errors[0] || displayValue | trimText(45) }}
</strong>
</validation-provider>
</validation-observer>
</v-col>
<v-col cols="1">
<v-icon v-show="!isDrawerOpen()">mdi-pencil</v-icon>
</v-col>
</v-row>
<v-divider class="mt-3"></v-divider>
</div>
</template>
<script>
import { ValidationObserver, ValidationProvider } from "vee-validate"
export default {
components: {
ValidationProvider,
ValidationObserver,
},
props: {
type: {
type: String,
required: false,
default: "text",
validator: value => {
return ["text", "select"].includes(value)
},
},
uniqueName: {
type: String,
required: true,
},
label: {
type: String,
required: true,
},
rules: {
type: String,
required: true,
},
value: {
type: [String, Array, Number],
required: true,
},
choices: {
// items for input type 'select'. Format: [{ value: 1, text: 'Option 1' }, { ... }]
type: Array,
required: false,
},
multiselect: {
type: Boolean,
default: true,
},
},
data() {
return {
drawerOpened: false,
}
},
methods: {
openDrawer() {
this.drawerOpened = true
},
closeDrawer() {
this.drawerOpened = false
},
isDrawerOpen() {
return this.drawerOpened
},
clickOutsideInclude() {
// don't collapse input-drawer if click happened inside v-select
return [...document.getElementsByClassName("menuable__content__active")]
},
},
computed: {
displayValue() {
if (this.type === "select") {
// display textual values of the selected items
let displayValues = []
for (let item of this.choices) {
if (this.value.includes(item.value)) {
displayValues.push(item.text)
}
}
return displayValues.join(", ")
}
return this.value
},
},
}
</script>
<style style="scss" scoped>
.drawer:hover {
background-color: rgb(245, 245, 245);
cursor: pointer;
transform: scale(1.05);
}
</style>
<file_sep>import moment from "moment"
import Papa from "papaparse"
import camelCase from "lodash/camelCase"
import isArray from "lodash/isArray"
import {
YOUTUBE_ID_REGEX_PATTERN,
YOUTUBE_EMBED_URL,
} from "./constants/constants"
const utils = {
uploadedFileToUrl(file) {
return window.URL.createObjectURL(file)
},
downloadTextAsFile(filename, content) {
// :str filename: name to download by
// :str content: file content
let e = document.createElement("a")
e.setAttribute(
"href",
"data:text/plain;charset=utf-8," + encodeURIComponent("\uFEFF" + content)
)
e.setAttribute("download", filename)
document.body.appendChild(e)
e.click()
document.body.removeChild(e)
},
arrayToCsvFormat(arr) {
return Papa.unparse(JSON.stringify(arr))
},
async csvToArray(csvFile) {
let csvData = await csvFile.text()
return Papa.parse(csvData, { header: true }).data
},
isNativeObject(obj) {
// check if received parameter is a "simple" object
return (
obj instanceof Object && Object.getPrototypeOf(obj) === Object.prototype
)
},
camelToSnakeCase(str) {
if (str.toUpperCase() === str) {
return str
}
return str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)
},
convertKeysCase(obj, convertCase) {
// create a duplicate object with snake/camel case keys (recursively)
// supports nested FormData, basic objects, arrays, primitive types
// does not convert other objects, e.g., File
// :str convertCase: case to convert to: 'camel' / 'snake'
const convert = convertCase === "snake" ? this.camelToSnakeCase : camelCase
if (obj instanceof FormData) {
const convertedObj = new FormData()
for (const [key, value] of obj.entries()) {
convertedObj.append(
convert(key),
this.convertKeysCase(value, convertCase)
)
}
return convertedObj
} else if (isArray(obj)) {
return obj.map(item => this.convertKeysCase(item, convertCase))
} else if (this.isNativeObject(obj)) {
const convertedObj = {}
for (const [key, value] of Object.entries(obj)) {
convertedObj[convert(key)] = this.convertKeysCase(value, convertCase)
}
return convertedObj
}
// no key found
return obj
},
extractYoutubeVideoId(url) {
const match = url.match(YOUTUBE_ID_REGEX_PATTERN)
return match && match[2].length > 10 ? match[2] : null
},
youtubeToEmbeddedUrl(url) {
// convert youtube url to an embedded url, to avoid 'X-Frame-Options' errors
const vid = utils.extractYoutubeVideoId(url)
if (vid) {
return `${YOUTUBE_EMBED_URL}${vid}`
}
return url
},
dateBenchmarkToRange(benchmarkDate, daysRadius) {
// recieve a moment.js date object and return two dates - before and after the original
// :momentObject benchmarkDate
// :Number daysRadius: number of days to move from each side
const startDate = benchmarkDate.clone()
const endDate = benchmarkDate.clone()
startDate.subtract(daysRadius, "days")
endDate.add(daysRadius, "days")
return [startDate, endDate]
},
addDaysToToday(days) {
// return a moment date object adding days to current date
// :Int days: days to add, can be minus to subtract (doesn't support floats)
const date = moment()
date.add(days, "days")
return date
},
dateToApiString(date) {
// convert moment.js date object into a valid string to send to api
return date.format("YYYY-MM-DD HH:mm")
},
ApiStringToReadableDate(dateString) {
return moment(dateString).format("DD.MM.YYYY HH:mm")
},
stringToPsuedoRandomColor(str) {
// return a "random" color based on the first two characters
// it is useful when want to be color consistent, yet looking random
const colors = [
"blue",
"indigo",
"cyan",
"deep-purple",
"green",
"orange",
"grey darken-1",
]
if (str.length <= 1) {
return colors[1]
}
const colorPos = (str.charCodeAt(0) + str.charCodeAt(1)) % colors.length
return colors[colorPos]
},
objectToFormData(obj) {
const fd = new FormData()
for (const [key, value] of Object.entries(obj)) {
if (isArray(value)) {
fd.append(key, JSON.stringify(value))
} else {
fd.append(key, value)
}
}
return fd
},
}
export default utils
<file_sep>from datetime import datetime, timedelta
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.db import IntegrityError
from django.utils import timezone
from server.events.models import Event
from server.organizations.models import (
Activity,
Organization,
OrganizationMember,
SchoolActivityGroup,
SchoolActivityOrder,
)
from server.schools.models import School, SchoolMember
from server.users.models import Consumer, Coordinator, Instructor, Supervisor, Vendor
from .constants import (
ACTIVITY_PAYLOADS,
FEMALE_NAMES,
LAST_NAMES,
MALE_NAMES,
ORGANIZATION_PAYLOAD,
SCHOOL_PAYLOAD,
)
class Command(BaseCommand):
help = "Creates test users for development"
def add_arguments(self, parser):
"parser.add_argument('some_number', nargs='+', type=int)"
pass
def create_admin(self, email):
try:
user = get_user_model().objects.create_superuser(
"admin", email, "Aa123456789"
)
self.stdout.write(
self.style.SUCCESS(f"Successfully created user with {user.email}")
)
return user
except IntegrityError:
self.stdout.write(
self.style.WARNING("Dev admin already exists. Skipping...")
)
def create_user(self, user_model, email, password, name):
try:
user = user_model.objects.create(email=email, password=<PASSWORD>, name=name)
user.set_password(<PASSWORD>)
user.save()
self.stdout.write(
self.style.SUCCESS(f"Successfully created user with {user.email}")
)
return user
except IntegrityError:
self.stdout.write(
self.style.WARNING(f"{email} already exists. Skipping...")
)
def create_all(self, entitiesPrefix=""):
self.create_admin(f"{entitiesPrefix}<EMAIL>")
consumers = []
for i, name_record in enumerate(zip(MALE_NAMES, LAST_NAMES)):
first_name, last_name = name_record
user = self.create_user(
Consumer,
f"{entitiesPrefix}<EMAIL>",
"Aa123456789",
f"{first_name} {last_name}",
)
if user:
user.profile.gender = user.profile.Gender.MALE
user.profile.save()
consumers.append(user)
for i, name_record in enumerate(zip(FEMALE_NAMES, LAST_NAMES)):
first_name, last_name = name_record
user = self.create_user(
Consumer,
f"{entitiesPrefix}<EMAIL>",
"Aa123456789",
f"{first_name} {last_name}",
)
if user:
user.profile.gender = user.profile.Gender.FEMALE
user.profile.save()
consumers.append(user)
if len(consumers):
prev_email = consumers[0].email
consumers[0].email = f"{<EMAIL>}<EMAIL>"
consumers[0].save()
self.stdout.write(
self.style.SUCCESS(
f"Successfully changed {prev_email} to {consumers[0].email}"
)
)
coord = self.create_user(
Coordinator,
f"{entitiesPrefix}<EMAIL>",
"Aa123456789",
"דוד כהן",
)
instructor = self.create_user(
Instructor,
f"{entitiesPrefix}<EMAIL>",
"Aa123456789",
"דן יוסופוב",
)
self.create_user(
Supervisor,
f"{entitiesPrefix}<EMAIL>",
"Aa123456789",
"ישראל ישראלי",
)
vendor = self.create_user(
Vendor,
f"{entitiesPrefix}<EMAIL>",
"Aa123456789",
"משי בר אל",
)
if not (len(consumers) and coord and instructor and vendor):
return self.stdout.write(
self.style.ERROR(
"Users creation failed - already exist.\n\
You may flush all db using: `python manage.py flush`\n\
USE WITH CAUTION - THIS DELETES EVERYTHING"
)
)
org = Organization.objects.create(**ORGANIZATION_PAYLOAD)
self.stdout.write(self.style.SUCCESS("Successfully created Organization"))
school = School.objects.create(**SCHOOL_PAYLOAD)
self.stdout.write(self.style.SUCCESS("Successfully created School"))
OrganizationMember.objects.bulk_create(
[
OrganizationMember(organization=org, user=instructor),
OrganizationMember(organization=org, user=vendor),
]
)
self.stdout.write(
self.style.SUCCESS("Successfully created OrganizationMember relations")
)
SchoolMember.objects.create(school=school, user=coord)
SchoolMember.objects.bulk_create(
[SchoolMember(school=school, user=consumer) for consumer in consumers]
)
self.stdout.write(
self.style.SUCCESS("Successfully created SchoolMember relations")
)
activity_one, activity_two = Activity.objects.bulk_create(
map(
lambda activity: Activity(**activity, originization=org),
ACTIVITY_PAYLOADS,
)
)
self.stdout.write(self.style.SUCCESS("Successfully created Activities"))
activity_order_one = SchoolActivityOrder.objects.create(
school=school,
activity=activity_one,
status=SchoolActivityOrder.Status.APPROVED,
)
SchoolActivityOrder.objects.create(
school=school,
activity=activity_two,
status=SchoolActivityOrder.Status.PENDING_ADMIN_APPROVAL,
)
self.stdout.write(self.style.SUCCESS("Successfully created ActivityOrders"))
group_one = SchoolActivityGroup.objects.create(
activity_order=activity_order_one,
name="Group One",
description="Group One Description",
instructor=instructor,
)
group_two = SchoolActivityGroup.objects.create(
activity_order=activity_order_one,
name="Container Only",
description="Container Only",
group_type=SchoolActivityGroup.GroupTypes.CONTAINER_ONLY,
)
SchoolActivityGroup.objects.create(
activity_order=activity_order_one,
name="Cancelled Group",
description="Cancelled Group",
group_type=SchoolActivityGroup.GroupTypes.DISABLED_CONSUMERS,
)
group_one.consumers.add(consumers[0])
group_two.consumers.add(consumers[1])
self.stdout.write(
self.style.SUCCESS("Successfully created SchoolActivityGroups")
)
today = datetime.now(tz=timezone.utc).replace(microsecond=0, second=0, minute=0)
events = []
for i in range(20):
events.append(
Event(
school_group=group_one,
locations_name="חדר 202",
start_time=today + timedelta(days=i * 7),
end_time=today + timedelta(days=i * 7) + timedelta(hours=1.5),
)
)
Event.objects.bulk_create(events)
self.stdout.write(self.style.SUCCESS("Successfully created Events"))
def handle(self, *args, **options):
self.create_all()
self.create_all(entitiesPrefix="test-")
<file_sep><template>
<div class="">
<v-row>
<v-col cols="12" md="8">
<h1 v-text="$t('myActivity.myPrograms')" class="mb-5" />
<h2
v-text="$t('program.hereYouCanSeeAllTheProgramsListedUnderYou')"
class="pb-12"
/>
</v-col>
<v-col cols="12" md="4">
<v-btn
data-testid="program-create-btn"
tile
large
class="d-block mx-auto"
color="success"
@click="$router.push({ name: 'VendorProgramCreator' })"
>
{{ $tc("userActions.add", 1) }}
<v-icon right> mdi-plus </v-icon>
</v-btn>
</v-col>
</v-row>
<v-row class="pt-10 ml-0" justify="space-around">
<v-col
cols="12"
sm="6"
lg="4"
class="py-10"
v-for="program in programList"
:key="program.id"
>
<info-card
:hideStar="true"
:title="program.name"
:subtitle="program.domain ? $t(`programFilters.${camelCase(program.domain)}`) : $t('errors.domainUnspecified')"
:imgUrl="program.logo"
:buttonText="$t('program.toProgramPage')"
buttonColor="primary"
@click="
$router.push({
name: 'VendorDetailProgram',
params: { programSlug: program.slug },
})
"
>
{{ program.description | trimText(70) }}
</info-card>
</v-col>
</v-row>
<div class="text-center pt-10 overline">
{{ programList.length }} {{ $t("program.programsFound") }}
</div>
</div>
</template>
<script>
import { mapState } from "vuex"
import camelCase from "lodash/camelCase"
import store from "../vuex/store"
import InfoCard from "../components/InfoCard"
export default {
components: {
InfoCard,
},
async beforeRouteEnter(to, from, next) {
await store.dispatch("vendorProgram/getProgramList")
next()
},
computed: {
...mapState("vendorProgram", ["programList"]),
},
methods: {
camelCase,
}
}
</script>
<file_sep>import i18n from "../plugins/i18n"
import { required, email, size, max, numeric, digits } from "vee-validate/dist/rules"
import { extend } from "vee-validate"
import {
PASSWORD_REGEX_PATTERN,
ISRAELI_PHONE_REGEX_PATTERN,
WEBSITE_REGEX_PATTERN,
YOUTUBE_URL_REGEX_PATTERN,
} from "./constants/constants"
extend("required", {
...required,
message: i18n.tc("errors.requiredField"),
})
extend("email", {
...email,
message: i18n.tc("errors.invalidEmail"),
})
extend("numeric", {
...numeric,
message: i18n.tc("errors.NumbersOnlyField"),
})
extend("strongPass", {
message: i18n.tc("errors.strongPassHint"),
validate: value => {
let strongRegex = new RegExp(PASSWORD_REGEX_PATTERN)
return strongRegex.test(value)
},
})
extend("passConfirm", {
params: ["target"],
validate(value, { target }) {
return value === target
},
message: i18n.tc("errors.passwordsMismatch"),
})
extend("phoneNumberIsrael", {
message: i18n.tc("errors.invalidPhoneNumber"),
validate: value => {
let strongRegex = new RegExp(ISRAELI_PHONE_REGEX_PATTERN)
return strongRegex.test(value)
},
})
extend("website", {
message: i18n.tc("errors.invalidWebsiteAddress"),
validate: value => {
const regex = new RegExp(WEBSITE_REGEX_PATTERN, "i")
return regex.test(value)
},
})
extend("size", {
...size,
message: i18n.tc("errors.fileSizeLimitExceeded"),
})
extend("max", {
...max,
message: i18n.tc("errors.maxLengthExceeded"),
})
extend("digits", {
...digits,
message: i18n.tc("errors.incorrectNumberOfDigits"),
})
extend("youtubeUrl", {
message: i18n.tc("errors.invalidYoutubeUrl"),
validate: value => {
const regex = new RegExp(YOUTUBE_URL_REGEX_PATTERN, "i")
return regex.test(value)
},
})
<file_sep># Generated by Django 3.1.11 on 2021-07-13 07:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schools', '0005_auto_20210701_1440'),
]
operations = [
migrations.AlterField(
model_name='school',
name='description',
field=models.CharField(blank=True, max_length=150),
),
migrations.AlterField(
model_name='school',
name='website',
field=models.URLField(blank=True),
),
]
<file_sep># Generated by Django 3.1.11 on 2021-05-26 08:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('organizations', '0002_auto_20210523_1544'),
]
operations = [
migrations.RenameField(
model_name='organization',
old_name='nuber_of_members',
new_name='number_of_members',
),
]
<file_sep>from django.contrib.auth import get_user_model
from django.db import models
from server.events.models import Event
from server.utils.model_fields import random_slug
class Post(models.Model):
slug = models.CharField(
max_length=40,
default=random_slug,
unique=True,
)
created = models.DateTimeField(
auto_now_add=True,
)
event = models.ForeignKey(
Event,
on_delete=models.SET_NULL,
blank=False,
null=True,
)
author = models.ForeignKey(
get_user_model(),
on_delete=models.SET_NULL,
blank=False,
null=True,
)
post_content = models.TextField()
class PostImage(models.Model):
slug = models.CharField(max_length=40, default=random_slug, unique=True)
image_url = models.ImageField()
post = models.ForeignKey(
Post,
on_delete=models.CASCADE,
related_name="images",
)
def __str__(self):
return f"{self.image_url} | {self.slug} | {self.post.slug}"
<file_sep><template>
<div v-show="value">
<v-overlay />
<v-card v-bind="$attrs" class="px-7 py-5 fixed-center z-index-5" max-width="344">
<v-card-text>
<p v-text="topSubtitle" />
<p class="text-h4 text--primary" v-text="title" />
<p v-text="bottomSubtitle" />
<div class="text--primary">
<slot></slot>
</div>
</v-card-text>
<v-card-actions>
<v-btn
text
class="mx-auto"
color="primary"
v-text="buttonText"
@click="close"
/>
</v-card-actions>
</v-card>
</div>
</template>
<script>
export default {
inheritAttrs: false,
props: {
value: {
// is open
type: Boolean,
required: true,
},
topSubtitle: {
type: [String, Number],
default: "",
},
title: {
type: [String, Number],
required: true,
},
bottomSubtitle: {
type: [String, Number],
default: "",
},
buttonText: {
type: String,
default: "Close",
},
},
methods: {
close() {
this.$emit("input", false)
},
},
}
</script>
<file_sep>import Vue from "vue"
import Vuetify from "vuetify"
import cookies from "@/plugins/cookies"
import "@/helpers/validators"
Vue.use(Vuetify)
Vue.use(cookies)
<file_sep><template>
<v-hover v-slot="{ hover }">
<div class="w-fit-content">
<v-avatar size="260">
<validation-provider
slim
v-slot="{ errors }"
name="picUpload"
rules="size:5000"
>
<v-file-input
:id="inputId"
class="d-none"
type="file"
accept="image/*"
v-model="picFile"
>
</v-file-input>
<div
v-if="errors[0]"
class="error-msg red--text text-center font-weight-bold"
>
{{ errors[0] }}
</div>
</validation-provider>
<v-btn
@click="triggerPicUpload()"
v-show="hover"
color="blue-grey"
class="pic-btn ma-2 white--text"
fab
>
<v-icon dark>mdi-cloud-upload</v-icon>
</v-btn>
<img :src="picSource" />
</v-avatar>
</div>
</v-hover>
</template>
<script>
import { ValidationProvider } from "vee-validate"
import Utils from "../helpers/utils"
import { JPG_DOCUMENT } from "../helpers/constants/images"
export default {
components: {
ValidationProvider,
},
props: {
placeholderPicUrl: {
type: String,
required: false,
default: JPG_DOCUMENT,
},
},
data() {
return {
picFile: undefined,
inputId: `${this._uid}_picUpload`,
}
},
methods: {
triggerPicUpload() {
document.getElementById(this.inputId).click()
},
},
watch: {
picFile: function () {
this.$emit("fileUpload", this.picFile)
},
},
computed: {
picSource() {
if (this.picFile) {
return Utils.uploadedFileToUrl(this.picFile)
} else {
return this.placeholderPicUrl
}
},
},
}
</script>
<style lang="scss" scoped>
$dark-strong: rgba(0, 0, 0, 0.75);
$dark-light: rgba(0, 0, 0, 0.2);
.pic-btn {
z-index: 2;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-box-shadow: 0px 0px 26px 200px $dark-light;
-moz-box-shadow: 0px 0px 26px 200px $dark-light;
box-shadow: 0px 0px 26px 200px $dark-light;
}
.error-msg {
position: absolute;
top: 50%;
left: 50%;
width: 80%;
transform: translate(-50%, -50%);
background-color: $dark-strong;
-webkit-box-shadow: 0px 0px 26px 200px $dark-strong;
-moz-box-shadow: 0px 0px 26px 200px $dark-strong;
box-shadow: 0px 0px 26px 200px $dark-strong;
}
</style>
<file_sep># Generated by Django 3.1.11 on 2021-07-20 08:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schools', '0006_auto_20210713_1029'),
]
operations = [
migrations.AlterField(
model_name='school',
name='zip_city',
field=models.CharField(blank=True, max_length=15),
),
]
<file_sep>import Api from "../../api"
function getDefaultState() {
return {
groupList: [],
totalGroups: null,
}
}
const consumerProgramGroup = {
namespaced: true,
state: getDefaultState(),
mutations: {
FLUSH_STATE(state) {
Object.assign(state, getDefaultState())
},
ADD_GROUPS_TO_LIST(state, groupList) {
state.groupList.push(...groupList)
},
SET_GROUPS_LIST(state, groupList) {
state.groupList = groupList
},
SET_GROUPS_TOTAL(state, total) {
state.totalGroups = total
},
},
actions: {
flushState({ commit }) {
commit("FLUSH_STATE")
},
async getGroupList(
{ commit, state, rootGetters },
{ groupType, override }
) {
// :str groupType: which group type to fetch (if empty, fetch all groups)
// :boolean override: whether to override the groups list or not (i.e., extend)
const params = rootGetters["pagination/apiParams"]
if (groupType) {
params.group_type = groupType
}
const mutation = override ? "SET_GROUPS_LIST" : "ADD_GROUPS_TO_LIST"
let res = await Api.consumerProgramGroup.getGroupList(params)
commit(mutation, res.data.results)
commit("SET_GROUPS_TOTAL", res.data.count)
return state.groupList
},
},
}
export default consumerProgramGroup
<file_sep><template>
<div class="pa-10">
<route-tabs :tabs="tabs" />
<v-row>
<v-col class="mx-auto" sm="11" lg="9">
<router-view />
</v-col>
</v-row>
<div class="overline text-center">
*
{{
this.$t(
"invite.invitingUserOrChangingExistingEmailWillSendAnInviteToTheInviteesMailbox"
)
}}.
</div>
</div>
</template>
<script>
import RouteTabs from "../../components/RouteTabs"
export default {
components: { RouteTabs },
data() {
return {
tabs: [
{
componentName: "InviteConsumers",
text: this.$t("invite.inviteStudents"),
},
{
componentName: "InviteCoordinators",
text: this.$t("invite.inviteStaff"),
},
],
}
},
}
</script>
<file_sep><template>
<v-card class="pt-4">
<v-text-field
v-model="searchFilter"
append-icon="mdi-magnify"
:label="$t('userActions.search')"
single-line
hide-details
class="search-bar px-10 mt-5 mb-8 mx-auto"
@click:append="onSearch"
@keyup.enter="onSearch"
/>
<v-data-table
multi-sort
@update:options="paginate"
:headers="tableHeaders"
:items="items"
:loading="loading"
:loadingText="loadingText"
:server-items-length="totalServerItems"
>
<template v-slot:item.plus="{ item }">
<v-icon
size="20"
class="mr-2"
@click="toggleRowSelect(item)"
color="green darken-2"
>
{{ isSelected(item) ? "mdi-check" : "mdi-plus" }}
</v-icon>
</template>
</v-data-table>
</v-card>
</template>
<script>
import { mapActions } from "vuex"
import isEqual from "lodash/isEqual"
export default {
model: { prop: "selectedRows" },
props: {
headers: {
// v-data-table headers. e.g., [ { text: 'Calories', value: 'calories' }, ... ]
type: Array,
required: true,
},
items: {
// v-data-table items (i.e., table rows)
type: Array,
required: true,
},
selectedRows: {
type: Array,
required: true,
},
totalServerItems: {
// received from server via count field
type: Number,
required: true,
},
loading: {
type: Boolean,
default: false,
},
},
data() {
return {
loadingText: this.$t("general.loading"),
searchFilter: "",
options: {},
}
},
computed: {
tableHeaders() {
return [{ text: "", value: "plus", sortable: false }, ...this.headers]
},
},
methods: {
...mapActions("pagination", ["updatePagination"]),
toggleRowSelect(item) {
// add or remove from selected rows and emit correlating events
if (!this.isSelected(item)) {
this.$emit("input", [...this.selectedRows, item])
this.$emit("select", item)
return
}
this.$emit(
"input",
this.selectedRows.filter(row => !isEqual(row, item))
)
this.$emit("diselect", item)
},
paginate(options) {
this.updatePagination(options)
this.$emit("paginate")
},
onSearch() {
this.options.page = 1
this.updatePagination({ searchFilter: this.searchFilter })
this.$emit("paginate")
},
isSelected(row) {
// includes won't work due to re-fetch issues
return this.selectedRows.filter(selected => isEqual(selected, row))
.length
},
},
}
</script>
<style lang="scss" scoped>
.search-bar {
max-width: 450px !important;
}
</style>
<file_sep><template>
<div class="wrapper mt-15 mx-auto px-3">
<h1 class="mb-5">{{ $tc("general.schoolDetails", 0) }}</h1>
<h2 class="pb-12">{{ $t("general.pleaseFillAllDetailsBelow") }}</h2>
<validation-observer v-slot="{ invalid }">
<form @submit.prevent="submitSchoolDetails">
<v-row>
<v-col class="pb-10" cols="12" sm="12" lg="8">
<input-drawer
v-for="field in textFields"
:key="field.id"
v-model="field.value"
:uniqueName="field.uniqueName"
:label="field.label"
:rules="field.rules"
:choices="field.choices || []"
:type="field.type || 'text'"
/>
</v-col>
<v-col cols="12" sm="12" lg="3">
<picture-input
class="mx-auto"
:placeholderPicUrl="placeholderPicUrl"
@fileUpload="setPicture"
/>
</v-col>
</v-row>
<v-btn
class="my-16 white--text mx-auto mx-sm-0 d-block"
type="submit"
color="primary"
elevation="3"
:disabled="invalid"
>
{{ $t("userActions.save") }}
</v-btn>
</form>
</validation-observer>
<modal v-show="popupMsg !== ''" @close="popupMsg = ''">
{{ popupMsg }}
</modal>
</div>
</template>
<script>
import { ValidationObserver } from "vee-validate"
import { mapActions } from "vuex"
import debounce from "lodash/debounce"
import store from "../vuex/store"
import Modal from "../components/Modal"
import InputDrawer from "../components/InputDrawer"
import PictureInput from "../components/PictureInput"
import {
SCHOOL_GRADES_ITEMS,
ZIP_CODE_VALIDATION_RULE,
} from "../helpers/constants/constants"
import { HOUSE_ROUNDED_DRAWING } from "../helpers/constants/images"
export default {
components: {
ValidationObserver,
Modal,
InputDrawer,
PictureInput,
},
async beforeRouteEnter(to, from, next) {
try {
let schoolDetails = await store.dispatch("school/getSchoolDetails")
next(vm => vm.setSchoolAttributes(schoolDetails))
} catch (err) {
next(vm => (vm.popupMsg = vm.$t("errors.genericError")))
}
},
data() {
return {
textFields: {
name: {
uniqueName: "name",
label: this.$t("general.name"),
rules: "required",
value: "",
},
city: {
uniqueName: "city",
label: this.$t("general.city"),
rules: "required",
value: "",
},
street: {
uniqueName: "street",
label: this.$t("general.street"),
rules: "required",
value: "",
},
zipCode: {
uniqueName: "zipCode",
label: this.$t("general.zipCode"),
rules: ZIP_CODE_VALIDATION_RULE,
value: "",
},
schoolCode: {
uniqueName: "schoolCode",
label: this.$t("general.schoolCode"),
rules: "required|numeric",
value: "",
},
description: {
uniqueName: "description",
label: this.$t("general.description"),
rules: "",
value: "",
},
contactPhone: {
uniqueName: "contactPhone",
label: this.$t("general.phoneNumber"),
rules: "required|numeric|phoneNumberIsrael",
value: "",
},
website: {
uniqueName: "website",
label: this.$t("general.website"),
rules: "website",
value: "",
},
grades: {
uniqueName: "grades",
label: this.$t("general.schoolGrades"),
rules: "required",
value: [],
type: "select",
choices: SCHOOL_GRADES_ITEMS,
},
},
placeholderPicUrl: HOUSE_ROUNDED_DRAWING,
profilePicFile: null,
popupMsg: "",
}
},
methods: {
...mapActions("school", ["updateSchoolDetails"]),
setSchoolAttributes(schoolAttributes) {
// set school profile data received from server
this.textFields.name.value =
schoolAttributes.name || this.textFields.name.value
this.textFields.city.value =
schoolAttributes.addressCity || this.textFields.city.value
this.textFields.street.value =
schoolAttributes.address || this.textFields.street.value
this.textFields.zipCode.value =
schoolAttributes.addressZipcode || this.textFields.zipCode.value
this.textFields.schoolCode.value =
schoolAttributes.schoolCode || this.textFields.schoolCode.value
this.textFields.contactPhone.value =
schoolAttributes.contactPhone || this.textFields.contactPhone.value
this.textFields.description.value =
schoolAttributes.description || this.textFields.description.value
this.textFields.website.value =
schoolAttributes.website || this.textFields.website.value
this.textFields.grades.value =
schoolAttributes.gradeLevels || this.textFields.grades.value
this.placeholderPicUrl =
schoolAttributes.profilePicture || this.placeholderPicUrl
this.schoolSlug = schoolAttributes.slug
},
submitSchoolDetails: debounce(
function () {
let schoolDataPayload = this.createSchoolSubmitPayload()
this.postSchoolData(schoolDataPayload)
},
500,
{ leading: true, trailing: false }
),
createSchoolSubmitPayload() {
let data = new FormData()
data.append("slug", this.schoolSlug)
data.append("name", this.textFields.name.value)
data.append("address", this.textFields.street.value)
data.append("address_city", this.textFields.city.value)
data.append("address_zipcode", this.textFields.zipCode.value)
data.append("school_code", this.textFields.schoolCode.value)
data.append("description", this.textFields.description.value)
data.append("contact_phone", this.textFields.contactPhone.value)
data.append("website", this.textFields.website.value)
data.append("grade_levels", JSON.stringify(this.textFields.grades.value))
if (this.profilePicFile) {
data.append("profilePicture", this.profilePicFile)
}
return data
},
async postSchoolData(schoolPayload) {
try {
await this.updateSchoolDetails({
slug: this.schoolSlug,
schoolDetails: schoolPayload,
})
this.popupMsg = this.$t("general.detailsSuccessfullyUpdated")
} catch (err) {
if (
err.response.status === 400 &&
Object.keys(err.response.data).length > 0
) {
this.popupMsg =
err.response.data[Object.keys(err.response.data)[0]][0]
} else {
this.popupMsg = this.$t("errors.genericError")
}
}
},
setPicture(file) {
this.profilePicFile = file
},
},
}
</script>
<style lang="scss" scoped>
.wrapper {
width: 90%;
}
</style>
<file_sep>/// <reference types="cypress" />
describe("crud group", () => {
beforeEach(() => {
cy.visit(Cypress.env("clientUrl"))
cy.get('[data-testid="email-input"]').type("<EMAIL>")
cy.get('[data-testid="password-input"]').type("<PASSWORD>")
cy.get("form").submit()
cy.url().should("contain", "dashboard")
})
it("should create a group", () => {
cy.get('[data-testid="create-group"]').click()
cy.get('[data-testid="name"]').type("NewGroup")
cy.get('[data-testid="description"]').type("This is the group description")
cy.get('[data-testid="activityOrder"]').parent().click()
cy.get(".v-select-list").first().children().first().click()
cy.get('[data-testid="submit-button"]').click()
cy.url().should("contain", "/assign-group-students")
cy.get('[data-testid="submit-button"]').click()
})
})
<file_sep>ORGANIZATION_PAYLOAD = {
"email": "<EMAIL>",
"description": "Org Description",
"website_url": "https://org.com",
"name": "<NAME>",
"goal": "Goal",
"year_founded": "2005",
"status": "status",
"target_audience": [1, 2, 3, 4, 5, 6],
"number_of_employees": 100,
"number_of_members": 200,
"number_of_volunteers": 30,
"location_lon": 32.109333,
"location_lat": 34.855499,
"address_city": "city",
"address_street": "addr",
"address_house_num": "13",
"address_zipcode": "550202",
"cities": {},
"districts": {},
"union_type": "union type",
}
SCHOOL_PAYLOAD = {
"name": "<NAME> - דמו",
"address": "ארלוזורוב 75",
"address_city": "תל אביב",
"address_zipcode": "0564665",
"school_code": 546321,
"description": "בית ספר יסודי שרת",
"contact_phone": "0521234567",
"website": "https://school.com",
"grade_levels": [1, 2, 3, 4, 5, 6],
}
ACTIVITY_PAYLOADS = [
{
"name": "<NAME>",
"target_audience": [1, 2, 3, 4, 5, 6],
"domain": "FIELD",
"description": """תוכנית ערכים דרך ריצה היא תוכנית ריצת טבע.
רצים בשדות ולומדים על טבע ועל עצמנו דרך הרגליים""",
"contact_name": "<NAME>",
"phone_number": "0521234567",
},
{
"name": "שחמט <NAME>",
"target_audience": [1, 2, 3, 4, 5, 6],
"domain": "SCIENCE_AND_TECH",
"description": """שחמט לכל ילד הינה תוכנית ללימוד שחמט הקיימת מעל ל20 שנה ופועלת בכל רחבי הארץ.
אנו חורטים על דגלינו התפתחות חשיבה עצמאית ומסוגלת בקרב תלמידינו.""",
"contact_name": "<NAME>",
"phone_number": "0521234567",
},
]
MALE_NAMES = [
"נועם",
"אורי",
"איתי",
"דוד",
"יוסף",
"בן",
"רוני",
"אורי",
]
FEMALE_NAMES = [
"אביגיל",
"טליה",
"איילה",
"שרה",
"חנה",
"מור",
"מוריה",
"אלה",
]
LAST_NAMES = [
"כהן",
"לוי",
"שר",
"אורלין",
"להב",
"שימן",
"ברוש",
"שמיר",
]
<file_sep># Generated by Django 3.1.11 on 2021-07-18 14:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0008_auto_20210714_1121'),
]
operations = [
migrations.AddConstraint(
model_name='consumereventfeedback',
constraint=models.UniqueConstraint(fields=('consumer', 'event'), name='unique consumer feedback'),
),
]
<file_sep>from django.contrib import admin
from .models import Post, PostImage
admin.site.register(PostImage)
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ["slug", "created", "event", "author", "content"]
search_fields = [
"content",
"author",
]
def content(self, obj):
return f"{obj.post_content[:100]}..."
<file_sep><template>
<div class="wrapper mx-auto">
<h1 class="mb-5">{{ $t("general.myProfile") }}</h1>
<h2 class="pb-12">{{ $t("general.pleaseFillAllDetailsBelow") }}</h2>
<validation-observer v-slot="{ invalid }">
<form @submit.prevent="submitProfile">
<v-row>
<v-col class="pb-10" cols="12" sm="12" lg="8">
<input-drawer
v-for="field in textFields"
:key="field.id"
v-model="field.value"
:uniqueName="field.uniqueName"
:label="field.label"
:rules="field.rules"
></input-drawer>
</v-col>
<v-col cols="12" sm="12" lg="3">
<editable-avatar class="mr-lg-16 mx-auto avatar" v-model="profilePicture" />
</v-col>
</v-row>
<v-btn
class="d-block my-16 white--text mx-lg-0 mx-auto"
type="submit"
color="primary"
elevation="3"
:disabled="invalid"
>
{{ $t("userActions.save") }}
</v-btn>
</form>
</validation-observer>
<modal v-show="popupMsg !== ''" @close="popupMsg = ''">
{{ popupMsg }}
</modal>
</div>
</template>
<script>
import { mapActions } from "vuex"
import debounce from "lodash/debounce"
import store from "../../vuex/store"
import { ValidationObserver } from "vee-validate"
import Modal from "../../components/Modal"
import InputDrawer from "../../components/InputDrawer"
import EditableAvatar from "../../components/Avatar/EditableAvatar"
export default {
components: {
ValidationObserver,
Modal,
InputDrawer,
EditableAvatar,
},
async beforeRouteEnter(to, from, next) {
try {
// fetch profile data before load
let profile = await store.dispatch("vendor/getProfile")
let userDetails = await store.dispatch("user/getUserDetails")
let userAttributes = { ...profile, ...userDetails }
next(vm => vm.setUserAttributes(userAttributes))
} catch (err) {
next(vm => (vm.popupMsg = vm.$t("errors.genericError")))
}
},
data() {
return {
textFields: {
name: {
uniqueName: "name",
label: this.$t("general.name"),
rules: "required",
value: "",
},
email: {
uniqueName: "email",
label: this.$t("general.email"),
rules: "required|email",
value: "",
},
phone: {
uniqueName: "phone",
label: this.$t("general.phoneNumber"),
rules: "required|numeric|phoneNumberIsrael",
value: "",
},
},
profilePicture: {},
popupMsg: "",
slug: "",
}
},
methods: {
...mapActions("user", ["updateUserDetails"]),
...mapActions("vendor", ["updateProfile"]),
setUserAttributes(userAttributes) {
// set user data received from server
this.slug = userAttributes.slug
this.textFields.name.value = userAttributes.name || ""
this.textFields.email.value = userAttributes.email || ""
this.textFields.phone.value = userAttributes.phoneNumber || ""
this.profilePicture = userAttributes.profilePicture || {}
},
submitProfile: debounce(
function () {
let userDetailsPayload = this.createUserSubmitPayload()
let profilePayload = this.createProfileSubmitPayload()
this.postProfileData(userDetailsPayload, profilePayload)
},
500,
{ leading: true, trailing: false }
),
createUserSubmitPayload() {
return {
name: this.textFields.name.value,
email: this.textFields.email.value,
}
},
createProfileSubmitPayload() {
return {
phoneNumber: this.textFields.phone.value,
profilePicture: this.profilePicture,
}
},
async postProfileData(userDetails, profile) {
try {
await this.updateUserDetails({ slug: this.slug, userDetails })
await this.updateProfile({ slug: this.slug, profile })
this.popupMsg = this.$t("general.detailsSuccessfullyUpdated")
} catch (err) {
if (
err.response.status === 400 &&
Object.keys(err.response.data).length > 0
) {
this.popupMsg =
err.response.data[Object.keys(err.response.data)[0]][0]
} else {
this.popupMsg = this.$t("errors.genericError")
}
}
},
},
}
</script>
<style lang="scss" scoped>
.wrapper {
width: 90%;
}
.avatar {
max-width: 350px;
}
</style>
<file_sep><template>
<v-card class="mx-auto card overflow-hidden" elevation="1" :width="width" :height="height">
<v-card-title v-text="title" class="pa-2 font-weight-bold" />
<v-card-subtitle
v-text="subtitle"
class="px-2 pt-2 pb-1 subtitle-1"
/>
<v-img :height="imgHeight" :src="imgUrl" />
<v-card-text class="text--primary pt-3 px-2 subtitle-1 body">
<!-- if slot's text overflow, consider using the trim filter on parent -->
<slot></slot>
</v-card-text>
<v-card-actions class="absolute-bottom actions">
<v-btn
text
id="info-button"
data-testid="info-btn"
v-if="!hideButton"
:color="buttonColor"
class="subtitle-1 font-weight-bold absolute-center"
v-text="buttonText"
@click="$emit('click')"
/>
<v-icon
v-if="!hideStar"
@click="onStarClick"
:color="value ? buttonColor : 'grey'"
:class="{ 'mx-2': !$vuetify.breakpoint.mobile }"
>
{{ value ? "mdi-check-bold" : "mdi-check" }}
</v-icon>
</v-card-actions>
</v-card>
</template>
<script>
import { INFO_CARD_IMAGE } from "../helpers/constants/images"
import i18n from "../plugins/i18n"
export default {
props: {
// whether starred or not
value: {
type: Boolean,
required: false,
},
imgUrl: {
type: String,
default: INFO_CARD_IMAGE,
},
title: {
type: String,
required: true,
},
subtitle: {
type: String,
required: false,
},
height: {
type: String,
default: "382",
},
width: {
type: String,
default: "272",
},
imgHeight: {
type: String,
default: "195",
},
hideStar: {
type: Boolean,
default: false,
},
hideButton: {
type: Boolean,
default: false,
},
buttonColor: {
type: String,
default: "orange",
},
buttonText: {
type: String,
default: i18n.tc("general.additionalInfo", 1),
},
},
methods: {
onStarClick() {
this.$emit("input", !this.value)
},
},
}
</script>
<style scoped>
#info-button {
letter-spacing: 1.7px !important;
}
.actions {
height: 40px;
}
.card {
border-radius: 4px;
}
.body {
line-height: 1.4;
}
</style>
<file_sep><template>
<div>
<route-tabs :tabs="tabs" />
<router-view />
<div class="overline text-center">
*
{{
this.$t(
"invite.invitingUserOrChangingExistingEmailWillSendAnInviteToTheInviteesMailbox"
)
}}.
</div>
</div>
</template>
<script>
import RouteTabs from "../../components/RouteTabs"
export default {
components: { RouteTabs },
data() {
return {
tabs: [
{
componentName: "InviteInstructors",
text: this.$t("invite.inviteInstructors"),
},
{
componentName: "InviteVendors",
text: this.$t("invite.inviteVendors"),
},
],
}
},
}
</script>
<file_sep><template>
<v-toolbar dark prominent :src="bg">
<v-tooltip v-for="btn in buttons" :key="btn.id" bottom>
<template v-slot:activator="{ on, attrs }">
<v-btn :data-testid="btn.id" icon v-bind="attrs" v-on="on" @click="btn.onClick">
<v-icon>{{ btn.icon }}</v-icon>
</v-btn>
</template>
<span> {{ btn.text() }} </span>
</v-tooltip>
<v-toolbar-title :class="{ absolute: $vuetify.breakpoint.mobile }">
{{ $t("general.connective") }}
</v-toolbar-title>
<v-spacer />
<v-tooltip bottom>
<template v-slot:activator="{ on, attrs }">
<v-btn large icon v-bind="attrs" v-on="on" @click="$router.go(-1)">
<v-icon>mdi-arrow-left</v-icon>
</v-btn>
</template>
<span v-text="$t('general.toThePreviousPage')" />
</v-tooltip>
</v-toolbar>
</template>
<script>
import { BACKGROUNDS } from "../../helpers/constants/images"
import { userToButtons } from "./constants"
export default {
props: {
userType: {
type: String,
required: true,
validator(value) {
return ["coordinator", "consumer", "instructor", "vendor"].includes(
value
)
},
},
},
data() {
return {
bg: BACKGROUNDS.navbar,
buttons: userToButtons[this.userType],
}
},
}
</script>
<file_sep># Generated by Django 3.1.11 on 2021-07-14 08:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('organizations', '0018_activity_tags'),
('events', '0007_consumereventfeedback'),
]
operations = [
migrations.AlterField(
model_name='event',
name='school_group',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='organizations.schoolactivitygroup'),
),
]
<file_sep>import axios from "axios"
import {
GET_CONSUMER_PROFILE_API_URL,
UPDATE_CONSUMER_PROFILE_API_URL,
} from "../helpers/constants/constants"
const consumer = {
getProfile() {
return axios.get(GET_CONSUMER_PROFILE_API_URL)
},
updateProfile(slug, data) {
if (!slug) throw "updateProfile: received empty slug"
return axios.patch(`${UPDATE_CONSUMER_PROFILE_API_URL}${slug}/`, data)
},
}
export default consumer
<file_sep># Generated by Django 3.1.11 on 2021-07-01 11:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20210624_1022'),
('organizations', '0016_auto_20210629_1213'),
]
operations = [
migrations.AlterField(
model_name='schoolactivitygroup',
name='consumers',
field=models.ManyToManyField(blank=True, related_name='activity_groups', to='users.Consumer'),
),
]
<file_sep>import isArray from "lodash/isArray"
import i18n from "../plugins/i18n"
const utils = {
parseResponseError(err) {
// process and return the relevant response message
// :object err: error caught from response
try {
const response = err.response
if (response.status === 400 && Object.keys(response).length) {
let errors = response.data
if (isArray(response.data) && response.data.length) {
errors = response.data[0]
}
const firstError = Object.entries(errors)[0]
return `${firstError[0]} - ${firstError[1]}`
}
return i18n.t("errors.genericError")
} catch (err) {
return i18n.t("errors.genericError")
}
},
}
export default utils
<file_sep>import os
from contextlib import suppress
from datetime import datetime, timedelta
import pytest
from django.core.exceptions import ValidationError
from django.utils import timezone
from rest_framework import status
from rest_framework.test import APIClient
from server.events.models import Event
pytestmark = pytest.mark.django_db
RESET_BASE_URL = os.environ.get("GITPOD_WORKSPACE_URL")[8:]
today = datetime.now(tz=timezone.utc)
tomorrow = datetime.now(tz=timezone.utc) + timedelta(days=1)
class TestEventModel:
def test_end_time_validator(self):
event = Event(
start_time=tomorrow,
end_time=today,
)
with suppress(ValidationError):
event.full_clean()
assert False
class TestEventView:
uri = "/api/events/"
def test_end_time_validator(self, all_entities):
client = APIClient()
client.force_authenticate(user=all_entities["coord"])
post_response = client.post(
self.uri,
{
"start_time": tomorrow,
"end_time": today,
"consumers": [],
"school_group": all_entities["activity_group"].slug,
},
format="json",
)
assert post_response.status_code == status.HTTP_400_BAD_REQUEST
assert "end_time" in post_response.data
def test_create_event(self, all_entities):
coord = all_entities["coord"]
payload = {
"start_time": today,
"end_time": tomorrow,
"consumers": [all_entities["consumer"].slug],
"school_group": all_entities["activity_group"].slug,
}
client = APIClient()
client.force_authenticate(user=coord)
post_response = client.post(
self.uri,
payload,
format="json",
)
get_response = client.get(self.uri)
assert post_response.status_code == status.HTTP_201_CREATED
assert get_response.status_code == status.HTTP_200_OK
assert post_response.data == dict(get_response.data["results"][0])
assert post_response.data["consumers"] == payload["consumers"]
assert post_response.data["school_group"] == payload["school_group"]
<file_sep># Generated by Django 3.1.11 on 2021-06-24 07:22
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_20210608_1047'),
]
operations = [
migrations.CreateModel(
name='Instructor',
fields=[
],
options={
'verbose_name_plural': '4. Instructor (Guide)',
'proxy': True,
'indexes': [],
'constraints': [],
},
bases=('users.user',),
),
migrations.AlterField(
model_name='user',
name='user_type',
field=models.CharField(choices=[('CONSUMER', 'Consumer'), ('COORDINATOR', 'Coordinator'), ('VENDOR', 'Vendor'), ('INSTRUCTOR', 'Instructor')], default='CONSUMER', max_length=50, verbose_name='Type'),
),
migrations.CreateModel(
name='InstructorProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('gender', models.CharField(choices=[('MALE', 'Male'), ('FEMALE', 'Female'), ('OTHER', 'Other'), ('UNKNOWN', 'Unknown')], default='UNKNOWN', max_length=50, verbose_name='Gender')),
('profile_picture', models.JSONField(blank=True, default=dict, null=True)),
('phone_number', models.CharField(blank=True, max_length=15, validators=[django.core.validators.RegexValidator(message='phone number must be between 9-15 digits', regex='^\\d{9,15}$')])),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='instructorprofile', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
<file_sep><template>
<v-card
class="my-15 mx-auto px-16 py-10"
max-width="800"
:elevation="$vuetify.breakpoint.mobile ? 0 : 3"
>
<v-card-title v-text="$t('events.eventFeedback')" class="px-0" />
<v-card-subtitle v-text="event.activityName" class="px-0 pt-3 pb-10" />
<title-to-text
:title="$t('groups.groupName')"
:text="event.schoolGroupName || $t('errors.unavailable')"
/>
<title-to-text
:title="$t('time.startTime')"
:text="parseDate(event.startTime) || $t('errors.unavailable')"
/>
<title-to-text
:title="$t('time.endTime')"
:text="parseDate(event.endTime) || $t('errors.unavailable')"
/>
<title-to-text
:title="$t('myActivity.location')"
:text="event.locationsName || $t('errors.empty')"
/>
<form-card
elevation="0"
v-model="form"
@valid="isFormValid = true"
@invalid="isFormValid = false"
/>
<v-btn
large
color="primary"
class="mx-auto mt-9 mb-6 px-8"
elevation="3"
v-text="$t('userActions.save')"
@click="onSubmit"
:disabled="!isFormValid"
/>
</v-card>
</template>
<script>
import { mapActions } from "vuex"
import debounce from "lodash/debounce"
import store from "../vuex/store"
import Api from "../api"
import Utils from "../helpers/utils"
import TitleToText from "../components/TitleToText"
import FormCard from "../components/FormCard"
export default {
components: { TitleToText, FormCard },
props: {
slug: {
type: String,
required: true,
},
},
async beforeRouteEnter(to, from, next) {
const event = await store.dispatch("consumerEvent/getEvent", to.params.slug)
next(vm => (vm.event = event))
},
data() {
return {
isFormValid: false,
event: {},
form: [
{
name: "generalNotes",
rules: "required|max:400",
label: this.$t(
"events.summarizeYourExperienceInTheEventAndWriteWhatYouLearned"
),
value: "",
},
{
name: "secondaryNotes",
rules: "required|max:400",
label: this.$t("events.writeProsAndCons"),
value: "",
},
{
name: "generalRating",
rules: "required",
label: this.$t("events.chooseYourLevelOfSatisfactionFromTheEvent"),
type: "select",
choices: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
value: "",
},
{
name: "secondaryRating",
rules: "required",
type: "select",
choices: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
label: this.$t(
"events.chooseHowLikelyYouAreToRecommendThisActivityToAFriend"
),
value: "",
},
],
}
},
methods: {
...mapActions("consumerEvent", ["createEventFeedback"]),
...mapActions("snackbar", ["showMessage"]),
parseDate: Utils.ApiStringToReadableDate,
onSubmit: debounce(
async function () {
try {
const feedback = this.form.reduce(
(accum, field) => ({ ...accum, [field.name]: field.value }),
{ event: this.slug }
)
await this.createEventFeedback(feedback)
this.showMessage(this.$t("general.detailsSuccessfullyUpdated"))
this.$router.push({ name: "ConsumerPendingEventsFeedback" })
} catch (err) {
this.showMessage(Api.utils.parseResponseError(err))
}
},
500,
{ leading: true, trailing: false }
),
},
}
</script>
<file_sep>import axios from "axios"
import {
GET_CONSUMER_PROGRAM_LIST_API_URL,
GET_PROGRAM_MEDIA_LIST_API_URL,
CONSUMER_JOIN_PROGRAM_API_URL,
CONSUMER_LEAVE_PROGRAM_API_URL,
} from "../helpers/constants/constants"
const consumerProgram = {
getProgram(slug) {
if (!slug) throw "getProgram: received empty slug"
return axios.get(`${GET_CONSUMER_PROGRAM_LIST_API_URL}${slug}/`)
},
getProgramMediaList(programSlug) {
if (!programSlug) throw "getProgramMediaList: received empty slug"
return axios.get(GET_PROGRAM_MEDIA_LIST_API_URL, {
params: {
activity__slug: programSlug,
},
})
},
getProgramsList(params) {
// :Object params: query params
return axios.get(GET_CONSUMER_PROGRAM_LIST_API_URL, { params })
},
joinProgram(programSlug) {
if (!programSlug) throw "joinProgram: received empty slug"
const url = `${CONSUMER_JOIN_PROGRAM_API_URL}${programSlug}/join_group/`
return axios.post(url, {})
},
leaveProgram(programSlug) {
if (!programSlug) throw "leaveProgram: received empty slug"
const url = `${CONSUMER_LEAVE_PROGRAM_API_URL}${programSlug}/leave_group/`
return axios.post(url, {})
},
}
export default consumerProgram
<file_sep>import axios from "axios"
import { LOGIN_API_URL, RESET_PASSWORD_URL } from "../helpers/constants/constants"
const auth = {
login(email, password) {
// params are strings for login request
// return: axios Promise
return axios.post(LOGIN_API_URL, { email, password })
},
resetPassword(uid, token, password, passwordConfirmation) {
let url = `${RESET_PASSWORD_URL}${uid}/${token}/`
let data = {
uid,
token,
new_password1: <PASSWORD>,
new_password2: <PASSWORD>,
}
return axios.post(url, data)
},
}
export default auth
<file_sep>from server.users.forms import SendInviteForm
def send_user_invite(email):
# send invitation to reset password & join the platform
form = SendInviteForm(data={"email": email})
if form.is_valid():
form.save(None)
<file_sep><template>
<div
:style="{ background: `url('${bg}')` }"
class="error-bg d-flex justify-center align-center"
>
<v-col cols="11" sm="6" md="6" lg="5" xl="4">
<v-card class="py-12 px-5 error-card" elevation="20" outlined>
<v-card-title class="text-h3 justify-center mb-9"
>{{ titleKey ? $t(titleKey) : $t("errors.oops") }}!</v-card-title
>
<v-card-text class="text-h5 text-center">{{
bodyKey ? $t(bodyKey) : $t("errors.genericError")
}}</v-card-text>
<v-btn
@click="$router.push({ path: '/' })"
elevation="3"
class="back-btn px-8 py-5"
>
{{ $t("general.homepage") }}
</v-btn>
</v-card>
</v-col>
</div>
</template>
<script>
import { BACKGROUNDS } from "../helpers/constants/images"
export default {
props: {
// i18n JSONs keys for title and body
titleKey: String,
bodyKey: String,
},
data() {
return {
bg: BACKGROUNDS.error,
}
},
}
</script>
<style lang="scss" scoped>
.error-bg {
background-size: cover;
min-height: 100vh;
}
.error-card {
min-height: 350px;
background-color: rgba(255, 255, 255, 0.9);
}
.back-btn {
position: absolute;
bottom: 60px;
left: 50%;
transform: translateX(-50%);
}
</style>
<file_sep>
image:
file: .gitpod.Dockerfile
ports:
# django server
- port: 8000
onOpen: open-preview
visibility: public
- port: 8025
onOpen: open-preview
# PostgreSQL server
- port: 5432
onOpen: ignore
tasks:
- name: Server
init: >
pg_ctl status | grep PID || pg_start &&
cd server &&
pre-commit install && source .envs/.local/.django &&
source .envs/.local/.postgres && psql -c "CREATE DATABASE server" &&
python manage.py migrate && python manage.py create_test_data &&
cd ..
command: pg_ctl status | grep PID || pg_start && cd server && python manage.py runserver 0.0.0.0:8000
- command: redis-server
- command: MailHog
- name: Vue Client
init: >
cd client &&
yarn && cd .. &&
gp sync-done client-install
command: >
cd client &&
yarn serve
- name: Vue Storybook
init: gp sync-await client-install
command: >
cd client &&
yarn storybook
- command: >
echo welcome
- command: >
echo -e "\e[36mWELCOME CONTRIBUTER!"
# command: 'createdb server -U postgres --password $POSTGRES_PASSWORD'
vscode:
extensions:
- vsls-contrib.codetour
- octref.vetur
- esbenp.prettier-vscode
<file_sep>import Utils from "../helpers/utils"
import ActionsCalendar from "../components/ActionsCalendar"
import moment from "moment"
export default {
title: "ActionsCalendar",
component: ActionsCalendar,
}
const Template = args => ({
components: { ActionsCalendar },
data: () => ({ args }),
template: `
<actions-calendar
v-model="args.value"
first-interval="5"
interval-count="19"
:displayType.sync="args.displayType"
:events="args.events"
/>
`,
})
export const Primary = Template.bind({})
Primary.args = {
displayType: "week",
value: "",
events: [
{
name: "תופסים פוקימונים בפארק הירקון",
start: moment().toDate(),
end: moment().add(2, "hours").toDate(),
timed: true,
color: Utils.stringToPsuedoRandomColor("תופסים פוקימונים בפארק הירקון"),
},
{
name: "ראיון עבודה",
start: moment().add(1, "hours").toDate(),
end: moment().add(3, "hours").toDate(),
timed: true,
color: Utils.stringToPsuedoRandomColor("ראיון עבודה"),
},
{
name: "על האש בפארק לאומי",
start: moment().subtract(15, "hours").toDate(),
end: moment().subtract(10, "hours").toDate(),
timed: true,
color: Utils.stringToPsuedoRandomColor("על האש בפארק לאומי"),
},
{
name: "טורניר שחמט אקטיבי",
start: moment().add(100, "hours").toDate(),
end: moment().add(103, "hours").toDate(),
timed: true,
color: Utils.stringToPsuedoRandomColor("טורניר שחמט אקטיבי"),
},
{
name: "<NAME>",
start: moment().add(300, "hours").toDate(),
end: moment().add(306, "hours").toDate(),
timed: true,
color: Utils.stringToPsuedoRandomColor("יום כיף בפתח תקווה"),
},
]
}
<file_sep>from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class SchoolsConfig(AppConfig):
name = "server.schools"
verbose_name = _("Schools")
def ready(self):
try:
import server.schools.signals # noqa F401
except ImportError:
pass
<file_sep># Generated by Django 3.1.11 on 2021-06-24 15:10
from django.db import migrations, models
import server.utils.model_fields
class Migration(migrations.Migration):
dependencies = [
('organizations', '0012_auto_20210624_1810'),
]
operations = [
migrations.AlterField(
model_name='schoolactivitygroup',
name='slug',
field=models.CharField(default=server.utils.model_fields.random_slug, max_length=40, unique=True),
),
]
<file_sep>import { action } from "@storybook/addon-actions"
import InputDrawer from "../components/InputDrawer.vue"
export default {
title: "InputDrawer",
component: InputDrawer,
argTypes: { type: { action: "input" } },
}
const Template = args => ({
components: { InputDrawer },
methods: { action },
data: () => ({ args }),
template: `
<input-drawer
style="margin: 0 80px;"
v-model="args.value"
v-bind="args"
@input="action('input')()" />`
})
export const TextInput = Template.bind({})
TextInput.args = {
uniqueName: "firstName",
label: "<NAME>",
rules: "required",
value: "בנג'מין",
}
export const SelectInput = Template.bind({})
SelectInput.args = {
type: "select",
uniqueName: "Options",
label: "אפשרויות",
rules: "required",
value: [],
choices: [
{ value: 1, text: "Option A" },
{ value: 2, text: "Option B" },
{ value: 3, text: "Option C" },
],
}
<file_sep><template>
<div>
<validation-observer
tag="form"
v-slot="{ invalid }"
@submit.prevent="onSubmit"
v-if="program"
>
<v-row no-gutters>
<v-col cols="12" lg="7" class="mb-12 mb-lg-0">
<div class="d-sm-flex justify-space-between mb-10">
<div>
<h1 v-text="$t('program.programPage')" class="mb-5" />
<h2 v-text="$t('program.editAndViewTheProgramDetails')" />
</div>
<v-btn
tile
large
color="error"
class="mx-auto mx-sm-0 d-block my-10 my-sm-0"
data-testid="delete-btn"
@click="isModalOpen = true"
>
{{ $t("userActions.delete") }}
<v-icon right> mdi-close </v-icon>
</v-btn>
</div>
<input-drawer
v-for="field in VENDOR_PROGRAM_FIELDS"
v-model="program[field.name]"
:key="field.id"
:unique-name="field.name"
:label="field.label"
:rules="field.rules"
:type="field.type || 'text'"
:choices="field.choices"
:multiselect="field.multiselect"
/>
</v-col>
<v-col cols="12" lg="5" class="px-10" align-self="center">
<picture-input
class="mx-auto"
:placeholderPicUrl="logoPlaceholder"
@fileUpload="setLogo"
/>
</v-col>
</v-row>
<div class="mx-auto mx-md-0 my-16">
<v-btn
class="mx-2 white--text"
type="submit"
color="primary"
elevation="3"
v-text="$t('userActions.save')"
:disabled="invalid"
/>
<v-btn
class="mx-2 white--text"
elevation="3"
type="button"
color="primary"
outlined
v-text="$t('general.media')"
@click="
$router.push({
name: 'VendorProgramMediaUpload',
params: { programSlug },
})
"
/>
</div>
</validation-observer>
<modal-approve v-model="isModalOpen" @approve="handleDelete">
{{ this.$t("confirm.AreYouSureYouWantToDeleteThisProgram?") }}
</modal-approve>
</div>
</template>
<script>
import isString from "lodash/isString"
import { ValidationObserver } from "vee-validate"
import { mapActions } from "vuex"
import Utils from "../helpers/utils"
import Api from "../api"
import store from "../vuex/store"
import { CAMERA_ROUNDED_DRAWING } from "../helpers/constants/images"
import { VENDOR_PROGRAM_FIELDS } from "../helpers/constants/constants"
import inputDrawer from "../components/InputDrawer"
import ModalApprove from "../components/ModalApprove"
import PictureInput from "../components/PictureInput"
export default {
components: {
ValidationObserver,
inputDrawer,
ModalApprove,
PictureInput,
},
async beforeRouteEnter(to, from, next) {
const program = await store.dispatch(
"vendorProgram/getProgram",
to.params.programSlug
)
next(vm => (vm.program = program))
},
props: {
programSlug: {
type: String,
required: true,
},
},
data() {
return {
VENDOR_PROGRAM_FIELDS,
isModalOpen: false,
program: null,
}
},
methods: {
...mapActions("vendorProgram", ["updateProgram", "deleteProgram"]),
...mapActions("snackbar", ["showMessage"]),
async onSubmit() {
try {
const data = Utils.objectToFormData(this.program)
if (!this.program.logo || isString(this.program.logo)) {
// if logo not uploaded
data.delete("logo")
}
await this.updateProgram({
programSlug: this.programSlug,
data,
})
this.showMessage(this.$t("general.detailsSuccessfullyUpdated"))
this.$router.push({ name: "VendorProgramList" })
} catch (err) {
this.showMessage(Api.utils.parseResponseError(err))
}
},
async handleDelete() {
try {
await this.deleteProgram(this.programSlug)
this.showMessage(this.$t("success.programDeletedSuccessfully"))
this.$router.push({ name: "VendorProgramList" })
} catch (err) {
this.showMessage(Api.utils.parseResponseError(err))
}
},
setLogo(e) {
this.program.logo = e
},
},
computed: {
logoPlaceholder() {
return (this.program && this.program.logo) || CAMERA_ROUNDED_DRAWING
},
},
}
</script>
<file_sep>import django_filters
from django.db.models import Q
from server.organizations.models import Activity
class CharInFilter(django_filters.BaseInFilter, django_filters.CharFilter):
# comma-seperate the values before applying filters. used for "in" lookups
pass
class ActivityFilter(django_filters.FilterSet):
domain__in = CharInFilter(field_name="domain", lookup_expr="in")
target_audience = django_filters.CharFilter(method="target_audience_filter")
tags = django_filters.CharFilter(method="tags_filter")
class Meta:
model = Activity
fields = ["target_audience", "domain__in"]
def target_audience_filter(self, queryset, name, value):
if value.isnumeric():
return queryset.filter(target_audience__contains=int(value))
query = Q()
for str_numeric_grade in value.split(","):
query = query | Q(target_audience__contains=int(str_numeric_grade))
return queryset.filter(query)
def tags_filter(self, queryset, name, value):
return queryset.filter(tags__name__in=value.split(",")).distinct()
<file_sep># Generated by Django 3.1.11 on 2021-06-24 08:27
from django.db import migrations, models
import server.utils.model_fields
class Migration(migrations.Migration):
dependencies = [
('organizations', '0010_schoolactivitygroup_instructor'),
]
operations = [
migrations.AddField(
model_name='schoolactivitygroup',
name='slug',
field=models.CharField(default=server.utils.model_fields.random_slug, max_length=40, null=True),
),
]
<file_sep># Generated by Django 3.1.11 on 2021-06-13 08:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organizations', '0005_auto_20210610_1919'),
]
operations = [
migrations.AddField(
model_name='organization',
name='organization_number',
field=models.CharField(max_length=10, null=True, unique=True),
),
migrations.AlterField(
model_name='activity',
name='description',
field=models.CharField(default='', max_length=550),
),
]
<file_sep>import axios from "axios"
import { GET_INSTRUCTOR_PROGRAM_GROUP_CONSUMERS_API_URL } from "../helpers/constants/constants"
const instructorProgramGroup = {
getConsumers(groupSlug) {
if (!groupSlug) throw "getConsumers: received empty slug"
return axios.get(`${GET_INSTRUCTOR_PROGRAM_GROUP_CONSUMERS_API_URL}${groupSlug}/group_consumers/`)
},
}
export default instructorProgramGroup
<file_sep>---
name: Feature Template
about: New Feature Template.
title: "[Client/Server] | [Title]"
labels: feature
assignees: ''
---
### Feature Description
[A clear and concise description of the feature]
### Why do we need this feature?
[A clear explanation of the actual need]
### What does the proposed solution look like? (Balsamiq / Technical Overview)
[The solution proposition - as detailed as possible. If needed, attach screenshots and references]
### How to test?
[If there are available tests already, specify how to run them]
### Blocked
[If the task is currently blocked, enter its dependencies - e.g., links to other issues]
[](https://gitpod.io/from-referrer)
<file_sep>import { action } from "@storybook/addon-actions"
import SelectTable from "../components/SelectTable"
export default {
title: "SelectTable",
component: SelectTable,
}
const Template = args => ({
components: { SelectTable },
methods: { action },
data: () => ({ args }),
template: `
<select-table
class="w-75 mx-auto"
v-bind="args"
v-model="args.selected"
@input="action('input')()"
@select="action('select')()"
@diselect="action('diselect')()"
>
</select-table>
`,
})
export const Primary = Template.bind({})
Primary.args = {
headers: [
{ text: "Food Name", value: "name" },
{ text: "Num of Cals", value: "calories" },
],
selected: [
{
name: "Banana",
calories: "70",
},
],
items: [
{
name: "Banana",
calories: "70",
},
{
name: "Orange",
calories: "40",
},
{
name: "Cucumber",
calories: "35",
},
{
name: "Lemon",
calories: "45",
},
{
name: "Carrot",
calories: "20",
},
{
name: "Cookie",
calories: "45",
},
{
name: "Cake",
calories: "100",
},
{
name: "Burger",
calories: "200",
},
{
name: "French Fries",
calories: "100",
},
{
name: "Water",
calories: "0",
},
],
}
<file_sep># Generated by Django 3.1.11 on 2021-06-24 15:22
from django.db import migrations
import server.utils.model_fields
def gen_random_slug(apps, schema_editor):
Event = apps.get_model('events', 'Event')
for row in Event.objects.all():
row.slug = server.utils.model_fields.random_slug()
row.save(update_fields=['slug'])
class Migration(migrations.Migration):
dependencies = [
('events', '0002_auto_20210624_1022'),
]
operations = [
migrations.RunPython(gen_random_slug, reverse_code=migrations.RunPython.noop),
]<file_sep>import pytest
from server.organizations.models import (
Activity,
Organization,
OrganizationMember,
SchoolActivityGroup,
SchoolActivityOrder,
)
from server.organizations.tests.factories import (
ActivityFactory,
OrganizationFactory,
SchoolActivityGroupFactory,
SchoolActivityOrderFactory,
)
from server.schools.models import School, SchoolMember
from server.schools.tests.factories import SchoolFactory
from server.users.models import Consumer, Coordinator, Instructor, User, Vendor
from server.users.tests.factories import (
ConsumerFactory,
CoordinatorFactory,
InstructorFactory,
UserFactory,
VendorFactory,
)
@pytest.fixture(autouse=True)
def media_storage(settings, tmpdir):
settings.MEDIA_ROOT = tmpdir.strpath
@pytest.fixture
def user() -> User:
return UserFactory()
@pytest.fixture
def coordinator() -> Coordinator:
return CoordinatorFactory()
@pytest.fixture
def consumer() -> Consumer:
return ConsumerFactory()
@pytest.fixture
def vendor() -> Vendor:
return VendorFactory()
@pytest.fixture
def instructor() -> Instructor:
return InstructorFactory()
@pytest.fixture
def school() -> School:
return SchoolFactory()
@pytest.fixture
def organization() -> Organization:
return OrganizationFactory()
@pytest.fixture
def activity() -> Activity:
return ActivityFactory()
@pytest.fixture
def school_activity_order() -> SchoolActivityOrder:
return SchoolActivityOrderFactory()
@pytest.fixture
def school_activity_group() -> SchoolActivityGroup:
return SchoolActivityGroupFactory()
@pytest.fixture
def all_entities(
school_activity_group, coordinator, consumer, vendor, instructor
) -> dict:
activity_order = school_activity_group.activity_order
activity = activity_order.activity
organization = activity.originization
SchoolMember.objects.create(user=coordinator, school=activity_order.school)
SchoolMember.objects.create(user=consumer, school=activity_order.school)
OrganizationMember.objects.create(user=vendor, organization=organization)
OrganizationMember.objects.create(user=instructor, organization=organization)
return {
"activity_group": school_activity_group,
"activity_order": activity_order,
"school": activity_order.school,
"activity": activity,
"organization": organization,
"coord": coordinator,
"consumer": consumer,
"vendor": vendor,
"instructor": instructor,
}
school1 = school
<file_sep># Generated by Django 3.1.11 on 2021-07-25 11:42
from django.db import migrations, models
import server.schools.models
class Migration(migrations.Migration):
dependencies = [
('schools', '0007_auto_20210720_1122'),
]
operations = [
migrations.CreateModel(
name='ImportedSchool',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.CharField(default=server.schools.models.random_slug, max_length=40, unique=True)),
('name', models.CharField(max_length=50)),
('address', models.CharField(max_length=50)),
('address_city', models.CharField(max_length=50)),
('school_code', models.IntegerField(unique=True)),
('grade_levels', models.JSONField()),
('longtitude', models.FloatField()),
('latitude', models.FloatField()),
('region', models.CharField(max_length=50)),
('status', models.CharField(max_length=50)),
('boys', models.IntegerField()),
('girls', models.IntegerField()),
('male_teachers', models.IntegerField()),
('female_teachers', models.IntegerField()),
('migzar', models.CharField(blank=True, max_length=50, null=True)),
('school_type', models.CharField(blank=True, max_length=50, null=True)),
('school_stages', models.CharField(blank=True, max_length=50, null=True)),
('authority_city', models.CharField(blank=True, max_length=50, null=True)),
('is_bagrut', models.BooleanField()),
('immigrants_percent', models.FloatField(blank=True, null=True)),
('tech_students_percent', models.FloatField(blank=True, null=True)),
('tech_diploma_eligible_percent', models.FloatField(blank=True, null=True)),
('special_education_percent', models.FloatField(blank=True, null=True)),
('social_economic_status', models.IntegerField(blank=True, null=True)),
('decile_tipuah_hativa_benaim', models.IntegerField(blank=True, null=True)),
('decile_tipuah_hativa_eliona', models.IntegerField(blank=True, null=True)),
('decile_tipuah_yesodi', models.IntegerField(blank=True, null=True)),
('ivhun_percent', models.FloatField(blank=True, null=True)),
('boys_army_enlist_rate', models.FloatField(blank=True, null=True)),
('girls_army_enlist_rate', models.FloatField(blank=True, null=True)),
('hatmada_percent', models.FloatField(blank=True, null=True)),
('drop_rate', models.FloatField(blank=True, null=True)),
('bagrut_eligible_percent', models.FloatField(blank=True, null=True)),
('bagrut_excelent_eligible_percent', models.FloatField(blank=True, null=True)),
('bagrut_english_5u_percent', models.FloatField(blank=True, null=True)),
('bagrut_math_5u_percent', models.FloatField(blank=True, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
),
]
<file_sep># Generated by Django 3.1.11 on 2021-06-29 09:13
from django.db import migrations
import server.utils.model_fields
def gen_random_slug(apps, schema_editor):
SchoolActivityOrder = apps.get_model('organizations', 'SchoolActivityOrder')
for row in SchoolActivityOrder.objects.all():
row.slug = server.utils.model_fields.random_slug()
row.save(update_fields=['slug'])
class Migration(migrations.Migration):
dependencies = [
('organizations', '0014_schoolactivityorder_slug'),
]
operations = [
migrations.RunPython(gen_random_slug, reverse_code=migrations.RunPython.noop),
]
<file_sep>import Api from "../../api"
function getDefaultState() {
return {
profile: {
phoneNumber: null,
profilePicture: null,
},
}
}
const vendor = {
namespaced: true,
state: getDefaultState(),
mutations: {
FLUSH_STATE(state) {
Object.assign(state, getDefaultState())
},
SET_PROFILE(state, userProfile) {
state.profile = userProfile
},
},
actions: {
flushState({ commit }) {
commit("FLUSH_STATE")
},
async getProfile({ commit, state }) {
if (!state.profile.phoneNumber) {
// fetch if not in cache
let res = await Api.vendor.getProfile()
commit("SET_PROFILE", res.data)
}
return state.profile
},
async updateProfile({ commit, state }, { slug, profile }) {
let res = await Api.vendor.updateProfile(slug, profile)
commit("SET_PROFILE", res.data)
return state.profile
},
},
}
// i.e., org manager
export default vendor
<file_sep>import csv
import requests
from django.core.management.base import BaseCommand
from server.schools.models import ImportedSchool
class Command(BaseCommand):
help = "Fetch schools from gov site and load to db or csv"
def handle(self, *args, **options):
self.fetch(options["csv"])
def add_arguments(self, parser):
parser.add_argument("--csv", action="store_true")
def fetch(self, write_csv):
grades_letter_to_number = {
"גן": 0,
"א": 1,
"ב": 2,
"ג": 3,
"ד": 4,
"ה": 5,
"ו": 6,
"ז": 7,
"ח": 8,
"ט": 9,
"י": 10,
"יא": 11,
"יב": 12,
"יג": 13,
"יד": 14,
}
if write_csv:
fieldnames = [
"name",
"address",
"address_city",
"school_code",
"grade_levels",
"longtitude",
"latitude",
"region",
"status",
"boys",
"girls",
"male_teachers",
"female_teachers",
"migzar",
"school_type",
"school_stages",
"authority_city",
"is_bagrut",
"immigrants_percent",
"tech_students_percent",
"tech_diploma_eligible_percent",
"special_education_percent",
"social_economic_status",
"decile_tipuah_hativa_benaim",
"decile_tipuah_hativa_eliona",
"decile_tipuah_yesodi",
"ivhun_percent",
"hatmada_percent",
"drop_rate",
"bagrut_eligible_percent",
"bagrut_excelent_eligible_percent",
"bagrut_english_5u_percent",
"bagrut_math_5u_percent",
"boys_army_enlist_rate",
"girls_army_enlist_rate",
"last_updated",
]
csv_file = open("schools.csv", "w", encoding="UTF-8")
csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
csv_writer.writeheader()
all_schools = requests.get(
r"https://shkifut.education.gov.il/api/data/lists"
).json()
schools_codes = [
school["s"] for school in all_schools["infoLists"] if school["m"] == 3
]
for school_code in schools_codes:
raw_school = requests.get(
f"https://shkifut.education.gov.il/api/data/mosad/?semelMosad={school_code}&year=2019"
).json()
address, address_city = raw_school["mosadGenaralData"][
"KTOVET_MOSAD"
].split(",")
raw_grades = raw_school["mosadYearData"]["SHICHVA_AD_SHICHVA"]
start_grade, end_grade = raw_grades.split(" - ")
grades = list(
range(
grades_letter_to_number[start_grade],
grades_letter_to_number[end_grade] + 1,
)
)
education_picture = requests.get(
f"https://shkifut.education.gov.il/api/data/mosadEduPic/?semelMosad={school_code}"
)
girls_army_enlist_rate = None
boys_army_enlist_rate = None
bagrut_eligible_percent = None
bagrut_excelent_eligible_percent = None
bagrut_english_5u_percent = None
bagrut_math_5u_percent = None
if education_picture.status_code == 200:
education_picture = education_picture.json()
for picture in education_picture["groups"]:
if picture["Id"] == 5 and picture["Classes"]:
for class_data in picture["Classes"]:
if class_data["Id"] == 12:
for zacaut in class_data["Indexes"]:
if zacaut["Id"] == "ACHUZ_ZAKAIM":
bagrut_eligible_percent = zacaut["Value"]
elif zacaut["Id"] == "ACHUZ_ZAKAIM_MITZTYEN":
bagrut_excelent_eligible_percent = zacaut[
"Value"
]
elif zacaut["Id"] == "ACHUZ_ANGLIT_5YL":
bagrut_english_5u_percent = zacaut["Value"]
elif zacaut["Id"] == "ACHUZ_MATEM_5YL":
bagrut_math_5u_percent = zacaut["Value"]
elif picture["Id"] == 2 and picture["Classes"]:
class_data = picture["Classes"][0]
for index in class_data["Indexes"]:
if index["Id"] == "ACHUZ_MATMID":
hatmada_percent = index["Value"]
elif index["Id"] == "ACHUZ_NESHIRA":
drop_rate = index["Value"]
elif picture["Id"] == 1 and picture["Classes"]:
class_data = picture["Classes"][0]
for index in class_data["Indexes"]:
if index["Id"] == "GIUS_BANIM_LEZAVA":
boys_army_enlist_rate = index["Value"]
elif index["Id"] == "GIUS_BANOT_LEZAVA":
girls_army_enlist_rate = index["Value"]
school_data = {
"name": raw_school["mosadGenaralData"]["SHEM_MOSAD"],
"address": address.strip(),
"address_city": address_city.strip(),
"school_code": school_code,
"grade_levels": grades,
"longtitude": raw_school["mosadGenaralData"]["LONGITUDE"],
"latitude": raw_school["mosadGenaralData"]["LATITUDE"],
"region": raw_school["mosadGenaralData"]["MACHOZ_MEFAK"],
"status": raw_school["mosadGenaralData"]["STATUS_MOSAD"],
"boys": raw_school["mosadYearData"]["BANIM"],
"girls": raw_school["mosadYearData"]["BANOT"],
"male_teachers": raw_school["mosadYearData"]["MORIM"],
"female_teachers": raw_school["mosadYearData"]["MOROT"],
"migzar": raw_school["mosadYearData"]["MIGZAR_YY"],
"school_type": raw_school["mosadYearData"]["PIKOH_YY"],
"school_stages": raw_school["mosadYearData"]["SHLAVE_CHINUCH_MOSAD_YY"],
"authority_city": raw_school["mosadYearData"]["SHEM_RASHUT_YY"],
"is_bagrut": bool(raw_school["mosadGenaralData"]["MEGISH_LE_BAGRUT"]),
"immigrants_percent": raw_school["mosadYearData"]["TALMIDIM_OLIM"],
"tech_students_percent": raw_school["mosadYearData"][
"TALMIDIM_TECHNOLOGI"
],
"tech_diploma_eligible_percent": raw_school["mosadYearData"][
"Zakaut_Tech_Achuz_Zakaim"
],
"special_education_percent": raw_school["mosadYearData"][
"MADAD_CHINUCH_MEYUCHAD"
],
"social_economic_status": raw_school["mosadYearData"][
"MATSAV_SOTSYOEKONOMI"
],
"decile_tipuah_hativa_benaim": raw_school["mosadYearData"][
"ASIRON_HTB"
],
"decile_tipuah_hativa_eliona": raw_school["mosadYearData"][
"ASIRON_HTE"
],
"decile_tipuah_yesodi": raw_school["mosadYearData"]["ASIRON_YES"],
"ivhun_percent": raw_school["mosadYearData"][
"ACHUZ_MECHOZI_IM_IVCHUN_ARTZI"
],
"bagrut_eligible_percent": bagrut_eligible_percent,
"girls_army_enlist_rate": girls_army_enlist_rate,
"boys_army_enlist_rate": boys_army_enlist_rate,
"drop_rate": drop_rate,
"hatmada_percent": hatmada_percent,
"bagrut_math_5u_percent": bagrut_math_5u_percent,
"bagrut_english_5u_percent": bagrut_english_5u_percent,
"bagrut_excelent_eligible_percent": bagrut_excelent_eligible_percent,
}
if write_csv:
csv_writer.writerow(school_data)
csv_file.flush()
else:
ImportedSchool.objects.update_or_create(
defaults=school_data, school_code=school_code
)
<file_sep>from django.core.exceptions import ObjectDoesNotExist
from rest_framework import mixins, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from server.utils.permission_classes import AllowConsumerReadOnly, AllowCoordinator
from ..models import School
from .serializers import SchoolSerializer
class SchoolViewSet(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.ListModelMixin,
GenericViewSet,
):
permission_classes = [AllowCoordinator | AllowConsumerReadOnly]
serializer_class = SchoolSerializer
lookup_field = "slug"
def get_queryset(self):
try:
return School.objects.filter(
school_member__in=[self.request.user.school_member]
)
except ObjectDoesNotExist:
return School.objects.none()
def perform_create(self, serializer):
serializer.save(last_updated_by=self.request.user)
def perform_update(self, serializer):
serializer.save(last_updated_by=self.request.user)
@action(detail=False, methods=["GET"])
def me(self, request):
serializer = SchoolSerializer(
request.user.school_member.school, context={"request": request}
)
return Response(status=status.HTTP_200_OK, data=serializer.data)
<file_sep># Generated by Django 3.1.11 on 2021-05-20 12:58
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import server.utils.model_fields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Activity',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.CharField(default=server.utils.model_fields.random_slug, max_length=40, unique=True)),
('name', models.CharField(max_length=35)),
('target_audience', models.JSONField()),
('domain', models.CharField(max_length=55)),
('description', models.CharField(default='', max_length=400)),
('contact_name', models.CharField(default='', max_length=60)),
('logo', models.ImageField(blank=True, null=True, upload_to='')),
('phone_number', models.CharField(blank=True, max_length=15, validators=[django.core.validators.RegexValidator(message='phone number must be between 9-15 digits', regex='^\\d{9,15}$')])),
],
),
migrations.CreateModel(
name='Organization',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.CharField(default=server.utils.model_fields.random_slug, max_length=40, unique=True)),
('email', models.EmailField(max_length=254)),
('description', models.CharField(max_length=250)),
('website_url', models.URLField()),
('name', models.CharField(max_length=50)),
('goal', models.CharField(max_length=250)),
('year_founded', models.CharField(blank=True, max_length=4, null=True)),
('status', models.CharField(max_length=50)),
('target_audience', models.JSONField()),
('number_of_employees', models.PositiveIntegerField()),
('nuber_of_members', models.PositiveIntegerField()),
('number_of_volunteers', models.PositiveIntegerField()),
('location_lon', models.DecimalField(decimal_places=6, max_digits=9)),
('location_lat', models.DecimalField(decimal_places=6, max_digits=9)),
('address_city', models.CharField(max_length=150)),
('address_street', models.CharField(max_length=150)),
('address_house_num', models.CharField(max_length=4)),
('address_zipcode', models.CharField(max_length=9)),
('cities', models.JSONField()),
('districts', models.JSONField()),
('union_type', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='OrganizationMemeber',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('organization', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='organizations.organization')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='ActivityMedia',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.CharField(default=server.utils.model_fields.random_slug, max_length=40, unique=True)),
('name', models.CharField(max_length=40)),
('image_url', models.ImageField(blank=True, null=True, upload_to='')),
('video_url', models.URLField(blank=True, null=True)),
('activity', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rich_media', to='organizations.activity')),
],
),
migrations.AddField(
model_name='activity',
name='originization',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='organizations.organization'),
),
]
<file_sep>import axios from "axios"
import {
GET_INSTRUCTOR_EVENT_LIST_API_URL,
GET_INSTRUCTOR_EVENT_API_URL,
UPDATE_INSTRUCTOR_EVENT_API_URL,
CREATE_FEED_POST_API_URL,
CREATE_POST_IMAGES_API_URL,
} from "../helpers/constants/constants"
const instructorEvent = {
getEvent(slug) {
if (!slug) throw "getEvent: received empty slug"
return axios.get(`${GET_INSTRUCTOR_EVENT_API_URL}${slug}/`)
},
updateEvent(slug, data) {
if (!slug) throw "updateEvent: received empty slug"
return axios.patch(`${UPDATE_INSTRUCTOR_EVENT_API_URL}${slug}/`, data)
},
createFeedPost(data) {
return axios.post(`${CREATE_FEED_POST_API_URL}`, data)
},
createPostImages(data) {
return axios.post(`${CREATE_POST_IMAGES_API_URL}`, data)
},
getFeedPosts(params) {
return axios.get(`${CREATE_FEED_POST_API_URL}`, { params })
},
getEventList(params) {
return axios.get(GET_INSTRUCTOR_EVENT_LIST_API_URL, { params })
},
}
export default instructorEvent
<file_sep>from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class OrganizationsConfig(AppConfig):
name = "server.organizations"
verbose_name = _("Organizations")
def ready(self):
try:
import server.organizations.signals # noqa F401
except ImportError:
pass
<file_sep>FROM gitpod/workspace-full:latest
# increment by one to re-run dockerfile commands without cache
ENV INVALIDATE_CACHE=2
# Install PostgreSQL
RUN sudo install-packages postgresql-12 postgresql-contrib-12
# Setup PostgreSQL server for user gitpod
ENV PATH="$PATH:/usr/lib/postgresql/12/bin"
ENV PGDATA="/workspace/.pgsql/data"
RUN mkdir -p ~/.pg_ctl/bin ~/.pg_ctl/sockets \
&& printf '#!/bin/bash\n[ ! -d $PGDATA ] && mkdir -p $PGDATA && initdb -D $PGDATA\npg_ctl -D $PGDATA -l ~/.pg_ctl/log -o "-k ~/.pg_ctl/sockets" start\n' > ~/.pg_ctl/bin/pg_start \
&& printf '#!/bin/bash\npg_ctl -D $PGDATA -l ~/.pg_ctl/log -o "-k ~/.pg_ctl/sockets" stop\n' > ~/.pg_ctl/bin/pg_stop \
&& chmod +x ~/.pg_ctl/bin/*
ENV PATH="$PATH:$HOME/.pg_ctl/bin"
ENV DATABASE_URL="postgresql://gitpod@localhost"
ENV PGHOSTADDR="127.0.0.1"
ENV PGDATABASE="postgres"
# Install custom tools, runtimes, etc.
# For example "bastet", a command-line tetris clone:
# RUN brew install bastet
#
# More information: https://www.gitpod.io/docs/config-docker/
RUN sudo apt-get update && sudo apt-get install -y redis-server && sudo rm -rf /var/lib/apt/lists/* && brew update && brew install mailhog
RUN echo "export PIP_USER=false" >> /home/gitpod/.bashrc
RUN echo "export CELERY_BROKER_URL=redis://localhost:6379/0" >> /home/gitpod/.bashrc
RUN sudo apt-get update && sudo apt-get install -y redis-server && sudo rm -rf /var/lib/apt/lists/* && brew update && brew install mailhog
COPY server/requirements temp_requirements
RUN pip install -r temp_requirements/local.txt
COPY . .
RUN echo "export PIP_USER=false" >> /home/gitpod/.bashrc
RUN echo "export CELERY_BROKER_URL=redis://localhost:6379/0" >> /home/gitpod/.bashrc
<file_sep><template>
<div class="relative px-3 mt-8 px-lg-16 mx-lg-16 mt-lg-16">
<h1 v-text="$t('posts.myFeed')" class="mb-5" />
<h2
v-text="$t('posts.viewUpdatesAndPostsInRealTime!')"
class="pb-12"
/>
<v-row justify="center" v-for="post in posts" :key="post.slug" no-gutters>
<v-col cols="12" md="5" lg="4">
<post
class="mx-auto"
:author="post.authorName"
:author-avatar="post.authorProfilePicture"
:images="post.images.map(img => img.imageUrl)"
:content="post.postContent"
:subtitle="ApiStringToReadableDate(post.created)"
/>
</v-col>
</v-row>
<end-of-page-detector @end-of-page="onEndOfPage" />
</div>
</template>
<script>
import { mapActions, mapState } from "vuex"
import store from "../vuex/store"
import Utils from "../helpers/utils"
import Post from "../components/Post"
import EndOfPageDetector from "../components/EndOfPageDetector"
export default {
components: { Post, EndOfPageDetector },
async beforeRouteEnter(to, from, next) {
const posts = await store.dispatch("instructorEvent/getFeedPosts")
next(vm => (vm.posts = posts))
},
methods: {
...mapActions("instructorEvent", ["getFeedPosts"]),
...mapActions("pagination", ["incrementPage"]),
ApiStringToReadableDate: Utils.ApiStringToReadableDate,
onEndOfPage() {
this.incrementPage()
if (this.totalFeedPosts > this.posts.length) {
this.getFeedPosts(false)
}
},
},
data() {
return {
posts: [],
}
},
computed: {
...mapState("instructorEvent", ["totalFeedPosts"]),
},
}
</script>
<file_sep>import axios from "axios"
import {
GET_SCHOOL_DETAILS_API_URL,
UPDATE_SCHOOL_DETAILS_API_URL,
GET_SCHOOL_STUDENTS_LIST_API_URL,
ADD_SCHOOL_STUDENTS_API_URL,
ADD_SCHOOL_COORDINATORS_BULK_API_URL,
ADD_SCHOOL_STUDENTS_BULK_API_URL,
GET_SCHOOL_STUDENTS_EXPORT_FILE_API_URL,
GET_SCHOOL_COORDINATORS_EXPORT_FILE_API_URL,
DELETE_SCHOOL_STUDENTS_API_URL,
EDIT_SCHOOL_STUDENTS_API_URL,
GET_SCHOOL_COORDINATORS_LIST_API_URL,
ADD_SCHOOL_COORDINATORS_API_URL,
DELETE_SCHOOL_COORDINATORS_API_URL,
EDIT_SCHOOL_COORDINATORS_API_URL,
} from "../helpers/constants/constants"
const school = {
getSchoolDetails() {
return axios.get(GET_SCHOOL_DETAILS_API_URL)
},
updateSchoolDetails(schoolSlug, data) {
if (!schoolSlug) throw "updateSchoolDetails: received empty slug"
return axios.put(`${UPDATE_SCHOOL_DETAILS_API_URL}${schoolSlug}/`, data)
},
getStudentList(params) {
// :Object params: query params
return axios.get(GET_SCHOOL_STUDENTS_LIST_API_URL, { params })
},
addStudent(student) {
return axios.post(ADD_SCHOOL_STUDENTS_API_URL, student)
},
addCoordinatorsBulk(csvFile) {
// :File csvFile: file containing students to add to the school
let formData = new FormData()
formData.append("file", csvFile)
return axios.post(ADD_SCHOOL_COORDINATORS_BULK_API_URL, formData)
},
getCoordinatorsExportFile(params) {
// :Object params: query params
return axios.get(GET_SCHOOL_COORDINATORS_EXPORT_FILE_API_URL, { params })
},
addStudentsBulk(csvFile) {
// :File csvFile: file containing students to add to the school
let formData = new FormData()
formData.append("file", csvFile)
return axios.post(ADD_SCHOOL_STUDENTS_BULK_API_URL, formData)
},
getStudentsExportFile(params) {
// :Object params: query params
return axios.get(GET_SCHOOL_STUDENTS_EXPORT_FILE_API_URL, { params })
},
editStudent(slug, data) {
if (!slug) throw "editStudent: received empty slug"
return axios.patch(`${EDIT_SCHOOL_STUDENTS_API_URL}${slug}/`, data)
},
deleteStudents(studentSlugs) {
return Promise.all(
studentSlugs.map(slug =>
axios.delete(`${DELETE_SCHOOL_STUDENTS_API_URL}${slug}`)
)
)
},
getCoordinatorList(params) {
// :Object params: query params
return axios.get(GET_SCHOOL_COORDINATORS_LIST_API_URL, { params })
},
addCoordinator(coordinator) {
return axios.post(ADD_SCHOOL_COORDINATORS_API_URL, coordinator)
},
editCoordinator(slug, data) {
if (!slug) throw "editCoordinator: received empty slug"
return axios.patch(`${EDIT_SCHOOL_COORDINATORS_API_URL}${slug}/`, data)
},
deleteCoordinators(coordinatorSlugs) {
return Promise.all(
coordinatorSlugs.map(slug =>
axios.delete(`${DELETE_SCHOOL_COORDINATORS_API_URL}${slug}`)
)
)
},
}
export default school
<file_sep>for image optimization, upload your image to either /original/small, /original/big folders, and run:
> yarn imagemin
your image will appear in "optimized" folder, in webp format.
images in "big" folder will be optimized more, and the quality would reduce.
images in "small" would keep high quality
then, simply use the images creted in "optimized" folder.
<file_sep><template>
<v-row class="pa-10">
<v-col class="mx-auto" sm="11" lg="9">
<h1 v-text="$t('groups.groupsCreation')" />
<router-view />
</v-col>
</v-row>
</template>
<file_sep><template>
<div :style="style">
<navbar user-type="coordinator"/>
<router-view/>
</div>
</template>
<script>
import { BACKGROUNDS } from "../helpers/constants/images"
import Navbar from "../components/Navbar/Navbar"
export default {
components: {
Navbar,
},
data() {
return {
style: {
background: `url(${BACKGROUNDS.managementDashboard})`,
"min-height": "100vh",
},
}
},
}
</script>
<file_sep>from rest_framework import serializers
from server.events.models import Event
from server.posts.models import Post, PostImage
from server.users.models import InstructorProfile
class PostImageSerializer(serializers.ModelSerializer):
post = serializers.SlugRelatedField(
slug_field="slug",
queryset=Post.objects.all(),
)
class Meta:
model = PostImage
fields = [
"slug",
"image_url",
"post",
]
read_only_fields = ["slug"]
class ImageOnlyPostImageSerializer(serializers.ModelSerializer):
class Meta:
model = PostImage
fields = ["image_url"]
read_only_fields = ["image_url"]
class PostSerializer(serializers.ModelSerializer):
event = serializers.SlugRelatedField(
slug_field="slug",
queryset=Event.objects.all(),
)
author = serializers.SlugRelatedField(
slug_field="slug",
read_only=True,
)
author_profile_picture = serializers.SerializerMethodField()
author_name = serializers.CharField(source="author.name", read_only=True)
images = ImageOnlyPostImageSerializer(many=True, read_only=True)
class Meta:
model = Post
fields = [
"slug",
"created",
"event",
"author",
"author_name",
"author_profile_picture",
"post_content",
"images",
]
read_only_fields = [
"slug",
"created",
"author",
"author_profile_picture",
]
def get_author_profile_picture(self, obj):
return InstructorProfile.objects.get(user=obj.author).profile_picture
<file_sep>import Api from "../../api"
function getDefaultState() {
return {
programsList: [],
totalPrograms: null,
}
}
const consumerProgram = {
namespaced: true,
state: getDefaultState(),
mutations: {
FLUSH_STATE(state) {
Object.assign(state, getDefaultState())
},
ADD_PROGRAMS_TO_LIST(state, programsList) {
state.programsList.push(...programsList)
},
UPDATE_PROGRAM_IN_LIST(state, program) {
const filteredProgram = state.programsList.filter(
p => p.slug === program.slug
)[0]
Object.assign(filteredProgram, program)
},
SET_PROGRAM_LIST(state, programsList) {
state.programsList = programsList
},
SET_PROGRAMS_TOTAL(state, total) {
state.totalPrograms = total
},
},
actions: {
flushState({ commit }) {
commit("FLUSH_STATE")
},
async getProgram(ctx, programSlug) {
// fetch and return a specific slug. does not save to store.
let res = await Api.consumerProgram.getProgram(programSlug)
return res.data
},
async getProgramMediaList(ctx, programSlug) {
// fetch and return a specific program's media. does not save to store.
let res = await Api.consumerProgram.getProgramMediaList(programSlug)
return res.data.results
},
async getProgramsList({ commit, state, rootGetters }, override = true) {
// :boolean override: whether to override the programs list or not (i.e., extend)
const params = rootGetters["pagination/apiParams"]
const mutation = override ? "SET_PROGRAM_LIST" : "ADD_PROGRAMS_TO_LIST"
let res = await Api.consumerProgram.getProgramsList(params)
commit(mutation, res.data.results)
commit("SET_PROGRAMS_TOTAL", res.data.count)
return state.programsList
},
async joinProgram({ commit, dispatch }, programSlug) {
const res = await Api.consumerProgram.joinProgram(programSlug)
const program = await dispatch("getProgram", programSlug)
commit("UPDATE_PROGRAM_IN_LIST", program)
return res.data
},
async leaveProgram({ commit, dispatch }, programSlug) {
const res = await Api.consumerProgram.leaveProgram(programSlug)
const program = await dispatch("getProgram", programSlug)
commit("UPDATE_PROGRAM_IN_LIST", program)
return res.data
},
},
}
export default consumerProgram
<file_sep><template>
<v-tabs color="grey darken-4" class="pb-10">
<v-tab
v-for="tab in tabs"
:key="tab.id"
:to="{ name: tab.componentName }"
v-text="tab.text"
/>
</v-tabs>
</template>
<script>
export default {
props: {
tabs: {
// [ { componentName: "", text: "" }, ... ]
type: Array,
required: true,
},
},
}
</script>
<file_sep><template>
<v-card
class="wrapper mt-15 mx-auto px-10 py-10"
:elevation="$vuetify.breakpoint.mobile ? 0 : 3"
v-if="userAttributes"
>
<h1 class="mb-10">{{ $t("general.myProfile") }}</h1>
<title-to-text
v-for="(attrValue, attrName) in userAttributes"
:key="attrName"
:title="$t(`general.${attrName}`)"
:text="attrValue"
/>
<editable-avatar
class="mx-auto avatar mt-16"
v-model="profilePicture"
@input="updateProfilePicture"
/>
</v-card>
</template>
<script>
import TitleToText from "../../components/TitleToText"
import EditableAvatar from "../../components/Avatar/EditableAvatar"
import { mapActions } from "vuex"
export default {
components: {
TitleToText,
EditableAvatar,
},
async mounted() {
// get user details
const [userDetails, userProfile] = await Promise.all([
this.getUserDetails(),
this.getProfile(),
])
this.slug = userDetails.slug
this.profilePicture = userProfile.profilePicture
this.userAttributes = this.filterAttributes(userDetails)
},
data() {
return {
slug: null,
userAttributes: null,
profilePicture: null,
}
},
methods: {
...mapActions("user", ["getUserDetails"]),
...mapActions("instructor", ["getProfile"]),
...mapActions("instructor", ["updateProfile"]),
filterAttributes(userAttributes) {
return { email: userAttributes["email"], name: userAttributes["name"] }
},
updateProfilePicture(profilePicture) {
this.updateProfile({ slug: this.slug, profile: { profilePicture } })
},
},
}
</script>
<style lang="scss" scoped>
.wrapper {
max-width: 600px;
}
.avatar {
width: 300px;
}
</style>
<file_sep>ORG_NUMBER_FIELD = "regNum"
ORG_EMAIL_FIELD = "emailMalkar"
ORG_DESCRIPTION_FIELD = "greenInfo"
ORG_WEBSITE_FIELD = "websiteUrl"
ORG_NAME_FIELD = "Name"
ORG_GOAL_FIELD = "orgGoal"
ORG_FOUNDED_FIELD = "orgYearFounded"
ORG_STATUS = "isStatusActiveText"
ORG_TARGET_AUDIENCE_FIELD = "audience"
ORG_EMPLOYEES_FIELD = "employees"
ORG_MEMBERS_FIELD = "members"
ORG_VOLUNTEERS_FIELD = "volunteers"
ORG_LOCATION_LON = "lng"
ORG_LOCATION_LAT = "lat"
ORG_CITY_FIELD = "city"
ORG_STREET_FIELD = "addressStreet"
ORG_HOUSE_FIELD = "addressHouseNum"
ORG_ZIP_CODE_FIELD = "addressHouseNum"
ORG_CITIES_FIELD = "cities"
ORG_DISTRICTS_FIELD = "machoz" # malkarDistrict
ORG_UNION_TYPE = ""
FIELDS = {
"organization_number": ORG_NUMBER_FIELD,
"email": ORG_EMAIL_FIELD,
"description": ORG_DESCRIPTION_FIELD,
"website_url": ORG_WEBSITE_FIELD,
"name": ORG_NAME_FIELD,
"goal": ORG_GOAL_FIELD,
"year_founded": ORG_FOUNDED_FIELD,
"status": ORG_STATUS,
"target_audience": ORG_TARGET_AUDIENCE_FIELD,
"number_of_employees": ORG_EMPLOYEES_FIELD,
"number_of_members": ORG_MEMBERS_FIELD,
"number_of_volunteers": ORG_VOLUNTEERS_FIELD,
"location_lon": ORG_LOCATION_LON,
"location_lat": ORG_LOCATION_LAT,
"address_city": ORG_CITY_FIELD,
"address_street": ORG_STREET_FIELD,
"address_house_num": ORG_HOUSE_FIELD,
"address_zipcode": ORG_ZIP_CODE_FIELD,
"cities": ORG_CITIES_FIELD,
"districts": ORG_DISTRICTS_FIELD,
"union_type": ORG_UNION_TYPE,
}
RESULTS_PER_PAGE = 50
<file_sep>import NProgress from "nprogress"
NProgress.configure({ showSpinner: false })
const loading = {
namespaced: true,
state: {
waitingApiCalls: 0,
},
mutations: {
INCREMENT_API_CALLS(state) {
state.waitingApiCalls += 1
},
DECREMENT_API_CALLS(state) {
state.waitingApiCalls -= 1
},
},
actions: {
startLoading({ commit, state }) {
if (state.waitingApiCalls === 0) {
NProgress.start()
}
commit("INCREMENT_API_CALLS")
},
doneLoading({ commit, state }) {
commit("DECREMENT_API_CALLS")
if (state.waitingApiCalls === 0) {
NProgress.done()
}
},
},
}
export default loading
<file_sep><template>
<div class="w-100">
<v-row class="pt-10 ml-0">
<v-col cols="3" class="d-none right-pane white-bg">
<pagination-checkbox-group
v-for="filter in CONSUMER_LIST_CHECKBOX_FILTERS"
:key="filter.id"
:name="filter.name"
:title="filter.readableName"
:items="filter.options"
class="checkbox-group"
/>
</v-col>
<v-col cols="12" :class="{ 'px-10': !$vuetify.breakpoint.mobile }">
<h1 v-text="$t('myActivity.studentsDisplay')" class="pb-6" />
<pagination-search-bar class="search-bar mx-auto pt-16" />
<div class="text-center pt-10 overline">
{{ totalStudents }} {{ $t("myActivity.studentsFound") }}
</div>
<v-row
dense
justify="space-between"
class="cards-wrapper mx-auto py-10"
>
<v-col
cols="12"
sm="6"
lg="4"
class="py-10"
v-for="consumer in studentList"
:key="consumer.id"
>
<info-card
hide-star
hide-button
img-height="0"
:img-url="null"
:title="consumer.name"
:subtitle="$t(`gender.${consumer.profile.gender.toLowerCase()}`)"
:button-text="$t('myActivity.toThePersonalPage')"
@click="
$router.push({
name: 'ConsumerDetail',
params: { slug: consumer.slug },
})
"
>
<avatar
class="mx-auto d-block"
style="width: 200px"
:avatar-options="consumer.profile.profilePicture"
/>
</info-card>
</v-col>
</v-row>
</v-col>
</v-row>
<end-of-page-detector @end-of-page="onEndOfPage" />
</div>
</template>
<script>
import { mapActions, mapState } from "vuex"
import store from "../../vuex/store"
import InfoCard from "../../components/InfoCard"
import PaginationCheckboxGroup from "../../components/PaginationCheckboxGroup"
import PaginationSearchBar from "../../components/PaginationSearchBar"
import EndOfPageDetector from "../../components/EndOfPageDetector"
import { CONSUMER_LIST_CHECKBOX_FILTERS } from "./constants"
import Avatar from "../../components/Avatar/Avatar"
export default {
components: {
InfoCard,
PaginationCheckboxGroup,
PaginationSearchBar,
EndOfPageDetector,
Avatar,
},
async beforeRouteEnter(to, from, next) {
await store.dispatch("pagination/updatePagination", { itemsPerPage: 6 })
await store.dispatch("school/getStudentList", true)
next()
},
computed: {
...mapState("school", ["totalStudents", "studentList"]),
},
methods: {
...mapActions("snackbar", ["showMessage"]),
...mapActions("pagination", ["incrementPage", "updatePagination"]),
...mapActions("school", ["getStudentList"]),
onEndOfPage() {
// trigger load on end of page
this.recentlyScrolled = true
this.incrementPage()
},
async getConsumers() {
if (this.recentlyScrolled) {
this.recentlyScrolled = false
if (this.totalStudents > this.studentList.length) {
// add new if there are items left to fetch. do not override.
this.getStudentList(false)
}
} else {
// fetch & ovrride programs list
this.updatePagination({ page: 1 })
this.getStudentList(true)
}
},
},
data() {
return {
CONSUMER_LIST_CHECKBOX_FILTERS,
recentlyScrolled: false,
}
},
watch: {
"$store.state.pagination": {
// re-fetch if pagination changed
deep: true,
handler() {
this.getConsumers()
},
},
},
}
</script>
<style lang="scss" scoped>
.cards-wrapper {
max-width: 1200px;
}
.right-pane {
border-left: $light-grey 1px solid;
}
.checkbox-group {
float: right;
width: 100%;
}
.checkbox-small::v-deep label {
font-size: 12px;
}
.search-bar {
max-width: 450px;
}
</style>
<file_sep>import { action } from "@storybook/addon-actions"
import StickyNote from "../components/StickyNote.vue"
export default {
title: "StickyNote",
component: StickyNote,
}
const Template = args => ({
components: { StickyNote },
methods: { action },
data: () => ({ args }),
template: `
<sticky-note>
{{ args.defaultSlot }}
</sticky-note>
`,
})
export const Primary = Template.bind({})
Primary.args = {
defaultSlot: "My name is <NAME>, what's yours",
}
<file_sep>import store from "../vuex/store.js"
import i18n from "../plugins/i18n"
import { SERVER } from "../helpers/constants/constants"
import { CAROUSEL_PLACEHOLDER } from "../helpers/constants/images"
async function isStaffRegistered() {
// check if staff completed registration
let userDetails = await store.dispatch("user/getUserDetails")
let profile = await store.dispatch(
`${userDetails.userType.toLowerCase()}/getProfile`
)
return [profile.phoneNumber, userDetails.name].every(item => !!item)
}
async function isSchoolFilled() {
// check if school details already filled by a coordinator
const schoolDetails = await store.dispatch("school/getSchoolDetails")
return schoolDetails.lastUpdatedBy
}
export async function checkRegistrationStatus(to, from, next) {
// redirect based on user type & registration status
if (!store.state.auth.isAuthenticated) {
next("/")
return
}
const userDetails = await store.dispatch("user/getUserDetails")
if (userDetails.userType === SERVER.userTypes.consumer) {
return next({ name: "StudentDashboard", params: { lang: i18n.locale } })
} else if (userDetails.userType === SERVER.userTypes.instructor) {
return next({ name: "InstructorDashboard", params: { lang: i18n.locale } })
} else if (userDetails.userType === SERVER.userTypes.vendor) {
if (await isStaffRegistered()) {
return next({ name: "VendorDashboard", params: { lang: i18n.locale } })
}
return next({ name: "VendorRegister", params: { lang: i18n.locale } })
}
// coord
const shouldEditSchool = !(await isSchoolFilled())
if (!shouldEditSchool && (await isStaffRegistered())) {
return next({ name: "MyGroups", params: { lang: i18n.locale } })
}
return next({
name: "CoordinatorRegister",
params: { lang: i18n.locale, shouldEditSchool },
})
}
export function loginOrFlushStore(to, from, next) {
// if logged in already, redirect to dashboard
// else flush state (relevant on logouts)
if (store.state.auth.isAuthenticated) {
next({ name: "Dashboard", params: { lang: i18n.locale } })
} else {
store.dispatch("flushState")
next()
}
}
export async function initPrograms(to, from, next) {
// set pagination config & fetch initial program list from server
store.dispatch("pagination/flushState")
await store.dispatch("pagination/updatePagination", { itemsPerPage: 6 })
await store.dispatch("program/getProgramsList")
next()
}
export async function initConsumerPrograms(to, from, next) {
// set pagination config & fetch initial program list from server
store.dispatch("pagination/flushState")
await store.dispatch("pagination/updatePagination", { itemsPerPage: 6 })
await store.dispatch("consumerProgram/getProgramsList")
next()
}
export function flushPagination(to, from, next) {
store.dispatch("pagination/flushState")
next()
}
export function flushToken(to, from, next) {
store.dispatch("auth/logout", false)
next()
}
export function PopulateConsumerData(to, from, next) {
store.dispatch("user/getUserDetails")
store.dispatch("consumer/getProfile")
next()
}
export function PopulateCoordinatorData(to, from, next) {
store.dispatch("school/getSchoolDetails")
next()
}
export async function fetchProgramDetails(to, from, next) {
let vuexModule = "program"
if (store.getters["user/isConsumer"]) {
vuexModule = "consumerProgram"
}
let [program, mediaList] = await Promise.all([
store.dispatch(`${vuexModule}/getProgram`, to.params.slug),
store.dispatch(`${vuexModule}/getProgramMediaList`, to.params.slug),
])
if (!mediaList.length) {
mediaList = [{ imageUrl: CAROUSEL_PLACEHOLDER, mediaType: "image" }]
}
to.params.program = program
to.params.mediaList = mediaList
next()
}
<file_sep><template>
<avataaars v-bind="avataaarsOptions" />
</template>
<script>
import Avataaars from "vuejs-avataaars"
import { defaultAvatarOptions } from "./helpers"
export default {
components: { Avataaars },
props: {
avatarOptions: {
type: Object,
required: true,
},
},
data() {
return {
defaultAvatarOptions,
}
},
computed: {
avataaarsOptions() {
if (Object.keys(this.avatarOptions).length) {
return this.avatarOptions
}
return this.defaultAvatarOptions
},
},
}
</script>
<file_sep><template>
<v-dialog v-model="value" persistent max-width="360px">
<v-card>
<v-card-title class="headline pt-13 justify-center" v-text="title" />
<validation-observer v-slot="{ invalid }" ref="observer">
<form class="form mx-auto" @submit.prevent="save">
<v-card-text>
<v-row>
<v-col class="mt-8" cols="12">
<validation-provider
v-slot="{ errors }"
name="name"
rules="required"
>
<v-text-field
:label="$t('general.name')"
v-model="formInput.name"
:error-messages="errors"
></v-text-field>
</validation-provider>
</v-col>
<v-col class="mt-8" cols="12">
<validation-provider
v-slot="{ errors }"
name="email"
rules="required|email"
>
<v-text-field
:label="$t('general.email')"
v-model="formInput.email"
:error-messages="errors"
></v-text-field>
</validation-provider>
</v-col>
</v-row>
</v-card-text>
<v-card-actions class="pb-5 mt-12">
<v-spacer></v-spacer>
<v-btn color="blue darken-1" text @click="close" type="button">
{{ $t("userActions.close") }}
</v-btn>
<v-btn color="blue darken-1" text type="submit" :disabled="invalid">
{{ $t("userActions.save") }}
</v-btn>
</v-card-actions>
</form>
</validation-observer>
</v-card>
</v-dialog>
</template>
<script>
import { mapActions } from "vuex"
import { ValidationObserver, ValidationProvider } from "vee-validate"
import debounce from "lodash/debounce"
import Api from "../../api"
export default {
components: {
ValidationObserver,
ValidationProvider,
},
props: {
value: {
// is dialog open
type: Boolean,
required: true,
},
vendor: {
type: Object,
required: false,
},
title: {
type: String,
default: function () {
return `${this.$tc("invite.invite", 1)} ${this.$t("general.vendor")}`
},
},
slug: {
type: String,
required: false,
},
},
mounted() {
if (!this.formInput) {
this.initFormInput()
}
},
data() {
return {
formInput: this.vendor,
}
},
watch: {
vendor(obj) {
// apply vendor prop values to the form, if received
this.formInput = obj
},
},
methods: {
...mapActions("organization", ["addVendor", "editVendor"]),
...mapActions("snackbar", ["showMessage"]),
initFormInput() {
this.formInput = {
name: "",
email: "",
}
},
close() {
// clear form, close and notify parent
this.$refs.observer.reset()
this.$emit("input", false)
this.initFormInput()
},
save: debounce(
async function () {
// save to store and notify parent, close dialog
try {
if (this.slug) {
await this.editVendor({
slug: this.slug,
vendor: this.formInput,
})
this.showMessage(this.$t("success.userDetailsUpdatedSuccessfully"))
} else {
await this.addVendor(this.formInput)
this.showMessage(this.$t("success.userWasInvitedSuccessfully"))
}
this.$emit("save", this.formInput)
this.close()
} catch (err) {
this.showMessage(Api.utils.parseResponseError(err))
}
},
500,
{ leading: true, trailing: false }
),
},
}
</script>
<style lang="scss" scoped>
.form {
width: 86%;
}
.v-card__subtitle,
.v-card__text,
.v-card__title {
padding: 0;
}
</style>
<file_sep>import Api from "../../api"
import Utils from "../../helpers/utils"
function getDefaultState() {
return {
details: {
slug: null,
name: null,
address: null,
addressCity: null,
addressZipcode: null,
schoolCode: null,
description: null,
contactPhone: null,
website: null,
profilePicture: null,
gradeLevels: [],
lastUpdatedBy: null
},
studentList: [],
totalStudents: 0,
coordinatorList: [],
totalCoordinators: 0,
}
}
const school = {
namespaced: true,
state: getDefaultState(),
mutations: {
FLUSH_STATE(state) {
Object.assign(state, getDefaultState())
},
ADD_STUDENTS_TO_LIST(state, studentList) {
state.studentList.push(...studentList)
},
ADD_COORDINATORS_TO_LIST(state, coordinatorList) {
state.coordinatorList.push(...coordinatorList)
},
SET_DETAILS(state, schoolDetails) {
state.details = schoolDetails
},
SET_STUDENT_LIST(state, studentList) {
state.studentList = studentList
},
SET_STUDENTS_TOTAL(state, total) {
state.totalStudents = total
},
SET_COORDINATOR_LIST(state, coordinatorList) {
state.coordinatorList = coordinatorList
},
SET_COORDINATORS_TOTAL(state, total) {
state.totalCoordinators = total
},
},
getters: {
schoolSlug(state) {
return state.details.slug
},
},
actions: {
flushState({ commit }) {
commit("FLUSH_STATE")
},
async getSchoolDetails({ commit, state }) {
if (!state.details.slug) {
let res = await Api.school.getSchoolDetails()
commit("SET_DETAILS", res.data)
}
return state.details
},
async updateSchoolDetails({ commit, state }, { slug, schoolDetails }) {
let res = await Api.school.updateSchoolDetails(slug, schoolDetails)
commit("SET_DETAILS", res.data)
return state.details
},
async getStudentList({ commit, state, rootGetters }, override = true) {
// :boolean override: whether to override the list or not (i.e., extend)
const params = rootGetters["pagination/apiParams"]
const mutation = override ? "SET_STUDENT_LIST" : "ADD_STUDENTS_TO_LIST"
let res = await Api.school.getStudentList(params)
commit(mutation, res.data.results)
commit("SET_STUDENTS_TOTAL", res.data.count)
return state.studentList
},
getStudentsExportFile({ rootGetters }) {
const params = rootGetters["pagination/apiParams"]
Api.school.getStudentsExportFile(params).then(res => {
Utils.downloadTextAsFile("students.csv", res.request.response)
return res
})
},
getCoordinatorsExportFile({ rootGetters }) {
const params = rootGetters["pagination/apiParams"]
Api.school.getCoordinatorsExportFile(params).then(res => {
Utils.downloadTextAsFile("principals.csv", res.request.response)
return res
})
},
addStudent(ctx, student) {
return Api.school.addStudent(student)
},
async addStudentsBulk(ctx, csvFile) {
const res = await Api.school.addStudentsBulk(csvFile)
return res.data
},
deleteStudents(ctx, studentSlugs) {
return Api.school.deleteStudents(studentSlugs)
},
editStudent(ctx, { slug, student }) {
return Api.school.editStudent(slug, student)
},
async getCoordinatorList({ commit, state, rootGetters }, override = true) {
// :boolean override: whether to override the list or not (i.e., extend)
const params = rootGetters["pagination/apiParams"]
const mutation = override ? "SET_COORDINATOR_LIST" : "ADD_COORDINATORS_TO_LIST"
let res = await Api.school.getCoordinatorList(params)
commit(mutation, res.data.results)
commit("SET_COORDINATORS_TOTAL", res.data.count)
return state.coordinatorList
},
addCoordinator(ctx, coordinator) {
return Api.school.addCoordinator(coordinator)
},
async addCoordinatorsBulk(ctx, csvFile) {
const res = await Api.school.addCoordinatorsBulk(csvFile)
return res.data
},
deleteCoordinators(ctx, coordinatorSlugs) {
return Api.school.deleteCoordinators(coordinatorSlugs)
},
editCoordinator(ctx, { slug, coordinator }) {
return Api.school.editCoordinator(slug, coordinator)
},
},
}
export default school
<file_sep><template>
<v-chip-group
multiple
column
color="primary"
text-color="white"
v-model="selectedChipsNumeric"
class="mx-auto"
@change="chipFilterChange"
>
<v-chip
filter
v-for="chip in chips"
:key="chip"
active-class="primary--text"
class="filter-chip"
>
{{ chip }}
</v-chip>
</v-chip-group>
</template>
<script>
import { mapActions } from "vuex"
import debounce from "lodash/debounce"
export default {
props: {
chips: {
// e.g., [ "opt1", "opt2", ... ]
type: Array,
required: true,
},
},
methods: {
...mapActions("pagination", ["addFieldFilter", "removeFieldFilter"]),
chipFilterChange: debounce(async function() {
if (this.selectedChipsNumeric.length) {
const chipsSelected = this.selectedChipsNumeric.map(chip => this.chips[chip])
await this.addFieldFilter({ fieldName: "chips", value: chipsSelected })
} else {
await this.removeFieldFilter("chips")
}
}, 500),
},
data() {
return {
selectedChipsNumeric: [],
}
},
}
</script>
<style scoped>
.filter-chip {
margin: 5px;
}
</style>
<file_sep>import pytest
from rest_framework.test import APIClient
from server.schools.models import School, SchoolMember
from server.users.models import Coordinator
pytestmark = pytest.mark.django_db
class TestSchoolViewSet:
def test_school_endpoint(self):
"""
test school list & school details (specific school) GET requests.
authorization: see users can't see unrelated schools
integrity: see the data is as it should be
"""
school_data = {
"address": "123 foo foo",
"address_city": "city",
"address_zipcode": "1111111111111",
"school_code": "1111111111111",
"description": "A SCHOOL",
"contact_phone": "1111111111111",
"website": "http://example.com",
"profile_picture": None,
"grade_levels": [1, 2, 3],
}
school1_data = {"name": "school1", **school_data}
school2_data = {"name": "school2", **school_data}
user1 = Coordinator.objects.create(
email="<EMAIL>",
password="<PASSWORD>",
)
user2 = Coordinator.objects.create(
email="<EMAIL>",
password="<PASSWORD>",
)
client = APIClient(user1)
client.force_authenticate(user1)
# query API before adding schools
list_response_no_schools = client.get("/api/schools/")
school1 = School.objects.create(**school1_data)
school2 = School.objects.create(**school2_data)
SchoolMember.objects.create(user=user1, school=school1)
SchoolMember.objects.create(user=user2, school=school2)
# query API after adding schools
list_response_single_school = client.get("/api/schools/")
# check user can see exactly the schools it should
assert not list_response_no_schools.data["results"]
assert len(list_response_single_school.data["results"]) == 1
# check the data itself from a specific school & school list data
school1_slug = list_response_single_school.data["results"][0]["slug"]
school1_data["slug"] = school1_slug
detail_response = client.get(f"/api/schools/{school1_slug}/")
assert (
school1_data
== list_response_single_school.data["results"][0]
== detail_response.data
)
<file_sep><template>
<div>
<v-row>
<v-col cols="12" md="8">
<h1 v-text="$t('myActivity.myGroups')" class="mb-5" />
<h2
v-text="
$t(
'myActivity.hereYouCanSeeAllTheGroupsOfTheRunningProgramsOfTheSchool'
)
"
class="pb-12"
/>
</v-col>
<v-col cols="12" md="4">
<v-btn
tile
large
class="d-block mx-auto"
color="success"
data-testid="create-group"
@click="$router.push({ name: 'GroupEditor' })"
>
{{ $tc("userActions.add", 1) }}
<v-icon right> mdi-plus </v-icon>
</v-btn>
</v-col>
</v-row>
<v-row class="pt-10 ml-0" justify="space-around">
<v-col
cols="12"
sm="6"
lg="4"
class="py-10"
v-for="group in groupList"
:key="group.id"
>
<info-card
:hideStar="true"
:title="group.name"
:subtitle="group.activityName"
:imgUrl="group.activityLogo"
:buttonText="$t('myActivity.forGroupDetails')"
buttonColor="primary"
@click="
$router.push({
name: 'GroupDetail',
params: { groupSlug: group.slug },
})
"
>
<title-to-text
class="mb-1"
:title="$t('myActivity.groupDescription')"
:text="trimText(group.description, 21) || $t('errors.empty')"
/>
<title-to-text
class="my-0"
:title="$t('myActivity.studentsNumberInGroup')"
:text="group.consumers.length"
/>
</info-card>
</v-col>
</v-row>
<div class="text-center pt-10 overline">
{{ totalGroups }} {{ $t("myActivity.groupsFound") }}
</div>
<end-of-page-detector @end-of-page="onEndOfPage" />
</div>
</template>
<script>
import store from "../../vuex/store"
import { mapActions, mapState } from "vuex"
import { trimText } from "../../filters"
import EndOfPageDetector from "../../components/EndOfPageDetector"
import InfoCard from "../../components/InfoCard"
import TitleToText from "../../components/TitleToText.vue"
import { SERVER } from "../../helpers/constants/constants"
export default {
components: {
EndOfPageDetector,
InfoCard,
TitleToText,
},
async beforeRouteEnter(to, from, next) {
await store.dispatch("pagination/flushState")
await store.dispatch("programGroup/getGroupList", {
groupType: SERVER.programGroupTypes.standard,
override: true,
})
next()
},
computed: {
...mapState("programGroup", ["totalGroups", "groupList"]),
...mapState("pagination", ["page"]),
},
methods: {
...mapActions("pagination", ["incrementPage"]),
...mapActions("programGroup", ["getGroupList"]),
trimText,
onEndOfPage() {
this.incrementPage()
},
fetchGroups() {
if (this.groupList.length < this.totalGroups) {
this.getGroupList({
groupType: SERVER.programGroupTypes.standard,
override: false,
})
}
},
},
watch: {
page() {
this.fetchGroups()
},
},
}
</script>
<file_sep>from django.contrib.auth import get_user_model
from rest_framework import viewsets
from server.events.models import ConsumerEventFeedback, Event
from server.utils.permission_classes import (
AllowConsumer,
AllowConsumerReadOnly,
AllowCoordinator,
AllowInstructor,
)
from .serializers import (
ConsumerEventFeedbackSerializer,
ConsumerEventSerializer,
EventSerializer,
)
class EventViewSet(viewsets.ModelViewSet):
permission_classes = [AllowCoordinator | AllowInstructor]
serializer_class = EventSerializer
lookup_field = "slug"
filterset_fields = {"start_time": ["gte", "lte"], "has_summary": ["exact"]}
def get_queryset(self):
user = self.request.user
if user.user_type == get_user_model().Types.INSTRUCTOR:
return Event.objects.filter(school_group__instructor=user).order_by(
"-start_time"
)
return Event.objects.filter(
school_group__activity_order__in=user.school_member.school.school_activity_orders.all()
).order_by("-start_time")
class ConsumerEventViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = [AllowConsumerReadOnly]
serializer_class = ConsumerEventSerializer
lookup_field = "slug"
filterset_fields = {
"start_time": ["gte", "lte"],
}
def get_queryset(self):
return Event.objects.filter(school_group__consumers=self.request.user)
class ConsumerEventFeedbackViewset(viewsets.ModelViewSet):
permission_classes = [AllowConsumer]
serializer_class = ConsumerEventFeedbackSerializer
lookup_field = "slug"
def get_queryset(self):
return ConsumerEventFeedback.objects.filter(consumer=self.request.user)
def perform_create(self, serializer):
serializer.save(consumer=self.request.user)
def perform_update(self, serializer):
serializer.save(consumer=self.request.user)
<file_sep><template>
<div>
<h1 v-text="$t('events.eventsBoard')" class="mb-5" />
<h2
v-text="$t('myActivity.hereYouCanSeeAllThePlannedEvents')"
class="pb-12"
/>
<actions-calendar
v-model="value"
first-interval="5"
interval-count="19"
:displayType.sync="chosenDisplayType"
:events="formattedEvents"
@click:event="showEvent"
@moved="fetchEvents"
/>
<detail-modal
v-if="clickedEvent"
v-model="isModalOpen"
:title="clickedEvent.title || ''"
:topSubtitle="$t('myActivity.eventDetails')"
:bottomSubtitle="clickedEvent.bottomSubtitle || ''"
:buttonText="$t('userActions.close')"
>
<div class="modalBody">
{{ clickedEvent.body }}
</div>
</detail-modal>
</div>
</template>
<script>
import store from "../../vuex/store"
import { mapState, mapActions } from "vuex"
import moment from "moment"
import ActionsCalendar from "../../components/ActionsCalendar"
import DetailModal from "../../components/DetailModal"
import Utils from "../../helpers/utils"
export default {
components: {
DetailModal,
ActionsCalendar,
},
async beforeRouteEnter(to, from, next) {
await store.dispatch("consumerEvent/getEventList", {
benchmarkDate: moment(),
override: true,
})
next()
},
methods: {
...mapActions("consumerEvent", ["getEventList"]),
showEvent({ event }) {
this.clickedEvent = event
this.isModalOpen = true
},
fetchEvents(benchmarkDay) {
// :Object benchmarkDay: the date object to fetch "around" (e.g., )
const benchmarkDate = moment(benchmarkDay.date)
this.getEventList({ benchmarkDate, override: true })
},
},
data() {
return {
value: "",
chosenDisplayType: this.$vuetify.breakpoint.mobile ? "4day" : "week",
clickedEvent: null,
isModalOpen: false,
}
},
computed: {
...mapState("consumerEvent", ["eventList"]),
formattedEvents() {
return this.eventList.map(e => {
const start = moment(e.startTime)
const end = moment(e.endTime)
const startStr = start.format("DD/MM/YYYY HH:mm")
const endStr = end.format("DD/MM/YYYY HH:mm")
return {
start: start.toDate(),
end: end.toDate(),
name: e.activityName || this.$t("errors.nameUnavailable"),
color: Utils.stringToPsuedoRandomColor(e.activityName || ""),
timed: true,
// attaching also Modal related data for onClick usage:
title: e.activityName,
bottomSubtitle: e.schoolGroupName,
body: `
1. ${this.$t("myActivity.location")}: ${
e.locationsName || this.$t("errors.empty")
}
2. ${this.$t("time.startTime")}: ${startStr}
3. ${this.$t("time.endTime")}: ${endStr}
`,
}
})
},
},
}
</script>
<style lang="scss" scoped>
.modalBody {
white-space: pre-line;
line-height: 2.3;
padding-bottom: 5px;
margin-top: -20px;
}
</style>
<file_sep>const post_to_get_urls = ["login"]
module.exports = function (req, res, next) {
// convert requests to GET, if in whitelist
for (let url of post_to_get_urls) {
if (req.originalUrl.includes(url) && ["POST", "PUT"].indexOf(req.method) !== -1) {
req.method = "GET"
req.query = req.body
}
}
// Continue to JSON Server router
next()
}
<file_sep>import csv
import io
import os
from django.contrib.auth import get_user_model
from rest_framework import filters, status
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from server.utils.permission_classes import (
AllowConsumer,
AllowCoordinator,
AllowInstructor,
AllowVendor,
)
from ..models import (
Consumer,
ConsumerProfile,
Coordinator,
CoordinatorProfile,
Instructor,
InstructorProfile,
Vendor,
VendorProfile,
)
from .renderers import UsersCSVRenderer
from .serializers import (
ConsumerProfileSerializer,
CoordinatorProfileSerializer,
InstructorProfileSerializer,
ManageConsumersSerializer,
ManageCoordinatorsSerializer,
ManageInstructorsSerializer,
ManageVendorsSerializer,
UserSerializer,
VendorProfileSerializer,
)
User = get_user_model()
class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
lookup_field = "username"
def get_queryset(self, *args, **kwargs):
return self.queryset.filter(id=self.request.user.id)
@action(detail=False, methods=["GET"])
def me(self, request):
serializer = UserSerializer(request.user, context={"request": request})
return Response(status=status.HTTP_200_OK, data=serializer.data)
class ConsumerProfileViewSet(ModelViewSet):
permission_classes = [AllowConsumer]
serializer_class = ConsumerProfileSerializer
queryset = ConsumerProfile.objects.all()
lookup_field = "user__slug"
@action(detail=False, methods=["GET"])
def me(self, request):
serializer = ConsumerProfileSerializer(
request.user.consumerprofile, context={"request": request}
)
return Response(status=status.HTTP_200_OK, data=serializer.data)
class CoordinatorProfileViewSet(ModelViewSet):
permission_classes = [AllowCoordinator]
serializer_class = CoordinatorProfileSerializer
queryset = CoordinatorProfile.objects.all()
lookup_field = "user__slug"
@action(detail=False, methods=["GET"])
def me(self, request):
serializer = CoordinatorProfileSerializer(
request.user.coordinatorprofile, context={"request": request}
)
return Response(status=status.HTTP_200_OK, data=serializer.data)
class InstructorProfileViewSet(ModelViewSet):
permission_classes = [AllowInstructor]
serializer_class = InstructorProfileSerializer
queryset = InstructorProfile.objects.all()
lookup_field = "user__slug"
@action(detail=False, methods=["GET"])
def me(self, request):
serializer = InstructorProfileSerializer(
request.user.instructorprofile, context={"request": request}
)
return Response(status=status.HTTP_200_OK, data=serializer.data)
class VendorProfileViewSet(ModelViewSet):
permission_classes = [AllowVendor]
serializer_class = VendorProfileSerializer
queryset = VendorProfile.objects.all()
lookup_field = "user__slug"
@action(detail=False, methods=["GET"])
def me(self, request):
serializer = VendorProfileSerializer(
request.user.vendorprofile, context={"request": request}
)
return Response(status=status.HTTP_200_OK, data=serializer.data)
class ManageConsumersViewSet(ModelViewSet):
permission_classes = [AllowCoordinator]
serializer_class = ManageConsumersSerializer
lookup_field = "slug"
search_fields = ["email", "name"]
filter_backends = (filters.SearchFilter, filters.OrderingFilter)
def get_queryset(self):
return Consumer.objects.filter(
school_member__school=self.request.user.school_member.school
)
@action(detail=False, methods=["POST"])
def bulk_create(self, request):
users_to_invite = []
if not request.FILES:
return Response("File must be included", status=status.HTTP_400_BAD_REQUEST)
request_file = request.FILES["file"]
_, file_extension = os.path.splitext(request_file.name)
if file_extension != ".csv":
return Response("Unsupported file type", status=status.HTTP_400_BAD_REQUEST)
emails = set()
for row in csv.DictReader(
io.StringIO(request_file.read().decode(encoding="utf-8-sig"))
):
name = row.get("name").strip() if row.get("name") else ""
email = row.get("email").strip() if row.get("email") else ""
gender = (
row.get("gender").strip()
if row.get("gender")
else ConsumerProfile.Gender.UNKNOWN
)
if email not in emails:
emails.add(email)
users_to_invite.append(
{
"name": name,
"email": email,
"profile": {"gender": gender},
}
)
already_existing_emails = User.objects.filter(
email__in=[user["email"] for user in users_to_invite]
).values_list("email", flat=True)
users_to_invite = [
user
for user in users_to_invite
if user["email"] not in already_existing_emails
]
serializer = ManageConsumersSerializer(
data=users_to_invite,
context={"request": request},
many=True,
)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class ManageCoordinatorsViewSet(ModelViewSet):
permission_classes = [AllowCoordinator]
serializer_class = ManageCoordinatorsSerializer
lookup_field = "slug"
search_fields = ["email", "name"]
filter_backends = (filters.SearchFilter, filters.OrderingFilter)
def get_queryset(self):
return Coordinator.objects.filter(
school_member__school=self.request.user.school_member.school
)
@action(detail=False, methods=["POST"])
def bulk_create(self, request):
users_to_invite = []
if not request.FILES:
return Response("File must be included", status=status.HTTP_400_BAD_REQUEST)
request_file = request.FILES["file"]
_, file_extension = os.path.splitext(request_file.name)
if file_extension != ".csv":
return Response("Unsupported file type", status=status.HTTP_400_BAD_REQUEST)
emails = set()
for row in csv.DictReader(
io.StringIO(request_file.read().decode(encoding="utf-8-sig"))
):
name = row.get("name").strip() if row.get("name") else ""
email = row.get("email").strip() if row.get("email") else ""
if email not in emails:
# add user if email not seem already in the file
users_to_invite.append(
{
"name": name,
"email": email,
}
)
emails.add(email)
# remove already existing emails
already_existing_emails = User.objects.filter(
email__in=[user["email"] for user in users_to_invite]
).values_list("email", flat=True)
users_to_invite = [
user
for user in users_to_invite
if user["email"] not in already_existing_emails
]
serializer = ManageCoordinatorsSerializer(
data=users_to_invite,
context={"request": request},
many=True,
)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class ExportConsumerListViewSet(ModelViewSet):
permission_classes = [AllowCoordinator]
serializer_class = ManageConsumersSerializer
lookup_field = "slug"
renderer_classes = (UsersCSVRenderer,)
search_fields = ["email", "name"]
filter_backends = (filters.SearchFilter, filters.OrderingFilter)
def get_queryset(self):
return Consumer.objects.filter(
school_member__school=self.request.user.school_member.school
)
class ExportCoordinatorListViewSet(ModelViewSet):
permission_classes = [AllowCoordinator]
serializer_class = ManageCoordinatorsSerializer
lookup_field = "slug"
renderer_classes = (UsersCSVRenderer,)
search_fields = ["email", "name"]
filter_backends = (filters.SearchFilter, filters.OrderingFilter)
def get_queryset(self):
return Coordinator.objects.filter(
school_member__school=self.request.user.school_member.school
)
class ManageVendorsViewSet(ModelViewSet):
permission_classes = [AllowVendor]
serializer_class = ManageVendorsSerializer
lookup_field = "slug"
search_fields = ["email", "name"]
filter_backends = (filters.SearchFilter, filters.OrderingFilter)
def get_queryset(self):
return Vendor.objects.filter(
organization_member__organization=self.request.user.organization_member.organization
)
class ManageInstructorsViewSet(ModelViewSet):
permission_classes = [AllowVendor]
serializer_class = ManageInstructorsSerializer
lookup_field = "slug"
search_fields = ["email", "name"]
filter_backends = (filters.SearchFilter, filters.OrderingFilter)
def get_queryset(self):
return Instructor.objects.filter(
organization_member__organization=self.request.user.organization_member.organization
)
<file_sep>import axios from "axios"
import {
GET_INSTRUCTOR_PROFILE_API_URL,
UPDATE_INSTRUCTOR_PROFILE_API_URL,
} from "../helpers/constants/constants"
const instructor = {
getProfile() {
return axios.get(GET_INSTRUCTOR_PROFILE_API_URL)
},
updateProfile(slug, data) {
if (!slug) throw "updateProfile: received empty slug"
return axios.patch(`${UPDATE_INSTRUCTOR_PROFILE_API_URL}${slug}/`, data)
},
}
export default instructor
<file_sep>// based on VueTribute (https://github.com/syropian/vue-tribute)
import Tribute from "tributejs"
// disable eslint for file
/* eslint-disable */
const VTribute = {
name: "v-tribute",
props: {
options: {
type: Object,
required: true
}
},
watch: {
options: {
immediate: false,
deep: true,
handler() {
if (this.tribute) {
this.$nextTick(() => {
const $el = this.$el.querySelectorAll("textarea")[0];
this.tribute.detach($el);
this.$nextTick(() => {
const $el = this.$el.querySelectorAll("textarea")[0];
this.tribute = new Tribute(this.options);
this.tribute.attach($el);
$el.tributeInstance = this.tribute;
});
});
}
}
}
},
mounted() {
if (typeof Tribute === "undefined") {
throw new Error("[v-tribute] cannot locate tributejs!");
}
this.$nextTick(() => {
const $el = this.$el.querySelectorAll("textarea")[0];
this.tribute = new Tribute(this.options);
this.tribute.attach($el);
$el.tributeInstance = this.tribute;
$el.addEventListener("tribute-replaced", e => {
e.target.dispatchEvent(new Event("input", { bubbles: true }));
});
})
},
beforeDestroy() {
const $el = this.$el.querySelectorAll("textarea")[0];
if (this.tribute) {
this.tribute.detach($el);
}
},
render(h) {
return h(
"div",
{
staticClass: "v-tribute"
},
this.$slots.default
);
}
};
if (typeof window !== "undefined" && window.Vue) {
window.Vue.component(VTribute.name, VTribute);
}
export default VTribute;
<file_sep># Generated by Django 3.1.11 on 2021-06-14 08:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('organizations', '0008_auto_20210613_1554'),
('organizations', '0005_auto_20210610_1825'),
]
operations = [
]
<file_sep><template>
<v-dialog
max-width="290"
:value="isOpen"
@input="handleDisapprove"
>
<v-card>
<v-card-title class="text-h5" v-text="$t('general.message')" />
<v-card-text>
<slot>{{ this.$t("confirm.AreYouSureYouWantToDelete?") }}</slot>
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn
text
color="teal darken-4"
data-testid="modal-approve-yes"
v-text="$t('general.yes')"
@click="handleApprove"
/>
<v-btn
text
color="teal darken-4"
v-text="$t('general.no')"
@click="handleDisapprove"
/>
</v-card-actions>
</v-card>
</v-dialog>
</template>
<script>
export default {
model: { prop: "isOpen" },
props: {
isOpen: {
type: Boolean,
required: true,
},
},
methods: {
handleDisapprove(e) {
this.$emit("disapprove", e)
this.$emit("input", false)
},
handleApprove(e) {
this.$emit("approve", e)
this.$emit("input", false)
},
},
}
</script>
<file_sep>import Vuetify from "vuetify"
import Vuex from "vuex"
import { mount, createLocalVue } from "@vue/test-utils"
import Login from "@/views/Login.vue"
import flushPromises from "flush-promises"
const localVue = createLocalVue()
localVue.use(Vuex)
describe("Login.vue", () => {
const email = "<EMAIL>"
const password = "<PASSWORD>"
const vuetify = new Vuetify()
const actions = {
login: jest.fn(),
}
const store = new Vuex.Store({
modules: {
auth: {
namespaced: true,
actions,
},
},
})
it("should dispatch login action on submit", async () => {
const wrapper = mount(Login, {
vuetify,
localVue,
store,
mocks: {
$t: key => key,
},
})
let email = "<EMAIL>"
let password = "<PASSWORD>"
await wrapper.find('[data-testid="email-input"]').setValue(email)
await wrapper.find('[data-testid="password-input"]').setValue(password)
await wrapper.find("form").trigger("submit")
await flushPromises()
expect(actions.login).toHaveBeenCalledWith(expect.anything(), {
email,
password,
})
})
it("should display an error on invalid credentials response", async () => {
const wrapper = mount(Login, {
vuetify,
store,
localVue,
mocks: {
$t: key => key,
},
})
const loginFailureResponse = {
response: {
data: {
nonFieldErrors: ["Unable to log in with provided credentials."],
},
},
}
actions.login.mockRejectedValueOnce(loginFailureResponse)
await wrapper.find('[data-testid="email-input"]').setValue(email)
await wrapper.find('[data-testid="password-input"]').setValue(password)
await wrapper.find("form").trigger("submit")
await flushPromises()
expect(wrapper.find('[data-testid="modal"]').isVisible()).toBe(true)
expect(wrapper.vm.popupMsg).toBe("errors.invalidCreds")
})
it("should display a generic error on unknown response", async () => {
const wrapper = mount(Login, {
vuetify,
store,
localVue,
mocks: {
$t: key => key,
},
})
expect(wrapper.find('[data-testid="modal"]').isVisible()).toBe(false)
const loginFailureResponse = {
response: { data: { oops: "unexpected response from server" } },
}
actions.login.mockRejectedValueOnce(loginFailureResponse)
await wrapper.find('[data-testid="email-input"]').setValue(email)
await wrapper.find('[data-testid="password-input"]').setValue(password)
await wrapper.find("form").trigger("submit")
await flushPromises()
expect(wrapper.find('[data-testid="modal"]').isVisible()).toBe(true)
expect(wrapper.vm.popupMsg).toBe("errors.genericError")
})
})
<file_sep>import "@mdi/font/css/materialdesignicons.css"
import "../src/plugins/vuetify"
import "vuetify/dist/vuetify.min.css"
<file_sep>import Api from "../../api"
function getDefaultState() {
return {
instructorList: [],
totalInstructors: 0,
vendorList: [],
totalVendors: 0,
}
}
const organization = {
namespaced: true,
state: getDefaultState(),
mutations: {
FLUSH_STATE(state) {
Object.assign(state, getDefaultState())
},
ADD_INSTRUCTORS_TO_LIST(state, instructorList) {
state.instructorList.push(...instructorList)
},
ADD_VENDORS_TO_LIST(state, vendorList) {
state.vendorList.push(...vendorList)
},
SET_DETAILS(state, organizationDetails) {
state.details = organizationDetails
},
SET_INSTRUCTOR_LIST(state, instructorList) {
state.instructorList = instructorList
},
SET_INSTRUCTORS_TOTAL(state, total) {
state.totalInstructors = total
},
SET_VENDOR_LIST(state, vendorList) {
state.vendorList = vendorList
},
SET_VENDORS_TOTAL(state, total) {
state.totalVendors = total
},
},
getters: {
organizationSlug(state) {
return state.details.slug
},
},
actions: {
flushState({ commit }) {
commit("FLUSH_STATE")
},
async getOrganizationDetails({ commit, state }) {
if (!state.details.slug) {
let res = await Api.organization.getOrganizationDetails()
commit("SET_DETAILS", res.data)
}
return state.details
},
async getInstructorList({ commit, state, rootGetters }, override = true) {
// :boolean override: whether to override the list or not (i.e., extend)
const params = rootGetters["pagination/apiParams"]
const mutation = override
? "SET_INSTRUCTOR_LIST"
: "ADD_INSTRUCTORS_TO_LIST"
let res = await Api.organization.getInstructorList(params)
commit(mutation, res.data.results)
commit("SET_INSTRUCTORS_TOTAL", res.data.count)
return state.instructorList
},
addInstructor(ctx, instructor) {
return Api.organization.addInstructor(instructor)
},
addInstructors(ctx, csvFile) {
return Api.organization.addInstructors(csvFile)
},
deleteInstructors(ctx, instructorSlugs) {
return Api.organization.deleteInstructors(instructorSlugs)
},
editInstructor(ctx, { slug, instructor }) {
return Api.organization.editInstructor(slug, instructor)
},
async getVendorList({ commit, state, rootGetters }, override = true) {
// :boolean override: whether to override the list or not (i.e., extend)
const params = rootGetters["pagination/apiParams"]
const mutation = override ? "SET_VENDOR_LIST" : "ADD_VENDORS_TO_LIST"
let res = await Api.organization.getVendorList(params)
commit(mutation, res.data.results)
commit("SET_VENDORS_TOTAL", res.data.count)
return state.vendorList
},
addVendor(ctx, vendor) {
return Api.organization.addVendor(vendor)
},
deleteVendors(ctx, vendorSlugs) {
return Api.organization.deleteVendors(vendorSlugs)
},
editVendor(ctx, { slug, vendor }) {
return Api.organization.editVendor(slug, vendor)
},
},
}
export default organization
<file_sep># connective
[](https://circleci.com/gh/connectiveproject/connective/tree/main)
### Welcome
Welcome to _Connective_ - The Education Marketplace Open Source Project.
We'd like to thank you for investing time in the the project.
Your contribution brings us one step closer torwards making a true change in the Education System!
### Getting Started
1. Fork: Create a project fork using [this link](https://github.com/connectiveproject/connective/fork).
2. Open a Gitpod Workspace:
* Gitpod is an amazing OSS platform for dev in the cloud (an in-browser IDE).
* To start a workspace - whilst in the fork, simply click:
[](https://gitpod.io/from-referrer)
* **That's it!** You've got a VSCode with everything already installed and running!
* More details on starting workspaces can be found [here](https://www.gitpod.io/docs/getting-started/).
3. Relax & enjoy the _Code Tour_, which will go through everything you need to know
* You may find it in the bottom-left corner (see image). If not, check the note below.

4. Grab and [issue](../../issues), contribute & create a [pull request](https://www.youtube.com/watch?v=nT8KGYVurIU).
### We're Here to Help!
Got a question? Struggling with the environment?
Don't hesitate reaching out!
* Ronnie: <EMAIL>
* Ben: <EMAIL>
### Notes
Our dev environment currently requires **a restart** right after creating a workspace.
To do that, simply go to: https://gitpod.io/workspaces/, **stop and start** the workspace.
We work diligently to fix the issue, which will be hopefully solved soon.
#### Happy Coding!
### stack overview

<file_sep>import Api from "../../api"
import Utils from "../../helpers/utils"
function getDefaultState() {
return {
eventList: [],
totalEvents: null,
}
}
const event = {
namespaced: true,
state: getDefaultState(),
mutations: {
FLUSH_STATE(state) {
Object.assign(state, getDefaultState())
},
ADD_EVENTS_TO_LIST(state, eventList) {
state.eventList.push(...eventList)
},
SET_EVENTS_LIST(state, eventList) {
state.eventList = eventList
},
SET_EVENTS_TOTAL(state, total) {
state.totalEvents = total
},
},
actions: {
flushState({ commit }) {
commit("FLUSH_STATE")
},
async getEventList({ commit, state }, { benchmarkDate, override }) {
// :momentObject benchmarkDate: date to fetch the data near to (i.e., fetch the events in months around it)
// :boolean override: whether to override the events list or not (i.e., extend)
const mutation = override ? "SET_EVENTS_LIST" : "ADD_EVENTS_TO_LIST"
const [startDate, endDate] = Utils.dateBenchmarkToRange(benchmarkDate, 90)
const startDateString = Utils.dateToApiString(startDate)
const endDateString = Utils.dateToApiString(endDate)
const params = {
start_time__gte: startDateString,
start_time__lte: endDateString,
}
let res = await Api.event.getEventList(params)
commit(mutation, res.data.results)
commit("SET_EVENTS_TOTAL", res.data.count)
return state.eventList
},
},
}
export default event
<file_sep>import Api from "../../api"
import { SERVER } from "../../helpers/constants/constants"
function getDefaultState() {
return {
programsList: [],
approvedOrdersList: [],
totalPrograms: null,
topConsumerRequestsStats: []
}
}
const program = {
namespaced: true,
state: getDefaultState(),
mutations: {
FLUSH_STATE(state) {
Object.assign(state, getDefaultState())
},
ADD_PROGRAMS_TO_LIST(state, programsList) {
state.programsList.push(...programsList)
},
UPDATE_PROGRAM_ORDER_IN_LIST(
state,
{ programSlug, isOrdered, orderStatus }
) {
const filteredProgram = state.programsList.filter(
p => p.slug === programSlug
)[0]
filteredProgram.isOrdered = isOrdered
filteredProgram.orderStatus = orderStatus
},
SET_PROGRAM_LIST(state, programsList) {
state.programsList = programsList
},
SET_APPROVED_ORDERS_LIST(state, ordersList) {
state.approvedOrdersList = ordersList
},
SET_PROGRAMS_TOTAL(state, total) {
state.totalPrograms = total
},
SET_TOP_CONSUMER_REQUESTS_STATS(state, stats) {
state.topConsumerRequestsStats = stats
},
},
actions: {
flushState({ commit }) {
commit("FLUSH_STATE")
},
async getProgram(ctx, slug) {
// fetch and return a specific slug. does not save to store.
let res = await Api.program.getProgram(slug)
return res.data
},
async getProgramMediaList(ctx, slug) {
// fetch and return a specific program's media. does not save to store.
let res = await Api.program.getProgramMediaList(slug)
return res.data.results
},
async getProgramsList({ commit, state, rootGetters }, override = true) {
// :boolean override: whether to override the programs list or not (i.e., extend)
const params = rootGetters["pagination/apiParams"]
const mutation = override ? "SET_PROGRAM_LIST" : "ADD_PROGRAMS_TO_LIST"
let res = await Api.program.getProgramsList(params)
commit(mutation, res.data.results)
commit("SET_PROGRAMS_TOTAL", res.data.count)
return state.programsList
},
async getApprovedOrdersList({ commit, state }) {
let res = await Api.program.getOrdersList({
status: SERVER.programOrderStatus.approved,
})
commit("SET_APPROVED_ORDERS_LIST", res.data.results)
return state.approvedOrdersList
},
async createProgramOrder({ commit }, { schoolSlug, programSlug }) {
// order program for a school
const res = await Api.program.createProgramOrder(schoolSlug, programSlug)
commit("UPDATE_PROGRAM_ORDER_IN_LIST", {
programSlug,
isOrdered: true,
orderStatus: res.data.status,
})
return res.data
},
async reCreateProgramOrder({ commit }, { schoolSlug, programSlug }) {
// order program after cancellation (order update instead of create)
const res = await Api.program.reCreateProgramOrder(
schoolSlug,
programSlug
)
commit("UPDATE_PROGRAM_ORDER_IN_LIST", {
programSlug,
isOrdered: true,
orderStatus: res.data.status,
})
return res.data
},
async cancelProgramOrder({ commit }, { schoolSlug, programSlug }) {
// remove an order for a program in the school
const res = await Api.program.cancelProgramOrder(schoolSlug, programSlug)
commit("UPDATE_PROGRAM_ORDER_IN_LIST", {
programSlug,
isOrdered: false,
orderStatus: res.data.status,
})
return res.data
},
async getTopConsumerRequestsStats({ commit, state }) {
if (state.topConsumerRequestsStats.length) {
return state.topConsumerRequestsStats
}
const res = await Api.program.getTopConsumerRequestsStats()
commit("SET_TOP_CONSUMER_REQUESTS_STATS", res.data)
return res.data
}
},
}
export default program
<file_sep>import axios from "axios"
import {
GET_VENDOR_PROGRAM_LIST_API_URL,
GET_PROGRAM_MEDIA_LIST_API_URL,
CREATE_PROGRAM_MEDIA_API_URL,
DELETE_PROGRAM_MEDIA_API_URL,
CREATE_VENDOR_PROGRAM_API_URL,
UPDATE_VENDOR_PROGRAM_API_URL,
DELETE_VENDOR_PROGRAM_API_URL,
} from "../helpers/constants/constants"
const vendorProgram = {
getProgram(slug) {
return axios.get(`${GET_VENDOR_PROGRAM_LIST_API_URL}${slug}/`)
},
getProgramMediaList(programSlug) {
if (!programSlug)
throw "getProgramMediaList: received empty slug"
return axios.get(GET_PROGRAM_MEDIA_LIST_API_URL, {
params: {
activity__slug: programSlug,
},
})
},
deleteProgramMedia(mediaSlug) {
if (!mediaSlug)
throw "deleteProgramMedia: received empty slug"
return axios.delete(`${DELETE_PROGRAM_MEDIA_API_URL}${mediaSlug}/`)
},
createProgramMedia(data) {
return axios.post(CREATE_PROGRAM_MEDIA_API_URL, data)
},
getProgramList(params = null) {
// :Object params: query params
if (params) {
return axios.get(GET_VENDOR_PROGRAM_LIST_API_URL, { params })
}
return axios.get(GET_VENDOR_PROGRAM_LIST_API_URL)
},
createProgram(data) {
return axios.post(CREATE_VENDOR_PROGRAM_API_URL, data)
},
updateProgram(programSlug, data) {
if (!programSlug) throw "updateProgram: received empty slug"
return axios.patch(`${UPDATE_VENDOR_PROGRAM_API_URL}${programSlug}/`, data)
},
deleteProgram(programSlug) {
if (!programSlug) throw "deleteProgram: received empty slug"
return axios.delete(`${DELETE_VENDOR_PROGRAM_API_URL}${programSlug}/`)
},
}
export default vendorProgram
<file_sep>from django.contrib.auth import get_user_model
from rest_framework import viewsets
from server.posts.api.serializers import PostImageSerializer, PostSerializer
from server.posts.models import Post, PostImage
from server.utils.permission_classes import (
AllowConsumerReadOnly,
AllowCoordinatorReadOnly,
AllowInstructor,
AllowSupervisorReadOnly,
AllowVendorReadOnly,
)
class BulkCreateMixin:
"""
Allows bulk creation of a resource
"""
def get_serializer(self, *args, **kwargs):
if isinstance(kwargs.get("data", {}), list):
kwargs["many"] = True
return super().get_serializer(*args, **kwargs)
class PostImageViewSet(BulkCreateMixin, viewsets.ModelViewSet):
lookup_field = "slug"
queryset = PostImage.objects.all()
serializer_class = PostImageSerializer
permission_classes = [
AllowInstructor
| AllowConsumerReadOnly
| AllowCoordinatorReadOnly
| AllowSupervisorReadOnly
| AllowVendorReadOnly
]
# TODO: add filter by queryset
class PostViewSet(viewsets.ModelViewSet):
lookup_field = "slug"
serializer_class = PostSerializer
permission_classes = [
AllowInstructor
| AllowConsumerReadOnly
| AllowCoordinatorReadOnly
| AllowSupervisorReadOnly
| AllowVendorReadOnly
]
def get_queryset(self):
user = self.request.user
if user.user_type == get_user_model().Types.CONSUMER:
return Post.objects.filter(event__school_group__consumers=user)
elif user.user_type == get_user_model().Types.INSTRUCTOR:
return Post.objects.filter(event__school_group__instructor=user).order_by(
"-created"
)
elif user.user_type == get_user_model().Types.COORDINATOR:
return Post.objects.filter(
event__school_group__activity_order__school__school_member__user=user,
).order_by("-created")
elif user.user_type == get_user_model().Types.SUPERVISOR:
return Post.objects.all().order_by("-created")
elif user.user_type == get_user_model().Types.VENDOR:
return Post.objects.filter(
event__school_group__activity_order__activity__originization__organization_member__user=user,
).order_by("-created")
return []
def perform_create(self, serializer):
serializer.save(
author=self.request.user,
)
def perform_update(self, serializer):
serializer.save(
author=self.request.user,
)
<file_sep>import axios from "axios"
import {
GET_VENDOR_PROFILE_API_URL,
UPDATE_VENDOR_PROFILE_API_URL,
} from "../helpers/constants/constants"
const vendor = {
getProfile() {
return axios.get(GET_VENDOR_PROFILE_API_URL)
},
updateProfile(slug, data) {
if (!slug) throw "updateProfile: received empty slug"
return axios.patch(`${UPDATE_VENDOR_PROFILE_API_URL}${slug}/`, data)
},
}
export default vendor
<file_sep><template>
<v-card
class="my-15 mx-auto px-16 py-10"
max-width="800"
:elevation="$vuetify.breakpoint.mobile ? 0 : 3"
>
<v-card-title v-text="$t('events.eventSummary')" class="px-0" />
<v-card-subtitle v-text="event.activityName" class="px-0 pt-3 pb-10" />
<title-to-text
:title="$t('groups.groupName')"
:text="event.schoolGroupName || $t('errors.unavailable')"
/>
<title-to-text
:title="$t('time.startTime')"
:text="parseDate(event.startTime) || $t('errors.unavailable')"
/>
<title-to-text
:title="$t('time.endTime')"
:text="parseDate(event.endTime) || $t('errors.unavailable')"
/>
<title-to-text
:title="$t('myActivity.location')"
:text="event.locationsName || $t('errors.empty')"
/>
<form class="mt-16 form" @submit.prevent="onSubmit">
<v-card style="background: #feece5">
<v-row style="padding: 30px">
<v-col>
<img :src="CONFIDENTIAL_WATERMARK" alt="confidential" />
</v-col>
<v-card-text
v-text="`${$t('posts.thisPostIsNotVisibleForStudents')}.`"
/>
<v-col cols="12">
<v-tribute :options="tributeOptions">
<v-textarea
outlined
:label="$t('events.summaryGeneralNotes')"
v-model="summaryGeneralNotes"
class="my-6"
>
</v-textarea>
</v-tribute>
</v-col>
<v-col cols="12" sm="12" lg="6">
<v-select
outlined
:items="consumerchoices"
:label="$t('events.attendance')"
v-model="attendedConsumers"
class="my-6"
multiple
dense
/>
</v-col>
<v-col cols="12" sm="12" lg="6">
<v-select
outlined
:items="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
v-model="summaryGeneralRating"
:label="$t('events.summaryGeneralRating')"
dense
class="my-6"
/>
</v-col>
<v-col cols="12" sm="12" lg="6">
<v-select
outlined
:items="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
v-model="summaryChildrenBehavior"
:label="$t('events.summaryChildrenBehavior')"
dense
class="my-6"
/>
</v-col>
</v-row>
</v-card>
<v-checkbox
class="mt-16"
v-model="addPost"
:label="$t('userActions.addPublicPost')"
/>
<v-card elevation="0" v-if="addPost">
<v-card-title class="px-0" v-text="$t('userActions.addPost')" />
<v-card-subtitle
class="px-0"
v-text="`${$t('posts.thisPostWillBeVisibleForEveryone')}.`"
/>
<v-row class="my-2">
<v-col cols="12">
<v-tribute :options="tributeOptions">
<v-textarea
outlined
:label="$t('events.eventFeedShareContent')"
v-model="feedContent"
required
>
</v-textarea>
</v-tribute>
</v-col>
<v-col>
<v-file-input
v-model="images"
accept="image/*"
outlined
multiple
append-icon="mdi-paperclip"
prepend-icon=""
:label="$t('userActions.addMedia')"
@change="previewImage"
>
<template v-slot:selection="{ text }">
<v-chip small label color="primary" v-text="text" />
</template>
</v-file-input>
<v-img v-for="url in imageUrls" :key="url" :src="url" />
</v-col>
</v-row>
</v-card>
<v-btn
large
type="submit"
color="primary"
class="mx-auto mt-9 mb-6 px-8"
elevation="3"
v-text="$t('userActions.save')"
/>
</form>
<modal
redirectComponentName="InstructorUnsummarizedEvents"
v-show="isModalOpen"
>
{{ modalMsg }}
</modal>
</v-card>
</template>
<script>
import { mapActions } from "vuex"
import debounce from "lodash/debounce"
import store from "../vuex/store"
import Api from "../api"
import Utils from "../helpers/utils"
import { CONFIDENTIAL_WATERMARK } from "../helpers/constants/images"
import VTribute from "../components/VTribute"
import TitleToText from "../components/TitleToText"
import Modal from "../components/Modal"
export default {
components: {
TitleToText,
Modal,
VTribute,
},
props: {
slug: {
type: String,
required: true,
},
},
async beforeRouteEnter(to, from, next) {
const event = await store.dispatch(
"instructorEvent/getEvent",
to.params.slug
)
const consumers = await store.dispatch(
"instructorProgramGroup/getConsumers",
event.schoolGroup
)
next(vm => {
vm.event = event
vm.consumerchoices = consumers.map(c => ({ text: c.name, value: c.slug }))
vm.attendedConsumers = consumers.map(c => c.slug)
vm.tributeOptions.values = consumers.map(consumer => ({
key: consumer.name,
value: consumer.name.replace(" ", "_"),
}))
})
},
data() {
return {
CONFIDENTIAL_WATERMARK,
event: {},
addPost: true,
tributeOptions: {
trigger: "@",
values: [],
positionMenu: true,
// TODO: add noMatchTemplate
// noMatchTemplate: "<li>השם לא נמצא</li>",
menuContainer: document.querySelector(".menu-container"),
},
consumerchoices: [],
attendedConsumers: [],
feedContent: "",
summaryGeneralNotes: "",
summaryGeneralRating: 10,
summaryChildrenBehavior: 10,
modalMsg: this.$t("general.detailsSuccessfullyUpdated"),
isModalOpen: false,
imageUrls: [],
images: [],
}
},
methods: {
...mapActions("snackbar", ["showMessage"]),
...mapActions("instructorEvent", [
"updateEvent",
"createFeedPost",
"createPostImages",
]),
parseDate: Utils.ApiStringToReadableDate,
onSubmit: debounce(
async function () {
try {
if (this.addPost) {
await Promise.all([this.createSummary(), this.createPost()])
} else {
await this.createSummary()
}
this.isModalOpen = true
} catch (err) {
const message = Api.utils.parseResponseError(err)
this.showMessage(message)
}
},
500,
{ leading: true, trailing: false }
),
createSummary() {
const data = {
consumers: this.attendedConsumers,
summaryGeneralNotes: this.summaryGeneralNotes,
summaryGeneralRating: this.summaryGeneralRating,
summaryChildrenBehavior: this.summaryChildrenBehavior,
hasSummary: true,
}
return this.updateEvent({ slug: this.slug, data })
},
async createPost() {
const feedPostData = {
event: this.slug,
post_content: this.feedContent,
}
const post = await this.createFeedPost(feedPostData)
// TODO: send them as one payload (BE supports it)
return Promise.all(
this.images.map(image =>
this.createPostImages(
Utils.objectToFormData({ image_url: image, post: post.slug })
)
)
)
},
previewImage() {
if (!this.images.length) {
this.imageUrls = []
}
this.images.map(
image =>
(this.imageUrls = [...this.imageUrls, URL.createObjectURL(image)])
)
},
},
}
</script>
<style lang="scss">
div.tribute-container > ul > li {
-webkit-text-size-adjust: 100%;
word-break: normal;
tab-size: 4;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
font-family: Roboto, sans-serif;
text-align: center !important;
box-sizing: inherit;
align-items: center;
cursor: default;
display: inline-flex;
line-height: 20px;
max-width: 100%;
outline: none;
overflow: hidden;
padding: 0 12px;
position: relative;
text-decoration: none;
transition-duration: 0.28s;
transition-property: box-shadow, opacity;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
vertical-align: middle;
white-space: nowrap;
margin: 8px !important;
border-radius: 16px;
font-size: 14px;
height: 32px;
background-color: #5cbbf6 !important;
border-color: #5cbbf6 !important;
color: #fff;
background: #e0e0e0;
animation: bounce-in 0.3s;
@keyframes bounce-in {
0% {
transform: scale(.8);
}
50% {
transform: scale(1.1);
}
100% {
transform: scale(1);
}
}
}
</style>
<file_sep>import logging
from django.contrib import admin
from .models import ConsumerEventFeedback, Event
logger = logging.getLogger(__name__)
@admin.register(Event)
class EventAdmin(admin.ModelAdmin):
list_display = [
"school_group",
"start_time",
"end_time",
"school",
"activity",
"has_summary",
]
search_fields = [
"school_group__activity_order__school__name",
"school_group__activity_order__activity__name",
"school_group__name",
]
list_filter = ["school_group__name"]
def school(self, obj):
try:
return obj.school_group.activity_order.school
except AttributeError:
logger.warning(f"event {obj.slug} has no school_group attribute")
def activity(self, obj):
try:
return obj.school_group.activity_order.activity
except AttributeError:
logger.warning(f"event {obj.slug} has no school_group attribute")
admin.site.register(ConsumerEventFeedback)
<file_sep><template>
<div>
<form-card
v-model="fields"
elevation="0"
class="w-75 mx-auto"
@valid="isFormValid = true"
@invalid="isFormValid = false"
/>
<v-btn
class="white--text primary mt-10 d-block mx-auto"
data-testid="submit-button"
:disabled="!isFormValid"
@click="onSubmit"
v-text="$t('userActions.save')"
/>
</div>
</template>
<script>
import { mapActions } from "vuex"
import debounce from "lodash/debounce"
import store from "../vuex/store"
import i18n from "../plugins/i18n"
import Api from "../api"
import { SERVER } from "../helpers/constants/constants"
import FormCard from "../components/FormCard"
export default {
components: { FormCard },
async beforeRouteEnter(to, from, next) {
const approvedOrders = await store.dispatch("program/getApprovedOrdersList")
const parentPrograms = approvedOrders.map(order => ({
text: order.activityName,
value: order.slug,
}))
const fields = [
{
name: "name",
rules: "required",
label: i18n.t("groups.groupName"),
},
{
name: "description",
rules: "required",
label: i18n.t("general.description"),
},
{
name: "activityOrder",
rules: "required",
label: i18n.t("groups.parentProgram"),
type: "select",
choices: parentPrograms,
},
]
next(vm => (vm.fields = fields))
},
data() {
return {
fields: [],
isFormValid: false,
}
},
methods: {
...mapActions("programGroup", ["createGroup"]),
...mapActions("snackbar", ["showMessage"]),
onSubmit: debounce(
async function () {
const data = { groupType: SERVER.programGroupTypes.standard }
for (const f of this.fields) {
data[f.name] = f.value
}
try {
const group = await this.createGroup(data)
this.showMessage(this.$t("groups.groupCreatedSuccessfully"))
this.$router.push({
name: "AssignGroupConsumers",
params: { groupSlug: group.slug },
})
} catch (err) {
const message = Api.utils.parseResponseError(err)
this.showMessage(message)
}
},
500,
{ leading: true, trailing: false }
),
},
}
</script>
<file_sep>import random
import uuid
from django.db import models
from server.users.models import User
from server.utils.model_fields import PhoneNumberField
def random_slug():
return uuid.uuid4().hex.upper()[0 : random.randint(10, 22)] # noqa
class School(models.Model):
slug = models.CharField(max_length=40, default=random_slug, unique=True)
name = models.CharField(max_length=50)
address = models.CharField(max_length=50)
address_city = models.CharField(max_length=50)
address_zipcode = models.CharField(max_length=15, blank=True)
school_code = models.CharField(max_length=15)
description = models.CharField(max_length=150, blank=True)
contact_phone = PhoneNumberField(max_length=15)
website = models.URLField(blank=True)
profile_picture = models.ImageField(null=True, blank=True)
grade_levels = models.JSONField()
last_updated_by = models.ForeignKey(
User,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="last_updated_by_me_schools",
)
def __str__(self):
return f"{self.name} | {self.address_city} | {self.slug}"
class ImportedSchool(models.Model):
slug = models.CharField(max_length=40, default=random_slug, unique=True)
name = models.CharField(max_length=50)
address = models.CharField(max_length=50)
address_city = models.CharField(max_length=50)
school_code = models.IntegerField(unique=True)
grade_levels = models.JSONField()
longtitude = models.FloatField()
latitude = models.FloatField()
region = models.CharField(max_length=50)
status = models.CharField(max_length=50)
boys = models.IntegerField()
girls = models.IntegerField()
male_teachers = models.IntegerField()
female_teachers = models.IntegerField()
migzar = models.CharField(null=True, blank=True, max_length=50)
school_type = models.CharField(null=True, blank=True, max_length=50)
school_stages = models.CharField(null=True, blank=True, max_length=50)
authority_city = models.CharField(null=True, blank=True, max_length=50)
is_bagrut = models.BooleanField()
immigrants_percent = models.FloatField(null=True, blank=True)
tech_students_percent = models.FloatField(null=True, blank=True)
tech_diploma_eligible_percent = models.FloatField(null=True, blank=True)
special_education_percent = models.FloatField(null=True, blank=True)
social_economic_status = models.IntegerField(null=True, blank=True)
decile_tipuah_hativa_benaim = models.IntegerField(null=True, blank=True)
decile_tipuah_hativa_eliona = models.IntegerField(null=True, blank=True)
decile_tipuah_yesodi = models.IntegerField(null=True, blank=True)
ivhun_percent = models.FloatField(null=True, blank=True)
boys_army_enlist_rate = models.FloatField(null=True, blank=True)
girls_army_enlist_rate = models.FloatField(null=True, blank=True)
hatmada_percent = models.FloatField(null=True, blank=True)
drop_rate = models.FloatField(null=True, blank=True)
bagrut_eligible_percent = models.FloatField(null=True, blank=True)
bagrut_excelent_eligible_percent = models.FloatField(null=True, blank=True)
bagrut_english_5u_percent = models.FloatField(null=True, blank=True)
bagrut_math_5u_percent = models.FloatField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.name} | {self.address_city} | {self.school_code}"
class SchoolMember(models.Model):
user = models.OneToOneField(
User, on_delete=models.CASCADE, related_name="school_member"
)
school = models.ForeignKey(
School,
on_delete=models.CASCADE,
related_name="school_member",
)
def __str__(self):
return f"{self.user.email} | {self.school.name}"
<file_sep><template>
<div>
<canvas class="bubble" ref="bubble" />
</div>
</template>
<script>
import Chart from "chart.js/auto"
import ChartDataLabels from "chartjs-plugin-datalabels"
export default {
props: {
label: {
type: String,
default: "",
},
color: {
type: String,
default: "#4BC0C0",
},
data: {
type: Array,
default() {
return []
},
},
options: {
type: Object,
default() {
return {}
},
},
},
mounted() {
this.createChart({
datasets: [
{
label: this.label,
data: this.data,
backgroundColor: this.color,
datalabels: {
formatter(value) {
return value.label
},
},
},
],
})
},
methods: {
createChart(chartData) {
const canvas = this.$refs.bubble
const options = {
type: "bubble",
data: chartData,
options: this.opts,
plugins: [ChartDataLabels],
}
new Chart(canvas, options)
},
},
computed: {
opts() {
return Object.assign(
{
scales: {
x: {
ticks: {
callback() {
return ""
},
},
},
y: {
ticks: {
callback() {
return ""
},
},
},
},
plugins: {
datalabels: {
align: "start",
anchor: "start",
textAlign: "center",
},
tooltip: {
callbacks: {
label(context) {
return context.raw.label
},
},
rtl: true,
},
},
},
this.options
)
},
},
}
</script>
<file_sep># Generated by Django 3.1.11 on 2021-06-08 07:47
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import server.utils.model_fields
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20210520_1400'),
]
operations = [
migrations.AlterModelOptions(
name='consumer',
options={'verbose_name_plural': '1. Consumer (Students)'},
),
migrations.AlterModelOptions(
name='coordinator',
options={'verbose_name_plural': '2. Coordinator (Principals)'},
),
migrations.AlterModelOptions(
name='vendor',
options={'verbose_name_plural': '3. Vendor (Organization Managers)'},
),
migrations.AddField(
model_name='user',
name='slug',
field=models.CharField(default=server.utils.model_fields.random_slug, max_length=40, unique=True),
),
migrations.AlterField(
model_name='user',
name='email',
field=models.EmailField(max_length=254, unique=True),
),
migrations.AlterField(
model_name='user',
name='username',
field=models.CharField(default=server.utils.model_fields.random_slug, max_length=40, unique=True),
),
migrations.CreateModel(
name='VendorProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('gender', models.CharField(choices=[('MALE', 'Male'), ('FEMALE', 'Female'), ('OTHER', 'Other'), ('UNKNOWN', 'Unknown')], default='UNKNOWN', max_length=50, verbose_name='Gender')),
('profile_picture', models.JSONField(blank=True, default=dict, null=True)),
('phone_number', models.CharField(blank=True, max_length=15, validators=[django.core.validators.RegexValidator(message='phone number must be between 9-15 digits', regex='^\\d{9,15}$')])),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='vendorprofile', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='CoordinatorProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('gender', models.CharField(choices=[('MALE', 'Male'), ('FEMALE', 'Female'), ('OTHER', 'Other'), ('UNKNOWN', 'Unknown')], default='UNKNOWN', max_length=50, verbose_name='Gender')),
('profile_picture', models.JSONField(blank=True, default=dict, null=True)),
('job_description', models.CharField(default='', max_length=50)),
('phone_number', models.CharField(blank=True, max_length=15, validators=[django.core.validators.RegexValidator(message='phone number must be between 9-15 digits', regex='^\\d{9,15}$')])),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='coordinatorprofile', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='ConsumerProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('gender', models.CharField(choices=[('MALE', 'Male'), ('FEMALE', 'Female'), ('OTHER', 'Other'), ('UNKNOWN', 'Unknown')], default='UNKNOWN', max_length=50, verbose_name='Gender')),
('profile_picture', models.JSONField(blank=True, default=dict, null=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='consumerprofile', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
<file_sep>from rest_framework.permissions import SAFE_METHODS, BasePermission
class AllowCoordinator(BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
return False
return request.user.user_type == request.user.Types.COORDINATOR
class AllowConsumer(BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
return False
return request.user.user_type == request.user.Types.CONSUMER
class AllowInstructor(BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
return False
return request.user.user_type == request.user.Types.INSTRUCTOR
class AllowVendor(BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
return False
return request.user.user_type == request.user.Types.VENDOR
class AllowSupervisor(BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
return False
return request.user.user_type == request.user.Types.SUPERVISOR
class AllowCoordinatorReadOnly(BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
return False
return (
request.method in SAFE_METHODS
and request.user.user_type == request.user.Types.COORDINATOR
)
class AllowConsumerReadOnly(BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
return False
return (
request.method in SAFE_METHODS
and request.user.user_type == request.user.Types.CONSUMER
)
class AllowInstructorReadOnly(BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
return False
return (
request.method in SAFE_METHODS
and request.user.user_type == request.user.Types.INSTRUCTOR
)
class AllowVendorReadOnly(BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
return False
return (
request.method in SAFE_METHODS
and request.user.user_type == request.user.Types.VENDOR
)
class AllowSupervisorReadOnly(BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
return False
return (
request.method in SAFE_METHODS
and request.user.user_type == request.user.Types.SUPERVISOR
)
<file_sep># Generated by Django 3.1.11 on 2021-06-29 09:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('events', '0004_auto_20210624_1822'),
]
operations = [
migrations.AlterModelOptions(
name='event',
options={'ordering': ['-start_time']},
),
]
<file_sep># Generated by Django 3.1.11 on 2021-06-29 09:12
from django.db import migrations, models
import server.utils.model_fields
class Migration(migrations.Migration):
dependencies = [
('organizations', '0013_auto_20210624_1810'),
]
operations = [
migrations.AddField(
model_name='schoolactivityorder',
name='slug',
field=models.CharField(default=server.utils.model_fields.random_slug, max_length=40, null=True),
),
]
<file_sep><template>
<v-text-field
v-model="textInput"
class="input"
:label="$t('userActions.search')"
append-icon="mdi-magnify "
@click:append="updatePagination({ searchFilter: textInput })"
@keyup.enter="updatePagination({ searchFilter: textInput })"
></v-text-field>
</template>
<script>
import { mapActions } from "vuex"
export default {
data() {
return { textInput: "" }
},
methods: mapActions("pagination", ["updatePagination"]),
}
</script>
<file_sep>import axios from "axios"
import {
GET_ORGANIZATION_INSTRUCTORS_LIST_API_URL,
ADD_ORGANIZATION_INSTRUCTORS_API_URL,
DELETE_ORGANIZATION_INSTRUCTORS_API_URL,
EDIT_ORGANIZATION_INSTRUCTORS_API_URL,
GET_ORGANIZATION_VENDORS_LIST_API_URL,
ADD_ORGANIZATION_VENDORS_API_URL,
DELETE_ORGANIZATION_VENDORS_API_URL,
EDIT_ORGANIZATION_VENDORS_API_URL,
} from "../helpers/constants/constants"
const organization = {
getInstructorList(params) {
// :Object params: query params
return axios.get(GET_ORGANIZATION_INSTRUCTORS_LIST_API_URL, { params })
},
addInstructor(instructor) {
return axios.post(ADD_ORGANIZATION_INSTRUCTORS_API_URL, instructor)
},
editInstructor(slug, data) {
if (!slug) throw "editInstructor: received empty slug"
return axios.patch(`${EDIT_ORGANIZATION_INSTRUCTORS_API_URL}${slug}/`, data)
},
deleteInstructors(instructorSlugs) {
return Promise.all(
instructorSlugs.map(slug =>
axios.delete(`${DELETE_ORGANIZATION_INSTRUCTORS_API_URL}${slug}/`)
)
)
},
getVendorList(params) {
// :Object params: query params
return axios.get(GET_ORGANIZATION_VENDORS_LIST_API_URL, { params })
},
addVendor(vendor) {
return axios.post(ADD_ORGANIZATION_VENDORS_API_URL, vendor)
},
editVendor(slug, data) {
if (!slug) throw "editVendor: received empty slug"
return axios.patch(`${EDIT_ORGANIZATION_VENDORS_API_URL}${slug}/`, data)
},
deleteVendors(vendorSlugs) {
return Promise.all(
vendorSlugs.map(slug =>
axios.delete(`${DELETE_ORGANIZATION_VENDORS_API_URL}${slug}/`)
)
)
},
}
export default organization
<file_sep>from rest_framework import serializers
from ..models import School
class SchoolSerializer(serializers.ModelSerializer):
slug = serializers.SlugField(read_only=True)
last_updated_by = serializers.CharField(
source="last_updated_by.slug",
read_only=True,
)
class Meta:
model = School
fields = [
"slug",
"name",
"address",
"address_city",
"address_zipcode",
"school_code",
"description",
"contact_phone",
"website",
"profile_picture",
"grade_levels",
"last_updated_by",
]
extra_kwargs = {"url": {"view_name": "api:school-detail", "lookup_field": "slug"}}
<file_sep><template>
<div class="pa-10">
<route-tabs :tabs="tabs" />
<v-row>
<v-col class="mx-auto" sm="11" lg="9">
<router-view />
</v-col>
</v-row>
</div>
</template>
<script>
import RouteTabs from "../../components/RouteTabs"
export default {
components: { RouteTabs },
data() {
return {
tabs: [
{
componentName: "ConsumerMyGroups",
text: this.$t("myActivity.activeGroups"),
},
{
componentName: "ConsumerMyEvents",
text: this.$t("events.eventsBoard"),
},
{
componentName: "ConsumerPendingEventsFeedback",
text: this.$t("events.eventsFeedback"),
},
],
}
},
}
</script>
<file_sep># Generated by Django 3.1.11 on 2021-06-10 16:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organizations', '0004_auto_20210608_1047'),
]
operations = [
migrations.AlterField(
model_name='activity',
name='domain',
field=models.CharField(blank=True, max_length=55, null=True),
),
migrations.AlterField(
model_name='activitymedia',
name='name',
field=models.CharField(blank=True, max_length=40, null=True),
),
migrations.AlterField(
model_name='organization',
name='address_city',
field=models.CharField(blank=True, max_length=150, null=True),
),
migrations.AlterField(
model_name='organization',
name='address_house_num',
field=models.CharField(blank=True, max_length=4, null=True),
),
migrations.AlterField(
model_name='organization',
name='address_street',
field=models.CharField(blank=True, max_length=150, null=True),
),
migrations.AlterField(
model_name='organization',
name='address_zipcode',
field=models.CharField(blank=True, max_length=9, null=True),
),
migrations.AlterField(
model_name='organization',
name='cities',
field=models.JSONField(blank=True, null=True),
),
migrations.AlterField(
model_name='organization',
name='districts',
field=models.JSONField(blank=True, null=True),
),
migrations.AlterField(
model_name='organization',
name='goal',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='organization',
name='location_lat',
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
),
migrations.AlterField(
model_name='organization',
name='location_lon',
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
),
migrations.AlterField(
model_name='organization',
name='number_of_employees',
field=models.PositiveIntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='organization',
name='number_of_members',
field=models.PositiveIntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='organization',
name='number_of_volunteers',
field=models.PositiveIntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='organization',
name='status',
field=models.CharField(blank=True, max_length=50, null=True),
),
migrations.AlterField(
model_name='organization',
name='target_audience',
field=models.JSONField(blank=True, null=True),
),
migrations.AlterField(
model_name='organization',
name='union_type',
field=models.CharField(blank=True, max_length=50, null=True),
),
migrations.AlterField(
model_name='organization',
name='website_url',
field=models.URLField(blank=True, null=True),
),
]
<file_sep>from django.conf import settings
from rest_framework.routers import DefaultRouter, SimpleRouter
from server.events.api.views import (
ConsumerEventFeedbackViewset,
ConsumerEventViewSet,
EventViewSet,
)
from server.organizations.api.views import (
ActivityMediaViewSet,
ActivityViewSet,
ConsumerActivityViewSet,
ManageSchoolActivityViewSet,
OrganizationViewSet,
SchoolActivityGroupViewSet,
VendorActivityViewSet,
)
from server.posts.api.views import PostImageViewSet, PostViewSet
from server.schools.api.views import SchoolViewSet
from server.users.api.views import (
ConsumerProfileViewSet,
CoordinatorProfileViewSet,
ExportConsumerListViewSet,
ExportCoordinatorListViewSet,
InstructorProfileViewSet,
ManageConsumersViewSet,
ManageCoordinatorsViewSet,
ManageInstructorsViewSet,
ManageVendorsViewSet,
UserViewSet,
VendorProfileViewSet,
)
if settings.DEBUG:
router = DefaultRouter()
else:
router = SimpleRouter()
router.register("users", UserViewSet)
router.register(
"consumers_profiles",
ConsumerProfileViewSet,
basename="consumers_profiles",
)
router.register(
"coordinators_profiles",
CoordinatorProfileViewSet,
basename="coordinators_profiles",
)
router.register(
"instructors_profiles",
InstructorProfileViewSet,
basename="instructors_profiles",
)
router.register("vendors_profiles", VendorProfileViewSet, basename="vendors_profiles")
router.register("organizations", OrganizationViewSet, basename="organizations")
router.register("activity_media", ActivityMediaViewSet, basename="activity_media")
router.register("activities", ActivityViewSet, basename="activities")
router.register(
"consumer_activities",
ConsumerActivityViewSet,
basename="consumer_activities",
)
router.register(
"vendor_activities",
VendorActivityViewSet,
basename="vendor_activities",
)
router.register("schools", SchoolViewSet, "schools")
router.register("manage_consumers", ManageConsumersViewSet, basename="manage_consumers")
router.register(
"manage_coordinators", ManageCoordinatorsViewSet, basename="manage_coordinators"
)
router.register(
"export_consumer_list", ExportConsumerListViewSet, basename="export_consumer_list"
)
router.register(
"export_coordinator_list",
ExportCoordinatorListViewSet,
basename="export_coordinator_list",
)
router.register(
"manage_instructors", ManageInstructorsViewSet, basename="manage_instructors"
)
router.register("manage_vendors", ManageVendorsViewSet, basename="manage_vendors")
router.register(
"manage_school_activity",
ManageSchoolActivityViewSet,
basename="manage_school_activity",
)
router.register("school_activity_group", SchoolActivityGroupViewSet)
router.register("events", EventViewSet, basename="events")
router.register("consumer_events", ConsumerEventViewSet, basename="consumer_events")
router.register(
"consumer_event_feedback",
ConsumerEventFeedbackViewset,
basename="consumer_event_feedback",
)
router.register(
"posts",
PostViewSet,
basename="posts",
)
router.register(
"post_image",
PostImageViewSet,
basename="post_image",
)
app_name = "api"
urlpatterns = router.urls
<file_sep><template>
<div class="wrapper">
<v-card
class="py-12 px-7 mx-auto"
width="320"
elevation="16"
v-show="page === 1"
>
<v-card-title class="text-h4 justify-center mb-6">{{
$t("auth.detailsCompletion")
}}</v-card-title>
<v-card-subtitle class="text-h6 text-center mb-8">{{
$t("general.personalInfo")
}}</v-card-subtitle>
<validation-observer ref="observer" v-slot="{ invalid }">
<form @submit.prevent="incrementPage" data-testid="form-1">
<validation-provider v-slot="{ errors }" name="name" rules="required">
<v-text-field
v-model="registrationInfo.name"
data-testid="name"
:error-messages="errors"
:label="$t('general.name')"
required
></v-text-field>
</validation-provider>
<validation-provider
v-slot="{ errors }"
name="phone"
rules="required|numeric|phoneNumberIsrael"
>
<v-text-field
v-model="registrationInfo.phone"
data-testid="phone"
:error-messages="errors"
:label="$t('general.phoneNumber')"
required
/>
</validation-provider>
<div class="mx-auto d-flex justify-center mt-12">
<v-btn
class="ml-3 white--text"
type="submit"
color="primary"
elevation="3"
:disabled="invalid"
>
{{ $t("userActions.next") }}
</v-btn>
<v-btn
class="mr-3"
type="button"
color="primary"
elevation="3"
outlined
@click="logout"
>
{{ $t("userActions.toHomepage") }}
</v-btn>
</div>
</form>
</validation-observer>
</v-card>
<v-card
v-if="shouldEditSchool"
v-show="page === 2"
class="py-12 px-7 mx-auto"
width="320"
elevation="16"
>
<v-card-title class="text-h4 justify-center mb-6">{{
$t("auth.detailsCompletion")
}}</v-card-title>
<v-card-subtitle class="text-h6 text-center mb-6">{{
$t("general.schoolDetails")
}}</v-card-subtitle>
<validation-observer ref="observer" v-slot="{ invalid }">
<form @submit.prevent="incrementPage" data-testid="form-2">
<validation-provider
v-slot="{ errors }"
name="school"
rules="required"
>
<v-text-field
data-testid="school"
v-model="registrationInfo.schoolName"
:error-messages="errors"
:label="$t('general.schoolName')"
required
></v-text-field>
</validation-provider>
<validation-provider
v-slot="{ errors }"
name="schoolCode"
rules="required|numeric"
>
<v-text-field
data-testid="school-code"
v-model="registrationInfo.schoolCode"
:error-messages="errors"
:label="$t('general.schoolCode')"
required
></v-text-field>
</validation-provider>
<validation-provider
v-slot="{ errors }"
name="schoolCity"
rules="required"
>
<v-text-field
data-testid="school-city"
v-model="registrationInfo.schoolCity"
:error-messages="errors"
:label="$t('general.city')"
required
></v-text-field>
</validation-provider>
<validation-provider
v-slot="{ errors }"
name="schoolStreet"
rules="required"
>
<v-text-field
data-testid="street"
v-model="registrationInfo.schoolStreet"
:error-messages="errors"
:label="$t('general.street')"
required
></v-text-field>
</validation-provider>
<validation-provider
v-slot="{ errors }"
name="schoolPhone"
rules="required|numeric|phoneNumberIsrael"
>
<v-text-field
data-testid="school-phone"
v-model="registrationInfo.schoolPhone"
:error-messages="errors"
:label="$t('general.schoolPhoneNumber')"
required
></v-text-field>
</validation-provider>
<validation-provider
v-slot="{ errors }"
name="schoolGrades"
rules="required"
>
<v-select
data-testid="school-grades"
v-model="registrationInfo.schoolGrades"
:error-messages="errors"
:items="SCHOOL_GRADES_ITEMS"
:label="$t('general.schoolGrades')"
multiple
chips
deletable-chips
>
</v-select>
</validation-provider>
<div class="mx-auto d-flex justify-center mt-12">
<v-btn
class="ml-3 white--text"
type="submit"
color="primary"
elevation="3"
:disabled="invalid"
>
{{ $t("userActions.next") }}
</v-btn>
<v-btn
class="mr-3"
type="button"
color="primary"
elevation="3"
outlined
@click="decrementPage()"
>
{{ $t("userActions.back") }}
</v-btn>
</div>
</form>
</validation-observer>
</v-card>
<v-card
class="py-12 px-7 mx-auto"
width="320"
elevation="16"
v-show="
(page === 3 && shouldEditSchool) || (page === 2 && !shouldEditSchool)
"
>
<v-card-title class="text-h4 justify-center mb-6">{{
$t("auth.detailsCompletion")
}}</v-card-title>
<v-card-subtitle class="text-h6 text-center mb-8">{{
$t("auth.confirmDetails")
}}</v-card-subtitle>
<form @submit.prevent="submit" data-testid="form-3">
<v-card-text
class="text-center mb-5 text-subtitle-1 font-weight-bold"
>{{ $t("general.personalInfo") }}</v-card-text
>
<v-card-text
><b>{{ $t("general.name") }}:</b>
{{ registrationInfo.name }}
</v-card-text>
<v-card-text
><b>{{ $t("general.phoneNumber") }}:</b>
{{ registrationInfo.phone }}</v-card-text
>
<br />
<template v-if="shouldEditSchool">
<v-card-text
class="text-center mb-5 text-subtitle-1 font-weight-bold"
>{{ $t("general.schoolDetails") }}</v-card-text
>
<v-card-text
><b>{{ $t("general.name") }} {{ $tc("general.school", 0) }}:</b>
{{ registrationInfo.schoolName }}</v-card-text
>
<v-card-text
><b>{{ $t("general.schoolCode") }}:</b>
{{ registrationInfo.schoolCode }}</v-card-text
>
<v-card-text
><b>{{ $t("general.city") }}:</b>
{{ registrationInfo.schoolCity }}</v-card-text
>
<v-card-text
><b>{{ $t("general.street") }}:</b>
{{ registrationInfo.schoolStreet }}</v-card-text
>
<v-card-text
><b>{{ $t("general.phoneNumber") }}:</b>
{{ registrationInfo.schoolPhone }}</v-card-text
>
<v-card-text
><b>{{ $t("general.schoolGrades") }}:</b>
{{
registrationInfo.schoolGrades
.map(num => $t(`grades.${num}`))
.join(", ")
}}</v-card-text
>
</template>
<div class="mx-auto d-flex justify-center mt-12">
<v-btn
class="ml-3 white--text"
type="submit"
color="primary"
elevation="3"
>
{{ $t("auth.detailsConfirmation") }}
</v-btn>
<v-btn
class="mr-3"
type="button"
color="primary"
elevation="3"
outlined
@click="decrementPage()"
>
{{ $t("userActions.back") }}
</v-btn>
</div>
</form>
</v-card>
<modal
:redirectComponentName="modalRedirectComponentName"
v-show="popupMsg !== ''"
@close="popupMsg = ''"
>
{{ popupMsg }}
</modal>
</div>
</template>
<script>
import store from "../../vuex/store"
import debounce from "lodash/debounce"
import { mapActions } from "vuex"
import { ValidationObserver, ValidationProvider } from "vee-validate"
import { SCHOOL_GRADES_ITEMS } from "../../helpers/constants/constants"
import Modal from "../../components/Modal"
export default {
components: {
ValidationProvider,
ValidationObserver,
Modal,
},
props: {
shouldEditSchool: {
type: Boolean,
required: true,
},
},
data() {
return {
SCHOOL_GRADES_ITEMS,
modalRedirectComponentName: "",
slug: null,
schoolSlug: "",
showPass: false,
page: 1,
popupMsg: "",
registrationInfo: {
name: "",
phone: "",
schoolName: "",
schoolCode: "",
schoolCity: "",
schoolStreet: "",
schoolPhone: "",
schoolGrades: [],
},
}
},
async mounted() {
let userDetails = await store.dispatch("user/getUserDetails")
let schoolDetails = await store.dispatch("school/getSchoolDetails")
this.slug = userDetails.slug
this.schoolSlug = schoolDetails.slug
},
methods: {
...mapActions("user", ["updateUserDetails"]),
...mapActions("coordinator", ["updateProfile"]),
...mapActions("school", ["updateSchoolDetails"]),
...mapActions("auth", ["logout"]),
submit: debounce(
function () {
let userDetailsPayload = this.createUserSubmitPayload()
let profilePayload = this.createProfileSubmitPayload()
let schoolPayload = this.createSchoolSubmitPayload()
this.postRegistrationData(
userDetailsPayload,
profilePayload,
schoolPayload
)
},
500,
{ leading: true, trailing: false }
),
createUserSubmitPayload() {
return {
name: this.registrationInfo.name,
}
},
createProfileSubmitPayload() {
let profilePayload = new FormData()
profilePayload.append("phone_number", this.registrationInfo.phone)
return profilePayload
},
createSchoolSubmitPayload() {
let data = new FormData()
data.append("slug", this.schoolSlug)
data.append("name", this.registrationInfo.schoolName)
data.append("address", this.registrationInfo.schoolStreet)
data.append("address_city", this.registrationInfo.schoolCity)
data.append("school_code", this.registrationInfo.schoolCode)
data.append("contact_phone", this.registrationInfo.schoolPhone)
data.append(
"grade_levels",
JSON.stringify(this.registrationInfo.schoolGrades)
)
return data
},
async postRegistrationData(
userDetailsPayload,
profilePayload,
schoolPayload
) {
try {
await this.updateProfile({ slug: this.slug, profile: profilePayload })
await this.updateUserDetails({
slug: this.slug,
userDetails: userDetailsPayload,
})
if (this.shouldEditSchool) {
await this.updateSchoolDetails({
slug: this.schoolSlug,
schoolDetails: schoolPayload,
})
}
this.modalRedirectComponentName = "MyGroups"
this.popupMsg = this.$t("general.detailsSuccessfullyUpdated")
} catch (err) {
if (
err.response &&
err.response.status === 400 &&
Object.keys(err.response.data).length > 0
) {
this.popupMsg =
err.response.data[Object.keys(err.response.data)[0]][0]
} else {
this.popupMsg = this.$t("errors.genericError")
}
}
},
incrementPage() {
this.page += 1
},
decrementPage() {
this.page -= 1
},
},
}
</script>
<style lang="scss" scoped>
.wrapper {
margin-top: 100px;
margin-bottom: 30px;
}
.v-card__subtitle,
.v-card__text,
.v-card__title {
padding: 0;
}
</style>
<file_sep><template>
<v-card :elevation="elevation">
<v-card-text>
<validation-observer ref="observer">
<v-row>
<v-col
v-for="(field, i) in value"
:key="i"
class="mt-8"
cols="12"
md="6"
>
<validation-provider
v-slot="{ errors }"
:name="field.name"
:rules="field.rules"
>
<v-select
v-if="field.type && field.type === 'select'"
class="mx-2"
:data-testid="field.name"
:label="field.label"
:error-messages="errors"
:value="field.value"
:items="field.choices"
@input="input => updateField(i, input)"
:multiple="field.multiselect"
/>
<v-text-field
v-else
class="mx-2"
:data-testid="field.name"
:label="field.label"
:error-messages="errors"
:value="field.value"
@input="input => updateField(i, input)"
/>
</validation-provider>
</v-col>
</v-row>
</validation-observer>
</v-card-text>
</v-card>
</template>
<script>
import Vue from "vue"
import { ValidationObserver, ValidationProvider } from "vee-validate"
export default {
components: {
ValidationObserver,
ValidationProvider,
},
props: {
value: {
// the form's prototype
// e.g., [ { name: 'field1', rules: 'required|size:5000', label: $t('translation'), value: 'placeholderValue' }, { ... }, ... ]
type: Array,
required: true,
},
elevation: {
type: [Number, String],
default: 2,
},
},
watch: {
value: {
// emit validation events
deep: true,
async handler() {
await Vue.nextTick()
const isValid = await this.$refs.observer.validate({ silent: true })
if (isValid) {
this.$emit("valid")
} else {
this.$emit("invalid")
}
},
},
},
methods: {
updateField(fieldIndex, input) {
// v-model implementation
const fields = [...this.value]
fields[fieldIndex].value = input
this.$emit("input", fields)
},
},
}
</script>
<style lang="scss" scoped>
.v-card__subtitle,
.v-card__text,
.v-card__title {
padding: 0;
}
</style>
<file_sep>from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.core.validators import RegexValidator
from django.db import models
from django.db.models import CharField, EmailField, TextChoices
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from server.utils.model_fields import random_slug
class User(AbstractUser):
"""Default user for server."""
class Types(TextChoices):
CONSUMER = "CONSUMER", "Consumer"
COORDINATOR = "COORDINATOR", "Coordinator"
VENDOR = "VENDOR", "Vendor"
INSTRUCTOR = "INSTRUCTOR", "Instructor"
SUPERVISOR = "SUPERVISOR", "Supervisor"
base_user_type = Types.CONSUMER
user_type = CharField(
_("Type"), max_length=50, choices=Types.choices, default=base_user_type
)
#: First and last name do not cover name patterns around the globe
name = CharField(_("Name of User"), blank=True, max_length=255)
first_name = None # type: ignore
last_name = None # type: ignore
email = EmailField(unique=True)
username = CharField(max_length=40, default=random_slug, unique=True)
slug = CharField(max_length=40, default=random_slug, unique=True)
def get_absolute_url(self):
"""Get url for user's detail view.
Returns:
str: URL for user detail.
"""
return reverse("users:detail", kwargs={"username": self.username})
def save(self, *args, **kwargs):
if not self.id:
self.user_type = self.base_user_type
self.slug = self.username
self.email = self.email.lower()
return super().save(*args, **kwargs)
def __str__(self):
return self.email
class ConsumerManager(BaseUserManager):
def get_queryset(self, *args, **kwargs):
return (
super()
.get_queryset(*args, **kwargs)
.filter(
user_type=User.Types.CONSUMER,
)
)
class CoordinatorManager(BaseUserManager):
def get_queryset(self, *args, **kwargs):
return (
super()
.get_queryset(*args, **kwargs)
.filter(
user_type=User.Types.COORDINATOR,
)
)
class SupervisorManager(BaseUserManager):
def get_queryset(self, *args, **kwargs):
return (
super()
.get_queryset(*args, **kwargs)
.filter(
user_type=User.Types.SUPERVISOR,
)
)
class VendorManager(BaseUserManager):
def get_queryset(self, *args, **kwargs):
return (
super()
.get_queryset(*args, **kwargs)
.filter(
user_type=User.Types.VENDOR,
)
)
class InstructorManager(BaseUserManager):
def get_queryset(self, *args, **kwargs):
return (
super()
.get_queryset(*args, **kwargs)
.filter(
user_type=User.Types.INSTRUCTOR,
)
)
class Consumer(User):
base_user_type = User.Types.CONSUMER
objects = ConsumerManager()
class Meta:
proxy = True
verbose_name_plural = "1. Consumer (Students)"
@property
def profile(self):
return self.consumerprofile
class Coordinator(User):
base_user_type = User.Types.COORDINATOR
objects = CoordinatorManager()
class Meta:
proxy = True
verbose_name_plural = "2. Coordinator (Principals)"
@property
def profile(self):
return self.coordinatorprofile
class Vendor(User):
base_user_type = User.Types.VENDOR
objects = VendorManager()
class Meta:
proxy = True
verbose_name_plural = "3. Vendor (Organization Managers)"
@property
def profile(self):
return self.vendorprofile
class Instructor(User):
base_user_type = User.Types.INSTRUCTOR
objects = InstructorManager()
class Meta:
proxy = True
verbose_name_plural = "4. Instructor (Guide)"
@property
def profile(self):
return self.instructorprofile
class Supervisor(User):
base_user_type = User.Types.SUPERVISOR
objects = SupervisorManager()
class Meta:
proxy = True
verbose_name_plural = "5. Supervisor"
@property
def profile(self):
return self.supervisorprofile
class BaseProfile(models.Model):
class Gender(TextChoices):
MALE = "MALE", "Male"
FEMALE = "FEMALE", "Female"
OTHER = (
"OTHER",
"Other",
)
UNKNOWN = "UNKNOWN", "Unknown"
base_gender = Gender.UNKNOWN
user = models.OneToOneField(
User, related_name="%(class)s", on_delete=models.CASCADE, unique=True
)
gender = models.CharField(
_("Gender"), max_length=50, choices=Gender.choices, default=base_gender
)
profile_picture = models.JSONField(blank=True, null=True, default=dict)
class Meta:
abstract = True
def __str__(self):
return f"PROFILE | {self.user.user_type} | {self.user.email}"
class CoordinatorProfile(BaseProfile):
job_description = models.CharField(max_length=50, default="")
phone_number = models.CharField(
blank=True,
max_length=15,
validators=[
RegexValidator(
regex=r"^\d{9,15}$",
message=_("phone number must be between 9-15 digits"),
)
],
)
class SupervisorProfile(BaseProfile):
job_description = models.CharField(max_length=50, default="")
phone_number = models.CharField(
blank=True,
max_length=15,
validators=[
RegexValidator(
regex=r"^\d{9,15}$",
message=_("phone number must be between 9-15 digits"),
)
],
)
class ConsumerProfile(BaseProfile):
pass
class VendorProfile(BaseProfile):
phone_number = models.CharField(
blank=True,
max_length=15,
validators=[
RegexValidator(
regex=r"^\d{9,15}$",
message=_("phone number must be between 9-15 digits"),
)
],
)
class InstructorProfile(BaseProfile):
phone_number = models.CharField(
blank=True,
max_length=15,
validators=[
RegexValidator(
regex=r"^\d{9,15}$",
message=_("phone number must be between 9-15 digits"),
)
],
)
<file_sep><template>
<v-card
class="my-15 mx-auto px-sm-10 py-sm-10"
max-width="1000"
:min-height="$vuetify.breakpoint.mobile ? 350 : 500"
:elevation="$vuetify.breakpoint.mobile ? 0 : 3"
>
<v-card-title
class="text-sm-h4"
v-text="$t('events.unsummarizedPastEvents')"
/>
<v-card-subtitle
class="text-md-h6 pt-3"
v-text="$t('events.clickAnEventToSummarizeIt')"
/>
<click-list
v-if="formattedEvents.length"
v-model="selected"
class="my-12"
:title="$t('events.eventsToSummarize')"
:items="formattedEvents"
@input="onEventClick"
/>
<div v-else class="text-center text-md-h6 absolute-center text-body-1" v-text="$t('events.eventsToSummarizeWereNotFound')" />
</v-card>
</template>
<script>
import store from "../vuex/store"
import moment from "moment"
import { mapState } from "vuex"
import ClickList from "../components/ClickList"
export default {
components: { ClickList },
data() {
return {
selected: [],
isEventClicked: false,
}
},
async beforeRouteEnter(to, from, next) {
await store.dispatch("instructorEvent/getPastEvents", { daysAgo: 60, unsummarizedOnly: true })
next()
},
computed: {
...mapState("instructorEvent", ["eventList"]),
formattedEvents() {
return this.eventList
.filter(event => !event.hasSummary)
.map(event => ({
action: moment(event.startTime).format("DD.MM.YYYY"),
subtitle: event.activityName,
title: event.schoolGroupName,
}))
},
},
methods: {
onEventClick(e) {
// extract event slug & route to event summary
if (this.isEventClicked) return
this.isEventClicked = true
const eventPos = e[0]
this.$router.push({
name: "InstructorEventSummary",
params: { slug: this.eventList[eventPos].slug },
})
},
},
}
</script>
<file_sep>import axios from "axios"
import {
GET_PROGRAM_GROUPS_API_URL,
CREATE_PROGRAM_GROUP_API_URL,
GET_PROGRAM_GROUP_CONSUMERS_API_URL,
UPDATE_PROGRAM_GROUP_CONSUMERS_API_URL,
UPDATE_PROGRAM_GROUP_API_URL,
DELETE_PROGRAM_GROUP_API_URL,
} from "../helpers/constants/constants"
const programGroup = {
getGroup(groupSlug) {
if (!groupSlug) throw "getGroup: received empty slug"
return axios.get(`${GET_PROGRAM_GROUPS_API_URL}${groupSlug}/`)
},
getGroupList(params) {
return axios.get(GET_PROGRAM_GROUPS_API_URL, { params })
},
createGroup(data) {
return axios.post(CREATE_PROGRAM_GROUP_API_URL, data)
},
updateGroup(groupSlug, data) {
if (!groupSlug) throw "updateGroup: received empty slug"
return axios.patch(`${UPDATE_PROGRAM_GROUP_API_URL}${groupSlug}/`, data)
},
deleteGroup(groupSlug) {
if (!groupSlug) throw "deleteGroup: received empty slug"
return axios.delete(`${DELETE_PROGRAM_GROUP_API_URL}${groupSlug}/`)
},
getConsumers(groupSlug) {
if (!groupSlug) throw "getConsumers: received empty slug"
return axios.get(
`${GET_PROGRAM_GROUP_CONSUMERS_API_URL}${groupSlug}/group_consumers/`
)
},
updateGroupConsumers(groupSlug, consumerSlugs) {
if (!groupSlug) {
throw "updateGroupConsumers: received empty slug"
}
return axios.patch(
`${UPDATE_PROGRAM_GROUP_CONSUMERS_API_URL}${groupSlug}/update_group_consumers/`,
consumerSlugs
)
},
}
export default programGroup
<file_sep><template>
<v-container fluid>
<p>{{ title }}</p>
<v-radio-group :value="selectedItem" @change="onChange">
<v-radio
v-for="choice in choices"
:key="choice.id"
:label="choice.label"
:value="choice.value"
/>
</v-radio-group>
</v-container>
</template>
<script>
export default {
model: {
prop: "selectedItem",
},
props: {
selectedItem: {
// empty string or item a value from choices prop
type: String,
required: true,
},
choices: {
type: Array,
required: true,
validator(value) {
return value.every(
item =>
Object.keys(item).includes("label") &&
Object.keys(item).includes("value")
)
},
},
title: {
type: String,
required: true,
},
},
methods: {
onChange(e) {
this.$emit("input", e)
},
},
}
</script>
<file_sep>import FormCard from "../components/FormCard.vue"
export default {
title: "FormCard",
component: FormCard,
}
const Template = args => ({
components: { FormCard },
data: () => ({ args }),
template: `
<form-card
class="mx-auto"
style="width: 800px;"
v-model="args.value"
elevation="args.elevation"
/>
`,
})
export const Primary = Template.bind({})
Primary.args = {
value: [
{
name: "firstName",
rules: "required",
label: "<NAME>",
value: ""
},
{
name: "lastName",
rules: "required",
label: "<NAME>",
value: ""
},
{
name: "phoneNumber",
rules: "required",
label: "Phone",
value: "0521234567"
},
],
elevation: 2,
}
<file_sep># Generated by Django 3.1.11 on 2021-07-25 11:09
from django.db import migrations, models
import server.utils.model_fields
class Migration(migrations.Migration):
dependencies = [
('organizations', '0020_auto_20210718_1254'),
]
operations = [
migrations.CreateModel(
name='ImportedOrganization',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.CharField(default=server.utils.model_fields.random_slug, max_length=40, unique=True)),
('organization_number', models.CharField(max_length=10, unique=True)),
('email', models.EmailField(blank=True, max_length=254, null=True)),
('description', models.CharField(blank=True, max_length=4096, null=True)),
('website_url', models.URLField(blank=True, null=True)),
('name', models.CharField(blank=True, max_length=256, null=True)),
('goal', models.CharField(blank=True, max_length=4096, null=True)),
('year_founded', models.CharField(blank=True, max_length=128, null=True)),
('status', models.CharField(blank=True, max_length=50, null=True)),
('target_audience', models.JSONField(blank=True, null=True)),
('number_of_employees', models.PositiveIntegerField(blank=True, null=True)),
('number_of_members', models.PositiveIntegerField(blank=True, null=True)),
('number_of_volunteers', models.PositiveIntegerField(blank=True, null=True)),
('location_lon', models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True)),
('location_lat', models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True)),
('address_city', models.CharField(blank=True, max_length=256, null=True)),
('address_street', models.CharField(blank=True, max_length=256, null=True)),
('address_house_num', models.CharField(blank=True, max_length=30, null=True)),
('address_zipcode', models.CharField(blank=True, max_length=9, null=True)),
('cities', models.JSONField(blank=True, null=True)),
('districts', models.JSONField(blank=True, null=True)),
('union_type', models.CharField(blank=True, max_length=50, null=True)),
],
),
migrations.AlterField(
model_name='organization',
name='address_house_num',
field=models.CharField(blank=True, max_length=20, null=True),
),
migrations.AlterField(
model_name='organization',
name='description',
field=models.CharField(max_length=300),
),
migrations.AlterField(
model_name='organization',
name='goal',
field=models.CharField(blank=True, max_length=300, null=True),
),
migrations.AlterField(
model_name='organization',
name='name',
field=models.CharField(max_length=100),
),
]
<file_sep>import axios from "axios"
import { GET_CONSUMER_PROGRAM_GROUPS_API_URL } from "../helpers/constants/constants"
const consumerProgramGroup = {
getGroupList(params) {
return axios.get(GET_CONSUMER_PROGRAM_GROUPS_API_URL, { params })
},
}
export default consumerProgramGroup
<file_sep><template>
<div class="my-3" :width="width">
<v-card
class="card overflow-hidden w-100 pt-5 pb-10 mx-auto px-7"
elevation="10"
>
<div class="d-flex justify-space-between">
<v-card-title v-text="author" class="font-weight-bold pa-2" />
<avatar style="width: 50px" :avatar-options="authorAvatar" />
</div>
<v-card-subtitle v-text="subtitle" class="px-2 py-1" />
<v-card-text
class="text--primary pt-3 px-2 body"
:class="{ 'text-h4': !images.length, 'text-h6': images.length }"
>
"{{ content }}"
</v-card-text>
<v-row class="my-10" justify="center" no-gutters>
<v-col
v-for="image in images.slice(0, 3)"
:key="image.id"
cols="6"
class="pa-1"
>
<v-img
class="cursor-pointer"
@click="showCarousel = true"
height="200"
width="300"
:src="image"
:lazy-src="LAZY_IMAGE_PLACEHOLDER"
>
<template v-slot:placeholder>
<v-row class="fill-height ma-0" align="center" justify="center">
<v-progress-circular indeterminate color="grey lighten-1" />
</v-row>
</template>
</v-img>
</v-col>
<v-col v-if="showMore" cols="6" class="pa-1">
<v-img
class="cursor-pointer"
@click="showCarousel = true"
height="200"
width="300"
:src="images[3]"
:lazy-src="LAZY_IMAGE_PLACEHOLDER"
>
<v-overlay absolute color="#036358">
<h1>{{ additionalImages }}+</h1>
</v-overlay>
</v-img>
</v-col>
</v-row>
</v-card>
<v-dialog v-model="showCarousel" max-width="650">
<carousel :media-list="carouselMedia" />
</v-dialog>
</div>
</template>
<script>
import { LAZY_IMAGE_PLACEHOLDER } from "../helpers/constants/images"
import Avatar from "./Avatar/Avatar"
import Carousel from "./Carousel"
export default {
components: { Avatar, Carousel },
props: {
width: {
type: String,
default: "100%",
},
content: {
type: String,
required: true,
},
author: {
type: String,
required: true,
},
authorAvatar: {
type: Object,
required: true,
},
subtitle: {
type: String,
required: true,
},
images: {
type: Array,
default: () => [],
},
},
data() {
return {
LAZY_IMAGE_PLACEHOLDER,
showCarousel: false,
showMore: this.images.length > 3,
additionalImages: this.images.length - 3,
}
},
computed: {
carouselMedia() {
return this.images.map(image => ({
mediaType: "image",
imageUrl: image,
}))
},
},
}
</script>
<style scoped>
#info-button {
letter-spacing: 1.7px !important;
}
.actions {
height: 40px;
}
.card {
border-radius: 4px;
min-height: 285px;
}
.body {
line-height: 1.4;
}
</style>
<file_sep>import Vue from "vue"
import axios from "axios"
import Utils from "../helpers/utils"
import store from "../vuex/store"
import { TOKEN_COOKIE_NAME } from "../helpers/constants/constants"
function addTokenHeader(token) {
axios.defaults.headers.common["Authorization"] = `Token ${token}`
}
function removeTokenHeader() {
delete axios.defaults.headers.common["Authorization"]
}
function addInvalidTokenHandler() {
axios.interceptors.response.use(
// pop token if backend rejects it
response => response,
error => {
if (error.response.data.detail === "Invalid token.") {
config.removeToken()
Vue.$router.push({
name: "Error",
params: { bodyKey: "errors.tokenExpired" },
})
}
return Promise.reject(error)
}
)
}
function addProgressBarInterceptors() {
axios.interceptors.request.use(config => {
store.dispatch("loading/startLoading")
return config
})
axios.interceptors.response.use(
response => {
store.dispatch("loading/doneLoading")
return response
},
error => {
store.dispatch("loading/doneLoading")
return Promise.reject(error)
}
)
}
function addDataCaseConversion() {
// add camelCase <-> snake_case conversion on request and response
axios.defaults.transformResponse = [
(data, headers) => {
if (data && headers["content-type"].includes("application/json")) {
let converted = Utils.convertKeysCase(JSON.parse(data), "camel")
return JSON.stringify(converted)
}
},
...axios.defaults.transformResponse,
]
axios.defaults.transformRequest = [
data => {
if (data) {
return Utils.convertKeysCase(data, "snake")
}
},
...axios.defaults.transformRequest,
]
}
const config = {
initAxiosSettings() {
// init app's axios settings - set token header is token exists, handle token backend expiry
let token = Vue.$cookies.get(TOKEN_COOKIE_NAME)
if (token) {
addTokenHeader(token)
}
addInvalidTokenHandler()
addProgressBarInterceptors()
addDataCaseConversion()
},
setToken(token) {
// save token as cookie and as axios header
// :string token: the token to use
Vue.$cookies.set(TOKEN_COOKIE_NAME, token)
addTokenHeader(token)
},
removeToken() {
// remove token from cookie and axios header
Vue.$cookies.erase(TOKEN_COOKIE_NAME)
removeTokenHeader()
},
}
export default config
<file_sep><template>
<v-card class="chips-container mx-auto mt-15" elevation="5" v-bind="$attrs">
<v-card-title><slot/></v-card-title>
<v-chip-group class="chips-group" column show-arrows>
<v-chip
color="primary"
text-color="white"
class="ma-2"
v-for="label in labels"
:key="label.index"
>
<v-avatar v-if="icon" left>
<v-icon>{{ icon }}</v-icon>
</v-avatar>
{{ label }}
</v-chip>
</v-chip-group>
</v-card>
</template>
<script>
export default {
inheritAttrs: false,
props: {
labels: {
type: Array,
required: true,
},
icon: {
type: String,
required: false,
},
},
}
</script>
<file_sep>from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.db import IntegrityError
from server.users.models import Consumer, Coordinator, Instructor, Vendor
class Command(BaseCommand):
help = "Creates test users for development"
def add_arguments(self, parser):
"parser.add_argument('some_number', nargs='+', type=int)"
pass
def create_user(self, user_model, email, password):
try:
user = user_model.objects.create(email=email, password=password)
user.set_password(user.password)
user.save()
self.stdout.write(
self.style.SUCCESS(f"Successfully created user with {user.email}")
)
except IntegrityError:
self.stdout.write(
self.style.WARNING(f"{email} already exists. Skipping...")
)
def create_admin(self):
try:
user = get_user_model().objects.create_superuser(
"admin", "<EMAIL>", "<PASSWORD>"
)
self.stdout.write(
self.style.SUCCESS(f"Successfully created user with {user.email}")
)
except IntegrityError:
self.stdout.write(
self.style.WARNING("Dev admin already exists. Skipping...")
)
def handle(self, *args, **options):
if not settings.DEBUG:
raise RuntimeError("create_test_users is meant for dev environments.")
self.create_user(Coordinator, "<EMAIL>", "<PASSWORD>")
self.create_user(Consumer, "<EMAIL>", "<PASSWORD>")
self.create_user(Instructor, "<EMAIL>", "<PASSWORD>")
self.create_user(Vendor, "<EMAIL>", "<PASSWORD>")
self.create_admin()
<file_sep># Generated by Django 3.1.11 on 2021-07-25 13:49
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import server.utils.model_fields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('events', '0009_auto_20210718_1751'),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.CharField(default=server.utils.model_fields.random_slug, max_length=40, unique=True)),
('creation_time', models.DateTimeField(auto_now=True)),
('post_content', models.TextField()),
('author', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
('event', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='events.event')),
],
),
migrations.CreateModel(
name='PostImage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.CharField(default=server.utils.model_fields.random_slug, max_length=40, unique=True)),
('image_url', models.ImageField(upload_to='')),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='posts.post')),
],
),
]
<file_sep><template>
<v-carousel
v-bind="$attrs"
height="350"
class="mt-6 mx-auto rounded-lg grey darken-3"
show-arrows-on-hover
hide-delimiter-background
delimiter-icon="mdi-minus"
@change="e => $emit('input', e)"
>
<v-carousel-item
v-for="media in mediaList"
:key="media.id"
reverse-transition="fade-transition"
transition="fade-transition"
class="text-center"
>
<iframe
v-if="media.mediaType === 'video'"
class="w-100"
height="350"
:src="youtubeToEmbeddedUrl(media.videoUrl)"
frameborder="0"
allow="autoplay; encrypted-media"
allowfullscreen
/>
<img v-else :src="media.imageUrl" height="350" />
</v-carousel-item>
</v-carousel>
</template>
<script>
import Utils from "../helpers/utils"
export default {
inheritAttrs: false,
props: {
mediaList: {
// format: [ { mediaType: "image/video", videoUrl: "", imageUrl: ""} ]
type: Array,
required: true,
},
},
methods: {
youtubeToEmbeddedUrl: Utils.youtubeToEmbeddedUrl,
},
}
</script>
<file_sep># Generated by Django 3.1.11 on 2021-05-23 12:44
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('organizations', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='OrganizationMember',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('organization', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='organization_member', to='organizations.organization')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='organization_member', to=settings.AUTH_USER_MODEL)),
],
),
migrations.DeleteModel(
name='OrganizationMemeber',
),
]
<file_sep># Generated by Django 3.1.11 on 2021-07-27 10:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organizations', '0023_auto_20210725_1442'),
]
operations = [
migrations.AlterField(
model_name='activity',
name='activity_website_url',
field=models.URLField(blank=True, max_length=750, null=True),
),
migrations.AlterField(
model_name='importedactivity',
name='activity_website_url',
field=models.URLField(blank=True, max_length=750, null=True),
),
]
<file_sep>import Vue from "vue"
import Vuetify from "vuetify"
import VueI18n from "vue-i18n"
import i18n from "../src/plugins/i18n.js"
import "../src/helpers/validators"
import "!style-loader!css-loader!sass-loader!../src/styles/main.scss"
import "./vuetify"
import "../src/filters"
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
}
Vue.use(Vuetify)
Vue.use(VueI18n)
const vuetify = new Vuetify()
export const decorators = [
(story, context) => {
// wrap the passed component within the passed context
const wrapped = story(context)
// extend Vue to use Vuetify around the wrapped component
return Vue.extend({
vuetify,
i18n,
components: { wrapped },
props: {
locale: {
type: String,
default: "he",
},
},
watch: {
dark: {
immediate: true,
handler(val) {
this.$vuetify.theme.dark = val
},
},
locale: {
immediate: true,
handler(val) {
this.$i18n.locale = val
},
},
},
template: `
<v-app>
<v-container fluid>
<wrapped />
</v-container>
</v-app>
`,
})
},
]
<file_sep><template>
<v-row justify="center">
<v-dialog :value="value" @input="close" width="540px">
<v-card class="px-5">
<v-card-title
v-text="$t('general.media')"
class="py-8 justify-center"
/>
<validation-observer v-slot="{ invalid }" slim>
<v-card-text>
<v-select
v-model="mediaType"
data-testid="media-type-select"
:items="mediaTypeList"
:label="$t('program.mediaType')"
/>
<validation-provider
v-slot="{ errors }"
:rules="mediaType === 'image' && 'required|size:5000'"
>
<v-file-input
append-icon="mdi-camera"
:prepend-icon="null"
type="file"
accept="image/*"
v-model="image"
:disabled="mediaType === 'video'"
:label="$t('program.imageUpload')"
:error-messages="errors"
clearable
/>
</validation-provider>
<validation-provider
v-slot="{ errors }"
:rules="mediaType === 'video' && 'required|youtubeUrl'"
>
<v-text-field
append-icon="mdi-video"
v-model="videoUrl"
:disabled="mediaType === 'image'"
:label="$t('program.youtubeVideoUrl')"
:error-messages="errors"
clearable
/>
</validation-provider>
</v-card-text>
<v-card-actions class="py-6">
<v-btn
text
large
color="success"
v-text="$t('userActions.save')"
:disabled="invalid"
data-testid="save-btn"
@click="upload"
/>
<v-btn large v-text="$t('userActions.close')" text @click="close" />
</v-card-actions>
</validation-observer>
</v-card>
</v-dialog>
</v-row>
</template>
<script>
import { ValidationObserver, ValidationProvider } from "vee-validate"
export default {
components: { ValidationObserver, ValidationProvider },
props: {
value: {
type: Boolean,
required: true,
},
},
data() {
return {
image: null,
videoUrl: null,
mediaType: "image",
mediaTypeList: [
{
value: "image",
text: this.$t("general.image"),
},
{
value: "video",
text: this.$t("general.video"),
},
],
}
},
methods: {
close() {
this.$emit("input", false)
},
upload() {
const userInput = { mediaType: this.mediaType }
this.mediaType === "image"
? (userInput.imageUrl = this.image)
: (userInput.videoUrl = this.videoUrl)
this.$emit("upload", userInput)
this.$emit("input", false)
this.image = null
this.videoUrl = null
},
},
watch: {
mediaType(value) {
if (value === "image") {
this.videoUrl = null
return
}
this.image = null
},
},
}
</script>
<file_sep>const snackbar = {
namespaced: true,
state: {
text: "",
},
mutations: {
SHOW_MESSAGE(state, text) {
state.text = text
},
},
actions: {
showMessage({ commit }, text) {
commit("SHOW_MESSAGE", text)
},
},
}
export default snackbar
<file_sep>import Vue from "vue"
import VueI18n from "vue-i18n"
Vue.use(VueI18n)
function loadLocaleMessages() {
// return an object containing translations from specified locale JSON files
const fileNames = ["he"]
let messages = {}
for (let name of fileNames) {
messages[name] = require(`../locales/${name}.json`)
}
return messages
}
export default new VueI18n({
locale: "he",
fallbackLocale: "he",
messages: loadLocaleMessages(),
})
<file_sep>function get(cookieName) {
// return the cookie value corresponding to cookieName, void if doesn't exist
// :type cookieName: str
// :rtype: str
let allCookies = `; ${document.cookie}`
let splitByName = allCookies.split(`; ${cookieName}=`)
if (splitByName.length > 1) {
return splitByName.pop().split(";").shift()
}
}
function set(cookieName, cookieValue, days = undefined) {
// set cookie value to cookie name, for a specified number of days
// :type cookieName: str
// :type cookieValue: str
// :type days: int
let expiryString = ""
if (days) {
let date = new Date()
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)
expiryString = `; expires=${date.toUTCString()}`
}
document.cookie = `${cookieName}=${cookieValue}${expiryString}; path=/`
}
function erase(cookieName) {
// delete a cookie by changing expiry date
// :type cookieName: str
set(cookieName, "", -1)
}
const methods = { get, set, erase }
export default {
// this is a local plugin
install: function (Vue) {
Vue.prototype.$cookies = methods
Vue.$cookies = methods
},
}
<file_sep>import os
import pytest
from django.core import mail
from django.test import RequestFactory, override_settings
from rest_framework import status
from rest_framework.test import APIClient
from server.schools.models import SchoolMember
from server.users.api.views import UserViewSet
from server.users.models import BaseProfile, User
pytestmark = pytest.mark.django_db
RESET_BASE_URL = os.environ.get("GITPOD_WORKSPACE_URL")[8:]
class TestUserViewSet:
def test_get_queryset(self, user: User, rf: RequestFactory):
view = UserViewSet()
request = rf.get("/fake-url/")
request.user = user
view.request = request
assert user in view.get_queryset()
def test_me(self, user: User, rf: RequestFactory):
view = UserViewSet()
request = rf.get("/fake-url/")
request.user = user
view.request = request
response = view.me(request)
assert response.data == {
"slug": user.username,
"email": user.email,
"name": user.name,
"url": f"http://testserver/api/users/{user.username}/",
"user_type": user.user_type,
}
class TestManageConsumersView:
url = "/api/manage_consumers/"
@override_settings(
DEBUG=True,
RESET_BASE_URL="https://8000-{0}".format(RESET_BASE_URL),
)
def test_coordinator_can_create_get_consumer(self, coordinator, school):
create_payload = {
"name": "name",
"email": "<EMAIL>",
"profile": {"gender": BaseProfile.Gender.MALE},
}
SchoolMember.objects.create(user=coordinator, school=school)
client = APIClient(coordinator)
client.force_authenticate(coordinator)
# create consumer
consumer_post_response = client.post(self.url, create_payload, format="json")
consumer_slug = consumer_post_response.data["slug"]
detail_url = f"{self.url}{consumer_slug}/"
# get created consumer (via list & detailed)
consumer_list_get_response = client.get(self.url)
consumer_detail_get_response = client.get(detail_url)
assert (
consumer_list_get_response.status_code
== consumer_detail_get_response.status_code
== status.HTTP_200_OK
)
# validate get requests
list_results = consumer_list_get_response.data["results"]
assert len(list_results) == 1
assert list_results[0] == consumer_detail_get_response.data
assert list_results[0]["name"] == create_payload["name"]
# currently a bug - waiting for resolve:
# check post response: check nested serializer changed from default value
# assert (
# consumer_post_response.data["profile"]["gender"]
# == create_payload["profile"]["gender"]
# )
@override_settings(
DEBUG=True,
RESET_BASE_URL="https://8000-{0}".format(RESET_BASE_URL),
)
def test_email_on_create(self, coordinator, school):
"""
make sure an email is sent on creation
"""
create_payload = {"email": "<EMAIL>", "profile": {}}
SchoolMember.objects.create(user=coordinator, school=school)
client = APIClient(coordinator)
client.force_authenticate(coordinator)
client.post(self.url, create_payload, format="json")
assert len(mail.outbox) == 1
assert mail.outbox[0].to[0] == create_payload["email"]
def test_email_on_update(self, all_entities):
"""
make sure an email is sent on email update only
"""
email = "<EMAIL>"
client = APIClient(all_entities["coord"])
client.force_authenticate(all_entities["coord"])
client.patch(
f"{self.url}{all_entities['consumer'].slug}/",
{"email": email},
format="json",
)
client.patch(
f"{self.url}{all_entities['consumer'].slug}/",
{"name": "Dave"},
format="json",
)
assert len(mail.outbox) == 1
assert mail.outbox[0].to[0] == email
class TestManageCoordinatorsView:
url = "/api/manage_coordinators/"
@override_settings(
DEBUG=True,
RESET_BASE_URL="https://8000-{0}".format(RESET_BASE_URL),
)
def test_coordinator_can_create_get_coordinators(self, coordinator, school):
create_payload = {
"name": "name",
"email": "<EMAIL>",
}
SchoolMember.objects.create(user=coordinator, school=school)
client = APIClient(coordinator)
client.force_authenticate(coordinator)
# create coord
coordinator_post_response = client.post(self.url, create_payload, format="json")
coordinator_slug = coordinator_post_response.data["slug"]
detail_url = f"{self.url}{coordinator_slug}/"
# get created coord (via list & detailed)
coordinator_list_get_response = client.get(self.url)
coordinator_detail_get_response = client.get(detail_url)
assert (
coordinator_list_get_response.status_code
== coordinator_detail_get_response.status_code
== status.HTTP_200_OK
)
# validate get requests
list_results = coordinator_list_get_response.data["results"]
assert len(list_results) == 2
assert (
len(
[
res
for res in list_results
if res == coordinator_detail_get_response.data
and res["name"] == create_payload["name"]
]
)
== 1
)
@override_settings(
DEBUG=True,
RESET_BASE_URL="https://8000-{0}".format(RESET_BASE_URL),
)
def test_email_on_create(self, coordinator, school):
"""
make sure an email is sent on creation
"""
create_payload = {"email": "<EMAIL>"}
SchoolMember.objects.create(user=coordinator, school=school)
client = APIClient(coordinator)
client.force_authenticate(coordinator)
client.post(self.url, create_payload, format="json")
assert len(mail.outbox) == 1
assert mail.outbox[0].to[0] == create_payload["email"]
def test_email_on_update(self, all_entities):
"""
make sure an email is sent on email update only
"""
email = "<EMAIL>"
client = APIClient(all_entities["coord"])
client.force_authenticate(all_entities["coord"])
client.patch(
f"{self.url}{all_entities['coord'].slug}/",
{"email": email},
format="json",
)
client.patch(
f"{self.url}{all_entities['coord'].slug}/",
{"name": "Dave"},
format="json",
)
assert len(mail.outbox) == 1
assert mail.outbox[0].to[0] == email
<file_sep># Generated by Django 3.1.11 on 2021-07-18 09:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organizations', '0018_activity_tags'),
]
operations = [
migrations.AlterField(
model_name='activity',
name='domain',
field=models.CharField(blank=True, choices=[('SCIENCE_AND_TECH', 'Science And Tech'), ('EXTREME_SPORTS', 'Extreme Sports'), ('FIELD', 'Field')], max_length=55, null=True),
),
]
<file_sep># Generated by Django 3.1.11 on 2021-05-20 11:05
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import server.schools.models
import server.utils.model_fields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='School',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.CharField(default=server.schools.models.random_slug, max_length=40, unique=True)),
('name', models.CharField(max_length=50)),
('address', models.CharField(max_length=50)),
('address_city', models.CharField(max_length=50)),
('zip_city', models.CharField(max_length=15)),
('school_code', models.CharField(max_length=15)),
('description', models.CharField(max_length=150)),
('contact_phone', server.utils.model_fields.PhoneNumberField(max_length=15)),
('website', models.URLField()),
('profile_picture', models.ImageField(blank=True, null=True, upload_to='')),
('grade_levels', models.JSONField()),
],
),
migrations.CreateModel(
name='SchoolMemeber',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('school', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='schools.school')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
<file_sep>import Api from "../../api"
import Utils from "../../helpers/utils"
function getDefaultState() {
return {
eventList: [],
totalEvents: null,
feedPosts: [],
totalFeedPosts: null,
}
}
const instructorEvent = {
namespaced: true,
state: getDefaultState(),
mutations: {
FLUSH_STATE(state) {
Object.assign(state, getDefaultState())
},
SET_EVENTS_LIST(state, eventList) {
state.eventList = eventList
},
SET_EVENTS_TOTAL(state, total) {
state.totalEvents = total
},
SET_FEED_POSTS_LIST(state, posts) {
state.feedPosts = posts
},
SET_FEED_POSTS_TOTAL(state, total) {
state.totalFeedPosts = total
},
ADD_FEED_POSTS_TO_LIST(state, posts) {
state.feedPosts.push(...posts)
},
},
actions: {
flushState({ commit }) {
commit("FLUSH_STATE")
},
async getEvent(ctx, slug) {
let res = await Api.instructorEvent.getEvent(slug)
return res.data
},
async updateEvent(ctx, { slug, data }) {
let res = await Api.instructorEvent.updateEvent(slug, data)
return res.data
},
async getFeedPosts({ commit, rootGetters }, override = true) {
const params = rootGetters["pagination/apiParams"]
let res = await Api.instructorEvent.getFeedPosts(params)
const mutation = override
? "SET_FEED_POSTS_LIST"
: "ADD_FEED_POSTS_TO_LIST"
commit(mutation, res.data.results)
commit("SET_FEED_POSTS_TOTAL", res.data.count)
return res.data.results
},
async createFeedPost(ctx, data) {
let res = await Api.instructorEvent.createFeedPost(data)
return res.data
},
async createPostImages(ctx, data) {
let res = await Api.instructorEvent.createPostImages(data)
return res.data
},
async getPastEvents({ commit, state }, { daysAgo, unsummarizedOnly }) {
// :Number daysAgo: days ago to get the events from (e.g., 21 means all events 3 weeks ago until today)
const startDateString = Utils.dateToApiString(
Utils.addDaysToToday(-daysAgo)
)
const endDateString = Utils.dateToApiString(Utils.addDaysToToday(0))
const params = {
start_time__gte: startDateString,
start_time__lte: endDateString,
}
if (unsummarizedOnly) {
params.has_summary = false
}
let res = await Api.instructorEvent.getEventList(params)
commit("SET_EVENTS_LIST", res.data.results)
commit("SET_EVENTS_TOTAL", res.data.count)
return state.eventList
},
},
}
export default instructorEvent
<file_sep>import { action } from "@storybook/addon-actions"
import EditableAvatar from "../components/Avatar/EditableAvatar"
export default {
title: "EditableAvatar",
component: EditableAvatar,
}
const Template = args => ({
components: { EditableAvatar },
methods: { action },
data: () => ({ args }),
template: `
<editable-avatar
style="width: 200px;"
class="mx-auto"
v-model="args.avatarOptions"
/>
`,
})
export const Primary = Template.bind({})
Primary.args = {
avatarOptions: {},
}
<file_sep>from django.contrib import admin
from .models import (
Activity,
ActivityMedia,
ImportedActivity,
ImportedOrganization,
Organization,
OrganizationMember,
SchoolActivityGroup,
SchoolActivityOrder,
)
def approve_order(self, request, queryset):
for order in queryset:
order.status = SchoolActivityOrder.Status.APPROVED
order.save()
approve_order.short_description = "Approve Selected Orders"
class OrganizationMemberTabularInline(admin.TabularInline):
model = OrganizationMember
min_num = 1
@admin.register(SchoolActivityOrder)
class SchoolActivityOrderAdmin(admin.ModelAdmin):
list_display = ["school", "activity", "created_at", "updated_at", "status"]
search_fields = ["school__name", "activity__name"]
actions = [approve_order]
@admin.register(Activity)
class ActivityAdmin(admin.ModelAdmin):
list_display = ["slug", "name", "originization", "tags"]
search_fields = ["name"]
@admin.register(SchoolActivityGroup)
class SchoolActivityGroupAdmin(admin.ModelAdmin):
list_display = [
"slug",
"name",
"school",
"activity",
"group_type",
"instructor",
"activity_order",
]
def school(self, obj):
return obj.activity_order.school
def activity(self, obj):
return obj.activity_order.activity
admin.site.register(Organization)
admin.site.register(ActivityMedia)
admin.site.register(OrganizationMember)
admin.site.register(ImportedOrganization)
admin.site.register(ImportedActivity)
<file_sep><template>
<div>
<v-sheet tile height="70" class="d-flex mx-auto" max-width="500">
<v-toolbar flat>
<v-btn icon class="ma-2" @click="$refs.calendar.prev()">
<v-icon>mdi-chevron-right</v-icon>
</v-btn>
<v-select
value="displayType"
@input="onDisplayTypeChange"
:items="displayTypes"
dense
outlined
hide-details
class="ma-2"
:label="$t('general.display')"
/>
<v-btn icon class="ma-2" @click="$refs.calendar.next()">
<v-icon>mdi-chevron-left</v-icon>
</v-btn>
<v-btn
outlined
color="grey darken-1"
class="ma-2"
@click="e => $emit('input', '')"
v-text="$t('time.today')"
/>
</v-toolbar>
</v-sheet>
<calendar
ref="calendar"
v-bind="$attrs"
v-on="$listeners"
:type="displayType"
:value="value"
@input="e => $emit('input', e)"
/>
</div>
</template>
<script>
import Calendar from "./Calendar.vue"
export default {
components: { Calendar },
inheritAttrs: false,
props: {
value: {
// pass empty string for current date
required: true,
type: [String, Number, Date],
},
displayType: {
type: String,
required: true,
validator(value) {
return ["month", "week", "day", "4day"].includes(value)
},
},
},
methods: {
onDisplayTypeChange(e) {
this.$emit("update:displayType", e)
},
},
data() {
return {
displayTypes: [
{
text: this.$t("time.monthly"),
value: "month",
},
{
text: this.$t("time.weekly"),
value: "week",
},
{
text: this.$t("time.daily"),
value: "day",
},
{
text: this.$t("time.halfWeekly"),
value: "4day",
},
],
}
},
}
</script>
<file_sep><template>
<div class="pt-8 pa-lg-16">
<v-row class="mx-0">
<v-col cols="12" lg="7">
<div class="d-sm-flex justify-space-between mb-10">
<div>
<h1 v-text="$t('groups.groupPage')" class="mb-5" />
<h2 v-text="$t('groups.editAndViewTheGroupDetails')" class="" />
</div>
<v-btn
tile
large
color="error"
class="mx-auto mx-sm-0 d-block my-10 my-sm-0"
@click="isModalOpen = true"
>
{{ $t("userActions.delete") }}
<v-icon right> mdi-close </v-icon>
</v-btn>
</div>
<validation-observer
tag="form"
v-slot="{ invalid }"
@submit.prevent="onSubmit"
>
<input-drawer
unique-name="name"
:label="$t('groups.groupName')"
rules="required"
v-model="name"
/>
<input-drawer
unique-name="description"
:label="$t('general.description')"
rules="required"
v-model="description"
/>
<v-btn
class="my-16 py-5 white--text"
type="submit"
color="primary"
elevation="3"
v-text="$t('userActions.save')"
:disabled="invalid"
/>
<v-btn
class="my-16 mx-2 mx-lg-8 py-5 white--text"
elevation="3"
type="button"
color="primary"
outlined
v-text="$t('groups.viewAndEditStudents')"
@click="
$router.push({
name: 'AssignGroupConsumers',
params: { groupSlug },
})
"
/>
</validation-observer>
</v-col>
<v-col cols="12" lg="5">
<sticky-note>
{{ this.$t("groups.thisGroupIsUnderProgram") }}
"{{ this.programName }}"
</sticky-note>
<sticky-note class="mt-14">
{{ this.$t("groups.numberOfStudentsSignedInToThisGroup") }}:
{{ this.consumersNumber }}
</sticky-note>
</v-col>
</v-row>
<modal-approve v-model="isModalOpen" @approve="handleDelete">
{{ this.$t("confirm.AreYouSureYouWantToDeleteThisGroup?") }}
</modal-approve>
</div>
</template>
<script>
import { ValidationObserver } from "vee-validate"
import { mapActions } from "vuex"
import debounce from "lodash/debounce"
import Api from "../api"
import store from "../vuex/store"
import inputDrawer from "../components/InputDrawer"
import StickyNote from "../components/StickyNote"
import ModalApprove from "../components/ModalApprove"
export default {
components: { ValidationObserver, inputDrawer, StickyNote, ModalApprove },
async beforeRouteEnter(to, from, next) {
const group = await store.dispatch(
"programGroup/getGroup",
to.params.groupSlug
)
next(vm => {
vm.name = group.name
vm.description = group.description
vm.programName = group.activityName
vm.consumersNumber = group.consumers.length
})
},
props: {
groupSlug: {
type: String,
required: true,
},
},
data() {
return {
isModalOpen: false,
name: "",
description: "",
programName: "",
consumersNumber: 0,
}
},
methods: {
...mapActions("programGroup", ["updateGroup", "deleteGroup"]),
...mapActions("snackbar", ["showMessage"]),
onSubmit: debounce(
async function () {
try {
await this.updateGroup({
groupSlug: this.groupSlug,
data: {
name: this.name,
description: this.description,
},
})
this.showMessage(this.$t("general.detailsSuccessfullyUpdated"))
this.$router.push({ name: "MyGroups" })
} catch (err) {
this.showMessage(Api.utils.parseResponseError(err))
}
},
500,
{ leading: true, trailing: false }
),
async handleDelete() {
try {
await this.deleteGroup(this.groupSlug)
this.showMessage(this.$t("groups.groupDeletedSuccessfully"))
this.$router.push({ name: "MyGroups" })
} catch (err) {
this.showMessage(Api.utils.parseResponseError(err))
}
},
},
}
</script>
<file_sep>from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from server.organizations.admin import OrganizationMemberTabularInline
from server.schools.admin import SchoolMemberTabularInline
from server.users.forms import UserChangeForm
from server.users.helpers import send_user_invite
from .models import (
Consumer,
ConsumerProfile,
Coordinator,
CoordinatorProfile,
Instructor,
InstructorProfile,
Supervisor,
SupervisorProfile,
Vendor,
VendorProfile,
)
User = get_user_model()
def send_invite(self, request, queryset):
for user in queryset:
send_user_invite(user.email)
send_invite.short_description = "Invite user"
@admin.register(User, Supervisor)
class BaseUserTypesAdmin(auth_admin.UserAdmin):
form = UserChangeForm
fieldsets = (
(_("Account info"), {"fields": ("slug", "email", "password", "user_type")}),
(_("Personal info"), {"fields": ("name",)}),
(
_("Permissions"),
{
"fields": (
"is_active",
"is_staff",
"is_superuser",
"groups",
"user_permissions",
),
},
),
(_("Important dates"), {"fields": ("last_login", "date_joined")}),
)
add_fieldsets = (
(None, {"classes": ("wide",), "fields": ("email", "password1", "password2")}),
)
list_display = ["email", "slug"]
search_fields = ["email"]
actions = [send_invite]
@admin.register(Coordinator, Consumer)
class SchoolUserTypesAdmin(BaseUserTypesAdmin):
inlines = [SchoolMemberTabularInline]
@admin.register(Instructor, Vendor)
class OrgUserTypesAdmin(BaseUserTypesAdmin):
inlines = [OrganizationMemberTabularInline]
admin.site.register(CoordinatorProfile)
admin.site.register(ConsumerProfile)
admin.site.register(InstructorProfile)
admin.site.register(VendorProfile)
admin.site.register(SupervisorProfile)
<file_sep># Generated by Django 3.1.11 on 2021-07-27 13:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('schools', '0008_importedschool'),
]
operations = [
migrations.RenameField(
model_name='school',
old_name='zip_city',
new_name='address_zipcode',
),
]
<file_sep><template>
<transition name="modal">
<div class="modal-mask" data-testid="modal">
<div class="modal-wrapper">
<div class="modal-container">
<div class="text-h6 font-weight-bold text-center">
<slot name="header">
{{ $t("general.message") }}
</slot>
</div>
<div class="mb-11 mt-5 mx-3 text-center">
<slot>
<!-- Default slot: body text -->
</slot>
</div>
<v-btn
class="d-block mx-auto"
@click="onBtnClick"
data-testid="modal-button"
>
<slot name="btn">
{{ $t("general.understood") }}
</slot>
</v-btn>
</div>
</div>
</div>
</transition>
</template>
<script>
import debounce from "lodash/debounce"
export default {
props: {
redirectUrl: {
// URL to redirect to on button click
type: String,
required: false,
},
redirectComponentName: {
type: String,
required: false,
},
},
methods: {
onBtnClick: debounce(
function () {
if (this.redirectUrl) {
this.$router.push({ path: this.redirectUrl })
} else if (this.redirectComponentName) {
this.$router.push({ name: this.redirectComponentName })
} else {
this.$emit("close")
}
},
500,
{ leading: true, trailing: false }
),
},
}
</script>
<style lang="scss" scoped>
.modal-mask {
position: fixed;
z-index: 9998;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: table;
transition: opacity 0.3s ease;
}
.modal-wrapper {
display: table-cell;
vertical-align: middle;
}
.modal-container {
width: min(370px, 90vw);
margin: 0px auto;
padding: 20px 30px;
background-color: white;
border-radius: 2px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.33);
transition: all 0.3s ease;
}
// following are transition-related styling
.modal-enter {
opacity: 0;
}
.modal-leave-active {
opacity: 0;
}
.modal-enter .modal-container,
.modal-leave-active .modal-container {
-webkit-transform: scale(1.1);
transform: scale(1.1);
}
</style>
<file_sep><template>
<v-row justify="center">
<v-dialog v-if="program" :value="value" @input="close" width="540px">
<v-card class="px-5">
<v-card-title v-text="program.name" class="py-8 justify-center" />
<v-card-text>
<title-to-text
v-if="program.organization"
:text="program.organization"
:title="$t('program.organization')"
/>
<title-to-text
v-if="program.targetAudience.length"
:text="program.targetAudience.map(num => $t(`grades.${num}`)).join(', ')"
:title="$t('program.targetAudience')"
/>
<title-to-text
v-if="program.description"
:text="program.description"
:title="$t('program.description')"
/>
<title-to-text
v-if="program.contactName"
:text="program.contactName"
:title="$t('program.contactName')"
/>
<title-to-text
v-if="program.phoneNumber"
:text="program.phoneNumber"
:title="$t('program.contactPhone')"
/>
<title-to-text
v-if="program.domain"
:text="program.domain"
:title="$t('program.domain')"
/>
</v-card-text>
<carousel
v-if="mediaList.length"
:media-list="mediaList"
/>
<v-card-actions class="py-6">
<v-btn
large
class="mx-auto"
v-text="$t('userActions.close')"
color="orange"
text
@click="close"
/>
</v-card-actions>
</v-card>
</v-dialog>
</v-row>
</template>
<script>
import TitleToText from "../components/TitleToText"
import Carousel from "../components/Carousel"
export default {
components: { TitleToText, Carousel },
props: {
value: {
// indicates whether dialog is open or not
type: Boolean,
required: true,
},
program: {
type: Object,
required: true,
},
mediaList: {
type: Array,
required: true,
},
},
methods: {
close() {
this.$emit("input", false)
},
},
}
</script>
<style lang="scss" scoped>
.carousel {
width: 85%;
}
</style>
<file_sep># Generated by Django 3.1.11 on 2021-06-24 15:22
from django.db import migrations, models
import server.utils.model_fields
class Migration(migrations.Migration):
dependencies = [
('events', '0003_auto_20210624_1822'),
]
operations = [
migrations.AlterField(
model_name='event',
name='slug',
field=models.CharField(default=server.utils.model_fields.random_slug, max_length=40, unique=True),
),
]
<file_sep># Generated by Django 3.1.11 on 2021-07-25 11:24
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import server.utils.model_fields
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('taggit', '0003_taggeditem_add_unique_index'),
('organizations', '0021_auto_20210725_1409'),
]
operations = [
migrations.CreateModel(
name='ImportedActivity',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.CharField(default=server.utils.model_fields.random_slug, max_length=40, unique=True)),
('activity_code', models.IntegerField()),
('name', models.CharField(max_length=550)),
('raw_name', models.CharField(max_length=550)),
('target_audience', models.JSONField()),
('domain', models.CharField(blank=True, choices=[('SCIENCE_AND_TECH', 'Science And Tech'), ('EXTREME_SPORTS', 'Extreme Sports'), ('FIELD', 'Field')], max_length=55, null=True)),
('organization_number', models.IntegerField()),
('organization_name', models.CharField(default='', max_length=1550)),
('target_gender', models.JSONField()),
('target_population', models.JSONField()),
('target_time', models.JSONField()),
('target_size', models.JSONField()),
('target_migzar', models.JSONField()),
('target_pikuah', models.JSONField()),
('proffesion', models.JSONField()),
('goal', models.CharField(default='', max_length=1550)),
('is_active', models.BooleanField()),
('activity_website_url', models.URLField(blank=True, null=True)),
('activity_email', models.EmailField(blank=True, max_length=254, null=True)),
('description', models.CharField(default='', max_length=1550)),
('contact_name', models.CharField(default='', max_length=100)),
('logo', models.ImageField(blank=True, null=True, upload_to='')),
('phone_number', models.CharField(blank=True, max_length=15, validators=[django.core.validators.RegexValidator(message='phone number must be between 9-15 digits', regex='^\\d{9,15}$')])),
('originization', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='organizations.organization')),
('tags', taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags')),
],
),
]
<file_sep>release: cd server && python manage.py migrate
frontend: bin/boot
web: cd server && gunicorn config.asgi:application -k uvicorn.workers.UvicornWorker
worker: cd server && celery worker --app=config.celery_app --loglevel=info
beat: cd server && celery beat --app=config.celery_app --loglevel=info
<file_sep><template>
<v-card class="mx-auto" max-width="500" v-bind="$attrs">
<v-toolbar :color="color" :dark="dark">
<v-toolbar-title v-text="title" />
<v-spacer />
</v-toolbar>
<v-list two-line>
<v-list-item-group
:value="selected"
@change="emitChange"
:active-class="`${color}--text`"
multiple
>
<div v-for="(item, index) in items" :key="index">
<v-list-item>
<v-list-item-content>
<v-list-item-title v-text="item.title" />
<v-list-item-subtitle
class="text--primary"
v-text="item.headline"
/>
<v-list-item-subtitle v-text="item.subtitle" />
</v-list-item-content>
<div
color="grey lighten-2"
class="text-caption mb-6"
v-text="item.action"
/>
</v-list-item>
<v-divider v-if="index < items.length - 1" />
</div>
</v-list-item-group>
</v-list>
</v-card>
</template>
<script>
export default {
inheritAttrs: false,
model: {
prop: "selected",
},
props: {
selected: {
type: Array,
required: true,
},
title: {
type: String,
default: "",
},
items: {
// array of objs, containing caption, headline, subtitle, title
type: Array,
required: true,
},
color: {
// vuetify color pallete
type: String,
default: "primary",
},
dark: {
type: Boolean,
default: true,
},
},
methods: {
emitChange(e) {
this.$emit("input", e)
},
},
}
</script>
<file_sep>import TitleToText from "../components/TitleToText.vue"
//👇 This default export determines where your story goes in the story list
export default {
title: "TitleToText",
component: TitleToText,
}
//👇 We create a “template” of how args map to rendering
const Template = args => ({
components: { TitleToText },
data: () => ({ args }),
template: '<title-to-text v-bind="args" />',
})
export const Primary = Template.bind({})
Primary.args = {
text: "text",
title: "title",
}
<file_sep><template>
<div>
<v-row class="pt-10 ml-0">
<v-col
cols="4"
md="3"
class="right-pane white-bg"
:class="{ 'pr-10': !$vuetify.breakpoint.mobile }"
>
<pagination-checkbox-group
v-for="filter in PROGRAMS_CHECKBOX_FILTERS"
:key="filter.id"
:name="filter.name"
:title="filter.readableName"
:items="filter.options"
class="checkbox-group"
:class="{ 'checkbox-small': $vuetify.breakpoint.mobile }"
/>
</v-col>
<v-col cols="8" md="9" :class="{ 'px-10': !$vuetify.breakpoint.mobile }">
<h1 v-text="$t('program.programsExplorer')" class="pb-6" />
<h3
v-text="
$t(
'program.findForProgramsThatFitTheSchoolPedagogicalApproachAndStartCollaborating!'
)
"
/>
<pagination-search-bar class="search-bar mx-auto pt-16" />
<div class="text-center pt-10 overline">
{{ totalPrograms }} {{ $t("program.programsFound") }}
</div>
<v-row
dense
justify="space-between"
class="cards-wrapper mx-auto py-10"
>
<v-col
cols="12"
sm="6"
lg="4"
class="py-10"
v-for="program in programsList"
:key="program.id"
>
<info-card
v-model="program.isOrdered"
:imgUrl="program.logo"
:title="program.name"
:subtitle="getCardSubtitle(program.orderStatus)"
:button-text="$t('program.forProgramDetails')"
@input="e => onStarChange(program, e)"
@click="openProgram(program.slug)"
>
{{ program.description | trimText(70) }}
</info-card>
</v-col>
</v-row>
</v-col>
</v-row>
<router-view v-model="isProgramOpen" />
<end-of-page-detector @end-of-page="onEndOfPage" />
</div>
</template>
<script>
import { mapActions, mapGetters, mapState } from "vuex"
import Api from "../../api"
import InfoCard from "../../components/InfoCard"
import PaginationCheckboxGroup from "../../components/PaginationCheckboxGroup"
import PaginationSearchBar from "../../components/PaginationSearchBar"
import EndOfPageDetector from "../../components/EndOfPageDetector"
import {
PROGRAMS_CHECKBOX_FILTERS,
SERVER,
} from "../../helpers/constants/constants"
export default {
components: {
InfoCard,
PaginationCheckboxGroup,
PaginationSearchBar,
EndOfPageDetector,
},
computed: {
...mapState("program", ["programsList", "totalPrograms"]),
...mapGetters("school", ["schoolSlug"]),
},
methods: {
...mapActions("snackbar", ["showMessage"]),
...mapActions("pagination", ["incrementPage", "updatePagination"]),
...mapActions("program", [
"getProgramsList",
"createProgramOrder",
"cancelProgramOrder",
"reCreateProgramOrder",
]),
onEndOfPage() {
// trigger programs load on end of page
this.recentlyScrolled = true
this.incrementPage()
},
openProgram(slug) {
this.isProgramOpen = true
this.$router.push({ name: "ProgramModal", params: { slug } })
},
async getPrograms() {
if (this.recentlyScrolled) {
this.recentlyScrolled = false
if (this.totalPrograms > this.programsList.length) {
// add new programs if there are items left to fetch. do not override.
this.getProgramsList(false)
}
} else {
// fetch & ovrride programs list
this.updatePagination({ page: 1 })
this.getProgramsList(true)
}
},
getCardSubtitle(orderStatus) {
const prefix = this.$t("general.status")
let status = this.$t("program.available")
if (orderStatus) {
status = this.$t(`program.${orderStatus}`)
}
return `${prefix}: ${status}`
},
async onStarChange(program, isStarred) {
// (dis)request a program and change order status accordingly
try {
if (isStarred) {
await this.requestProgram(program)
this.showMessage(this.$t("success.programJoinRequestSent"))
} else {
await this.disRequestProgram(program)
this.showMessage(this.$t("success.programParticipationCancelled"))
}
} catch (err) {
this.showMessage(Api.utils.parseResponseError(err))
}
},
requestProgram(program) {
if (program.orderStatus === SERVER.programOrderStatus.cancelled) {
return this.reCreateProgramOrder({
schoolSlug: this.schoolSlug,
programSlug: program.slug,
})
}
return this.createProgramOrder({
schoolSlug: this.schoolSlug,
programSlug: program.slug,
})
},
disRequestProgram(program) {
return this.cancelProgramOrder({
schoolSlug: this.schoolSlug,
programSlug: program.slug,
})
},
},
data() {
return {
PROGRAMS_CHECKBOX_FILTERS,
recentlyScrolled: false,
isProgramOpen: true,
}
},
watch: {
"$store.state.pagination": {
// re-fetch if pagination changed
deep: true,
handler() {
this.getPrograms()
},
},
isProgramOpen(value) {
// route back on close
if (!value) {
this.$router.push({ name: "ProgramsExplorer" })
}
},
},
}
</script>
<style lang="scss" scoped>
.cards-wrapper {
max-width: 1200px;
}
.right-pane {
border-left: $light-grey 1px solid;
}
.checkbox-group {
float: right;
width: 100%;
}
.checkbox-small::v-deep label {
font-size: 12px;
}
.search-bar {
max-width: 450px;
}
</style>
<file_sep># Generated by Django 3.1.11 on 2021-05-30 07:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('schools', '0002_auto_20210523_1507'),
]
operations = [
migrations.AlterField(
model_name='schoolmember',
name='school',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='school_member', to='schools.school'),
),
]
<file_sep>import csv
import json
import logging
import re
import requests
from django.core.management.base import BaseCommand
import server.organizations.management.commands.config as config
from server.organizations.models import ImportedOrganization
logger = logging.getLogger(__name__)
ajax_data = {
"Content-Type": "application/json",
"action": "GSTAR_Ctrl",
"data": ["580430767"],
"method": "getMalkarDetails",
"tid": 14,
"type": "rpc",
"ctx": {
"csrf": "<KEY>",
"ns": "",
"ver": 43,
"vid": "06624000000VGgM",
},
}
ajax_headers = {
"Referer": "https://www.guidestar.org.il/search-malkars?Sug_Hitagdut=%D7%A2%D7%9E%D7%95%D7%AA%D7%94"
}
ajax_get_ids = {
"action": "GSTAR_Ctrl",
"method": "searchMalkars",
"data": [{}, {"apiName": "Name", "sortDesc": False}],
"type": "rpc",
"tid": 10,
"ctx": {
"csrf": "<KEY>",
"vid": "06624000000VGgM",
"ns": "",
"ver": 43,
},
}
ajax_amount_of_results = {
"action": "GSTAR_Ctrl",
"method": "getSeachMalkarCount",
"data": [
{"Sug_Hitagdut": ["עמותה"], "CLSS_Main_Classification_Num": ["21"]},
{"apiName": "Name", "sortDesc": False},
],
"type": "rpc",
"tid": 13,
"ctx": {
"csrf": "<KEY>",
"vid": "06624000000VGgM",
"ns": "",
"ver": 43,
},
}
AJAX_URL = "https://www.guidestar.org.il/apexremote"
ROOT_URL = "https://www.guidestar.org.il"
class Command(BaseCommand):
help = "Fetch schools from gov site and load to db"
def add_arguments(self, parser):
parser.add_argument("--csv", action="store_true")
def get_csrf(self):
"""
This function should get from the site the csrf in order to send the request.
:return string
"""
_response = requests.get(ROOT_URL)
_response.raise_for_status()
_response = _response.text
_csrf = re.findall(r'csrf":"([\w\d]+)"', _response)
# if csrf is in the page else return default value
if _csrf:
return _csrf[0]
return "<KEY>"
def get_total_results_from_guidestar(self):
"""
This function returns the total results to save into the DB.
:return: int
"""
ajax_amount_of_results["ctx"]["csrf"] = self.get_csrf()
post_response = requests.post(
AJAX_URL, json=ajax_amount_of_results, headers=ajax_headers
)
post_response.raise_for_status()
post_response = json.loads(post_response.text)
amount_of_results = post_response[0]["result"]
# In case their are more than 999 results
if "," in amount_of_results:
amount_of_results = int(amount_of_results.replace(",", ""))
else:
amount_of_results = int(amount_of_results)
return amount_of_results
def collect_ids_from_guidestar(self, amount_of_pages):
"""
This function should collect all the relevant ids in order to gather information about each company.
:param amount_of_pages: the number of pages should be collected
:return: list
"""
ids_collection = set()
last_company_name = ""
# Run for each iteration
for page_number in range(1, amount_of_pages):
logger.info("complete {}/{}".format(page_number, amount_of_pages))
# Set the requested page
ajax_get_ids["data"][0]["pageNumber"] = page_number
ajax_get_ids["ctx"]["csrf"] = self.get_csrf()
if page_number > 1:
ajax_get_ids["data"][1]["value"] = last_company_name
# Request for 50 more companies
post_response = requests.post(
AJAX_URL, json=ajax_get_ids, headers=ajax_headers
)
post_response.raise_for_status()
post_response = json.loads(post_response.text)
# Run for each company and saves the company's id
for company_json in post_response[0]["result"]["result"]:
ids_collection.add(company_json["regNum"])
last_company_name = company_json["Name"]
return list(ids_collection)
def collect_company_information(self, _id):
"""
This function should collect company information and return dictionary with
all the relevant data about the company.
:param _id: string represents the ID for a company
:return: Dictionary
"""
company_information = {}
# Set the requested ID
ajax_data["data"][0] = _id
ajax_data["ctx"]["csrf"] = self.get_csrf()
# Sending post request to collect the data
response = requests.post(AJAX_URL, json=ajax_data, headers=ajax_headers)
response.raise_for_status()
# Load the results
try:
results = json.loads(response.text)
except json.JSONDecodeError:
logger.info("failed to parse server response")
company = results[0]["result"]["result"]
# Check if organization object contains number field
for key in config.FIELDS.keys():
field = config.FIELDS[key]
if field == config.ORG_DESCRIPTION_FIELD:
if config.ORG_DESCRIPTION_FIELD in company.keys():
company_information[key] = company[
config.ORG_DESCRIPTION_FIELD
].get("description", None)
else:
company_information[key] = company.get(field, None)
return company_information
def handle(self, *args, **options):
self.fetch(options["csv"])
def fetch(self, should_write_csv):
"""
:bool should_write_csv: wheather to write to a csv file or not (i.e., dump to DB)
"""
# Calculates the amount of queries should be done in order to collect all IDs
total_results = self.get_total_results_from_guidestar()
logger.info("{} results found".format(total_results))
num_of_iterations = int(total_results / config.RESULTS_PER_PAGE + 1)
# Run for each page between 1, (total_iteration / per_page_results) + 1
logger.info("total iterations: {}".format(num_of_iterations))
companies_ids = self.collect_ids_from_guidestar(num_of_iterations)
# In case the user asked to write results to local csv
if should_write_csv:
fieldnames = [
"organization_number",
"email",
"description",
"website_url",
"name",
"goal",
"year_founded",
"status",
"target_audience",
"number_of_employees",
"number_of_members",
"number_of_volunteers",
"location_lon",
"location_lat",
"address_city",
"address_street",
"address_house_num",
"address_zipcode",
"cities",
"districts",
"union_type",
]
csv_file = open("organizations.csv", "w", encoding="UTF-8")
csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
csv_writer.writeheader()
# For each IP create the object
for _id in companies_ids:
org_data = self.collect_company_information(_id)
if org_data["cities"] is not None:
org_data["cities"] = ",".join(org_data["cities"])
if org_data["districts"] is not None:
districts = org_data["districts"]
districts = districts.replace('"', "").replace("'", "")
districts = districts.replace("[", "").replace("]", "").split(",")
org_data["districts"] = districts
if should_write_csv:
csv_writer.writerow(org_data)
csv_file.flush()
else:
ImportedOrganization.objects.update_or_create(
defaults=org_data,
organization_number=org_data["organization_number"],
)
<file_sep><template>
<div>
<table-rows-to-chips
class="my-14"
chipsLabelHeader="name"
v-model="selectedConsumers"
:headers="tableHeaders"
:items="availableConsumers"
/>
<div class="mx-auto mt-10 text-center">
<v-btn
class="mx-3 white--text primary"
data-testid="submit-button"
@click="onSubmit"
v-text="$t('userActions.save')"
/>
<v-btn
class="mx-3 white--text"
color="primary"
outlined
v-text="$t('userActions.back')"
@click="$router.go(-1)"
/>
</div>
</div>
</template>
<script>
import { mapActions } from "vuex"
import debounce from "lodash/debounce"
import store from "../vuex/store"
import Api from "../api"
import { SERVER } from "../helpers/constants/constants"
import TableRowsToChips from "../components/TableRowsToChips"
export default {
components: { TableRowsToChips },
props: {
groupSlug: {
type: String,
required: true,
},
},
async beforeRouteEnter(to, from, next) {
// fetch assigned & unassigned consumers
const group = await store.dispatch(
"programGroup/getGroup",
to.params.groupSlug
)
const groupConsumers = await store.dispatch(
"programGroup/getConsumers",
to.params.groupSlug
)
const containerGroups = await store.dispatch(
"programGroup/getGroupsByFilter",
{
group_type: SERVER.programGroupTypes.containerOnly,
activity_order__slug: group.activityOrder,
}
)
let unassignedConsumers = []
if (containerGroups.length) {
unassignedConsumers = await store.dispatch(
"programGroup/getConsumers",
containerGroups[0].slug
)
}
next(vm => {
vm.selectedConsumers = groupConsumers
vm.availableConsumers = [...groupConsumers, ...unassignedConsumers]
vm.containerGroup = containerGroups[0]
})
},
data() {
return {
selectedConsumers: [],
availableConsumers: [],
containerGroup: null,
tableHeaders: [
{ text: this.$t("general.name"), value: "name" },
{ text: this.$t("general.email"), value: "email" },
],
}
},
methods: {
...mapActions("programGroup", ["updateGroupConsumers"]),
...mapActions("snackbar", ["showMessage"]),
onSubmit: debounce(
async function () {
const consumerSlugs = this.selectedConsumers.map(c => c.slug)
if (this.containerGroup) {
try {
await this.updateGroupConsumers({
groupSlug: this.groupSlug,
consumerSlugs,
})
} catch (err) {
return this.showMessage(Api.utils.parseResponseError(err))
}
}
this.showMessage(this.$t("general.detailsSuccessfullyUpdated"))
this.$router.push({
name: "GroupDetail",
params: { groupSlug: this.groupSlug },
})
},
500,
{ leading: true, trailing: false }
),
},
}
</script>
<file_sep>from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from server.organizations.models import OrganizationMember
from server.schools.models import SchoolMember
from ..helpers import send_user_invite
from ..models import (
Consumer,
ConsumerProfile,
Coordinator,
CoordinatorProfile,
Instructor,
InstructorProfile,
Vendor,
VendorProfile,
)
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["slug", "name", "email", "url", "user_type"]
extra_kwargs = {
"url": {"view_name": "api:user-detail", "lookup_field": "username"}
}
class ConsumerProfileSerializer(serializers.ModelSerializer):
slug = serializers.ReadOnlyField(source="user.slug")
class Meta:
model = ConsumerProfile
fields = ["slug", "gender", "profile_picture"]
class CoordinatorProfileSerializer(serializers.ModelSerializer):
slug = serializers.ReadOnlyField(source="user.slug")
class Meta:
model = CoordinatorProfile
fields = [
"slug",
"gender",
"profile_picture",
"job_description",
"phone_number",
]
class InstructorProfileSerializer(serializers.ModelSerializer):
slug = serializers.ReadOnlyField(source="user.slug")
class Meta:
model = InstructorProfile
fields = ["slug", "gender", "profile_picture"]
class VendorProfileSerializer(serializers.ModelSerializer):
slug = serializers.ReadOnlyField(source="user.slug")
class Meta:
model = VendorProfile
fields = ["slug", "gender", "profile_picture", "phone_number"]
class ManageConsumersSerializer(serializers.ModelSerializer):
profile = ConsumerProfileSerializer()
class Meta:
model = Consumer
fields = ["slug", "name", "email", "profile"]
extra_kwargs = {
"email": {
"validators": [
UniqueValidator(queryset=User.objects.all(), lookup="iexact")
]
},
}
def create(self, validated_data):
"""
create user, update profile, attach to school, invite user via email
"""
profile_data = validated_data.pop("profile", None)
consumer = Consumer.objects.create(**validated_data)
if profile_data:
profile = ConsumerProfile.objects.get(user=consumer)
for attr, value in profile_data.items():
setattr(profile, attr, value)
profile.save()
SchoolMember.objects.create(
user=consumer, school=self.context["request"].user.school_member.school
)
send_user_invite(validated_data["email"])
return consumer
def update(self, instance, validated_data):
"""
update user & profile
"""
has_email_changed = validated_data.get(
"email"
) and instance.email != validated_data.get("email")
instance.name = validated_data.get("name", instance.name)
instance.email = validated_data.get("email", instance.email)
profile_data = validated_data.pop("profile", None)
if profile_data:
profile = instance.profile
for attr, value in profile_data.items():
setattr(profile, attr, value)
profile.save()
instance.save()
if has_email_changed:
send_user_invite(validated_data["email"])
return instance
class ManageCoordinatorsSerializer(serializers.ModelSerializer):
class Meta:
model = Coordinator
fields = ["slug", "name", "email"]
extra_kwargs = {
"email": {
"validators": [
UniqueValidator(queryset=User.objects.all(), lookup="iexact")
]
},
}
def create(self, validated_data):
"""
create user, attach to school, invite user via email
"""
coordinator = Coordinator.objects.create(**validated_data)
SchoolMember.objects.create(
user=coordinator, school=self.context["request"].user.school_member.school
)
send_user_invite(validated_data["email"])
return coordinator
def update(self, instance, validated_data):
has_email_changed = validated_data.get(
"email"
) and instance.email != validated_data.get("email")
instance.name = validated_data.get("name", instance.name)
instance.email = validated_data.get("email", instance.email)
instance.save()
if has_email_changed:
send_user_invite(validated_data["email"])
return instance
class ManageVendorsSerializer(serializers.ModelSerializer):
class Meta:
model = Vendor
fields = ["slug", "name", "email"]
extra_kwargs = {
"email": {
"validators": [
UniqueValidator(queryset=User.objects.all(), lookup="iexact")
]
},
}
def create(self, validated_data):
"""
create user, attach to org, invite user via email
"""
vendor = Vendor.objects.create(**validated_data)
OrganizationMember.objects.create(
user=vendor,
organization=self.context["request"].user.organization_member.organization,
)
send_user_invite(validated_data["email"])
return vendor
def update(self, instance, validated_data):
has_email_changed = validated_data.get(
"email"
) and instance.email != validated_data.get("email")
instance.name = validated_data.get("name", instance.name)
instance.email = validated_data.get("email", instance.email)
instance.save()
if has_email_changed:
send_user_invite(validated_data["email"])
return instance
class ManageInstructorsSerializer(serializers.ModelSerializer):
class Meta:
model = Instructor
fields = ["slug", "name", "email"]
extra_kwargs = {
"email": {
"validators": [
UniqueValidator(queryset=User.objects.all(), lookup="iexact")
]
},
}
def create(self, validated_data):
"""
create user, attach to org, invite user via email
"""
instructor = Instructor.objects.create(**validated_data)
OrganizationMember.objects.create(
user=instructor,
organization=self.context["request"].user.organization_member.organization,
)
send_user_invite(validated_data["email"])
return instructor
def update(self, instance, validated_data):
has_email_changed = validated_data.get(
"email"
) and instance.email != validated_data.get("email")
instance.name = validated_data.get("name", instance.name)
instance.email = validated_data.get("email", instance.email)
instance.save()
if has_email_changed:
send_user_invite(validated_data["email"])
return instance
<file_sep><template>
<div>
<v-card class="absolute-center py-12 px-7" width="320" elevation="16">
<v-card-title class="text-h4 justify-center mb-6">{{
$t("general.connective")
}}</v-card-title>
<v-card-subtitle class="text-h6 text-center mb-8">{{
$t("auth.chooseNewPassword")
}}</v-card-subtitle>
<validation-observer v-slot="{ invalid }">
<form @submit.prevent="onSubmit">
<validation-provider
v-slot="{ errors }"
name="password"
rules="required|strongPass"
>
<v-text-field
class="mt-5"
v-model="password"
:append-icon="showPass ? 'mdi-eye' : 'mdi-eye-off'"
:error-messages="errors"
:type="showPass ? 'text' : 'password'"
name="password"
:label="$t('auth.newPassword')"
@click:append="showPass = !showPass"
></v-text-field>
</validation-provider>
<validation-provider
v-slot="{ errors }"
name="passwordConfirmation"
rules="required|passConfirm:@password"
>
<v-text-field
class="mt-5"
v-model="passwordConfirmation"
:error-messages="errors"
type="password"
name="passwordConfirmation"
:label="$t('auth.reEnterPassword')"
></v-text-field>
</validation-provider>
<div class="mx-auto d-flex justify-center mt-12">
<v-btn
class="ml-3 white--text"
type="submit"
color="primary"
elevation="3"
:disabled="invalid"
>
{{ $t("auth.finishRegistration") }}
</v-btn>
</div>
</form>
</validation-observer>
</v-card>
<modal
:redirectUrl="modalRedirectUrl"
v-show="popupMsg !== ''"
@close="popupMsg = ''"
>
{{ popupMsg }}
<template v-if="modalRedirectUrl" v-slot:btn>
{{ $t("general.homepage") }}
</template>
</modal>
</div>
</template>
<script>
import { mapActions } from "vuex"
import { ValidationObserver, ValidationProvider } from "vee-validate"
import debounce from "lodash/debounce"
import Modal from "../components/Modal"
export default {
components: {
ValidationProvider,
ValidationObserver,
Modal,
},
props: {
uid: {
type: String,
required: true,
},
token: {
type: String,
required: true,
},
},
data: () => ({
showPass: false,
popupMsg: "",
identityNumber: "",
password: "",
passwordConfirmation: "",
// for redirection to login screen on success
modalRedirectUrl: "",
}),
methods: {
...mapActions("auth", ["resetPassword"]),
onSubmit: debounce(
function () {
this.resetPassword({
uid: this.uid,
token: this.token,
pass: <PASSWORD>,
passConfirm: <PASSWORD>,
})
.then(this.handleSubmitSuccess)
.catch(this.handleSubmitError)
},
500,
{ leading: true, trailing: false }
),
handleSubmitSuccess() {
this.modalRedirectUrl = "/"
this.popupMsg = this.$t("auth.registrationSucceeded") + "!"
},
handleSubmitError(msg) {
try {
if (msg.response.status === 400) {
this.handleBadRequestResponse(msg)
} else {
this.$router.push({ name: "Error" })
}
} catch (err) {
this.$router.push({ name: "Error" })
}
},
handleBadRequestResponse(msg) {
// handle status 400 server response
// redirect on form expiry, display popup msg otherwise
let errorKeys = Object.keys(msg.response.data)
if (errorKeys.includes("uid") || errorKeys.includes("token")) {
this.$router.push({
name: "Error",
params: { bodyKey: "auth.registrationFormExpired" },
})
} else {
// display the message received from the server
this.popupMsg = msg.response.data[errorKeys[0]][0]
}
},
},
}
</script>
<file_sep><template>
<div>
<v-card class="absolute-center py-12 px-7" width="320" elevation="16">
<v-card-title
id="letter-spacing-2"
class="text-h4 justify-center mb-3 font-weight-bold"
>{{ $t("general.connective") }}</v-card-title
>
<validation-observer ref="observer">
<form @submit.prevent="submit">
<validation-provider
v-slot="{ errors }"
name="email"
rules="required|email"
>
<v-text-field
data-testid="email-input"
class="mt-2"
v-model="email"
:error-messages="errors"
:label="$t('general.email')"
required
></v-text-field>
</validation-provider>
<validation-provider
v-slot="{ errors }"
name="password"
rules="required"
>
<v-text-field
data-testid="password-input"
class="mt-2"
v-model="password"
:append-icon="showPass ? 'mdi-eye' : 'mdi-eye-off'"
:error-messages="errors"
:type="showPass ? 'text' : 'password'"
name="password"
:label="$t('auth.password')"
@click:append="showPass = !showPass"
></v-text-field>
</validation-provider>
<div class="mx-auto d-flex justify-center mt-8 mb-4">
<v-btn
data-testid="login-btn"
class="white--text"
type="submit"
color="primary"
elevation="3"
block
>
{{ $t("auth.login") }}
</v-btn>
</div>
</form>
</validation-observer>
</v-card>
<modal v-show="popupMsg !== ''" @close="popupMsg = ''">
{{ popupMsg }}
</modal>
</div>
</template>
<script>
import { mapActions } from "vuex"
import debounce from "lodash/debounce"
import { ValidationObserver, ValidationProvider } from "vee-validate"
import Modal from "../components/Modal"
export default {
components: {
ValidationProvider,
ValidationObserver,
Modal,
},
data: () => ({
showPass: false,
popupMsg: "",
email: "",
password: "",
}),
methods: {
...mapActions("auth", ["login"]),
submit: debounce(
async function () {
if (!(await this.$refs.observer.validate())) return
this.login({ email: this.email, password: this.password }).catch(
this.displayLoginError
)
},
500,
{ leading: true, trailing: false }
),
displayLoginError(msg) {
try {
if (
Object.prototype.hasOwnProperty.call(msg, "response") &&
Object.prototype.hasOwnProperty.call(msg.response, "data")
) {
let error_msg = msg.response.data.nonFieldErrors[0]
if (error_msg === "Unable to log in with provided credentials.") {
this.popupMsg = this.$t("errors.invalidCreds")
return
}
}
this.popupMsg = this.$t("errors.genericError")
} catch (err) {
this.popupMsg = this.$t("errors.genericError")
}
},
},
}
</script>
<style lang="scss" scoped>
#letter-spacing-2 {
letter-spacing: 2px !important;
}
</style>
<file_sep>import i18n from "../../plugins/i18n"
import Utils from "../../helpers/utils"
import {
ISRAELI_PHONE_REGEX_PATTERN,
EMAIL_REGEX_PATTERN,
} from "../../helpers/constants/constants"
export function exportCSV(studentsArray) {
let csvData = Utils.arrayToCsvFormat(studentsArray)
Utils.downloadTextAsFile("invitations.csv", csvData)
}
export function validateStudentsArray(arr) {
// validate students array
// return empty string on success, error string on error
let obj = arr[0]
if (
!obj.identityNumber ||
!obj.firstName ||
!obj.city ||
!obj.phoneNumber ||
!obj.email
) {
return i18n.t("errors.missingColumnsOrValues")
}
for (let student of arr) {
if (!new RegExp(ISRAELI_PHONE_REGEX_PATTERN).test(student.phoneNumber)) {
return `${i18n.t("errors.invalidPhoneNumber")} - ${student.phoneNumber}`
}
if (!new RegExp(EMAIL_REGEX_PATTERN).test(student.email)) {
return `${i18n.t("errors.invalidEmail")} ${student.email}`
}
}
return ""
}
export function translateStatus(status) {
switch (status) {
case "pending_request_accept":
return this.$t("invite.pendingRecipientApproval")
case "registered":
return this.$t("auth.registrationSucceeded")
}
return status
}
<file_sep>function createBackendUrl() {
if (process.env.NODE_ENV === "development") {
if (process.env.GITPOD_WORKSPACE_URL) {
return `https://8000-${process.env.GITPOD_WORKSPACE_URL.slice(8)}/api`
}
return "http://localhost:8000/api"
}
return "https://calm-hamlet-63949.herokuapp.com/api"
}
process.env.VUE_APP_BACKEND_URL = createBackendUrl()
module.exports = {
devServer: {
disableHostCheck: true,
},
transpileDependencies: ["vuetify"],
pages: {
index: {
entry: "src/main.js",
title: "Connective",
},
},
pluginOptions: {
i18n: {
locale: "he",
fallbackLocale: "he",
localeDir: "locales",
enableInSFC: false,
},
},
}
<file_sep>from django.core.validators import RegexValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
from taggit.managers import TaggableManager
from server.schools.models import School
from server.users.models import Consumer, Instructor, User
from server.utils.model_fields import random_slug
class SchoolActivityGroupManager(models.Manager):
def get_activity_container_only_group(self, activity_group):
container_only_groups = self.filter(
activity_order=activity_group.activity_order,
group_type=SchoolActivityGroup.GroupTypes.CONTAINER_ONLY,
)
if container_only_groups.exists():
return container_only_groups[0]
class ImportedOrganization(models.Model):
slug = models.CharField(max_length=40, default=random_slug, unique=True)
organization_number = models.CharField(max_length=10, unique=True)
email = models.EmailField(null=True, blank=True)
description = models.CharField(max_length=4096, null=True, blank=True)
website_url = models.URLField(null=True, blank=True)
name = models.CharField(max_length=256, null=True, blank=True)
goal = models.CharField(max_length=4096, null=True, blank=True)
year_founded = models.CharField(max_length=128, null=True, blank=True)
status = models.CharField(max_length=50, null=True, blank=True)
target_audience = models.JSONField(null=True, blank=True)
number_of_employees = models.PositiveIntegerField(null=True, blank=True)
number_of_members = models.PositiveIntegerField(null=True, blank=True)
number_of_volunteers = models.PositiveIntegerField(null=True, blank=True)
location_lon = models.DecimalField(
max_digits=9,
decimal_places=6,
null=True,
blank=True,
)
location_lat = models.DecimalField(
max_digits=9,
decimal_places=6,
null=True,
blank=True,
)
address_city = models.CharField(max_length=256, null=True, blank=True)
address_street = models.CharField(max_length=256, null=True, blank=True)
address_house_num = models.CharField(max_length=30, null=True, blank=True)
address_zipcode = models.CharField(max_length=9, null=True, blank=True)
cities = models.JSONField(null=True, blank=True)
districts = models.JSONField(null=True, blank=True)
union_type = models.CharField(max_length=50, null=True, blank=True)
def __str__(self):
return f"{self.name} | {self.organization_number} | {self.slug}"
class Organization(models.Model):
slug = models.CharField(max_length=40, default=random_slug, unique=True)
organization_number = models.CharField(max_length=10, unique=True, null=True)
email = models.EmailField()
description = models.CharField(max_length=300)
website_url = models.URLField(null=True, blank=True)
name = models.CharField(max_length=100)
goal = models.CharField(max_length=300, null=True, blank=True)
year_founded = models.CharField(max_length=4, null=True, blank=True)
status = models.CharField(max_length=50, null=True, blank=True)
target_audience = models.JSONField(null=True, blank=True)
number_of_employees = models.PositiveIntegerField(null=True, blank=True)
number_of_members = models.PositiveIntegerField(null=True, blank=True)
number_of_volunteers = models.PositiveIntegerField(null=True, blank=True)
location_lon = models.DecimalField(
max_digits=9,
decimal_places=6,
null=True,
blank=True,
)
location_lat = models.DecimalField(
max_digits=9,
decimal_places=6,
null=True,
blank=True,
)
address_city = models.CharField(max_length=150, null=True, blank=True)
address_street = models.CharField(max_length=150, null=True, blank=True)
address_house_num = models.CharField(max_length=20, null=True, blank=True)
address_zipcode = models.CharField(max_length=9, null=True, blank=True)
cities = models.JSONField(null=True, blank=True)
districts = models.JSONField(null=True, blank=True)
union_type = models.CharField(max_length=50, null=True, blank=True)
def __str__(self):
return f"{self.name} | {self.organization_number} | {self.slug}"
class Activity(models.Model):
class Domain(models.TextChoices):
SCIENCE_AND_TECH = "SCIENCE_AND_TECH", "Science And Tech"
EXTREME_SPORTS = "EXTREME_SPORTS", "Extreme Sports"
FIELD = "FIELD", "Field"
tags = TaggableManager(blank=True)
slug = models.CharField(max_length=40, default=random_slug, unique=True)
name = models.CharField(max_length=35)
target_audience = models.JSONField()
domain = models.CharField(
max_length=55, null=True, blank=True, choices=Domain.choices
)
originization = models.ForeignKey(
Organization, on_delete=models.SET_NULL, null=True, blank=True
)
activity_website_url = models.URLField(max_length=750, null=True, blank=True)
activity_email = models.EmailField(null=True, blank=True)
description = models.CharField(max_length=550, default="")
contact_name = models.CharField(max_length=60, default="")
logo = models.ImageField(blank=True, null=True)
phone_number = models.CharField(
blank=True,
max_length=15,
validators=[
RegexValidator(
regex=r"^\d{9,15}$",
message=_("phone number must be between 9-15 digits"),
)
],
)
def __str__(self):
try:
return f"{self.name} | {self.slug} | {self.originization.name}"
except AttributeError:
return f"{self.name} | {self.slug}"
class ImportedActivity(models.Model):
slug = models.CharField(max_length=40, default=random_slug, unique=True)
activity_code = models.IntegerField()
name = models.CharField(max_length=550)
raw_name = models.CharField(max_length=550)
target_audience = models.JSONField()
organization_number = models.IntegerField()
organization_name = models.CharField(max_length=1550, default="")
target_gender = models.JSONField()
target_gender = models.JSONField()
target_population = models.JSONField()
target_time = models.JSONField()
target_size = models.JSONField()
target_migzar = models.JSONField()
target_pikuah = models.JSONField()
profession = models.JSONField()
goal = models.CharField(max_length=1550, default="")
is_active = models.BooleanField()
activity_website_url = models.URLField(max_length=750, null=True, blank=True)
activity_email = models.EmailField(null=True, blank=True)
description = models.CharField(max_length=1550, default="")
contact_name = models.CharField(max_length=100, default="")
phone_number = models.CharField(
blank=True,
max_length=15,
validators=[
RegexValidator(
regex=r"^\d{9,15}$",
message=_("phone number must be between 9-15 digits"),
)
],
)
def __str__(self):
return f"{self.name} | {self.slug} | {self.activity_code}"
class ActivityMedia(models.Model):
slug = models.CharField(max_length=40, default=random_slug, unique=True)
name = models.CharField(max_length=40, null=True, blank=True)
image_url = models.ImageField(blank=True, null=True)
video_url = models.URLField(blank=True, null=True)
activity = models.ForeignKey(
Activity,
on_delete=models.CASCADE,
related_name="rich_media",
)
def __str__(self):
return f"{self.name} | {self.slug} | {self.activity.name}"
class OrganizationMember(models.Model):
user = models.OneToOneField(
User, on_delete=models.CASCADE, related_name="organization_member"
)
organization = models.ForeignKey(
Organization,
on_delete=models.CASCADE,
related_name="organization_member",
)
def __str__(self):
return f"{self.user.email} | {self.organization.name}"
class SchoolActivityOrder(models.Model):
class Meta:
constraints = [
models.UniqueConstraint(fields=["school", "activity"], name="unique_order")
]
class Status(models.TextChoices):
CANCELLED = "CANCELLED", "Cancelled"
PENDING_ADMIN_APPROVAL = "PENDING_ADMIN_APPROVAL", "Pending Admin Approval"
APPROVED = "APPROVED", "Approved"
base_status = Status.PENDING_ADMIN_APPROVAL
slug = models.CharField(max_length=40, default=random_slug, unique=True)
requested_by = models.ForeignKey(
User,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="requested_orders",
)
last_updated_by = models.ForeignKey(
User,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="last_updated_by_me_orders",
)
school = models.ForeignKey(
School, on_delete=models.CASCADE, related_name="school_activity_orders"
)
activity = models.ForeignKey(
Activity, on_delete=models.CASCADE, related_name="school_activity_orders"
)
status = models.CharField(
_("status"), max_length=50, choices=Status.choices, default=base_status
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.activity} | {self.school} | {self.status} | {self.pk}"
class SchoolActivityGroup(models.Model):
class GroupTypes(models.TextChoices):
CONTAINER_ONLY = "CONTAINER_ONLY", "Container Only"
DISABLED_CONSUMERS = "DISABLED_CONSUMERS", "Disabled Consumers"
DEFAULT = "DEFAULT", "Default"
objects = SchoolActivityGroupManager()
slug = models.CharField(max_length=40, default=random_slug, unique=True)
activity_order = models.ForeignKey(
SchoolActivityOrder, on_delete=models.CASCADE, related_name="activity_groups"
)
name = models.CharField(_("name"), max_length=50)
description = models.CharField(_("description"), max_length=550)
consumers = models.ManyToManyField(
Consumer,
related_name="activity_groups",
blank=True,
)
group_type = models.CharField(
_("group type"),
max_length=50,
choices=GroupTypes.choices,
default=GroupTypes.DEFAULT,
)
instructor = models.ForeignKey(
Instructor,
on_delete=models.SET_NULL,
related_name="managed_activity_groups",
null=True,
blank=True,
)
def __str__(self):
return f"""
{self.name} : {self.group_type} : {self.slug} :
{self.activity_order.activity.name} : {self.activity_order.school.name}
"""
<file_sep># Generated by Django 3.1.11 on 2021-06-24 07:22
import django.core.validators
from django.db import migrations, models
import server.utils.model_fields
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20210624_1022'),
('events', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='event',
name='has_summary',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='event',
name='slug',
field=models.CharField(default=server.utils.model_fields.random_slug, max_length=40, null=True),
),
migrations.AddField(
model_name='event',
name='summary_children_behavior',
field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)]),
),
migrations.AddField(
model_name='event',
name='summary_general_notes',
field=models.CharField(blank=True, max_length=400, null=True),
),
migrations.AddField(
model_name='event',
name='summary_general_rating',
field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)]),
),
migrations.AlterField(
model_name='event',
name='consumers',
field=models.ManyToManyField(blank=True, to='users.Consumer'),
),
]
<file_sep><template>
<div
class="pt-16 absolute-bottom"
v-intersect="{
handler: onIntersect,
options: { threshold: [0.1] },
}"
></div>
</template>
<script>
export default {
methods: {
onIntersect(event) {
if (event[0].isIntersecting) {
this.$emit("end-of-page")
}
},
},
}
</script>
<file_sep>from contextlib import suppress
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Count
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, mixins, status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from server.organizations.models import (
Activity,
ActivityMedia,
Organization,
SchoolActivityGroup,
SchoolActivityOrder,
)
from server.users.api.serializers import UserSerializer
from server.utils.permission_classes import (
AllowConsumer,
AllowConsumerReadOnly,
AllowCoordinator,
AllowCoordinatorReadOnly,
AllowInstructorReadOnly,
AllowVendor,
)
from .filters import ActivityFilter
from .serializers import (
ActivityMediaSerializer,
ActivitySerializer,
ConsumerActivitySerializer,
ConsumerRequestDataSerializer,
ManageSchoolActivitySerializer,
OrganizationSerializer,
SchoolActivityGroupSerializer,
VendorActivitySerializer,
)
class OrganizationViewSet(
mixins.RetrieveModelMixin,
mixins.ListModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet,
):
permission_classes = [AllowCoordinatorReadOnly | AllowVendor]
serializer_class = OrganizationSerializer
lookup_field = "slug"
def get_queryset(self):
try:
return Organization.objects.filter(
organization_member__in=[self.request.user.organization_member]
)
except ObjectDoesNotExist:
return Organization.objects.none()
class ActivityViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = [AllowCoordinatorReadOnly]
serializer_class = ActivitySerializer
lookup_field = "slug"
filterset_class = ActivityFilter
search_fields = ["name", "description"]
filter_backends = [filters.SearchFilter, DjangoFilterBackend]
queryset = Activity.objects.all()
class VendorActivityViewSet(viewsets.ModelViewSet):
permission_classes = [AllowVendor]
serializer_class = VendorActivitySerializer
lookup_field = "slug"
def get_queryset(self):
user = self.request.user
return Activity.objects.filter(
originization=user.organization_member.organization,
)
def perform_create(self, serializer):
serializer.save(
originization=self.request.user.organization_member.organization
)
def perform_update(self, serializer):
serializer.save(
originization=self.request.user.organization_member.organization
)
class ConsumerActivityViewSet(
mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet
):
permission_classes = [AllowConsumer]
serializer_class = ConsumerActivitySerializer
lookup_field = "slug"
filterset_class = ActivityFilter
search_fields = ["name", "description", "tags__name"]
filter_backends = [filters.SearchFilter, DjangoFilterBackend]
filterset_fields = ["tags"]
def get_queryset(self):
user = self.request.user
approved_orders = SchoolActivityOrder.objects.filter(
school=user.school_member.school,
status=SchoolActivityOrder.Status.APPROVED,
).values("activity")
return Activity.objects.filter(id__in=approved_orders)
@action(detail=True, methods=["POST"])
def join_group(self, request, slug=None):
if not hasattr(request.user, "school_member"):
return Response(
{"non_field_errors": ["must be a school member"]},
status=status.HTTP_400_BAD_REQUEST,
)
order = SchoolActivityOrder.objects.get(
school=request.user.school_member.school,
activity__slug=slug,
)
with suppress(ObjectDoesNotExist):
# check if user already in a group, and handle accordingly
existing_group = SchoolActivityGroup.objects.get(
activity_order=order,
consumers=request.user.pk,
)
if (
existing_group.group_type
== SchoolActivityGroup.GroupTypes.DISABLED_CONSUMERS
):
existing_group.consumers.remove(request.user.pk)
else:
return Response(
{"non_field_errors": ["user already in a group"]},
status=status.HTTP_400_BAD_REQUEST,
)
group, _ = SchoolActivityGroup.objects.get_or_create(
activity_order=order,
group_type=SchoolActivityGroup.GroupTypes.CONTAINER_ONLY,
)
group.consumers.add(self.request.user.pk)
return Response(status=status.HTTP_204_NO_CONTENT)
@action(detail=True, methods=["POST"])
def leave_group(self, request, slug=None):
"""
move consumer to a "disabled consumers" group
"""
if not hasattr(request.user, "school_member"):
return Response(
{"non_field_errors": ["must be a school member"]},
status=status.HTTP_400_BAD_REQUEST,
)
order = SchoolActivityOrder.objects.get(
school=request.user.school_member.school,
activity__slug=slug,
)
try:
SchoolActivityGroup.objects.exclude(
group_type=SchoolActivityGroup.GroupTypes.DISABLED_CONSUMERS
).get(activity_order=order, consumers=request.user.pk,).consumers.remove(
request.user.pk
)
except ObjectDoesNotExist:
return Response(
{"non_field_errors": ["user is not in an active group"]},
status=status.HTTP_400_BAD_REQUEST,
)
group, _created = SchoolActivityGroup.objects.get_or_create(
activity_order=order,
group_type=SchoolActivityGroup.GroupTypes.DISABLED_CONSUMERS,
)
group.consumers.add(request.user.pk)
return Response(status=status.HTTP_204_NO_CONTENT)
class ActivityMediaViewSet(viewsets.ModelViewSet):
permission_classes = [
AllowVendor
| AllowCoordinatorReadOnly
| AllowInstructorReadOnly
| AllowConsumerReadOnly
]
serializer_class = ActivityMediaSerializer
lookup_field = "slug"
queryset = ActivityMedia.objects.all()
filterset_fields = ("activity__slug",)
class ManageSchoolActivityViewSet(viewsets.ModelViewSet):
permission_classes = [AllowCoordinator]
serializer_class = ManageSchoolActivitySerializer
lookup_field = "activity__slug"
filterset_fields = ("status",)
def get_queryset(self):
coord_school = self.request.user.school_member.school
return SchoolActivityOrder.objects.filter(school=coord_school)
def perform_create(self, serializer):
serializer.save(
requested_by=self.request.user, last_updated_by=self.request.user
)
def perform_update(self, serializer):
serializer.save(last_updated_by=self.request.user)
class SchoolActivityGroupViewSet(viewsets.ModelViewSet):
permission_classes = [
AllowCoordinator | AllowConsumerReadOnly | AllowInstructorReadOnly
]
serializer_class = SchoolActivityGroupSerializer
queryset = SchoolActivityOrder.objects.all()
filterset_fields = ["group_type", "activity_order__slug"]
lookup_field = "slug"
def get_queryset(self):
user = self.request.user
if user.user_type == get_user_model().Types.CONSUMER:
return SchoolActivityGroup.objects.filter(consumers=user)
if user.user_type == get_user_model().Types.INSTRUCTOR:
return SchoolActivityGroup.objects.filter(instructor=user)
return SchoolActivityGroup.objects.filter(
activity_order__in=user.school_member.school.school_activity_orders.all(),
)
@action(detail=True, methods=["GET"])
def group_consumers(self, request, slug=None):
serializer = UserSerializer(
self.get_object().consumers,
context={"request": request},
many=True,
)
return Response(status=status.HTTP_200_OK, data=serializer.data)
@action(detail=True, methods=["PATCH"])
def update_group_consumers(self, request, slug=None):
# receive consumer slugs list, override existing consumers & move the removed to container-only group
current_group = self.get_object()
container_only_group = (
SchoolActivityGroup.objects.get_activity_container_only_group(current_group)
)
if not container_only_group:
return Response(
{"non_field_errors": ["container group could not be found"]},
status=status.HTTP_400_BAD_REQUEST,
)
to_remove = current_group.consumers.all().exclude(slug__in=request.data)
to_add = container_only_group.consumers.all().filter(slug__in=request.data)
current_group.consumers.remove(*to_remove)
current_group.consumers.add(*to_add)
container_only_group.consumers.remove(*to_add)
container_only_group.consumers.add(*to_remove)
return Response(status=status.HTTP_204_NO_CONTENT)
@action(detail=False, methods=["GET"])
def consumer_requests_data(self, request):
"""
requests to each activity, based on container_only consumers
"""
qs = (
self.get_queryset()
.filter(group_type=SchoolActivityGroup.GroupTypes.CONTAINER_ONLY)
.annotate(consumer_requests=Count("consumers"))
.order_by("-consumer_requests")[:10]
)
return Response(ConsumerRequestDataSerializer(qs, many=True).data)
<file_sep>from django.contrib import admin
from .models import ImportedSchool, School, SchoolMember
@admin.register(School)
class SchoolAdmin(admin.ModelAdmin):
exclude = ["last_updated_by"]
class SchoolMemberTabularInline(admin.TabularInline):
model = SchoolMember
min_num = 1
admin.site.register(SchoolMember)
admin.site.register(ImportedSchool)
<file_sep>npm i -g json-server
json-server --watch db.json --routes routes.json --middlewares ./middleware.js --port 8001
<file_sep># This file is expected by Heroku.
-r server/requirements/production.txt
<file_sep>import csv
import logging
import requests
from django.core.management.base import BaseCommand
from server.organizations.models import ImportedActivity
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Fetch activities from gov site and load to db"
def handle(self, *args, **options):
self.fetch(options["csv"])
def add_arguments(self, parser):
parser.add_argument("--csv", action="store_true")
def fetch(self, should_write_csv):
BASE_URL = "https://apps.education.gov.il"
ACTIVITIES_API_URL = f"{BASE_URL}/TyhNet/ClientWs/TochnitCh.asmx/IturTochnitChByMeafyenim" # noqa
ACTIVITIES_DEFAULT_PAGE_SIZE = 100
ACTIVITY_FIELD_MAPPING = {
"name": "ShemTochnit",
"target_audience": "ShichvatLomdim",
"activity_website_url": None,
"activity_email": None,
"description": "TaktsirTochnit",
"activity_code": "MisparTochnit",
"contact_name": None,
"phone_number": None,
"is_active": "CodeStatusTochnit",
"longtitude": None,
"latitude": None,
# New fields
"goal": "MataraMerkazit",
"raw_name": "ShemTochnit_Raw",
}
grades_letter_to_number = {
"חיילים": 23,
"צוותי חינוך": 22,
"מנהלים": 21,
"הורים": 20,
"ילדי הגן": 0,
"גן": 0,
"א": 1,
"ב": 2,
"ג": 3,
"ד": 4,
"ה": 5,
"ו": 6,
"ז": 7,
"ח": 8,
"ט": 9,
"י": 10,
"יא": 11,
"יב": 12,
"יג": 13,
"יד": 14,
}
if should_write_csv:
fieldnames = [
"name",
"target_audience",
"activity_website_url",
"activity_email",
"organization_name",
"organization_number",
"description",
"activity_code",
"contact_name",
"phone_number",
"is_active",
"goal",
"raw_name",
"profession",
"target_gender",
"target_population",
"target_time",
"target_size",
"target_migzar",
"target_pikuah",
]
csv_file = open("activities.csv", "w", encoding="UTF-8")
csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
csv_writer.writeheader()
total_records = None
activities = []
page_number = 1
while total_records is None or len(activities) < total_records:
response = requests.post(
ACTIVITIES_API_URL,
headers={
"Accept": "application/json",
"Content-Type": "application/json",
"Accept-Language": "en-US,en;q=0.9",
},
json={
"MeafyeneiTochnit": "",
"strTchumMerkazi": "",
"strMakorTochnit": "",
"strStatusTochnit": "",
"CodeYechidaAchrayit": -1,
"Cipuschofshi": "",
"MisparTochnit": -1,
"TochnitBelivuiMisrad": -1,
"kyamDerugMenahalim": -1,
"KyemotChavotDaatMefakchim": -1,
"Natsig": "",
"ShemTochnit": "",
"Taagid": "",
"TaagidMishtamesh": "",
"TochnitActive": False,
"NidrashAlut": -1,
"PageNumber": page_number,
"PageSize": ACTIVITIES_DEFAULT_PAGE_SIZE,
"OrderBy": "",
"IncludeYechidotBat": True,
"TochnitLeumit": -1,
},
)
response.raise_for_status()
content = response.json()["d"]
for raw_activity in content["Data"]:
activity_code = raw_activity["MisparTochnit"]
contact_info = requests.post(
"https://apps.education.gov.il/TyhNet/ClientWs/TochnitCh.asmx/GetDataAc6",
json={"MisparTochnit": activity_code},
)
raw_contact_info = contact_info.json()["d"]
targets = requests.post(
"https://apps.education.gov.il/TyhNet/ClientWs/TochnitCh.asmx/GetDataAc2",
json={"MisparTochnit": activity_code},
)
raw_targets = targets.json()["d"]
target_audience = [
grades_letter_to_number[grade]
for grade in raw_activity[ACTIVITY_FIELD_MAPPING["target_audience"]]
.replace("'", "")
.replace('"', "")
.split(" | ")
]
target_audience.sort()
activity = {
"name": raw_activity[ACTIVITY_FIELD_MAPPING["name"]],
"target_audience": target_audience,
"activity_website_url": raw_contact_info[
"ktovet_kishur_atar_taagid"
],
"activity_email": raw_contact_info["EMAIL"],
"organization_name": raw_contact_info["SHEM_TAAGID"],
"organization_number": raw_contact_info["MISPAR_TAAGID"],
"description": raw_activity[ACTIVITY_FIELD_MAPPING["description"]],
"activity_code": activity_code,
"contact_name": raw_contact_info["GOREM_KESHER_BATAAGID"],
"phone_number": raw_contact_info["NAYAD"],
"is_active": raw_activity[ACTIVITY_FIELD_MAPPING["is_active"]] == 4,
"goal": raw_activity[ACTIVITY_FIELD_MAPPING["goal"]],
"raw_name": raw_activity[ACTIVITY_FIELD_MAPPING["raw_name"]],
"profession": raw_activity["MiktsoaNoseIkari"].split("| "),
"target_gender": raw_targets[1]["Value"].split(" | "),
"target_population": raw_targets[2]["Value"].split(" | "),
"target_time": raw_targets[3]["Value"].split(" | "),
"target_size": raw_targets[4]["Value"].split(" | "),
"target_migzar": raw_targets[7]["Value"].split(" | "),
"target_pikuah": raw_targets[8]["Value"].split(" | "),
}
if should_write_csv:
csv_writer.writerow(activity)
csv_file.flush()
else:
logger.info(activity)
ImportedActivity.objects.update_or_create(
defaults=activity, activity_code=activity_code
)
page_number += 1
total_records = content["TotalResultCount"]
<file_sep><template>
<div>
<v-row no-gutters>
<v-col cols="12" lg="7" class="mb-12 mb-lg-0">
<div class="pb-12">
<h1 v-text="$t('program.mediaUpload')" class="mb-5" />
<h2 v-text="$t('program.uploadVideosAndImagesSoSchoolsCanView')" />
</div>
<carousel
v-model="currentMediaIndex"
:media-list="mediaList.length ? mediaList : mediaListPlaceholder"
/>
<div class="text-center pt-12 relative">
<v-btn class="mx-4" fab color="error" @click="triggerMediaDelete">
<v-icon>mdi-delete</v-icon>
</v-btn>
<v-btn
fab
data-testid="add-media-btn"
class="mx-4"
color="success"
@click="triggerMediaUpload"
>
<v-icon>mdi-plus</v-icon>
</v-btn>
<v-btn
data-testid="finish-btn"
class="absolute-left"
x-large
outlined
color="success"
@click="
$router.push({
name: 'VendorDetailProgram',
params: { programSlug },
})
"
v-text="$t('userActions.finish')"
/>
</div>
</v-col>
<v-col cols="12" lg="5" class="px-10">
<sticky-note v-if="!$vuetify.breakpoint.mobile">
<b>{{ this.$t("general.didYouKnow?") }}</b>
<div
class="pt-5 sticky-span"
v-text="
$t(
'program.uploadingImagesAndVideosCanImproveTheProgramPopularity!'
)
"
/>
</sticky-note>
</v-col>
</v-row>
<modal-approve
v-model="isApproveModalOpen"
@approve="deleteMedia(currentMediaIndex)"
>
{{
this.$t(
"confirm.thisActionWillDeleteTheMediaYouAreCurrentlyWatching-Proceed?"
)
}}
</modal-approve>
<upload-modal v-model="isUploadModalOpen" @upload="uploadMedia" />
</div>
</template>
<script>
import { mapActions } from "vuex"
import debounce from "lodash/debounce"
import Api from "../api"
import Utils from "../helpers/utils"
import { CAROUSEL_PLACEHOLDER } from "../helpers/constants/images"
import store from "../vuex/store"
import ModalApprove from "../components/ModalApprove"
import Carousel from "../components/Carousel"
import StickyNote from "../components/StickyNote"
import UploadModal from "../components/VendorProgramMediaUploadModal"
export default {
components: { ModalApprove, StickyNote, Carousel, UploadModal },
async beforeRouteEnter(to, from, next) {
const mediaList = await store.dispatch(
"vendorProgram/getProgramMediaList",
to.params.programSlug
)
next(vm => (vm.mediaList = mediaList))
},
props: {
programSlug: {
type: String,
required: true,
},
},
data() {
return {
currentMediaIndex: 0,
mediaList: [],
mediaListPlaceholder: [{ imageUrl: CAROUSEL_PLACEHOLDER }],
isApproveModalOpen: false,
isUploadModalOpen: false,
}
},
methods: {
...mapActions("vendorProgram", [
"deleteProgramMedia",
"createProgramMedia",
"getProgramMediaList",
]),
...mapActions("snackbar", ["showMessage"]),
async deleteMedia(index) {
try {
await this.deleteProgramMedia(this.mediaList[index].slug)
this.mediaList = await this.getProgramMediaList(this.programSlug)
this.showMessage(this.$t("success.mediaDeletedSuccessfully"))
} catch (err) {
this.showMessage(Api.utils.parseResponseError(err))
}
},
triggerMediaUpload() {
if (this.mediaList.length < 5) {
return (this.isUploadModalOpen = true)
}
this.showMessage(this.$t("errors.uploadLimitIsFive"))
},
triggerMediaDelete() {
this.isApproveModalOpen = true
},
uploadMedia: debounce(
async function (mediaPayload) {
try {
const data = Utils.objectToFormData({
activity: this.programSlug,
...mediaPayload,
})
await this.createProgramMedia(data)
this.mediaList = await this.getProgramMediaList(this.programSlug)
this.showMessage(this.$t("success.mediaUploadedSuccessfully"))
} catch (err) {
this.showMessage(Api.utils.parseResponseError(err))
}
},
500,
{ leading: true, trailing: false }
),
},
}
</script>
<style scoped>
.sticky-span {
font-size: 22px;
}
</style>
<file_sep>import { action } from "@storybook/addon-actions"
import TableRowsToChips from "../components/TableRowsToChips"
export default {
title: "TableRowsToChips",
component: TableRowsToChips,
}
const Template = args => ({
components: { TableRowsToChips },
methods: { action },
data: () => ({ args }),
template: `
<table-rows-to-chips
class="w-75 mx-auto"
v-model="args.selected"
:items="args.items"
:headers="args.headers"
:chips-label-header="args.chipsLabelHeader"
@input="action('input')()"
>
</table-rows-to-chips>
`,
})
export const Primary = Template.bind({})
Primary.args = {
chipsLabelHeader: "name",
selected: [
{
name: "Banana",
calories: "70",
},
],
headers: [
{ text: "Food Name", value: "name" },
{ text: "Num of Cals", value: "calories" },
],
items: [
{
name: "Banana",
calories: "70",
},
{
name: "Orange",
calories: "40",
},
{
name: "Cucumber",
calories: "35",
},
{
name: "Lemon",
calories: "45",
},
{
name: "Carrot",
calories: "20",
},
{
name: "Cookie",
calories: "45",
},
{
name: "Cake",
calories: "100",
},
{
name: "Burger",
calories: "200",
},
{
name: "French Fries",
calories: "100",
},
{
name: "Water",
calories: "0",
},
],
}
<file_sep>import { action } from "@storybook/addon-actions"
import FormDialog from "../components/FormDialog.vue"
export default {
title: "FormDialog",
component: FormDialog,
}
const Template = args => ({
components: { FormDialog },
methods: { action },
data: () => ({ args }),
template: `
<form-dialog
class="mx-auto"
style="width: 800px;"
v-model="args.value"
:inputFields="args.inputFields"
:title="args.title"
@save="action('save')()"
@input="action('input')()"
/>
`,
})
export const Primary = Template.bind({})
Primary.args = {
value: true,
inputFields: [
{
name: "firstName",
rule: "required",
label: "שם פרטי",
value: "",
},
{
name: "lastName",
rule: "required",
label: "שם משפחה",
value: "",
},
{
name: "phoneNumber",
rule: "required",
label: "טלפון",
value: "0521234567",
},
{
name: "favPokemon",
type: "select",
rule: "required",
label: "פוקימון אהוב",
choices: ["Pikachu", "Charizard", "Bulbasaur", "Snorlax"],
value: "",
},
],
title: "אני כותרת",
}
<file_sep>import os
import pytest
from django.test import override_settings
from rest_framework import status
from rest_framework.test import APIClient
from server.organizations.models import SchoolActivityGroup, SchoolActivityOrder
from server.schools.models import SchoolMember
pytestmark = pytest.mark.django_db
RESET_BASE_URL = os.environ.get("GITPOD_WORKSPACE_URL")[8:]
class TestManageSchoolProgramsView:
uri = "/api/manage_school_activity/"
@override_settings(DEBUG=True)
def test_create(self, school, coordinator, activity):
SchoolMember.objects.create(school=school, user=coordinator)
client = APIClient()
client.force_authenticate(user=coordinator)
post_response = client.post(
self.uri, {"school": school.slug, "activity": activity.slug}, format="json"
)
get_response = client.get(self.uri)
assert len(get_response.data["results"]) == 1
assert post_response.status_code == status.HTTP_201_CREATED
assert get_response.status_code == status.HTTP_200_OK
assert post_response.data == get_response.data["results"][0]
assert (
post_response.data["requested_by"]
== post_response.data["last_updated_by"]
== coordinator.slug
)
assert post_response.data["status"] == "PENDING_ADMIN_APPROVAL"
@override_settings(DEBUG=True)
def test_create_without_member(self, school, school1, coordinator, activity):
"""
make sure can't create when not a school member of the relevant school
"""
self.uri = "/api/manage_school_activity/"
client = APIClient()
client.force_authenticate(user=coordinator)
post_response = client.post(
self.uri, {"school": school.slug, "activity": activity.slug}, format="json"
)
SchoolMember.objects.create(school=school1, user=coordinator)
post_response_2 = client.post(
self.uri, {"school": school.slug, "activity": activity.slug}, format="json"
)
assert (
status.HTTP_400_BAD_REQUEST
== post_response.status_code
== post_response_2.status_code
)
class TestConsumerActivityView:
uri = "/api/consumer_activities/"
@override_settings(DEBUG=True)
def test_consumer_can_view_only_approved_activities(
self, consumer, school, activity
):
SchoolMember.objects.create(user=consumer, school=school)
client = APIClient()
client.force_authenticate(user=consumer)
get_response_before_order = client.get(self.uri)
order = SchoolActivityOrder.objects.create(activity=activity, school=school)
get_response_after_order_creation = client.get(self.uri)
order.status = SchoolActivityOrder.Status.APPROVED
order.save()
get_response_after_order_approval = client.get(self.uri)
assert (
status.HTTP_200_OK
== get_response_before_order.status_code
== get_response_after_order_creation.status_code
== get_response_after_order_approval.status_code
)
assert (
get_response_before_order.data["results"]
== get_response_after_order_creation.data["results"]
== []
)
assert len(get_response_after_order_approval.data["results"]) == 1
@override_settings(DEBUG=True)
def test_consumer_can_view_join_status(self, consumer, school, activity):
"""
test if join status is true if in group, false otherwise
"""
SchoolMember.objects.create(user=consumer, school=school)
activity_order = SchoolActivityOrder.objects.create(
activity=activity, school=school, status=SchoolActivityOrder.Status.APPROVED
)
activity_group = SchoolActivityGroup.objects.create(
activity_order=activity_order
)
client = APIClient()
client.force_authenticate(user=consumer)
response_before_consumer_in_group = client.get(self.uri)
activity_group.consumers.add(consumer)
response_after_consumer_in_group = client.get(self.uri)
assert (
response_before_consumer_in_group.data["results"][0]["is_consumer_joined"]
is False
)
assert (
response_after_consumer_in_group.data["results"][0]["is_consumer_joined"]
is True
)
class TestJoinGroupAction:
uri = "/api/consumer_activities/{0}/join_group/"
@override_settings(
DEBUG=True,
RESET_BASE_URL="https://8000-{0}".format(RESET_BASE_URL),
)
def test_create_and_join(self, consumer, school_activity_order):
"""
test consumer can join to an activity, when there are no groups (i.e., group is created)
"""
SchoolMember.objects.create(user=consumer, school=school_activity_order.school)
client = APIClient()
client.force_authenticate(user=consumer)
activity_slug = school_activity_order.activity.slug
response = client.post(self.uri.format(activity_slug))
assert (
SchoolActivityGroup.objects.get(
activity_order=school_activity_order,
).consumers.first()
== consumer
)
assert response.status_code == status.HTTP_204_NO_CONTENT
@override_settings(
DEBUG=True,
RESET_BASE_URL="https://8000-{0}".format(RESET_BASE_URL),
)
def test_join_to_existing(self, consumer, school_activity_group):
"""
test consumer can join to an existing activity group
"""
school_activity_group.group_type = (
school_activity_group.GroupTypes.CONTAINER_ONLY
)
school_activity_group.save()
school_activity_order = school_activity_group.activity_order
SchoolMember.objects.create(user=consumer, school=school_activity_order.school)
client = APIClient()
client.force_authenticate(user=consumer)
activity_slug = school_activity_order.activity.slug
response = client.post(self.uri.format(activity_slug))
assert school_activity_group.consumers.first() == consumer
assert response.status_code == status.HTTP_204_NO_CONTENT
def test_cant_join_group_twice(self, consumer, school_activity_group):
"""
test consumer who is already on a group cant join again
"""
school_activity_group.consumers.add(consumer)
school_activity_group.save()
school_activity_order = school_activity_group.activity_order
SchoolMember.objects.create(user=consumer, school=school_activity_order.school)
client = APIClient()
client.force_authenticate(user=consumer)
activity_slug = school_activity_order.activity.slug
response = client.post(self.uri.format(activity_slug))
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.data == {"non_field_errors": ["user already in a group"]}
class TestLeaveGroupAction:
uri = "/api/consumer_activities/{0}/leave_group/"
def test_leave_group(self, consumer, school_activity_group):
"""
test consumer who is already on a group cant join again
"""
school_activity_group.consumers.add(consumer)
school_activity_group.save()
school_activity_order = school_activity_group.activity_order
SchoolMember.objects.create(user=consumer, school=school_activity_order.school)
client = APIClient()
client.force_authenticate(user=consumer)
activity_slug = school_activity_order.activity.slug
response = client.post(self.uri.format(activity_slug))
assert response.status_code == status.HTTP_204_NO_CONTENT
assert not school_activity_group.consumers.all().exists()
assert (
SchoolActivityGroup.objects.get(
group_type=SchoolActivityGroup.GroupTypes.DISABLED_CONSUMERS,
).consumers.first()
== consumer
)
class TestVendorActivityView:
uri = "/api/vendor_activities/"
@override_settings(DEBUG=True)
def test_create_activity(self, all_entities):
payload = {
"name": "Activity Name",
"target_audience": [1, 2, 3],
"domain": "SCIENCE_AND_TECH",
"description": "Activity Description",
"contact_name": "<NAME>",
"logo": None,
"phone_number": "0521234567",
"tags": [],
}
vendor = all_entities["vendor"]
client = APIClient()
client.force_authenticate(user=vendor)
post_response = client.post(self.uri, payload, format="json")
activity_slug = post_response.data["slug"]
get_response = client.get(f"{self.uri}{activity_slug}/")
assert post_response.status_code == status.HTTP_201_CREATED
assert get_response.status_code == status.HTTP_200_OK
assert get_response.data["originization"] == all_entities["organization"].pk
<file_sep>from rest_framework import serializers
from server.events.models import ConsumerEventFeedback, Event
from server.organizations.models import SchoolActivityGroup
from server.users.models import Consumer
class EventSerializerMixin(metaclass=serializers.SerializerMetaclass):
activity_name = serializers.CharField(
source="school_group.activity_order.activity.name",
read_only=True,
)
school_group_name = serializers.CharField(
source="school_group.name",
read_only=True,
)
consumers = serializers.SlugRelatedField(
slug_field="slug",
queryset=Consumer.objects.all(),
many=True,
)
school_group = serializers.SlugRelatedField(
slug_field="slug",
queryset=SchoolActivityGroup.objects.all(),
)
def validate(self, data):
"""
Check that start is before finish.
"""
if (
"end_time" in data
and "start_time" in data
and data["start_time"] > data["end_time"]
):
raise serializers.ValidationError(
{"end_time": "end time must occur after start time"}
)
return data
class EventSerializer(EventSerializerMixin, serializers.ModelSerializer):
class Meta:
model = Event
fields = [
"slug",
"activity_name",
"school_group_name",
"start_time",
"end_time",
"consumers",
"school_group",
"locations_name",
"has_summary",
"summary_general_notes",
"summary_general_rating",
"summary_children_behavior",
]
class ConsumerEventSerializer(EventSerializerMixin, serializers.ModelSerializer):
has_feedback = serializers.SerializerMethodField()
class Meta:
model = Event
fields = [
"slug",
"activity_name",
"school_group_name",
"start_time",
"end_time",
"consumers",
"school_group",
"locations_name",
"has_feedback",
]
def get_has_feedback(self, obj):
user = self.context["request"].user
return ConsumerEventFeedback.objects.filter(
event=obj.pk,
consumer=user,
).exists()
class ConsumerEventFeedbackSerializer(serializers.ModelSerializer):
event = serializers.SlugRelatedField(
slug_field="slug",
queryset=Event.objects.all(),
)
consumer = serializers.SlugRelatedField(
slug_field="slug",
read_only=True,
)
class Meta:
model = ConsumerEventFeedback
fields = [
"slug",
"event",
"consumer",
"general_notes",
"secondary_notes",
"general_rating",
"secondary_rating",
]
read_only_fields = ["slug"]
<file_sep># Generated by Django 3.1.11 on 2021-06-10 15:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organizations', '0004_auto_20210608_1047'),
]
operations = [
migrations.RemoveField(
model_name='schoolactivitygroup',
name='container_only',
),
migrations.AddField(
model_name='schoolactivitygroup',
name='group_type',
field=models.CharField(choices=[('CONTAINER_ONLY', 'Container Only'), ('DISABLED_CONSUMERS', 'Disabled Consumers'), ('DEFAULT', 'Default')], default='DEFAULT', max_length=50, verbose_name='group type'),
),
]
<file_sep><template>
<v-container fluid class="overline">
<h3 v-text="title" class="pb-7" />
<v-row class="justify-start">
<v-col cols="12" md="6" v-for="item in items" :key="item.id">
<v-checkbox
v-model="selected"
:label="item.label"
:value="item.value"
class="text-right my-n2"
></v-checkbox>
</v-col>
</v-row>
</v-container>
</template>
<script>
import { mapActions } from "vuex"
import debounce from "lodash/debounce"
export default {
props: {
name: {
type: String,
required: true,
},
title: {
type: String,
required: true,
},
items: {
type: Array,
required: true,
},
},
methods: {
...mapActions("pagination", ["addFieldFilter", "removeFieldFilter"]),
},
data() {
return {
selected: [],
}
},
watch: {
selected: {
// update pagination filter
deep: true,
handler: debounce(function (value) {
if (value.length) {
this.addFieldFilter({ fieldName: this.name, value })
} else {
this.removeFieldFilter(this.name)
}
}, 500),
},
},
}
</script>
<file_sep><template>
<v-hover v-slot="{ hover }">
<div class="wrapper relative" :class="{ circle }">
<slot />
<v-btn
@click="$emit('click')"
:class="{ shadow }"
color="blue-grey"
v-show="hover"
class="btn ma-2 white--text"
fab
>
<v-icon dark>mdi-pencil</v-icon>
</v-btn>
</div>
</v-hover>
</template>
<script>
export default {
props: {
circle: {
type: Boolean,
default: false,
},
shadow: {
type: Boolean,
default: true,
},
},
}
</script>
<style lang="scss" scoped>
$dark-light: rgba(0, 0, 0, 0.2);
.btn {
z-index: 2;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.wrapper {
width: fit-content;
height: fit-content;
overflow: hidden;
}
.circle {
border-radius: 50%;
}
.shadow {
-webkit-box-shadow: 0px 0px 26px 1000px $dark-light;
-moz-box-shadow: 0px 0px 26px 1000px $dark-light;
box-shadow: 0px 0px 26px 1000px $dark-light;
}
</style>
<file_sep>import Vue from "vue"
export function trimText(str, maxLength) {
if (str.length > maxLength) {
return `${str.slice(0, maxLength)}....`
}
return str
}
Vue.filter("trimText", trimText)
<file_sep># Generated by Django 3.1.11 on 2021-07-01 11:36
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20210624_1022'),
('schools', '0003_auto_20210530_1028'),
]
operations = [
migrations.AddField(
model_name='school',
name='last_updated_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='last_updated_by_me_schools', to='users.coordinator'),
),
]
<file_sep># Generated by Django 3.1.11 on 2021-07-11 07:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('events', '0005_auto_20210629_1212'),
]
operations = [
migrations.AlterModelOptions(
name='event',
options={},
),
]
<file_sep>import Vue from "vue"
import Vuex from "vuex"
import auth from "./modules/auth"
import user from "./modules/user"
import consumer from "./modules/consumer"
import coordinator from "./modules/coordinator"
import instructor from "./modules/instructor"
import vendor from "./modules/vendor"
import school from "./modules/school"
import organization from "./modules/organization"
import program from "./modules/program"
import consumerProgram from "./modules/consumerProgram"
import vendorProgram from "./modules/vendorProgram"
import pagination from "./modules/pagination"
import loading from "./modules/loading"
import snackbar from "./modules/snackbar"
import programGroup from "./modules/programGroup"
import consumerProgramGroup from "./modules/consumerProgramGroup"
import instructorProgramGroup from "./modules/instructorProgramGroup"
import event from "./modules/event"
import consumerEvent from "./modules/consumerEvent"
import instructorEvent from "./modules/instructorEvent"
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
auth,
user,
consumer,
coordinator,
instructor,
vendor,
school,
organization,
program,
consumerProgram,
vendorProgram,
loading,
snackbar,
pagination,
programGroup,
consumerProgramGroup,
instructorProgramGroup,
event,
consumerEvent,
instructorEvent,
},
actions: {
flushState({ dispatch }) {
// flush all modules
const modules = Object.getOwnPropertyNames(this._modulesNamespaceMap)
for (const m of modules) {
if (!["loading/", "snackbar/"].includes(m)) {
dispatch(`${m}flushState`)
}
}
},
},
})
export default store
<file_sep>import { action } from "@storybook/addon-actions"
import ModalApprove from "../components/ModalApprove.vue"
export default {
title: "ModalApprove",
component: ModalApprove,
}
const Template = args => ({
components: { ModalApprove },
methods: { action },
data: () => ({ args }),
template: `
<modal-approve
v-model="args.isOpen"
@input="action('input')()"
@approve="action('approve')()"
@disapprove="action('disapprove')()"
>
{{ args.defaultSlot }}
</modal-approve>
`,
})
export const Primary = Template.bind({})
Primary.args = {
isOpen: true,
defaultSlot: "האם אתם בטוחים שברצונכם למחוק?",
}
<file_sep><template>
<div class="wrapper">
<line-chart v-bind="$attrs" />
</div>
</template>
<script>
import LineChart from "./LineChart"
export default {
inheritAttrs: false,
components: { LineChart },
}
</script>
<style scoped>
.wrapper {
max-width: 600px;
margin: 150px auto;
}
</style>
<file_sep>import Api from "../../api"
import { SERVER } from "../../helpers/constants/constants"
function getDefaultState() {
return {
userDetails: {
slug: null,
name: null,
email: null,
// e.g., COORDINATOR
userType: null,
},
}
}
const user = {
namespaced: true,
state: getDefaultState(),
mutations: {
FLUSH_STATE(state) {
Object.assign(state, getDefaultState())
},
SET_USER_DETAILS(state, userDetails) {
state.userDetails = userDetails
},
},
getters: {
isConsumer(state) {
return state.userDetails.userType === SERVER.userTypes.consumer
},
},
actions: {
flushState({ commit }) {
commit("FLUSH_STATE")
},
async getUserDetails({ commit, state }) {
if (!state.userDetails.slug) {
// fetch if not in cache
let res = await Api.user.getUserDetails()
commit("SET_USER_DETAILS", res.data)
}
return state.userDetails
},
async updateUserDetails({ commit, state }, { slug, userDetails }) {
let res = await Api.user.updateUserDetails(slug, userDetails)
commit("SET_USER_DETAILS", res.data)
return state.userDetails
},
},
}
export default user
<file_sep><template>
<v-dialog max-width="600px" v-model="value" persistent>
<v-card>
<v-card-title class="headline pt-13 justify-center" v-text="title" />
<validation-observer v-slot="{ invalid }" ref="observer">
<form class="w-75 mx-auto" @submit.prevent="save">
<v-card-text>
<v-row>
<v-col
v-for="field in formInput"
:key="field.id"
class="mt-8"
cols="12"
md="6"
>
<validation-provider
v-slot="{ errors }"
:name="field.name"
:rules="field.rule"
>
<v-select
v-if="field.type && field.type === 'select'"
class="mx-2"
v-model="field.value"
:label="field.label"
:items="field.choices"
:error-messages="errors"
/>
<v-text-field
v-else
class="mx-2"
:label="field.label"
v-model="field.value"
:error-messages="errors"
/>
</validation-provider>
</v-col>
</v-row>
</v-card-text>
<v-card-actions class="pb-5 mt-12">
<v-spacer></v-spacer>
<v-btn color="blue darken-1" text @click="close" type="button">
{{ $t("userActions.close") }}
</v-btn>
<v-btn color="blue darken-1" text type="submit" :disabled="invalid">
{{ $t("userActions.save") }}
</v-btn>
</v-card-actions>
</form>
</validation-observer>
</v-card>
</v-dialog>
</template>
<script>
import { ValidationObserver, ValidationProvider } from "vee-validate"
import cloneDeep from "lodash/cloneDeep"
export default {
components: {
ValidationObserver,
ValidationProvider,
},
props: {
value: {
// is dialog open
type: Boolean,
required: true,
},
inputFields: {
// the form's prototype
// e.g., [ { name: 'field1', rule: 'required|size:5000', label: $t('translation'), value: 'placeholderValue' }, { ... }, ... ]
type: Array,
required: true,
},
title: {
type: String,
default: function () {
return this.$tc("userActions.add", 1)
},
},
},
data() {
return {
formInput: this.getInputFields(),
}
},
watch: {
inputFields: {
// change local input object according to prop changes
deep: true,
handler() {
this.formInput = this.getInputFields()
},
},
},
methods: {
close() {
// clear errors & close form
this.$refs.observer.reset()
this.$emit("input", false)
},
save() {
// notify parent on save & init
this.$emit("save", this.createFormResult(this.formInput))
this.formInput = this.getInputFields()
this.close()
},
createFormResult(formInput) {
// return the user input as { fieldName: userInputValue, ... }
const formResult = {}
for (const field of formInput) {
formResult[field.name] = field.value
}
return formResult
},
getInputFields() {
// init based on prop
return cloneDeep(this.inputFields)
},
},
}
</script>
<style lang="scss" scoped>
.v-card__subtitle,
.v-card__text,
.v-card__title {
padding: 0;
}
</style>
<file_sep>import { action } from "@storybook/addon-actions"
import Carousel from "../components/Carousel"
export default {
title: "Carousel",
component: Carousel,
}
const Template = args => ({
components: { Carousel },
methods: { action },
data: () => ({ args }),
template: `
<carousel
style="width: 650px;"
class="mx-auto"
:media-list="args.mediaList"
/>
`,
})
export const Primary = Template.bind({})
Primary.args = {
mediaList: [
{
mediaType: "image",
imageUrl: "https://picsum.photos/200/300",
},
{
mediaType: "video",
videoUrl: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
},
],
}
<file_sep>import Vue from "vue"
import VueRouter from "vue-router"
import i18n from "../plugins/i18n"
import {
checkRegistrationStatus,
loginOrFlushStore,
initPrograms,
initConsumerPrograms,
flushPagination,
flushToken,
PopulateConsumerData,
PopulateCoordinatorData,
fetchProgramDetails,
} from "./guards"
import Welcome from "../layouts/Welcome"
import CoordinatorDashboard from "../layouts/CoordinatorDashboard"
import StudentDashboard from "../layouts/StudentDashboard"
import InstructorDashboard from "../layouts/InstructorDashboard"
import VendorDashboard from "../layouts/VendorDashboard"
import MyActivity from "../layouts/MyActivity/MyActivity"
import ConsumerMyActivity from "../layouts/MyActivity/ConsumerMyActivity"
import Login from "../views/Login"
import CoordinatorRegister from "../views/Register/CoordinatorRegister"
import VendorRegister from "../views/Register/VendorRegister"
import CoordinatorProfile from "../views/Profile/CoordinatorProfile"
import ConsumerProfile from "../views/Profile/ConsumerProfile"
import InstructorProfile from "../views/Profile/InstructorProfile"
import VendorProfile from "../views/Profile/VendorProfile"
import SchoolDetails from "../views/SchoolDetails"
import InstructorEventFeedView from "../views/InstructorEventFeedView"
import ProgramsExplorer from "../views/ProgramsExplorer/ProgramsExplorer"
import ConsumerProgramsExplorer from "../views/ProgramsExplorer/ConsumerProgramsExplorer"
import SchoolInviteWrapper from "../views/Invite/SchoolInviteWrapper"
import OrganizationInviteWrapper from "../views/Invite/OrganizationInviteWrapper"
import InviteConsumers from "../views/Invite/InviteConsumers"
import InviteCoordinators from "../views/Invite/InviteCoordinators"
import InviteInstructors from "../views/Invite/InviteInstructors"
import InviteVendors from "../views/Invite/InviteVendors"
import ResetPassword from "../views/ResetPassword"
import GenericError from "../views/Error"
import ProgramModal from "../views/ProgramModal"
import MyGroups from "../views/MyGroups/MyGroups"
import ConsumerMyGroups from "../views/MyGroups/ConsumerMyGroups"
import MyEvents from "../views/MyEvents/MyEvents"
import ConsumerList from "../views/ConsumerList/ConsumerList"
import ConsumerMyEvents from "../views/MyEvents/ConsumerMyEvents"
import ConsumerPendingEventsFeedback from "../views/ConsumerPendingEventsFeedback"
import ConsumerEventFeedback from "../views/ConsumerEventFeedback"
import CoordinatorStatistics from "../views/CoordinatorStatistics"
import InstructorUnsummarizedEvents from "../views/InstructorUnsummarizedEvents"
import InstructorEventSummary from "../views/InstructorEventSummary"
import GroupEditor from "../views/GroupEditor"
import CreateGroup from "../views/CreateGroup"
import AssignGroupConsumers from "../views/AssignGroupConsumers"
import GroupDetail from "../views/GroupDetail"
import VendorProgramList from "../views/VendorProgramList"
import VendorDetailProgram from "../views/VendorDetailProgram"
import VendorProgramMediaUpload from "../views/VendorProgramMediaUpload"
import VendorProgramCreator from "../views/VendorProgramCreator"
Vue.use(VueRouter)
const routes = [
{
path: "/",
redirect: `/${i18n.locale}/welcome/login`,
},
{
path: "/:lang(he)",
component: {
render(c) {
return c("router-view")
},
},
children: [
{
path: "welcome",
name: "Welcome",
component: Welcome,
children: [
{
path: "school-staff-register",
name: "CoordinatorRegister",
component: CoordinatorRegister,
props: true,
},
{
path: "vendor-register",
name: "VendorRegister",
component: VendorRegister,
},
{
path: "reset-password/:uid/:token",
name: "ResetPassword",
component: ResetPassword,
beforeEnter: flushToken,
props: true,
},
{
path: "login",
name: "Login",
component: Login,
beforeEnter: loginOrFlushStore,
},
],
},
{
path: "dashboard",
name: "Dashboard",
component: {
render(c) {
return c("router-view")
},
},
beforeEnter: checkRegistrationStatus,
},
{
path: "student-dashboard",
component: StudentDashboard,
beforeEnter: PopulateConsumerData,
children: [
{
path: "",
name: "StudentDashboard",
redirect: { name: "ConsumerProfile" },
},
{
path: "profile",
name: "ConsumerProfile",
component: ConsumerProfile,
},
{
path: "programs-explorer",
name: "ConsumerProgramsExplorer",
component: ConsumerProgramsExplorer,
beforeEnter: initConsumerPrograms,
children: [
{
path: "program-modal/:slug",
name: "ConsumerProgramModal",
component: ProgramModal,
beforeEnter: fetchProgramDetails,
props: true,
},
],
},
{
path: "my-activity",
component: ConsumerMyActivity,
children: [
{
path: "",
name: "ConsumerMyActivity",
redirect: { name: "ConsumerMyGroups" },
},
{
path: "my-groups",
name: "ConsumerMyGroups",
component: ConsumerMyGroups,
},
{
path: "my-events",
name: "ConsumerMyEvents",
component: ConsumerMyEvents,
},
{
path: "events-pending-feedbacks",
name: "ConsumerPendingEventsFeedback",
component: ConsumerPendingEventsFeedback,
},
{
path: "event-feedback/:slug",
name: "ConsumerEventFeedback",
component: ConsumerEventFeedback,
props: true,
},
],
},
],
},
{
path: "coordinator-dashboard",
component: CoordinatorDashboard,
beforeEnter: PopulateCoordinatorData,
children: [
{
path: "",
name: "CoordinatorDashboard",
redirect: { name: "CoordinatorProfile" },
},
{
path: "profile",
name: "CoordinatorProfile",
component: CoordinatorProfile,
},
{
path: "schoolDetails",
name: "SchoolDetails",
component: SchoolDetails,
},
{
path: "invite",
component: SchoolInviteWrapper,
children: [
{
path: "",
name: "SchoolInviteWrapper",
redirect: { name: "InviteConsumers" },
},
{
path: "invite-students",
name: "InviteConsumers",
component: InviteConsumers,
beforeEnter: flushPagination,
},
{
path: "invite-staff",
name: "InviteCoordinators",
component: InviteCoordinators,
beforeEnter: flushPagination,
},
],
},
{
path: "programs-explorer",
name: "ProgramsExplorer",
component: ProgramsExplorer,
beforeEnter: initPrograms,
children: [
{
path: "program-modal/:slug",
name: "ProgramModal",
component: ProgramModal,
beforeEnter: fetchProgramDetails,
props: true,
},
],
},
{
path: "my-activity",
component: MyActivity,
children: [
{
path: "",
name: "MyActivity",
redirect: { name: "MyGroups" },
},
{
path: "my-groups",
name: "MyGroups",
component: MyGroups,
},
{
path: "my-events",
name: "MyEvents",
component: MyEvents,
},
{
path: "student-list",
name: "ConsumerList",
component: ConsumerList,
beforeEnter: flushPagination,
},
{
path: "statistics",
name: "CoordinatorStatistics",
component: CoordinatorStatistics,
},
],
},
{
path: "detail-group/:groupSlug",
name: "GroupDetail",
component: GroupDetail,
props: true,
},
{
path: "group-editor",
component: GroupEditor,
children: [
{
path: "",
name: "GroupEditor",
redirect: { name: "CreateGroup" },
},
{
path: "create-group",
name: "CreateGroup",
component: CreateGroup,
},
{
path: "assign-group-students/:groupSlug",
name: "AssignGroupConsumers",
component: AssignGroupConsumers,
props: true,
},
],
},
],
},
{
path: "instructor-dashboard",
component: InstructorDashboard,
children: [
{
path: "",
name: "InstructorDashboard",
redirect: { name: "InstructorProfile" },
},
{
path: "profile",
name: "InstructorProfile",
component: InstructorProfile,
},
{
path: "unsummarized-events",
name: "InstructorUnsummarizedEvents",
component: InstructorUnsummarizedEvents,
},
{
path: "event-summary/:slug",
name: "InstructorEventSummary",
component: InstructorEventSummary,
props: true,
},
{
path: "event-feed-view",
name: "InstructorEventFeedView",
component: InstructorEventFeedView,
beforeEnter: flushPagination
},
],
},
{
path: "vendor-dashboard",
component: VendorDashboard,
children: [
{
path: "",
name: "VendorDashboard",
redirect: { name: "VendorProfile" },
},
{
path: "profile",
name: "VendorProfile",
component: VendorProfile,
},
{
path: "my-programs",
name: "VendorProgramList",
component: VendorProgramList,
},
{
path: "detail-program/:programSlug",
name: "VendorDetailProgram",
component: VendorDetailProgram,
props: true,
},
{
path: "program-creator",
name: "VendorProgramCreator",
component: VendorProgramCreator,
},
{
path: "program-media-upload/:programSlug",
name: "VendorProgramMediaUpload",
component: VendorProgramMediaUpload,
props: true,
},
{
path: "invite",
component: OrganizationInviteWrapper,
children: [
{
path: "",
name: "OrganizationInviteWrapper",
redirect: { name: "InviteInstructors" },
},
{
path: "invite-instructors",
name: "InviteInstructors",
component: InviteInstructors,
beforeEnter: flushPagination,
},
{
path: "invite-vendors",
name: "InviteVendors",
component: InviteVendors,
beforeEnter: flushPagination,
},
],
},
],
},
{
path: "error",
name: "Error",
component: GenericError,
props: true,
},
],
},
{
path: "*",
redirect: "/",
},
]
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes,
})
// make accessible across modules, to avoid Vue.use(VueRouter) reuse
Vue.$router = router
export default router
<file_sep><template>
<div>
<h1 v-text="$t('myActivity.statistics')" class="mb-5" />
<h2
v-text="$t('myActivity.advancedViewOfAllYourActivities')"
class="pb-12"
/>
<bubble-chart
class="mx-auto"
:data="bubbleChartData"
:label="bubbleChartLabel"
/>
<doughnut
style="width: 450px;"
class="mx-auto my-10"
:data="doughnutChartData"
:labels="doughnutChartLabels"
/>
</div>
</template>
<script>
import { mapState } from "vuex"
import store from "../vuex/store"
import BubbleChart from "../components/Charts/BubbleChart"
import Doughnut from "../components/Charts/Doughnut"
export default {
components: { BubbleChart, Doughnut },
async beforeRouteEnter(to, from, next) {
await store.dispatch("program/getTopConsumerRequestsStats")
next()
},
data() {
return {
hideDoughnut: true,
bubbleChartLabel: this.$t(
"myActivity.mostPopularProgramsByPendingRequests"
),
}
},
computed: {
...mapState("program", ["topConsumerRequestsStats"]),
bubbleChartData() {
return this.topConsumerRequestsStats.map(program => ({
x: Math.random() * 30,
y: Math.random() * 30,
r: program.consumerRequests * 10,
label: `${program.activityName} (${program.consumerRequests})`,
}))
},
doughnutChartLabels() {
return this.topConsumerRequestsStats.map(program => program.activityName)
},
doughnutChartData() {
return this.topConsumerRequestsStats.map(program => program.consumerRequests)
},
},
}
</script>
<file_sep>import random
from factory.django import DjangoModelFactory
from server.schools.models import School
class SchoolFactory(DjangoModelFactory):
name = "<NAME>"
address = "Shinkin 87"
address_city = "Tel Aviv"
address_zipcode = "0564665"
school_code = str(random.randint(10000, 99999))
description = "School description"
contact_phone = "0521234567"
website = "https://school.com"
profile_picture = None
grade_levels = [1, 2, 3, 4, 5, 6]
class Meta:
model = School
<file_sep># Generated by Django 3.1.11 on 2021-05-20 11:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Consumer',
fields=[
],
options={
'proxy': True,
'indexes': [],
'constraints': [],
},
bases=('users.user',),
),
migrations.CreateModel(
name='Coordinator',
fields=[
],
options={
'proxy': True,
'indexes': [],
'constraints': [],
},
bases=('users.user',),
),
migrations.CreateModel(
name='Vendor',
fields=[
],
options={
'proxy': True,
'indexes': [],
'constraints': [],
},
bases=('users.user',),
),
migrations.AddField(
model_name='user',
name='user_type',
field=models.CharField(choices=[('CONSUMER', 'Consumer'), ('COORDINATOR', 'Coordinator'), ('VENDOR', 'Vendor')], default='CONSUMER', max_length=50, verbose_name='Type'),
),
]
<file_sep>/// <reference types="cypress" />
describe("auth", () => {
beforeEach(() => {
cy.visit(Cypress.env("clientUrl"))
})
it("should login as a consumer", () => {
cy.get('[data-testid="email-input"]').type("<EMAIL>")
cy.get('[data-testid="password-input"]').type("<PASSWORD>")
cy.get("form").submit()
cy.url().should("contain", "dashboard")
})
it("should login as a coord for the first time & finish registration", () => {
cy.get('[data-testid="email-input"]').type("<EMAIL>")
cy.get('[data-testid="password-input"]').type("<PASSWORD>")
cy.get("form").submit()
// page 1
cy.get('[data-testid="name"]').type("<NAME>")
cy.get('[data-testid="phone"]').type("0521234567")
cy.get('[data-testid="form-1"]').submit()
// page 2
cy.get('[data-testid="school"]').type("בית ספר שרונים")
cy.get('[data-testid="school-code"]').type("05646564")
cy.get('[data-testid="school-city"]').type("תל אביב")
cy.get('[data-testid="street"]').type("רחוב החבצלת 56")
cy.get('[data-testid="school-zip-code"]').type("0522131")
cy.get('[data-testid="school-phone"]').type("0521234567")
cy.get('[data-testid="school-description"]').type("ביס יסודי שרונים")
cy.get('[data-testid="school-website"]').type("https://example.com")
cy.get('[data-testid="school-grades"]').parent().click()
cy.get(".v-select-list").first().children().first().click()
cy.get('[data-testid="form-2"]').submit()
cy.get('[data-testid="form-3"]').submit()
cy.get('[data-testid="modal-button"]').click()
cy.url().should("contain", "dashboard")
})
})
<file_sep>/// <reference types="cypress" />
describe("crud activity", () => {
beforeEach(() => {
cy.visit(Cypress.env("clientUrl"));
cy.get('[data-testid="email-input"]').type("<EMAIL>");
cy.get('[data-testid="password-input"]').type("<PASSWORD>");
cy.get("form").submit();
cy.url().should("contain", "dashboard");
cy.get('[data-testid="my-programs-navbar-btn"]').click();
cy.url().should("contain", "my-programs");
});
it("should create an activity", () => {
cy.get('[data-testid="program-create-btn"]').click();
cy.url().should("contain", "program-creator");
cy.get('[data-testid="name"]').type("Rapping with the Stars");
cy.get('[data-testid="description"]').type(
"I'm Slim Shady, yes, I'm the real Shady"
);
cy.get('[data-testid="targetAudience"]').parent().click();
cy.get(".v-select-list").first().children().first().click();
cy.get('[data-testid="domain"]').parent().click();
cy.get(".v-select-list").last().children().first().click();
cy.get('[data-testid="activityWebsiteUrl"]').type("https://website.com");
cy.get('[data-testid="activityEmail"]').type("<EMAIL>");
cy.get('[data-testid="contactName"]').type("דוד דוד");
cy.get('[data-testid="phoneNumber"]').type("0521234567");
cy.get('input[type="file"]').attachFile("testImage.jpg");
cy.get('[data-testid="save-btn"]').click();
cy.url().should("contain", "program-media-upload");
// media upload page
cy.get('[data-testid="add-media-btn"]').click();
cy.get('input[type="file"]').attachFile("testImage.jpg");
cy.get('[data-testid="save-btn"]').click();
cy.get('[data-testid="add-media-btn"]').click();
cy.get('[data-testid="media-type-select"]').parent().click();
cy.get(".v-select-list").last().children().last().click();
cy.get('input[type="text"]')
.last()
.type("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
cy.get('[data-testid="save-btn"]').click();
cy.get('[data-testid="finish-btn"]').click();
});
it("should update an activity", () => {
cy.get('[data-testid="info-btn"]').last().click();
cy.url().should("contain", "detail-program");
cy.get('[data-testid="input-drawer"]').first().click();
cy.get('[data-testid="name"]').clear().type("The Slim Shady Program");
cy.get("form").submit();
cy.url().should("contain", "my-programs");
cy.contains("The Slim Shady Program")
});
it("should delete an activity", () => {
cy.get('[data-testid="info-btn"]').last().click();
cy.url().should("contain", "detail-program");
cy.get('[data-testid="delete-btn"]').click();
cy.get('[data-testid="modal-approve-yes"]').click();
cy.url().should("contain", "my-programs");
});
});
<file_sep><template>
<div>
<canvas ref="doughnut" />
</div>
</template>
<script>
import Chart from "chart.js/auto"
export default {
props: {
labels: {
type: Array,
default() {
return []
},
},
colors: {
type: Array,
default() {
return ["#FFAEBC", "#A0E7E5", "#B4F8C8", "#FBE7C6", "#A49393", "#67595E"]
},
},
data: {
type: Array,
default() {
return []
},
},
options: {
type: Object,
default() {
return Chart.defaults.doughnut
},
},
},
mounted() {
this.createChart({
datasets: [
{
data: this.data,
backgroundColor: this.colors,
},
],
labels: this.labels,
})
},
methods: {
createChart(chartData) {
const canvas = this.$refs.doughnut
const options = {
type: "doughnut",
data: chartData,
options: this.options,
}
new Chart(canvas, options)
},
},
}
</script>
<file_sep>import pytest
from server.users.models import (
Consumer,
ConsumerProfile,
Coordinator,
CoordinatorProfile,
Vendor,
VendorProfile,
)
pytestmark = pytest.mark.django_db
def test_update_user_profile_signal():
consumer = Consumer.objects.create(email="<EMAIL>")
coordinator = Coordinator.objects.create(email="<EMAIL>")
vendor = Vendor.objects.create(email="<EMAIL>")
assert isinstance(consumer.profile, ConsumerProfile)
assert isinstance(coordinator.profile, CoordinatorProfile)
assert isinstance(vendor.profile, VendorProfile)
<file_sep>---
name: Bug Template
about: New Bug Template
title: "[Client/Server] | [Title]"
labels: bug
assignees: ''
---
### Bug Description
[Description of the bug]
### Steps to Reproduce
[Clear steps to reproduce the bug]
### Expected Behavior
[What should hapeen and currently doesn't]
### Actual Behavior
[The current behavior]
### Screenshots
[If applicable, add screenshots to help explain your problem]
### How to test?
[If there are available tests already, specify how to run them]
[](https://gitpod.io/from-referrer)
<file_sep>import random
import uuid
from django.core.validators import RegexValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
class PhoneNumberField(models.CharField):
def __init__(self, verbose_name=None, name=None, **kwargs):
kwargs.setdefault("max_length", 15)
super().__init__(verbose_name, name, **kwargs)
default_validators = [
RegexValidator(
regex=r"^\d{9,15}$",
message=_("Phone number must be between 9-15 digits."),
)
]
description = _("Phone Number")
class IdNumberField(models.CharField):
def __init__(self, verbose_name=None, name=None, **kwargs):
kwargs.setdefault("max_length", 9)
super().__init__(verbose_name, name, **kwargs)
default_validators = [
RegexValidator(
regex=r"^\d{9}$",
message=_("Id number must be between 9 digits."),
)
]
description = _("Id number")
def random_slug():
return uuid.uuid4().hex.upper()[0 : random.randint(10, 22)] # noqa
<file_sep># Generated by Django 3.1.11 on 2021-07-01 11:40
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('schools', '0004_school_last_updated_by'),
]
operations = [
migrations.AlterField(
model_name='school',
name='last_updated_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='last_updated_by_me_schools', to=settings.AUTH_USER_MODEL),
),
]
<file_sep>from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import (
Consumer,
ConsumerProfile,
Coordinator,
CoordinatorProfile,
Instructor,
InstructorProfile,
Supervisor,
SupervisorProfile,
Vendor,
VendorProfile,
)
@receiver(post_save, sender=Consumer)
@receiver(post_save, sender=Coordinator)
@receiver(post_save, sender=Instructor)
@receiver(post_save, sender=Vendor)
@receiver(post_save, sender=Supervisor)
def update_user_profile(sender, instance, created, **kwargs):
user_type_to_profile = {
get_user_model().Types.COORDINATOR: CoordinatorProfile,
get_user_model().Types.CONSUMER: ConsumerProfile,
get_user_model().Types.INSTRUCTOR: InstructorProfile,
get_user_model().Types.VENDOR: VendorProfile,
get_user_model().Types.SUPERVISOR: SupervisorProfile,
}
if created:
user_type_to_profile[instance.user_type].objects.create(
user=instance,
)
<file_sep># Generated by Django 3.1.11 on 2021-06-08 07:47
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_20210608_1047'),
('schools', '0003_auto_20210530_1028'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('organizations', '0003_auto_20210526_1138'),
]
operations = [
migrations.AlterField(
model_name='organizationmember',
name='organization',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='organization_member', to='organizations.organization'),
),
migrations.CreateModel(
name='SchoolActivityOrder',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status', models.CharField(choices=[('CANCELLED', 'Cancelled'), ('PENDING_ADMIN_APPROVAL', 'Pending Admin Approval'), ('APPROVED', 'Approved')], default='PENDING_ADMIN_APPROVAL', max_length=50, verbose_name='status')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('activity', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='school_activity_orders', to='organizations.activity')),
('last_updated_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='last_updated_by_me_orders', to=settings.AUTH_USER_MODEL)),
('requested_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='requested_orders', to=settings.AUTH_USER_MODEL)),
('school', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='school_activity_orders', to='schools.school')),
],
),
migrations.CreateModel(
name='SchoolActivityGroup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, verbose_name='name')),
('description', models.CharField(max_length=255, verbose_name='description')),
('container_only', models.BooleanField(default=False)),
('activity_order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='activity_groups', to='organizations.schoolactivityorder')),
('consumers', models.ManyToManyField(related_name='activity_groups', to='users.Consumer')),
],
),
migrations.AddConstraint(
model_name='schoolactivityorder',
constraint=models.UniqueConstraint(fields=('school', 'activity'), name='unique_order'),
),
]
<file_sep>from django.core.exceptions import ObjectDoesNotExist
from rest_framework import serializers
from taggit.serializers import TaggitSerializer, TagListSerializerField
from server.organizations.models import (
Activity,
ActivityMedia,
Organization,
SchoolActivityGroup,
SchoolActivityOrder,
)
from server.schools.models import School
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = [
"slug",
"email",
"description",
"website_url",
"name",
"goal",
"year_founded",
"status",
"target_audience",
"number_of_employees",
"number_of_members",
"number_of_volunteers",
"location_lon",
"location_lat",
"address_city",
"address_street",
"address_house_num",
"address_zipcode",
"cities",
"districts",
"union_type",
]
class ActivityMediaSerializer(serializers.ModelSerializer):
media_type = serializers.SerializerMethodField()
activity = serializers.SlugRelatedField(
queryset=Activity.objects.all(), slug_field="slug"
)
class Meta:
model = ActivityMedia
fields = [
"slug",
"name",
"media_type",
"video_url",
"image_url",
"activity",
]
def get_media_type(self, obj):
if obj.video_url:
return "video"
elif obj.image_url:
return "image"
def validate(self, data):
if data.get("video_url") and data.get("image_url"):
raise serializers.ValidationError("Cannot contain both image and video_url")
return data
def update(self, instance, validated_data):
if validated_data.get("video_url") and validated_data.get("image_url"):
raise serializers.ValidationError("Cannot contain both image and video_url")
return super().update(instance, validated_data)
class ActivitySerializer(TaggitSerializer, serializers.ModelSerializer):
is_ordered = serializers.SerializerMethodField()
order_status = serializers.SerializerMethodField()
tags = TagListSerializerField()
class Meta:
model = Activity
fields = [
"slug",
"name",
"target_audience",
"domain",
"originization",
"description",
"contact_name",
"phone_number",
"logo",
"phone_number",
"is_ordered",
"order_status",
"tags",
]
def get_order_status(self, obj):
user = self.context["request"].user
try:
return SchoolActivityOrder.objects.get(
school=user.school_member.school,
activity=obj,
).status
except ObjectDoesNotExist:
return None
def get_is_ordered(self, obj):
user = self.context["request"].user
if not hasattr(user, "school_member"):
return False
return (
SchoolActivityOrder.objects.filter(
school=user.school_member.school,
activity=obj,
)
.exclude(status=SchoolActivityOrder.Status.CANCELLED)
.exists()
)
class VendorActivitySerializer(serializers.ModelSerializer):
tags = TagListSerializerField()
class Meta:
model = Activity
fields = [
"slug",
"name",
"target_audience",
"domain",
"originization",
"activity_website_url",
"activity_email",
"description",
"contact_name",
"logo",
"phone_number",
"tags",
]
read_only_fields = ["slug", "originization"]
class ConsumerActivitySerializer(TaggitSerializer, serializers.ModelSerializer):
JOINED = "JOINED"
NOT_JOINED = "NOT_JOINED"
PENDING_GROUP_ASSIGNMENT = "PENDING_GROUP_ASSIGNMENT"
consumer_join_status = serializers.SerializerMethodField()
is_consumer_joined = serializers.SerializerMethodField()
tags = TagListSerializerField()
class Meta:
model = Activity
fields = [
"slug",
"name",
"target_audience",
"originization",
"description",
"logo",
"consumer_join_status",
"is_consumer_joined",
"tags",
]
def get_consumer_join_status(self, obj):
user = self.context["request"].user
# check if consumer is in a group
assigned_groups = SchoolActivityGroup.objects.filter(
activity_order__activity=obj,
consumers=user,
).exclude(group_type=SchoolActivityGroup.GroupTypes.DISABLED_CONSUMERS)
if not assigned_groups.exists():
return ConsumerActivitySerializer.NOT_JOINED
elif (
assigned_groups[0].group_type
== SchoolActivityGroup.GroupTypes.CONTAINER_ONLY
):
return ConsumerActivitySerializer.PENDING_GROUP_ASSIGNMENT
return ConsumerActivitySerializer.JOINED
def get_is_consumer_joined(self, obj):
user = self.context["request"].user
if not hasattr(user, "school_member"):
return False
if (
SchoolActivityGroup.objects.filter(
activity_order__activity=obj,
consumers=user,
)
.exclude(group_type=SchoolActivityGroup.GroupTypes.DISABLED_CONSUMERS)
.exists()
):
return True
return False
class ManageSchoolActivitySerializer(serializers.ModelSerializer):
school = serializers.SlugRelatedField(
queryset=School.objects.all(), slug_field="slug"
)
activity = serializers.SlugRelatedField(
queryset=Activity.objects.all(), slug_field="slug"
)
requested_by = serializers.CharField(source="requested_by.slug", read_only=True)
last_updated_by = serializers.CharField(
source="last_updated_by.slug",
read_only=True,
)
activity_name = serializers.CharField(source="activity.name", read_only=True)
class Meta:
model = SchoolActivityOrder
read_only_fields = (
"slug",
"created_at",
"updated_at",
)
fields = [
"slug",
"requested_by",
"last_updated_by",
"school",
"activity",
"status",
"created_at",
"updated_at",
"activity_name",
]
def validate(self, data):
"""
Check if the school is under the user & validate status
"""
user = self.context["request"].user
if (
not hasattr(user, "school_member")
or not data["school"] == user.school_member.school
):
raise serializers.ValidationError({"school": "must be a school member"})
if "status" in data and data["status"] not in [
SchoolActivityOrder.Status.CANCELLED,
SchoolActivityOrder.Status.PENDING_ADMIN_APPROVAL,
]:
raise serializers.ValidationError({"status": "invalid status"})
return data
class SchoolActivityGroupSerializer(serializers.ModelSerializer):
instructor_name = serializers.CharField(
source="instructor.name",
read_only=True,
)
activity_logo = serializers.ImageField(
source="activity_order.activity.logo",
read_only=True,
)
activity_name = serializers.CharField(
source="activity_order.activity.name",
read_only=True,
)
activity_order = serializers.SlugRelatedField(
queryset=SchoolActivityOrder.objects.all(), slug_field="slug"
)
class Meta:
model = SchoolActivityGroup
fields = [
"slug",
"activity_logo",
"activity_name",
"activity_order",
"name",
"description",
"consumers",
"group_type",
"instructor",
"instructor_name",
]
class ConsumerRequestDataSerializer(serializers.ModelSerializer):
activity_name = serializers.CharField(
source="activity_order.activity.name",
read_only=True,
)
consumer_requests = serializers.IntegerField()
class Meta:
model = SchoolActivityGroup
fields = [
"activity_name",
"consumer_requests",
]
<file_sep><template>
<div class="mx-auto">
<h1 class="mb-5" v-text="$t('invite.inviteVendors')" />
<h2
class="pb-12"
v-text="$t('invite.inviteAdditionalVendorsToJoinThePlatform')"
/>
<div class="mx-auto d-flex justify-center mt-10">
<v-card elevation="3" class="mb-15">
<v-card-title>
<v-text-field
v-model="searchFilter"
append-icon="mdi-magnify"
:label="$t('userActions.search')"
single-line
hide-details
class="px-10 mt-5 mb-8"
@click:append="
tableProps.options.page = 1
getVendors()
"
@keyup.enter="
tableProps.options.page = 1
getVendors()
"
/>
</v-card-title>
<v-data-table
show-select
multi-sort
v-bind.sync="tableProps"
v-model="selectedRows"
>
<template v-slot:item.actions="{ item }">
<v-icon size="20" class="mr-2" @click="editVendor(item)">
mdi-pencil
</v-icon>
</template>
</v-data-table>
<v-card-actions class="grey lighten-5 mt-3">
<v-btn
@click="addVendor"
:class="{ 'abs-center': $vuetify.breakpoint.smAndUp }"
text
v-text="$t('invite.inviteUser')"
/>
<v-spacer></v-spacer>
<div class="pl-2">
<v-btn
text
color="error"
@click="handleDeleteRequest"
:disabled="!selectedRows.length"
v-text="$t('invite.removeUser')"
/>
<v-tooltip bottom v-if="$vuetify.breakpoint.smAndUp">
<template v-slot:activator="{ on, attrs }">
<v-btn @click="triggerCSVUpload" icon v-bind="attrs" v-on="on">
<v-icon color="primary">mdi-file-upload</v-icon>
</v-btn>
</template>
<span class="px-3">{{ $t("userActions.import") }} CSV</span>
</v-tooltip>
<v-tooltip bottom v-if="$vuetify.breakpoint.smAndUp">
<template v-slot:activator="{ on, attrs }">
<v-btn
@click="exportCSV(tableProps.items)"
icon
v-bind="attrs"
v-on="on"
>
<v-icon color="primary">mdi-file-download-outline</v-icon>
</v-btn>
</template>
<span class="px-3">{{ $t("userActions.export") }}</span>
</v-tooltip>
</div>
</v-card-actions>
</v-card>
<v-file-input
id="csvImportInput"
class="d-none"
type="file"
accept=".csv"
v-model="csvFile"
>
</v-file-input>
<add-vendor-dialog
v-model="isDialogActive"
:title="dialogTitle"
:vendor="dialogVendor"
:slug="dialogSlug"
@save="getVendors"
/>
<modal v-show="popupMsg !== ''" @close="popupMsg = ''">
{{ popupMsg }}
</modal>
</div>
</div>
</template>
<script>
import { mapActions } from "vuex"
import debounce from "lodash/debounce"
import { exportCSV, translateStatus } from "./helpers"
import Modal from "../../components/Modal"
import AddVendorDialog from "../../components/AddDialog/AddVendorDialog"
export default {
components: {
Modal,
AddVendorDialog,
},
data() {
return {
searchFilter: "",
selectedRows: [],
tableProps: {
items: [],
itemKey: "email",
loading: false,
loadingText: this.$t("general.loading"),
serverItemsLength: this.$store.state.organization.totalVendors,
page: 1,
pageCount: undefined,
options: {},
headers: [
{ text: "", value: "actions", sortable: false },
{ text: this.$t("general.name"), value: "name" },
{ text: this.$t("general.email"), value: "email" },
],
},
csvFile: null,
isDialogActive: false,
popupMsg: "",
dialogVendor: {
name: "",
email: "",
},
dialogMode: "create",
dialogSlug: null,
}
},
computed: {
dialogTitle() {
if (this.dialogMode === "edit") {
return this.$t("invite.editVendor")
}
return this.$t("invite.inviteVendor")
},
},
watch: {
csvFile() {
if (this.csvFile) {
// on upload, run the import chain
this.importCSV()
}
},
"tableProps.options": {
// re-fetch data on user request (e.g., sort, next page)
deep: true,
handler() {
this.getVendors()
},
},
},
methods: {
...mapActions("pagination", ["updatePagination"]),
...mapActions("snackbar", ["showMessage"]),
...mapActions("organization", [
"getVendorList",
"deleteVendors",
"addVendors",
]),
exportCSV,
translateStatus,
async getVendors() {
this.tableProps.loading = true
let paginationOptions = {
itemsPerPage: this.tableProps.options.itemsPerPage,
page: this.tableProps.options.page,
searchFilter: this.searchFilter,
sortBy: this.tableProps.options.sortBy,
sortDesc: this.tableProps.options.sortDesc,
}
this.updatePagination(paginationOptions)
this.tableProps.items = await this.getVendorList()
this.tableProps.serverItemsLength =
this.$store.state.organization.totalVendors
this.tableProps.loading = false
},
async importCSV() {
try {
await this.addVendors(this.csvFile)
this.tableProps.options.page = 1
this.getVendors()
this.popupMsg = this.$t("general.detailsSuccessfullyUpdated")
} catch {
this.popupMsg = this.$t("errors.genericError")
}
},
triggerCSVUpload() {
document.getElementById("csvImportInput").click()
},
handleDeleteRequest: debounce(
async function () {
if (confirm(this.$t("confirm.AreYouSureYouWantToDelete?"))) {
let slugs = this.selectedRows.map(row => row.slug)
await this.deleteVendors(slugs)
this.selectedRows = []
this.getVendors()
this.showMessage(this.$t("success.userDeletedSuccessfully"))
}
},
500,
{ leading: true, trailing: false }
),
editVendor(vendor) {
this.dialogVendor = Object.assign({}, vendor)
delete this.dialogVendor.slug
this.dialogSlug = vendor.slug
this.dialogMode = "edit"
this.isDialogActive = true
},
addVendor() {
this.dialogSlug = null
this.dialogMode = "create"
this.isDialogActive = true
},
},
}
</script>
<style lang="scss" scoped>
.abs-center {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
</style>
<file_sep># Generated by Django 3.1.11 on 2021-07-11 12:46
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import server.utils.model_fields
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20210624_1022'),
('events', '0006_auto_20210711_1037'),
]
operations = [
migrations.CreateModel(
name='ConsumerEventFeedback',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.CharField(default=server.utils.model_fields.random_slug, max_length=40, unique=True)),
('general_notes', models.CharField(blank=True, max_length=400)),
('secondary_notes', models.CharField(blank=True, max_length=400)),
('general_rating', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)])),
('secondary_rating', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)])),
('consumer', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='users.consumer')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='events.event')),
],
),
]
<file_sep>from rest_framework_csv.renderers import CSVRenderer
class UsersCSVRenderer(CSVRenderer):
results_field = "results"
delete_fields = ["slug"]
def delete_keys_from_dict(self, dict_del, lst_keys):
"""
recursively delete keys from dict
"""
for k in lst_keys:
try:
del dict_del[k]
except KeyError:
pass
for v in dict_del.values():
if isinstance(v, dict):
self.delete_keys_from_dict(v, lst_keys)
return dict_del
def render(self, data, media_type=None, renderer_context=None):
if not isinstance(data, list):
data = data.get("results", [])
# Delete nested fields from objects.
data = [self.delete_keys_from_dict(obj, self.delete_fields) for obj in data]
# TODO: Refactor, this is magic that convert profile to gender only
data = [
{
**{k: v for k, v in obj.items() if k != "profile"},
**(
{"gender": obj["profile"]["gender"]} if "profile" in obj else {}
),
}
for obj in data
]
return super(UsersCSVRenderer, self).render(data, media_type, renderer_context)
<file_sep><template>
<v-card class="w-75 mx-auto pt-16">
<v-data-table
show-select
multi-sort
v-model="selectedRows"
:headers="headers"
:items="value"
:items-per-page="5"
:loadingText="loadingText"
:itemsPerPage="-1"
:item-key="itemKey"
>
<template v-slot:item.actions="{ item }">
<!-- edit row column ("pencil") -->
<v-icon size="20" class="mr-2" @click="editRow(item)">
mdi-pencil
</v-icon>
</template>
</v-data-table>
<v-card-actions class="relative grey lighten-5 mt-3">
<v-btn
@click="openDialog()"
:class="{ 'absolute-center': $vuetify.breakpoint.smAndUp }"
text
v-text="$tc('userActions.add', 1)"
/>
<v-spacer></v-spacer>
<div class="pl-2">
<v-btn
text
color="error"
@click="deleteRows(selectedRows)"
:disabled="!selectedRows.length"
v-text="$tc('userActions.remove', 2)"
/>
<v-tooltip bottom>
<template v-slot:activator="{ on, attrs }">
<v-btn icon v-bind="attrs" v-on="on">
<v-icon color="primary">mdi-file-upload</v-icon>
</v-btn>
</template>
<span class="px-3">{{ $t("userActions.import") }} CSV</span>
</v-tooltip>
<v-tooltip bottom>
<template v-slot:activator="{ on, attrs }">
<v-btn icon v-bind="attrs" v-on="on">
<v-icon color="primary">mdi-file-download-outline</v-icon>
</v-btn>
</template>
<span class="px-3">{{ $t("userActions.export") }}</span>
</v-tooltip>
</div>
</v-card-actions>
<form-dialog
v-model="isDialogActive"
:inputFields="formFields"
@save="saveRow"
/>
<modal v-show="popupMsg !== ''" @close="popupMsg = ''">
{{ popupMsg }}
</modal>
</v-card>
</template>
<script>
import FormDialog from "./FormDialog"
import Modal from "./Modal"
import isEqual from "lodash/isEqual"
import cloneDeep from "lodash/cloneDeep"
export default {
components: { FormDialog, Modal },
props: {
value: {
// the table rows
// empty Array, or: [ { col1: value, col2: value2, ... }, { col1: value, col2: value, ... }, ... ]
type: Array,
required: true,
},
columns: {
// [{ name: 'column name', rule: 'validation rules for input', label: 'readable column name' }, { ... }]
type: Array,
required: true,
validator(cols) {
// heuristic validation (on first column only)
const keys = Object.keys(cols[0])
keys.sort()
return isEqual(keys, ["label", "name", "rule"])
},
},
itemKey: {
// v-data-table item-key (column name to act as key)
type: String,
required: true,
},
},
created() {
// validate "value" prop based on column prop (check heuristically for missing fields)
if (!this.$props.value.length) {
return
}
const columnNames = this.$props.columns.map(col => col.name)
const firstRow = this.$props.value[0]
for (const field of Object.keys(firstRow)) {
if (!columnNames.includes(field)) {
throw `Prop Validation: '${field}' of prop 'value' does not exist in prop 'columns'`
}
}
},
data() {
return {
editedRowIndex: -1,
formFields: cloneDeep(this.columns),
isDialogActive: false,
csvFile: null,
selectedRows: [],
loadingText: this.$t("general.loading"),
headers: this.initHeaders(this.columns),
popupMsg: "",
}
},
methods: {
initHeaders(columns) {
// return a headers object for v-data-table based on the columns prop
const headers = [{ text: "", value: "actions", sortable: false }]
for (const col of columns) {
headers.push({ text: col.label, value: col.name })
}
return headers
},
editRow(row) {
this.editedRowIndex = this.value.indexOf(row)
this.openDialog(row)
},
saveRow(formResult) {
if (this.editedRowIndex > -1) {
// edit mode - modify row
const rows = [...this.value]
rows[this.editedRowIndex] = formResult
this.$emit("input", rows)
this.editedRowIndex = -1
} else {
// create new row
if (
this.value.filter(
row => row[this.itemKey] === formResult[this.itemKey]
).length
) {
this.popupMsg = `${this.$t(
"errors.recordWithTheSameValueAlreadyExists"
)}: ${formResult[this.itemKey]}`
} else {
this.$emit("input", [...this.value, formResult])
}
}
},
deleteRows(selectedRows) {
const remainingRows = this.value.filter(
row => !selectedRows.includes(row)
)
this.$emit("input", remainingRows)
},
openDialog(rowToEdit = {}) {
// add placeholder/default values to pass to form dialog (empty on new row, actual data on edit)
// open dialog
// :Object rowToEdit: { fieldName: value, ... } e.g., { city: 'Tel Aviv', ... }
for (const field of this.formFields) {
this.$set(field, "value", rowToEdit[field.name] || "")
}
this.isDialogActive = true
},
},
}
</script>
|
c350bf35a090833b183ca528b894fd2ea50c1884
|
[
"Shell",
"Markdown",
"Procfile",
"Dockerfile",
"YAML",
"Vue",
"JavaScript",
"Python",
"Text"
] | 217 |
Shell
|
Eyal-VR/connective
|
46857dd79dc58f63c3afb9791ecf8adf853a6c57
|
61e9cb756a8ce4e2c896162b7483e2a43dccdcd2
|
refs/heads/master
|
<file_sep># Analyzing Snapchat Advertisement using Social Media Spend Analytics
<p>The Snapchat data was analysed using Tableau and the trend was examined as to what events lead to an increase in the number of Ads across countries. They were analysed wrt their age, segments, language, interests and gender. The trend before and after election was also examined along with the Top 5 contributors of Ad production across various countries. #makeovermonday #tableaupublic </p>
<b>Link for the Tableau file:</b> https://public.tableau.com/profile/chetan1190#!/vizhome/AnalyzingSnapchatAdvertisementDatausingSocialMediaSpendAnalytics/Dashboard1?publish=yes
|
ef2c89172c8bc910bc4224ce901c560770a039a1
|
[
"Markdown"
] | 1 |
Markdown
|
chetan2511/Analyzing-Snapchat-Advertisement-using-Social-Media-Spend-Analytics
|
3fbf0621150a0f0c24389d51476a8c1995cc3b12
|
64f2ba5205f884fe28bf02aa57056405c1e9bc9c
|
refs/heads/master
|
<repo_name>byNova/TaxiClientApp<file_sep>/app/src/main/java/valsoft/darkfree/taxiclient/api/models/requests/AuthorizationRequest.java
package valsoft.darkfree.taxiclient.api.models.requests;
public class AuthorizationRequest {
String phone_number;
String password;
public AuthorizationRequest(String phone_number, String password) {
this.phone_number = phone_number;
this.password = <PASSWORD>;
}
}
<file_sep>/app/src/main/java/valsoft/darkfree/taxiclient/acrivities/NewOrderActivity.kt
package valsoft.darkfree.taxiclient.acrivities
import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.NetworkOnMainThreadException
import android.support.design.widget.TextInputEditText
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.Gravity
import android.widget.*
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.yandex.mapkit.MapKitFactory
import com.yandex.mapkit.driving.*
import com.yandex.mapkit.geometry.Point
import com.yandex.runtime.Error
import okhttp3.*
import org.json.JSONObject
import valsoft.darkfree.taxiclient.R
import valsoft.darkfree.taxiclient.adapters.AddressAutoCompleteAdapter
import valsoft.darkfree.taxiclient.api.models.requests.NewOrderRequest
import valsoft.darkfree.taxiclient.api.models.responses.NewOrderResponse
import valsoft.darkfree.taxiclient.app.App
import valsoft.darkfree.taxiclient.dialogs.DateDialog
import valsoft.darkfree.taxiclient.dialogs.TimeDialog
import valsoft.darkfree.taxiclient.utils.*
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
class NewOrderActivity : AppCompatActivity() , LocationListener{
private val TAG = "NewOrderActivity"
private var editTextClientName: TextInputEditText? = null
private var editTextPhone: TextInputEditText? = null
private var editTextFrom: AutoCompleteTextView? = null
private var editTextTo: AutoCompleteTextView? = null
private var textViewTaxiArrivalTime: TextView? = null
private var timeLayout: RelativeLayout? = null
private var optionConditioner: Boolean = false
private var optionChildSeat: Boolean = false
private var radioGroupPaymentType: RadioGroup? = null
private var distance: TextView? = null
private var totalPrice: TextView? = null
private var orderTaxi: Button? = null
private var myAddress = ""
private var totalDistance = 0.0
private var orderCost = 0.0
private var mFusedLocationClient: FusedLocationProviderClient? = null
private var clientLat: Double? = null
private var clientLng: Double? = null
private var drivingRouter: DrivingRouter? = null
private var drivingSummaryListener: DrivingSummarySession.DrivingSummaryListener? = null
private var clientId = 0
private var clientName = ""
private var clientPhone = ""
@SuppressLint("MissingPermission")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MapKitFactory.setApiKey(YANDEX_MAP_KIT_KEY)
MapKitFactory.initialize(this)
setContentView(R.layout.activity_new_order)
editTextClientName = findViewById(R.id.edit_text_client_name)
editTextPhone = findViewById(R.id.edit_text_phone)
editTextFrom = findViewById(R.id.edit_text_from)
editTextTo = findViewById(R.id.edit_text_to)
textViewTaxiArrivalTime = findViewById(R.id.text_view_taxi_arrival_time)
orderTaxi = findViewById(R.id.order_taxi)
timeLayout = findViewById(R.id.layout_time)
radioGroupPaymentType = findViewById(R.id.radio_group_payment_type)
totalPrice = findViewById(R.id.total_price)
distance = findViewById(R.id.distance)
loadSharedPreferences()
insertNameAndPhone()
prepareInputFields()
initializingOfYanDexDriverListeners()
grantLocationPermission()
setLocaleAddress()
}
private fun loadSharedPreferences() {
val sp = getSharedPreferences(LOG_IN_SP, Context.MODE_PRIVATE)
clientId = sp.getInt("client_id", 0)
clientName = sp.getString("surname_and_name", "")
clientPhone = sp.getString("phone", "")
}
override fun onStart() {
super.onStart()
MapKitFactory.getInstance().onStart()
}
override fun onStop() {
MapKitFactory.getInstance().onStop()
drivingRouter?.suspend()
super.onStop()
}
private fun insertNameAndPhone() {
editTextClientName?.setText(clientName)
editTextPhone?.setText(clientPhone)
if(editTextClientName?.text?.isNotEmpty()!!) {
with(editTextClientName!!){
isFocusable = false
isClickable = false
isCursorVisible = false
isFocusableInTouchMode = false
}
}
if(editTextPhone?.text?.isNotEmpty()!!){
with(editTextPhone!!){
isFocusable = false
isClickable = false
isCursorVisible = false
isFocusableInTouchMode = false
}
}
}
private fun prepareInputFields() {
radioGroupPaymentType?.setOnCheckedChangeListener{_, checkedId ->
val radioButtonPaymentCash: RadioButton? = findViewById(R.id.radio_button_payment_cash)
val radioButtonPaymentCard: RadioButton? = findViewById(R.id.radio_button_payment_card)
when (checkedId) {
R.id.radio_button_payment_cash -> {
radioButtonPaymentCash?.setButtonDrawable(R.drawable.radio_button_checked)
radioButtonPaymentCard?.setButtonDrawable(R.drawable.radio_button_unchecked)
}
R.id.radio_button_payment_card -> {
radioButtonPaymentCard?.setButtonDrawable(R.drawable.radio_button_checked)
radioButtonPaymentCash?.setButtonDrawable(R.drawable.radio_button_unchecked)
}
else -> {
}
}
}
timeLayout?.setOnClickListener {
TimeDialog(textViewTaxiArrivalTime).show(fragmentManager,"NewOrderActivity")
}
editTextFrom?.setAdapter(AddressAutoCompleteAdapter(this))
editTextTo?.setAdapter(AddressAutoCompleteAdapter(this))
editTextFrom?.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
val builder = AlertDialog.Builder(this)
val inflater = this.layoutInflater
val dialogView = inflater.inflate(R.layout.alert_dialog_input_address, null)
builder.setView(dialogView)
val editTextCity = dialogView.findViewById(R.id.edit_text_city) as AutoCompleteTextView?
val editTextStreet = dialogView.findViewById(R.id.edit_text_street) as AutoCompleteTextView?
val editTextBuilding = dialogView.findViewById(R.id.edit_text_building) as EditText?
val myAddressSet = myAddress.split(",")
editTextCity?.setText("${myAddressSet[0]},${myAddressSet[1]}")
editTextStreet?.requestFocus()
builder.setTitle("Ввод адреса \"Откуда\"")
.setCancelable(false)
.setPositiveButton("Ок", { _, _ ->
val city = editTextCity?.text.toString()
val street = editTextStreet?.text.toString()
val building = editTextBuilding?.text.toString()
val addressFrom = "$city, $street, $building"
editTextFrom?.setText(addressFrom)
// todo: посчитать стоимость поездки откуда\куда
val from = editTextFrom?.text.toString()
val to = editTextTo?.text.toString()
if (from != "" && to != "") {
computeOrderCost(from, to)
}
})
.setNeutralButton("Отмена", { _, _ ->
})
val alert = builder.create()
alert.show()
}
}
editTextTo?.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
val builder = AlertDialog.Builder(this)
val inflater = this.layoutInflater
val dialogView = inflater.inflate(R.layout.alert_dialog_input_address, null)
builder.setView(dialogView)
val editTextCity = dialogView.findViewById(R.id.edit_text_city) as AutoCompleteTextView?
val editTextStreet = dialogView.findViewById(R.id.edit_text_street) as AutoCompleteTextView?
val editTextBuilding = dialogView.findViewById(R.id.edit_text_building) as EditText?
val myAddressSet = myAddress.split(",")
editTextCity?.setText("${myAddressSet[0]}, ${myAddressSet[1]}")
editTextStreet?.requestFocus()
builder.setTitle("Ввод адреса \"Куда\"")
.setCancelable(false)
.setPositiveButton("Ок", { _, _ ->
val city = editTextCity?.text.toString()
val street = editTextStreet?.text.toString()
val building = editTextBuilding?.text.toString()
val addressFrom = "$city, $street, $building"
editTextTo?.setText(addressFrom)
// todo: посчитать стоимость поездки откуда\куда
val from = editTextFrom?.text.toString()
val to = editTextTo?.text.toString()
if (from != "" && to != "") {
computeOrderCost(from, to)
}
})
.setNeutralButton("Отмена", { _, _ ->
})
val alert = builder.create()
alert.show()
}
}
findViewById<RelativeLayout>(R.id.options_layout)?.setOnClickListener {
val builder = AlertDialog.Builder(this)
val dialogView = this.layoutInflater.inflate(R.layout.alert_dialog_options, null)
builder.setView(dialogView)
val conditioner = dialogView.findViewById<CheckBox>(R.id.option_conditioner)
val childSeat = dialogView.findViewById<CheckBox>(R.id.option_child_seat)
conditioner?.isChecked = optionConditioner
childSeat?.isChecked = optionChildSeat
builder.setTitle("Особые пожелания:").setCancelable(false).setPositiveButton("OK", {_,_->
optionConditioner = conditioner?.isChecked!!
optionChildSeat = childSeat?.isChecked!!
val extraOptions = findViewById<TextView>(R.id.tvExtraOptionsDescr)
when{
optionConditioner and optionChildSeat -> {
extraOptions?.text = "[Детское сиденье, Кондиционер]"
}
optionConditioner -> {
extraOptions?.text = "[Кондиционер]"
}
optionChildSeat -> {
extraOptions?.text = "[Детское сиденье]"
}
else -> {
extraOptions?.setText(R.string.without_extra_options)
}
}
}).setNeutralButton("Отмена", {_,_->}).create().show()
}
orderTaxi?.setOnClickListener {
when{
editTextFrom?.text?.isEmpty()!! -> {
Toast.makeText(this@NewOrderActivity, "Точка отправления не определена!", Toast.LENGTH_LONG).show()
}
editTextTo?.text?.isEmpty()!! -> {
Toast.makeText(this@NewOrderActivity, "Точка прибытия не определена!", Toast.LENGTH_LONG).show()
}
totalPrice?.text?.get(0) == '0' -> {
computeOrderCost(editTextFrom?.text?.toString()!!, editTextTo?.text?.toString()!!)
AlertDialog.Builder(this)
.setTitle("Не удалось проложить маршрут!")
.setMessage("Проверьте правильность введенных данных и повторите попытку")
.setCancelable(false)
.setPositiveButton(R.string.ok, {_,_->}).create().show()
}
clientId != 0 -> {
val calendar = Calendar.getInstance()
val time = if(textViewTaxiArrivalTime?.text?.contains(getString(R.string.now),ignoreCase = true)!!) {
SimpleDateFormat("HH:mm:ss").format(calendar.time)
}else{
"${textViewTaxiArrivalTime?.text}:00"
}
var paymentType = PAYMENT_TYPE_CASH
when (radioGroupPaymentType?.checkedRadioButtonId) {
R.id.radio_button_payment_cash -> {
paymentType = PAYMENT_TYPE_CASH // Наличные
}
R.id.radio_button_payment_card -> {
paymentType = PAYMENT_TYPE_CARD // Карта
}
}
App.api?.createNewOrder(NewOrderRequest(
clientId,
editTextFrom?.text?.toString()!!,
editTextTo?.text?.toString()!!,
optionChildSeat,
optionConditioner,
paymentType.toShort(),
totalDistance,
orderCost,
SimpleDateFormat("yyyy-MM-dd").format(calendar.time),
time
))?.enqueue(object: retrofit2.Callback<NewOrderResponse>{
override fun onFailure(call: retrofit2.Call<NewOrderResponse>?, t: Throwable?) {
AlertDialog.Builder(this@NewOrderActivity)
.setTitle("При создании нового заказа возникла ошибка!")
.setMessage("Проверьте правильность введенных данных и повторите попытку")
.setCancelable(false)
.setPositiveButton(R.string.ok, {_,_->}).create().show()
}
override fun onResponse(call: retrofit2.Call<NewOrderResponse>?, response: retrofit2.Response<NewOrderResponse>?) {
val r = response?.body()
Log.d(TAG, "onServerResponse:${r?.toString()}")
try{
if(r?.status!!){
Toast.makeText(this@NewOrderActivity, "Заказ успешно создан!", Toast.LENGTH_LONG).show()
with(getSharedPreferences(ORDER_SP, Context.MODE_PRIVATE).edit()){
putInt("order_id", r.order_id)
putString("from", r.order_detail.address_from)
putString("to", r.order_detail.address_to)
putFloat("distance", r.order_detail.distance.toFloat())
putFloat("order_price", r.order_detail.price.toFloat())
putInt("payment_type",r.order_detail.payment_type.toInt())
putString("date", r.order_detail.planed_date)
putString("time", r.order_detail.planed_time)
apply()
}
startActivity(Intent(this@NewOrderActivity, OrderDetailActivity::class.java))
}
}catch (e: KotlinNullPointerException){
AlertDialog.Builder(this@NewOrderActivity)
.setTitle("При создании нового заказа возникла ошибка!")
.setMessage("Проверьте правильность введенных данных и повторите попытку")
.setCancelable(false)
.setPositiveButton(R.string.ok, {_,_->}).create().show()
}
}
})
}
}
}
}
private fun initializingOfYanDexDriverListeners() {
drivingSummaryListener = object : DrivingSummarySession.DrivingSummaryListener {
override fun onDrivingSummaries(points: MutableList<Summary>?) {
totalDistance = 0.0
totalDistance += points!![0].weight.distance.value
// БИЗНЕС-ЛОГИКА РАСЧЁТА СТОИМОСТИ ЗАКАЗА:
totalDistance /= METERS_IN_KILOMETERS
totalDistance = Math.round(totalDistance).toDouble()
orderCost = if (totalDistance <= 7) {
MINIMAL_ORDER_COST.toDouble()
} else {
Math.round(totalDistance * COST_RUB_PER_KILOMETER).toDouble()
}
totalPrice?.text = "${orderCost.toInt()}руб."
distance?.text = "${totalDistance}км"
Log.d("MainActivity", "onDrivingSummariesSuccess")
}
override fun onDrivingSummariesError(p0: Error?) {
Log.e("MainActivity", "onDrivingSummariesError")
}
}
drivingRouter = MapKitFactory.getInstance().createDrivingRouter()
}
private fun computeOrderCost(from: String, to: String) {
Log.d("MainActivity", "computeOrderCost")
if (from != "" && to != "") {
Thread {
val fromAddress = getFromLocationName(from)
val toAddress = getFromLocationName(to)
val fromLat = fromAddress.latitude
val fromLng = fromAddress.longitude
Log.d("computeOrderCost", "from_lat:$fromLat")
Log.d("computeOrderCost", "from_lng:$fromLng")
val toLat = toAddress.latitude
val toLng = toAddress.longitude
Log.d("computeOrderCost", "to_lat:$toLat")
Log.d("computeOrderCost", "to_lng:$toLng")
val fromPoint = Point(fromLat, fromLng)
val toPoint = Point(toLat, toLng)
runOnUiThread {
submitRequest(fromPoint, toPoint)
}
}.start()
}
}
private fun submitRequest(route_start_location: com.yandex.mapkit.geometry.Point, route_end_location: com.yandex.mapkit.geometry.Point) {
Log.d("MainActivity", "submitRequest")
val options = DrivingOptions()
val requestPoints = ArrayList<RequestPoint>()
requestPoints.add(RequestPoint(
route_start_location, ArrayList(), RequestPointType.WAYPOINT))
requestPoints.add(RequestPoint(
route_end_location, ArrayList(), RequestPointType.WAYPOINT))
drivingRouter!!.requestRoutesSummary(requestPoints, options, drivingSummaryListener!!)
}
private fun getFromLocationName(place: String): Location {
Log.d("MainActivity", "getFromLocationName")
val url = "https://geocode-maps.yandex.ru/1.x/?format=json&geocode=$place"
val location = Location("")
try {
val okHttpClient = OkHttpClient()
val request = Request.Builder().url(url).build()
val response = okHttpClient.newCall(request).execute()
val stringResponse = response.body()?.string()
val jsonResponse = JSONObject(stringResponse)
val respJson = jsonResponse.getJSONObject("response")
val geoObjectCollection = respJson.getJSONObject("GeoObjectCollection")
val featureMember = geoObjectCollection.getJSONArray("featureMember")
val item = featureMember.getJSONObject(0)
val geoObject = item.getJSONObject("GeoObject")
val point = geoObject.getJSONObject("Point")
val pos = point.getString("pos")
val lng = pos.substring(0, pos.indexOf(" ")).toDouble()
val lat = pos.substring(pos.indexOf(" ") + 1).toDouble()
location.latitude = lat
location.longitude = lng
} catch (e: IOException) {}
return location
}
private fun grantLocationPermission() {
val fineLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
if (fineLocationPermission != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
MY_PERMISSIONS_REQUEST_LOCATION)
}
} else {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
(getSystemService(Context.LOCATION_SERVICE) as LocationManager).requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1.0f, this)
}
}
override
fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
MY_PERMISSIONS_REQUEST_LOCATION -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}
return
}
else -> return
}
}
@SuppressWarnings("MissingPermission")
private fun getLastLocation(callback: () -> Unit) {
mFusedLocationClient?.lastLocation?.addOnCompleteListener(this) { task ->
if (task.isSuccessful && task.result != null) {
val mLastLocation = task.result
clientLat = mLastLocation.latitude
clientLng = mLastLocation.longitude
callback()
} else {
val toast = Toast.makeText(this@NewOrderActivity, "Нет координат устройства!", Toast.LENGTH_LONG)
toast.setGravity(Gravity.CENTER, 0, 0)
toast.show()
}
}
}
override fun onLocationChanged(location: Location?) {
clientLat = location?.latitude
clientLng = location?.longitude
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
}
override fun onProviderEnabled(provider: String?) {
}
override fun onProviderDisabled(provider: String?) {
}
private fun setLocaleAddress() {
getLastLocation {
val url = "https://geocode-maps.yandex.ru/1.x/?format=json&geocode=" + clientLng?.toString() + "," + clientLat?.toString()
try {
val okHttpClient = OkHttpClient()
val request = Request.Builder().url(url).build()
val call = okHttpClient.newCall(request)
call.enqueue(object : Callback {
override fun onFailure(call: Call?, e: IOException?) {
Toast.makeText(this@NewOrderActivity, "Не удалось опредилить ваше место положения", Toast.LENGTH_SHORT).show()
}
override fun onResponse(call: Call?, response: Response?) {
myAddress = JSONObject(response!!.body()?.string()).getJSONObject("response").getJSONObject("GeoObjectCollection").getJSONArray("featureMember").getJSONObject(0).getJSONObject("GeoObject").getJSONObject("metaDataProperty").getJSONObject("GeocoderMetaData").getString("text")
runOnUiThread {
findViewById<TextView>(R.id.edit_text_from).text = myAddress
}
}
})
} catch (e: IOException) {
e.printStackTrace()
} catch (e: NetworkOnMainThreadException) {
e.printStackTrace()
Toast.makeText(this@NewOrderActivity, "Не удалось опредилить ваше место положения", Toast.LENGTH_SHORT).show()
}
}
}
}
<file_sep>/app/src/main/java/valsoft/darkfree/taxiclient/app/App.kt
package valsoft.darkfree.taxiclient.app
import android.support.multidex.MultiDexApplication
import android.util.Log
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import valsoft.darkfree.taxiclient.api.ClientApi
class App: MultiDexApplication(){
override fun onCreate() {
super.onCreate()
retrofit = Retrofit.Builder()
.baseUrl("http://192.168.3.11/api/client/")
.addConverterFactory(GsonConverterFactory.create())
.build()
api = retrofit?.create(ClientApi::class.java)
}
companion object {
var api: ClientApi? = null
var retrofit: Retrofit? = null
}
}<file_sep>/app/src/main/java/valsoft/darkfree/taxiclient/acrivities/IntroActivity.kt
package valsoft.darkfree.taxiclient.acrivities
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.LocationManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.widget.TextView
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import valsoft.darkfree.taxiclient.R
import valsoft.darkfree.taxiclient.utils.LOG_IN_SP
import valsoft.darkfree.taxiclient.utils.MY_PERMISSIONS_REQUEST_LOCATION
class IntroActivity : AppCompatActivity() {
private var mFusedLocationClient: FusedLocationProviderClient? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_intro)
grantLocationPermission()
findViewById<TextView>(R.id.sign_in)?.setOnClickListener {
startActivity(Intent(this, AuthorizationActivity::class.java))
}
findViewById<TextView>(R.id.sign_up)?.setOnClickListener {
startActivity(Intent(this, RegistrationActivity::class.java))
}
if(getSharedPreferences(LOG_IN_SP, Context.MODE_PRIVATE).getInt("client_id", 0) != 0){
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
private fun grantLocationPermission() {
val fineLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
if (fineLocationPermission != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
MY_PERMISSIONS_REQUEST_LOCATION)
}
} else {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}
}
}
<file_sep>/app/src/main/java/valsoft/darkfree/taxiclient/acrivities/AuthorizationActivity.kt
package valsoft.darkfree.taxiclient.acrivities
import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import valsoft.darkfree.taxiclient.R
import valsoft.darkfree.taxiclient.api.models.requests.AuthorizationRequest
import valsoft.darkfree.taxiclient.api.models.responses.AuthorizationResponse
import valsoft.darkfree.taxiclient.app.App
import valsoft.darkfree.taxiclient.utils.LOG_IN_SP
class AuthorizationActivity : AppCompatActivity() {
var phone: EditText? = null
var password: EditText? = null
var submit: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_authorization)
phone = findViewById(R.id.phone)
password = findViewById(R.id.password)
submit = findViewById(R.id.submit)
submit?.setOnClickListener {
when {
phone?.text?.toString()?.isEmpty()!! -> Toast.makeText(this, "Неверний номер",Toast.LENGTH_SHORT).show()
password?.text?.toString()?.isEmpty()!! -> Toast.makeText(this, "Неверний пароль",Toast.LENGTH_SHORT).show()
else -> {
submit?.isActivated = false
App.api?.authorization(AuthorizationRequest(
phone?.text?.toString(),
password?.text?.toString())
)?.enqueue(object : Callback<AuthorizationResponse>{
override fun onFailure(call: Call<AuthorizationResponse>?, t: Throwable?) {
submit?.isActivated = true
Toast.makeText(this@AuthorizationActivity, call?.request()?.body()?.toString(), Toast.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<AuthorizationResponse>?, response: Response<AuthorizationResponse>?) {
if(response?.body()?.status!!){
val client = response.body()?.client
Log.d("AuthorizationResponse", client?.toString())
with(getSharedPreferences(LOG_IN_SP, Context.MODE_PRIVATE).edit()){
putInt("client_id", client?.id!!)
putString("phone", client.phone_number)
putString("surname_and_name", "${client.surname} ${client.name}")
apply()
}
Toast.makeText(this@AuthorizationActivity, "Авторизация успешна", Toast.LENGTH_SHORT).show()
startActivity(Intent(this@AuthorizationActivity, MainActivity::class.java))
finish()
}else{
password?.text?.clear()
Toast.makeText(this@AuthorizationActivity, "Неверный номер или пароль", Toast.LENGTH_SHORT).show()
}
}
})
}
}
}
}
}
<file_sep>/app/src/main/java/valsoft/darkfree/taxiclient/adapters/AddressAutoCompleteAdapter.kt
package valsoft.darkfree.taxiclient.adapters
import android.content.Context
import android.location.Address
import android.location.Geocoder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Filter
import android.widget.Filterable
import android.widget.TextView
import valsoft.darkfree.taxiclient.R
import java.io.IOException
class AddressAutoCompleteAdapter : BaseAdapter, Filterable {
companion object {
const val GEOCODER_MAX_RESULTS = 10
}
private val mContext: Context
private var mResults: List<String>
private var addressesOrigin: List<Address>? = null
constructor(context: Context) {
mContext = context
mResults = ArrayList<String>()
}
override fun getCount(): Int {
return mResults.size
}
override fun getItem(index: Int): String {
return mResults.get(index)
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var convertView1 = convertView
if (convertView1 == null) {
val inflater = LayoutInflater.from(mContext)
convertView1 = inflater.inflate(R.layout.address_autocomplete_results_list, parent, false)
}
val place: String = getItem(position)
(convertView1?.findViewById(R.id.address_autocomplete_item) as TextView).setText(place)
return convertView1
}
override fun getFilter(): Filter {
return object: Filter() {
override fun performFiltering(constraint: CharSequence?): FilterResults {
val filterResults = FilterResults()
if (constraint != null) {
val places = findPlaces(constraint.toString())
filterResults.values = places
filterResults.count = places.size
}
return filterResults
}
override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
if (results != null && results.count > 0) {
mResults = results.values as (List<String>)
notifyDataSetChanged()
} else {
notifyDataSetInvalidated()
}
}}
}
/**
* поиск адресов по адресу
*/
private fun findPlaces(place: String): List<String> {
// todo: сделать запрос на сервер для получения списка адресов по выбранному
val results = ArrayList<String>()
val geocoder = Geocoder(mContext)
try {
addressesOrigin = geocoder.getFromLocationName(place, GEOCODER_MAX_RESULTS)
} catch (e: IOException) {
e.printStackTrace()
}
if (addressesOrigin != null) {
// добавить адреса в адаптер adapterDestPlaces
for (address in addressesOrigin!!) {
var addr = address.getAddressLine(0)
results.add(addr)
}
}
return results
}
}<file_sep>/app/src/main/java/valsoft/darkfree/taxiclient/utils/Utils.kt
package valsoft.darkfree.taxiclient.utils
const val YANDEX_MAP_KIT_KEY = "<KEY>"
const val LOG_IN_SP = "USER_LOG_IN_SP"
const val MY_PERMISSIONS_REQUEST_LOCATION = 1
const val METERS_IN_KILOMETERS = 1000
const val MINIMAL_ORDER_COST = 200
const val COST_RUB_PER_KILOMETER = 19
const val PAYMENT_TYPE_CASH = 0
const val PAYMENT_TYPE_CARD = 1
const val ORDER_SP = "ORDER_SP"<file_sep>/app/src/main/java/valsoft/darkfree/taxiclient/api/ClientApi.java
package valsoft.darkfree.taxiclient.api;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
import valsoft.darkfree.taxiclient.api.models.requests.*;
import valsoft.darkfree.taxiclient.api.models.responses.*;
public interface ClientApi {
@POST("registration/")
Call<RegistrationResponse> registration(@Body RegistrationRequest request);
@POST("authorization/")
Call<AuthorizationResponse> authorization(@Body AuthorizationRequest request);
@POST("order/create/")
Call<NewOrderResponse> createNewOrder(@Body NewOrderRequest request);
@POST("order/cancel/")
Call<CancelOrderResponse> cancelOrder(@Body CancelOrderRequest request);
@POST("request/destinations/")
Call<DestinationsResponse> requestFavouriteDestinations(@Body DestinationsRequest request);
@POST("request/driver/position/")
Call<DriverPositionResponse> requestDriverPosition(@Body DriverPositionRequest request);
@POST("driver/response/")
Call<RToDriverResponse> newResponseAboutDriver(@Body RToDriverRequest request);
@POST("driver/like/")
Call<LikeToDriverResponse> likeDriver(@Body LikeToDriverRequest request);
}
<file_sep>/app/src/main/java/valsoft/darkfree/taxiclient/api/models/responses/DestinationsResponse.java
package valsoft.darkfree.taxiclient.api.models.responses;
import java.util.ArrayList;
import valsoft.darkfree.taxiclient.api.models.simple.Destination;
public class DestinationsResponse {
private Boolean status;
private ArrayList<Destination> list;
public DestinationsResponse(Boolean status, ArrayList<Destination> list) {
this.status = status;
this.list = list;
}
public Boolean getStatus() {
return status;
}
public ArrayList<Destination> getList() {
return list;
}
@Override
public String toString() {
return "DestinationsResponse{" +
"status=" + status +
", list=" + list +
'}';
}
}
<file_sep>/app/src/main/java/valsoft/darkfree/taxiclient/api/models/responses/RegistrationResponse.java
package valsoft.darkfree.taxiclient.api.models.responses;
public class RegistrationResponse {
private Boolean status;
private String error;
private Integer client_id;
public RegistrationResponse(Boolean status, String error, Integer client_id) {
this.status = status;
this.error = error;
this.client_id = client_id;
}
public Boolean getStatus() {
return status;
}
public String getError() {
return error;
}
public Integer getClient_id() {
return client_id;
}
@Override
public String toString() {
return "RegistrationResponse{" +
"status=" + status +
", error='" + error + '\'' +
", client_id=" + client_id +
'}';
}
}
<file_sep>/app/src/main/java/valsoft/darkfree/taxiclient/api/models/responses/NewOrderResponse.java
package valsoft.darkfree.taxiclient.api.models.responses;
import valsoft.darkfree.taxiclient.api.models.simple.Order;
public class NewOrderResponse {
private Boolean status;
private String error;
private Integer order_id;
private Order order_detail;
public NewOrderResponse(Boolean status, String error, Integer order_id, Order order_detail) {
this.status = status;
this.error = error;
this.order_id = order_id;
this.order_detail = order_detail;
}
public Boolean getStatus() {
return status;
}
public String getError() {
return error;
}
public Integer getOrder_id() {
return order_id;
}
public Order getOrder_detail() {
return order_detail;
}
@Override
public String toString() {
return "NewOrderResponse{" +
"status=" + status +
", error='" + error + '\'' +
", order_id=" + order_id +
", order_detail=" + order_detail +
'}';
}
}
<file_sep>/app/src/main/java/valsoft/darkfree/taxiclient/acrivities/RegistrationActivity.kt
package valsoft.darkfree.taxiclient.acrivities
import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import valsoft.darkfree.taxiclient.R
import valsoft.darkfree.taxiclient.api.models.requests.RegistrationRequest
import valsoft.darkfree.taxiclient.api.models.responses.RegistrationResponse
import valsoft.darkfree.taxiclient.app.App
import valsoft.darkfree.taxiclient.utils.LOG_IN_SP
class RegistrationActivity : AppCompatActivity() {
val TAG:String = "RegistrationActivity"
var surname:EditText? = null
var name:EditText? = null
var phoneNumber:EditText? = null
var password:EditText? = null
var submit: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_registration)
surname = findViewById(R.id.surname)
name = findViewById(R.id.name)
phoneNumber = findViewById(R.id.phone)
password = findViewById(R.id.password)
submit = findViewById(R.id.submit)
submit?.setOnClickListener {
when {
surname?.text?.isEmpty()!! -> {
Toast.makeText(this@RegistrationActivity, "Введите фамилию", Toast.LENGTH_LONG).show()
}
name?.text?.isEmpty()!! -> {
Toast.makeText(this@RegistrationActivity, "Введите имя", Toast.LENGTH_LONG).show()
}
phoneNumber?.text?.isEmpty()!! -> {
Toast.makeText(this@RegistrationActivity, "Введите номер телефона", Toast.LENGTH_LONG).show()
}
password?.text?.isEmpty()!! -> {
Toast.makeText(this@RegistrationActivity, "Введите пароль", Toast.LENGTH_LONG).show()
}
else -> {
App.api?.registration(RegistrationRequest(
surname?.text?.toString(),
name?.text?.toString(),
phoneNumber?.text?.toString(),
password?.text?.toString())
)?.enqueue(object: Callback<RegistrationResponse>{
override fun onFailure(call: Call<RegistrationResponse>?, t: Throwable?) {
Toast.makeText(this@RegistrationActivity, "Попытка зарегистрироваться не удалась.", Toast.LENGTH_LONG).show()
}
override fun onResponse(call: Call<RegistrationResponse>?, response: Response<RegistrationResponse>?) {
val r = response?.body()
if(r?.status!!){
Log.d("AuthorizationResponse", r.toString())
with(getSharedPreferences(LOG_IN_SP, Context.MODE_PRIVATE).edit()){
putInt("client_id", r.client_id)
putString("phone", phoneNumber?.text?.toString())
putString("surname_and_name", "${surname?.text?.toString()} ${name?.text?.toString()}")
apply()
}
Toast.makeText(this@RegistrationActivity, "Вы успешно зарегистрировались", Toast.LENGTH_SHORT).show()
startActivity(Intent(this@RegistrationActivity, MainActivity::class.java))
finish()
}
else{
Log.e(TAG, r.error)
Toast.makeText(this@RegistrationActivity, "Попытка зарегистрироваться не удалась.\nВозможно, этот номер телефона уже используется.", Toast.LENGTH_LONG).show()
}
}
})
}
}
}
}
}
<file_sep>/app/src/main/java/valsoft/darkfree/taxiclient/acrivities/OrderDetailActivity.kt
package valsoft.darkfree.taxiclient.acrivities
import android.app.Dialog
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Space
import android.widget.TextView
import com.yandex.mapkit.MapKitFactory
import com.yandex.mapkit.driving.DrivingRouter
import com.yandex.mapkit.driving.DrivingSession
import com.yandex.mapkit.map.MapObjectCollection
import com.yandex.mapkit.mapview.MapView
import org.json.JSONObject
import valsoft.darkfree.taxiclient.R
import valsoft.darkfree.taxiclient.utils.*
class OrderDetailActivity : AppCompatActivity() {
private var drivingRouter: DrivingRouter? = null
private var drivingSession: DrivingSession? = null
private var mapObjects: MapObjectCollection? = null
private var mMap: MapView? = null
private var button_pay: Button? = null
private var button_close: Button? = null
private var button_cancel: Button? = null
private var button_driver: Button? = null
private var text_view_order_cost: TextView? = null
private var text_view_driver_info: TextView? = null
private var drivingRouteListener: DrivingSession.DrivingRouteListener? = null
private var space: Space? = null
private var orderDetailJson: JSONObject? = null
private var driverDetailDialog: Dialog? = null
private var driverResponseAskDialog: Dialog? = null
private var driverLikeDialog: Dialog? = null
private var driverDislikeDialog: Dialog? = null
private var order_id:Int? = null
private var from:String? = null
private var to:String? = null
private var distance:Double? = null
private var price:Double? = null
private var paymentTime:Int? = null
private var date:String? = null
private var time:String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MapKitFactory.setApiKey(YANDEX_MAP_KIT_KEY)
MapKitFactory.initialize(this)
setContentView(R.layout.activity_order_detail)
loadOrderDetailFromSharedPreferences()
}
private fun loadOrderDetailFromSharedPreferences() {
val sp = getSharedPreferences(ORDER_SP, Context.MODE_PRIVATE)
order_id = sp.getInt("order_id", 0)
from = sp.getString("from", "")
to = sp.getString("to", "")
distance = sp.getFloat("distance",0.0f).toDouble()
price = sp.getFloat("order_price",0.0f).toDouble()
paymentTime = sp.getInt("payment_type",0)
date = sp.getString("date","")
time = sp.getString("time", "")
}
override fun onStart() {
super.onStart()
MapKitFactory.getInstance().onStart()
mMap?.onStart()
}
override fun onStop() {
mMap?.onStop()
MapKitFactory.getInstance().onStop()
drivingRouter?.suspend()
drivingSession?.cancel()
super.onStop()
}
}
|
065a3a9495667d4af0a3add4f58cbd1ef341f208
|
[
"Java",
"Kotlin"
] | 13 |
Java
|
byNova/TaxiClientApp
|
b13615af4e5cd95068fd8ee83a9f8c7b7017d1d0
|
3a77e7f35d79ec6c389ad176baf25dadb804b74d
|
refs/heads/master
|
<repo_name>nstanzani/TRAB3POO<file_sep>/src/br/usp/icmc/ssc0103/Library.java
package br.usp.icmc.ssc0103;
import java.io.*;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
public class Library {
int nextCode = 0;
LocalDate today;
static List<User> userList = new LinkedList<User>();
static List<Book> bookList = new LinkedList<Book>();
static List<Loan> loanList = new LinkedList<Loan>();
public void setSimulatedDate() {
Scanner scanner = new Scanner(System.in);
int dia, mes, ano;
System.out.println("Digite o dia que a simulação deve ser executada (formato numerico): ");
dia = scanner.nextInt();
System.out.println("Digite o mes que a simulação deve ser executada (formato numerico): ");
mes = scanner.nextInt();
System.out.println("Digite o ano que a simulação deve ser executada (formato numerico): ");
ano = scanner.nextInt();
today = LocalDate.of(ano, mes, dia);
}
public void loadLists() {
try {
BufferedReader inUser = new BufferedReader(new FileReader("users.csv"));
BufferedReader inBook = new BufferedReader(new FileReader("books.csv"));
BufferedReader inLoan = new BufferedReader(new FileReader("loans.csv"));
String[] splitLine;
String line;
Optional<LocalDate> aux;
while ((line = inUser.readLine()) != null) {
splitLine = line.split(",");
if(splitLine[3].equals("null")){
aux = Optional.empty();
}
else if(today.isAfter(LocalDate.of(Integer.parseInt(splitLine[3]), Integer.parseInt(splitLine[4]), Integer.parseInt(splitLine[5])))){
aux = Optional.empty();
}
else{
aux = Optional.of(LocalDate.of(Integer.parseInt(splitLine[3]), Integer.parseInt(splitLine[4]), Integer.parseInt(splitLine[5])));
}
if (splitLine[6].toLowerCase().equals("estudante")) {
Student user = new Student(splitLine[0], Integer.parseInt(splitLine[1]), Integer.parseInt(splitLine[2]), Integer.parseInt(splitLine[7]));
user.setPenalty(aux);
userList.add(user);
nextCode++;
}
if (splitLine[6].toLowerCase().equals("professor")) {
Professor user = new Professor(splitLine[0], Integer.parseInt(splitLine[1]), Integer.parseInt(splitLine[2]), Integer.parseInt(splitLine[7]));
user.setPenalty(aux);
userList.add(user);
nextCode++;
} else if (splitLine[6].toLowerCase().equals("comunidade")) {
Community user = new Community(splitLine[0], Integer.parseInt(splitLine[1]), Integer.parseInt(splitLine[2]), Integer.parseInt(splitLine[7]));
user.setPenalty(aux);
userList.add(user);
nextCode++;
}
}
while ((line = inBook.readLine()) != null) {
splitLine = line.split(",");
Book book;
book = new Book(splitLine[0], splitLine[1], splitLine[2].toLowerCase().equals("true"));
if (splitLine[3].toLowerCase().equals("null") != true) {
book.setLender(Optional.of(splitLine[3]));
book.setRentDate(Optional.of(LocalDate.of(Integer.parseInt(splitLine[4]), Integer.parseInt(splitLine[5]), Integer.parseInt(splitLine[6]))));
book.setDevDate(Optional.of(LocalDate.of(Integer.parseInt(splitLine[7]), Integer.parseInt(splitLine[8]), Integer.parseInt(splitLine[9]))));
}
bookList.add(book);
}
while ((line = inLoan.readLine()) != null){
splitLine = line.split(",");
LocalDate rentDate = LocalDate.of(Integer.parseInt(splitLine[2]), Integer.parseInt(splitLine[3]), Integer.parseInt(splitLine[4]));
LocalDate devDate = LocalDate.of(Integer.parseInt(splitLine[5]), Integer.parseInt(splitLine[6]), Integer.parseInt(splitLine[7]));
Loan loan;
loan = new Loan(splitLine[0], splitLine[1], rentDate, devDate, Integer.parseInt(splitLine[8]));
loanList.add(loan);
}
} catch (IOException e) {
System.out.println("Erro ao abrir o arquivo");
}
}
public void menu() {
int op;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Data do sistema: " + today.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
System.out.println("\t\tMenu\n");
System.out.println("1 - Cadastrar novo usuário");
System.out.println("2 - Cadastrar novo livro");
System.out.println("3 - Registrar empréstimo");
System.out.println("4 - Registrar devolução");
System.out.println("5 - Salvar alterações");
System.out.println("6 - Imprimir todos os usuários");
System.out.println("7 - Imprimir todos os livros");
System.out.println("8 - Imprimir todos os empréstimos");
System.out.println("9 - Imprimir os empréstimos em atraso");
System.out.println("0 - Sair");
op = scanner.nextInt();
switch (op) {
case 1:
registerNewUser();
break;
case 2:
registerNewBook();
break;
case 3:
registerNewLoan();
break;
case 4:
registerNewDev();
break;
case 5:
saveChanges();
break;
case 6:
User u = null;
printAll(u);
break;
case 7:
Book b = null;
printAll(b);
break;
case 8:
Loan l = null;
printAll(l);
break;
case 9:
checkLate();
break;
case 0:
System.out.println("Sair pode significar perda de dados. Antes de sair, certifique-se de salvar as modificações. Digite 0 se realmente quiser sair");
if(scanner.nextInt() == 0)
System.exit(0);
break;
}
} while (op != 0);
}
private void registerNewLoan() {
Optional<Book> book;
Optional<User> user;
Scanner scanner = new Scanner(System.in);
String bookTitle;
int userCode;
System.out.println("Digite o nome do livro que o usuario deseja pegar emprestado: ");
bookTitle = scanner.nextLine();
book = bookList
.stream()
.filter(b -> b.getTitle().toLowerCase().equals(bookTitle.toLowerCase()))
.filter(b -> b.getLender().toLowerCase().equals("null"))
.findFirst();
System.out.println("Digite o codigo do usuario que deseja fazer o emprestimo: ");
userCode = scanner.nextInt();
user = userList
.stream()
.filter(u -> u.getCode() == userCode)
.filter(u -> u.getPenalty().isAfter(today) != true)
.filter(u -> u.getRemainingQuota() != 0)
.findFirst();
if (user.isPresent() && book.isPresent()) {
if(user.get().getType().toLowerCase().equals("comunidade") && book.get().getTextBook()){
System.out.println("O usuario nao tem permissao suficiente para pegar esse livro emprestado");
}
else {
Loan loan = new Loan(user.get().getName(), book.get().getTitle(), today, today.plusDays(user.get().getTime()), user.get().getCode());
book.get().setLender(Optional.of(user.get().getName()));
book.get().setRentDate(Optional.of(today));
book.get().setDevDate(Optional.of(today.plusDays(user.get().getTime())));
user.get().decRemainingQuota();
loanList.add(loan);
}
}
else if(user.isPresent() != true){
System.out.println("O usuario nao foi encontrado, ou nao tem cota disponivel ou tem uma penalidade pendente");
}
else if(book.isPresent() != true){
System.out.println("Nao foi encontrado nenhum livro com tal titulo disponivel para emprestimo");
}
}
private void registerNewDev(){
try {
FileWriter fw = new FileWriter("closedloans.csv", true);
Scanner scanner = new Scanner(System.in);
int code;
String title, name;
Optional<Book> book = Optional.empty();
Optional<Loan> loan = Optional.empty();
Optional<User> user = Optional.empty();
System.out.println("Escreva o codigo do usuario que ira devolver o livro");
code = Integer.parseInt(scanner.nextLine());
System.out.println("Escreva o titulo do livro que o usuario ira devolver");
title = scanner.nextLine();
loan = loanList
.stream()
.filter(l -> l.getCode() == code)
.filter(l -> l.getTitle().toLowerCase().equals(title.toLowerCase()))
.findFirst();
user = userList
.stream()
.filter(u -> u.getCode() == code)
.findFirst();
if(user.isPresent()) {
name = user.get().getName();
}
else{
System.out.println("Nao foi possivel encontrar nenhum usuario com esse codigo");
fw.close();
return;
}
book = bookList
.stream()
.filter(b -> b.getTitle().toLowerCase().equals(title.toLowerCase()))
.filter(b -> b.getLender().toLowerCase().equals(name.toLowerCase()))
.findFirst();
if(loan.isPresent() && book.isPresent()){
if(today.isAfter(loan.get().getDevDate())) {
long dif = ChronoUnit.DAYS.between(loan.get().getDevDate(), today);
user.get().calculatePenalty(today, dif);
System.out.println("O livro estava atrasado, por isso foi adicionado uma penalidade ao usuario");
}
fw.write(loan.get().toFile() + "\n");
loanList.remove(loan.get());
book.get().setLender(Optional.empty());
book.get().setDevDate(Optional.empty());
book.get().setRentDate(Optional.empty());
user.get().incRemainingQuota();
}
else if(loan.isPresent() != true){
System.out.println("Nao foi encontrado nenhum emprestimo com esse codigo e esse livro");
}
fw.close();
}
catch(IOException e)
{
System.out.println("Erro ao abrir o arquivo");
}
}
private void registerNewUser() {
Scanner scanner = new Scanner(System.in);
String name;
String userType;
System.out.println("Digite o nome do usuário: ");
name = scanner.nextLine();
System.out.println("Digite o tipo de conta do usuário (estudante, professor ou comunidade): ");
userType = scanner.nextLine();
if (userType.toLowerCase().equals("estudante")) {
Student user = new Student(name, 4, 15, nextCode);
userList.add(user);
nextCode++;
} else if (userType.toLowerCase().equals("professor")) {
Professor user = new Professor(name, 6, 60, nextCode);
userList.add(user);
nextCode++;
} else if (userType.toLowerCase().equals("comunidade")) {
Community user = new Community(name, 2, 15, nextCode);
userList.add(user);
nextCode++;
} else {
System.out.println("Tipo de usuário inválido!");
}
}
private void printAll(User user) {
userList
.stream()
.sorted(Comparator.comparing(User::getCode))
.forEach(System.out::println);
}
private void printAll(Book book) {
bookList
.stream()
.sorted(Comparator.comparing(Book::getTitle))
.forEach(System.out::println);
}
private void printAll(Loan book) {
loanList
.stream()
.sorted(Comparator.comparing(Loan::getDevDate).reversed())
.forEach(System.out::println);
}
private void saveChanges() {
Thread t = new Thread(() ->{
try {
ListIterator userItr = userList.listIterator();
ListIterator bookItr = bookList.listIterator();
ListIterator loanItr = loanList.listIterator();
FileWriter fwUser = new FileWriter("users.csv");
FileWriter fwBook = new FileWriter("books.csv");
FileWriter fwLoan = new FileWriter("loans.csv");
while (userItr.hasNext()) {
User user = (User) userItr.next();
fwUser.write(user.toFile() + "\n");
}
while (bookItr.hasNext()) {
Book book = (Book) bookItr.next();
fwBook.write(book.toFile() + "\n");
}
while (loanItr.hasNext()) {
Loan loan = (Loan) loanItr.next();
fwLoan.write(loan.toFile() + "\n");
}
fwUser.close();
fwBook.close();
fwLoan.close();
menu();
}
catch (IOException e){
System.out.println("Erro ao abrir o arquivo");
}});
t.start();
}
private void registerNewBook() {
Scanner scanner = new Scanner(System.in);
String title;
String author;
String auxString;
boolean textBook;
Book book;
System.out.println("Digite o título do livro: ");
title = scanner.nextLine();
System.out.println("Digite o nome do autor: ");
author = scanner.nextLine();
System.out.println("É um livro texto? (Sim/Nao)");
auxString = scanner.nextLine().toLowerCase();
textBook = auxString.toLowerCase().equals("sim");
book = new Book(title, author, textBook);
bookList.add(book);
}
private void checkLate(){
loanList
.stream()
.filter(l -> today.isAfter(l.getDevDate()) == true)
.forEach(l -> System.out.println("Livro atrasado:\n\n" + l.toString()));
}
}<file_sep>/src/br/usp/icmc/ssc0103/Date.java
package br.usp.icmc.ssc0103;
/**
* Created by naldost on 19/05/15.
*/
public class Date {
private final int day;
private final int month;
private final int year;
Date(int day, int month, int year){
this.day = day;
this.month = month;
this.year = year;
}
@Override
public String toString(){
return day + "/" + month + "/" + year;
}
}
<file_sep>/src/br/usp/icmc/ssc0103/Book.java
package br.usp.icmc.ssc0103;
import java.time.LocalDate;
import java.util.Optional;
public class Book {
private String title;
private String author;
private Optional<LocalDate> rentDate;
private Optional<LocalDate> devDate;
private Optional<String> lender;
private boolean textBook;
Book(String title, String author, boolean textBook){
this.title = title;
this.author = author;
this.textBook = textBook;
this.lender = Optional.empty();
this.rentDate = Optional.empty();
this.devDate = Optional.empty();
}
@Override
public String toString(){
if (lender.isPresent())
return "Titulo: " + this.title + "\nAutor: " + this.author + "\nEmprestado: Sim" + "\n";
else
return "Titulo: " + this.title + "\nAutor: " + this.author + "\nEmprestado: Nao" + "\n";
}
public String toFile() {
if (lender.isPresent())
return this.title + "," + this.author + "," + this.textBook + "," + lender.get() + ","
+ rentDate.get().getYear() + "," + rentDate.get().getMonthValue() + "," + rentDate.get().getDayOfMonth()
+ "," + devDate.get().getYear() + "," + devDate.get().getMonthValue() + "," + devDate.get().getDayOfMonth();
else
return this.title + "," + this.author + "," + this.textBook + ",null,null,null,null,null,null,null";
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setRentDate(Optional<LocalDate> rentDate) {
this.rentDate = rentDate;
}
public void setDevDate(Optional<LocalDate> devDate) {
this.devDate = devDate;
}
public void setLender(Optional<String> lender) {
this.lender = lender;
}
public void setTextBook(boolean textBook) {
this.textBook = textBook;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public Optional<LocalDate> getRentDate() {
return rentDate;
}
public Optional<LocalDate> getDevDate() {
return devDate;
}
public String getLender() {
if (this.lender.isPresent())
return this.lender.get();
return "null";
}
public boolean getTextBook(){
return textBook;
}
}
<file_sep>/src/br/usp/icmc/ssc0103/Loan.java
package br.usp.icmc.ssc0103;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/**
* Created by naldost on 19/05/15.
*/
public class Loan {
private String name;
private String title;
private int code;
private LocalDate rentDate;
private LocalDate devDate;
Loan(String name, String title, LocalDate rentDate, LocalDate devDate, int code) {
this.name = name;
this.title = title;
this.rentDate = rentDate;
this.devDate = devDate;
this.code = code;
}
@Override
public String toString(){
return "Nome: " + this.name + "\nLivro: " + this.title + "\nData de devolucao: " + this.devDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "\n";
}
public String toFile() {
return this.name + "," + this.title + "," + this.rentDate.getYear() + "," + this.rentDate.getMonthValue() + ","
+ this.rentDate.getDayOfMonth() + "," + this.devDate.getYear() + "," + this.devDate.getMonthValue() + ","
+ this.devDate.getDayOfMonth() + "," + this.code;
}
public void setName(String name) {
this.name = name;
}
public void setTitle(String title) {
this.title = title;
}
public void setCode(int code){
this.code = code;
}
public void setRentDate(LocalDate rentDate){
this.rentDate = rentDate;
}
public void setDevDate(LocalDate devDate){
this.devDate = devDate;
}
public String getName(){
return this.name;
}
public String getTitle(){
return this.title;
}
public int getCode(){
return this.code;
}
public LocalDate getRentDate(){
return this.rentDate;
}
public LocalDate getDevDate(){
return this.devDate;
}
}
<file_sep>/src/br/usp/icmc/ssc0103/Student.java
package br.usp.icmc.ssc0103;
public class Student extends User {
Student(String name, int remainingQuota, long time, int code) {
this.name = name;
this.remainingQuota = remainingQuota;
this.time = time;
this.type = "Estudante";
this.code = code;
}
}
|
3db45d3857cf230b995309a845b273252cadd725
|
[
"Java"
] | 5 |
Java
|
nstanzani/TRAB3POO
|
fd9d576dc39807d0591852ad6d5ea1aefb9f149b
|
5a4e8f63a4e541db750393e5c7a96b5c1ed63d00
|
refs/heads/master
|
<file_sep>Working with JSON and PHP
===================
This video introduces working with JSON and PHP together, using the built-in json_encode function. In this tutorial, we create a short example of a calculator to submit, request and add two numbers together. We ajax for the results and return them in valid JSON format.
https://www.youtube.com/watch?v=2qJT09LAh64<file_sep><!DOCTYPE html>
<html>
<head>
<title>Working with JSON and PHP</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<form method="post" action="add.php" id="add">
<input type="text" name="first"> +
<input type="text" name="second">
<input type="submit" value="Work this out">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
<file_sep>phpacademy_csrf
===================
Code based on this video http://www.youtube.com/watch?v=VflbINBabc4
In this video we create and implement a class that generates tokens and checks a supplied token when a form is submitted.<file_sep><?php
require_once 'classes/Zipper.php';
$zipper = new Zipper;
$zipper->add(array('files/1.txt', 'files/2.txt'));
$zipper->add('test.txt');
$zipper->store('files/test.zip');
<file_sep>phpacademy_easyajax
===================
An example AJAX request to check if a username is available in a database. Using a simple AJAX request, we can send a GET request to the server, return JSON and display a message.
<file_sep>$('#add').on('submit', function () {
var form = $(this);
var content = form.serialize();
$.ajax({
url: 'add.php',
dataType: 'json',
type: 'post',
data: content,
success: function (data) {
if (data.success) {
alert('The result is ' + data.result);
}
console.log(data);
},
error: function () {
}
});
return false;
});
<file_sep><?php
class Zipper
{
private $_files = array();
private $_zip;
const DEBUG = true;
public function __construct()
{
$this->_zip = new ZipArchive;
}
public function add($input)
{
if (is_array($input))
{
$this->_files = array_merge($this->_files, $input);
} else
{
$this->_files[] = $input;
}
}
public function store($location = null)
{
$this->cleanUnexistingFiles();
if (!count($this->_files))
{
throw new Exception('Zip archive can not be empty. Add some files');
}
if (!$location)
{
throw new Exception('Location of zip archive must be set');
}
if ($this->_zip->open($location, file_exists($location) ? ZipArchive::OVERWRITE : ZipArchive::CREATE))
{
foreach ($this->_files as $filename)
{
if (self::DEBUG)
{
echo 'Adding file: ' . $filename . '<br>';
}
$this->_zip->addFile($filename);
}
if (self::DEBUG)
{
echo 'Archive file: ' . $location . ' has been created<br>';
}
$this->_zip->close();
}
}
private function cleanUnexistingFiles()
{
foreach ($this->_files as $index => $file)
{
if (!file_exists($file))
{
if (self::DEBUG)
{
echo 'Removing unexisting file: ' . $file . '<br>';
}
unset($this->_files[$index]);
}
}
}
}
<file_sep>phpacademy
==========
Training repository based on phpacademy series https://www.youtube.com/user/phpacademy/videos
<file_sep>$('.username-check').on('click', function () {
var target = $('.username-target');
var feedback = $('.username-feedback');
function changeFeedbackText(text) {
feedback.text(text);
}
function couldNotCheck() {
changeFeedbackText('Could not check at this time.');
}
$.ajax({
url: './check/username.php',
type: 'get',
data: {
username: target.val()
},
dataType: 'json',
success: function (data) {
if (data.available !== undefined) {
if (data.available === true) {
changeFeedbackText('That username is available.');
}
else {
changeFeedbackText('That username is not available.');
}
}
else {
couldNotCheck();
}
},
error: function () {
couldNotCheck();
}
});
console.log('test');
});<file_sep><!doctype>
<html>
<head>
<title>Desktop notification</title>
</head>
<body>
<a href="#" id="dnperm">Request permission</a>
<a href="#" id="dntrigger">Trigger</a>
<script>
var dnperm = document.getElementById('dnperm');
var dntrigger = document.getElementById('dntrigger');
dnperm.addEventListener('click', function (e) {
e.preventDefault();
if (!window.Notification) {
alert('Sorry, notification are not supported.');
}
else {
Notification.requestPermission(function (p) {
console.log(p);
if (p === 'granted') {
console.log('You have granted notifications.');
}
if (p === 'denied') {
console.log('You have denied notifications.');
}
});
}
});
dntrigger.addEventListener('click', function (e) {
var notify;
e.preventDefault();
console.log(Notification.permission);
if (Notification.permission === 'default') {
console.log('Please allow notifications');
}
else {
notify = new Notification('New message from Rataja', {
body: 'This is great tutorial, as always',
icon: 'logo.jpg'
});
notify.onclick = function () {
console.log(this);
}
}
});
</script>
</body>
</html>
<file_sep><?php
function randomAnswer()
{
return rand(0, 1) === 0 ? false : true;
}
echo json_encode(
array(
'username' => 'Martin',
'available' => randomAnswer()
)
);
|
6ec575d18a49daa03c588ecff246dba11dd392c0
|
[
"Markdown",
"JavaScript",
"Hack",
"PHP"
] | 11 |
Markdown
|
rataja/phpacademy
|
533e775bac7ebf5e8064a8d033bb1006510cbf4c
|
b3969ebbc7f53988ae1d27eb2f297e49ebcdf33b
|
refs/heads/master
|
<file_sep><%@ Application Codebehind="Global.asax.cs" Inherits="IKT_Proekt.MvcApplication" Language="C#" %>
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IT_Core
{
public class Seat:Base
{
public string Class { get; set; }
}
}
<file_sep>using System;
public class Customer:Base
{
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Email { get; set; }
public string Image { get; set; }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IT_Core
{
public class Plane:Base
{
public string SerialNum { get; set; }
public int Capacity { get; set; }
public List<Seat> Seats { get; set; }
}
}
<file_sep>using IT_Core;
using IT_Repository.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IT_Repository.Repository
{
public class PlaneRepository
{
private DatabaseContext db = new DatabaseContext();
public List<Plane> GetAll()
{
List<Plane> planes = db.Planes.ToList();
return planes;
}
public void Create(Plane newPlane)
{
db.Planes.Add(newPlane);
db.SaveChanges();
}
public Plane GetBySerial(string serial)
{
return db.Planes.FirstOrDefault(x => x.SerialNum == serial);
}
public Plane GetByID(int ID)
{
return db.Planes.FirstOrDefault(x => x.ID == ID);
}
}
}
<file_sep>using System;
public class Plane:Base
{
public string Company { get; set; }
public string SerialNumber { get; set; }
}
<file_sep>using IT_Core;
using IT_Repository.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IT_Repository.Repository
{
public class ClientRepository
{
private DatabaseContext db = new DatabaseContext();
public List<Customer> GetAll()
{
List<Customer> customers = db.Customers.ToList();
return customers;
}
public void Create(Customer newCustomer)
{
db.Customers.Add(newCustomer);
db.SaveChanges();
}
public Customer GetByUsername(string username)
{
return db.Customers.FirstOrDefault(x => x.Username == username);
}
public Customer GetById(int id)
{
return db.Customers.FirstOrDefault(x => x.ID == id);
}
public Customer GetByFirstName(string firstName)
{
return db.Customers.FirstOrDefault(x => x.FirstName==firstName);
}
public Customer GetByEmail(string email)
{
return db.Customers.FirstOrDefault(x => x.Email == email);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IT_Core
{
public class Base
{
public int ID { get; set; }
public DateTime DateCreated = DateTime.Now;
}
}
<file_sep>using System;
public class Base
{
public int ID { get; set; }
public DateTime DateCreated { get; set; }
}
<file_sep>using IT_Core;
using IT_Repository.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IT_Repository.Repository
{
public class SeatsRepository
{
private DatabaseContext db = new DatabaseContext();
public Seat getByID(int ID)
{
return db.Seats.FirstOrDefault(x => x.ID == ID);
}
public List<Seat> GetAll()
{
List<Seat> seats = db.Seats.ToList();
return seats;
}
}
}
<file_sep>using IT_Core;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
namespace IT_Repository.Database
{
public class DatabaseContext:DbContext
{
public DatabaseContext() : base("name=DatabaseContext")
{
}
public DbSet<Customer> Customers { get; set; }
public DbSet<Plane> Planes { get; set; }
public DbSet<Seat> Seats { get; set; }
}
}
|
bf25e3a50bc0168b3ace9f7b67bf88a6d2642eca
|
[
"C#",
"ASP.NET"
] | 11 |
C#
|
twoheadedmona/IT-Repository
|
e14ce21aebc8d84b4a74d68298573e81b3eae7bd
|
802fc6a8748b68ba3fac080d3491e8f99aef8c16
|
refs/heads/master
|
<file_sep># Shiny Development Playground With Modules
#
# This is the server logic for a Shiny web application.
# Please keep all libraries here!
library("shiny")
library("shinydashboard")
library("data.table")
library("arules")
library("DT")
library("arulesViz")
library("shinycssloaders")
# Load shiny modules by listing all R files in the workspace and filtering
# to those that contain "modules" in their path (i.e. the folder)
fileSources <- list.files(pattern = "*.R", recursive = T)
fileSources <- fileSources[grepl("modules", fileSources)]
sapply(fileSources, source, .GlobalEnv)
<file_sep># eBiz Visual Graph Analytics
#
# This is the user-interface definition of a Shiny web application.
appName <- "Loyalty Cards"
dashboardPage(skin = "blue",
dashboardHeader(title = appName,
tags$li(tags$a("A prototype of the Recommender System for Loyalty cards users."), class="dropdown")),
dashboardSidebar(shinyjs::useShinyjs(),
collapsed = FALSE,
# ceate sidebarMenu in server side because it depends on the data
# loaded in server
sidebarMenuOutput("sidebarMenu") %>% withSpinner),
dashboardBody(
tags$head(HTML('<link rel="stylesheet" href="css/style.css" />')),
# while sidebarMenu is loading, show welcome UI as startup page
div(
id = "startup_page",
welcomeUI("welcome")),
tabItems(
tabItem(tabName = "tab_welcome", welcomeUI("welcome")),
tabItem(tabName = "tab_recommendation", recommendationUI("recommendation"))
)
)
)<file_sep># Recommender System
## Project
This is a prototype of Recommender System to recommend loyalty cards to customers.
## How does it work?
Assume the case where customers have some loyalty cards of different brands in their wallets.
Customer 1 has cards of brands **A, B, C, D, E** whereas customer 2 has cards of **A, B, C, D**. Customer 2 is better to consider the possibility of getting the loyalty card of the brand **E** because some other customers have a similar taste on brands. The system will recommend **E** to customer 2 provided that a sufficient number of other customers have already had similar loyalty cards including **E** in their wallets.
## What is under the hood?
To build recommendations the system use **Apriori algorithm for frequent item set mining and association rule learning**.
R code is wrapped into interactive web apps with RShiny.
## Dataset
Dataset for this project is randomly generated relationships between customers and loyalty cards of brands.
## Enjoy the demo
<a href="https://ksenia-l.shinyapps.io/shinydev/">Play with the prototype!</a>
<file_sep>values <- reactiveValues(recommendation_initialized = FALSE,
egonetwork_initialized = FALSE,
data_loaded = FALSE)
shinyServer(function(input, output, session) {
# output sidebar menu only after necessary data has been read from database
output$sidebarMenu <- renderMenu({
s <- sidebarMenu(id = "tabs",
# here are the menu items
# find icons here: https://fontawesome.com/v4.7.0/icons/
menuItem("Welcome", tabName = "tab_welcome", icon = icon("dashboard"), selected = TRUE),
menuItem("Card Recommendation", tabName = "tab_recommendation", icon = icon("line-chart"))
)
values$data_loaded = TRUE
return(s)
})
# when data has been loaded from db and sidebarMenu is shown, hide startup page
observeEvent(values$data_loaded, {
shinyjs::hide("startup_page")
})
data <- fread("Cards_.csv")
######################################## Recommendation based on association rules mining
####### Association Rules Calculation:
# Bild Apriori_Matrix as an auxiliary initial object for:
# 1. mining Associations Rules;
# 2. mining account basket of selected customer
Apriori_Matrix_Calculation <- function(data){
validate(need(data, "Calculate Recommendations"))
# Converting to a logic Matrix
data$const <- TRUE
# Need to reshape the matrix
apriori_input_matrix_full <- reshape(data = data, idvar = "customer", timevar = "card", direction = "wide")
# Clean up the missing values to be FALSE
apriori_input_matrix_full[is.na(apriori_input_matrix_full)] <- FALSE
return(apriori_input_matrix_full)
}
# Mine Associations Rules set over entire set
Calculate_Apriori_Rules <- function(Apriori_Matrix){
# Drop the customers and creale logic matrix contains TRUE-FALSE
apriori_input_matrix <- as.matrix(Apriori_Matrix[,-1])
# Clean up names
colnames(apriori_input_matrix) <- gsub(x=colnames(apriori_input_matrix),
pattern="const\\.", replacement="")
# convert to 'transactions' class (apriori_input_matrix is logic matrix: it's required for as())
tData <- as(apriori_input_matrix, "transactions")
rules <- apriori(tData, parameter = list(supp = 0.01, conf = 0.75, minlen = 2, maxlen=12), control = list(verbose = FALSE))
# Order rules by decreasing support
rules_support <- sort(rules, by="support", decreasing=TRUE)
return(rules_support)
}
Apriori_Matrix <- Apriori_Matrix_Calculation(data)
Apriori_Rules <- Calculate_Apriori_Rules(Apriori_Matrix)
# observe menu tabs and call modules once to initialize the first time that
# the relevant menu item is selected
callModule(recommendation, "recommendation",
data,
Apriori_Matrix,
Apriori_Rules)
session$onSessionEnded(stopApp)
})
<file_sep># This module shows the balance of a particular tenant id, ibannumber
recommendationUI <- function(id) {
ns <- NS(id)
fluidPage(headerPanel(title = "Card recommendations"),
helpText("Choose a customer to see recommendations"),
wellPanel(fluidRow(column(width = 12, uiOutput(ns("customer_select")),
tags$h5(HTML("<strong> His cards: <strong>")),
tags$h5(htmlOutput(ns("selected_customer_cards")))))),
mainPanel(tabsetPanel(type = "tab",
tabPanel("Customer Recommendations",
tags$h5("Recommended cards:"),
tags$br(),
fluidRow(column(width = 12, uiOutput(outputId = ns("Apriori_Account_Recommendations")))),
tags$br(),
box(DTOutput(outputId = ns('Apriori_Account_suitableRules')), title = "Suitable Apriori rules:", width = 12, solidHeader = T, collapsible = T, collapsed = T)),
tabPanel("Apriory Plot",
helpText("Scatter plot where dots are relevant rules with high support and confidence rates."),
tags$br(),
fluidRow(column(width = 6, plotOutput(outputId = ns("Apriori_Account_Recommendations_Plot")))))
), width = 12
)
)
}
recommendation <- function(input, output, session, data, Apriori_Matrix, Apriori_Rules) {
ns=session$ns
######################################## Choose customer:
output$customer_select<- renderUI({
selectizeInput(ns('SelectedCustomer'), label = 'Choose a customer', choices = data$customer)
})
Customer <- reactive({
validate(need(input$SelectedCustomer, "Choose customer!"))
input$SelectedCustomer
})
Customer_cards <- reactive({data[customer == Customer()]$card})
output$selected_customer_cards <- renderUI({HTML(paste0(seq(1,length(Customer_cards())), " ", as.character(Customer_cards()), " <br>"))})
####### Bild recommendations for selected Company name:
Apriori_Account_suitableRules_indices <- reactive({
# Bild account basket from full Apriori_Matrix by extracting only one row corresponded to Account name
# From Apriori Matrix extract an account row, which contains TRUE for occured Recipient Codes:
basket <- Apriori_Matrix[customer == Customer()]
# Convert the set of Recipients' codes to Account basket:
# Drop the transaction ID and create a logic matrix:
basket <- as.matrix(basket[,-1])
# Clean up the missing values to be FALSE
basket[is.na(basket)] <- FALSE
# Clean up names
colnames(basket) <- gsub(x=colnames(basket), pattern="const\\.", replacement="")
basket <- as(basket, "transactions") # convert 1-row Account matrix to 'transactions' class
# Scan LHS parts of rules to find sutable matches with customer basket:
rulesMatchLHS <- is.subset(Apriori_Rules@lhs, basket)
# Searching for indices of rules having the same LHS parts
suitableRules <- rulesMatchLHS & !(is.subset(Apriori_Rules@rhs,basket))
# Set of sutable for selected account rules
suitableRules
})
output$Apriori_Account_suitableRules <- renderDT({
inspect(Apriori_Rules[as.logical(Apriori_Account_suitableRules_indices())])
})
Recommended_cards <- reactive({unique(unlist(LIST((Apriori_Rules[as.logical(Apriori_Account_suitableRules_indices())]@rhs))))})
output$Apriori_Account_Recommendations <- renderUI({
validate(need(Recommended_cards(), "Sorry, we don't have reliable recommendations for this customer. Either he hasn't had enough cards yet or other customers have very different loyalty cards sets."))
HTML(paste0("<strong> ", seq(1,length(Recommended_cards())), " ", as.character(Recommended_cards()), " <strong> <br>"))
})
output$Apriori_Account_Recommendations_Plot <- renderPlot({
plot(Apriori_Rules[as.logical(Apriori_Account_suitableRules_indices())], measure = c("support", "confidence"), shading = "lift", jitter = 0)
})
}
<file_sep>welcomeUI <- function(id){
ns <- NS(id)
fluidPage(
headerPanel(title = "Welcome"),
wellPanel(
fluidRow(
column(width = 12,
h5("This is a prototype of Recommender System to recommend loyalty cards to customers."),
br(),
p("Assume the case where customers have some loyalty cards of different brands in their wallets."),
p("Customer 1 has cards of brands A, B, C, D, E whereas customer 2 has cards of A, B, C, D. The Recommender System will recommend to customer 2 to consider the possibility of getting the loyalty card of the brand E because he has a similar taste on brands with customer 1 based on similarity of their wallets' content." ),
br()
)
)
)
)
}
welcome <- function(input, output, session) {
# set namespace
ns <- session$ns
}
|
56d2abdd2ae629bf16847b4db8ef02221a96054e
|
[
"Markdown",
"R"
] | 6 |
Markdown
|
Ksyula/ML-Recommender-System-RShiny
|
ebc3b071d2d364f32b83a44caf6c7238cc21c080
|
f541636d1b263798517f4d59fa44aeecf9570d1e
|
refs/heads/master
|
<repo_name>mauhdz/AR-Drawing<file_sep>/AR_Drawing/ViewController.swift
//
// ViewController.swift
// AR_Drawing
//
// Created by <NAME> on 5/12/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
import ARKit
class ViewController: UIViewController,ARSCNViewDelegate {
@IBOutlet weak var draw: UIButton!
@IBOutlet weak var sceneView: ARSCNView!
let configuration=ARWorldTrackingConfiguration()
override func viewDidLoad() {
super.viewDidLoad()
self.sceneView.debugOptions=[ARSCNDebugOptions.showWorldOrigin,ARSCNDebugOptions.showFeaturePoints]
self.sceneView.showsStatistics=true
self.sceneView.session.run(configuration)
self.sceneView.delegate=self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func renderer(_ renderer: SCNSceneRenderer, willRenderScene scene: SCNScene, atTime time: TimeInterval) {
guard let pointOfView=sceneView.pointOfView else{return}
let transform=pointOfView.transform
//orientation is where my phone is facing
let orientation=SCNVector3(-transform.m31,-transform.m32,-transform.m33)
//where phone is located relative to scene view, transitionally
let location=SCNVector3(transform.m41,transform.m42,transform.m43)
let currentPositionOfCamera=orientation+location
DispatchQueue.main.async {
if(self.draw.isHighlighted){
let sphereNode=SCNNode(geometry:SCNSphere(radius: 0.02))
sphereNode.position=currentPositionOfCamera
self.sceneView.scene.rootNode.addChildNode(sphereNode)
sphereNode.geometry?.firstMaterial?.diffuse.contents=UIColor.red
print("It is highlited")
}
else{
let pointer=SCNNode(geometry:SCNSphere(radius: 0.01))
pointer.name="pointer"
pointer.position=currentPositionOfCamera
self.sceneView.scene.rootNode.enumerateChildNodes({(node,_) in
if node.name == "pointer"{
node.removeFromParentNode()
}
})
self.sceneView.scene.rootNode.addChildNode(pointer)
pointer.geometry?.firstMaterial?.diffuse.contents=UIColor.red
}
}
}
}
//Sums Vectors
func +(left:SCNVector3, right:SCNVector3)-> SCNVector3{
return SCNVector3Make(left.x+right.x,left.y+right.y, left.z+right.z)
}
|
a0a4a0a9eca7ba186b0f17e2d4692c59278a8143
|
[
"Swift"
] | 1 |
Swift
|
mauhdz/AR-Drawing
|
12bebba56320d57206713ccd89d216a92d1abbbc
|
06ae61cf5d04953edc2fb1180a607a97f56a36b7
|
refs/heads/master
|
<repo_name>skyformat99/fish-chart<file_sep>/src/components/base/Legend.vue
<template>
<g class="legend" :transform="rootTransform" ref="root">
<g class="item" v-for="(legend, index) in data" :transform="itemsTransform[index]" ref="items">
<rect x="2" y="4" :height="size" :width="size" :fill="legend.color" :rx="radius" :ry="radius"></rect>
<text x="20" y="15"><tspan>{{ legend.name }}</tspan></text>
</g>
</g>
</template>
<script>
import { _space } from '../../config'
const spacing = 20
export default {
name: 'fish-chart-legend',
props: {
start: { type: Object, default: () => { return {x: 0, y: 0} } },
size: { type: Number, default: 12 },
radius: { type: Number, default: 6 },
data: { type: Array, required: true } // [{name: '', color: ''}]
},
data () {
return {
rootTransform: '',
itemsTransform: []
}
},
mounted () {
let start = 0
let offset = _space.bottom / 2
const { width, height } = this.$parent.$el.getBoundingClientRect()
this.$refs.items.forEach((item, index) => {
let clientRect = item.getBoundingClientRect()
this.itemsTransform.splice(index, 1, `translate(${start},0)`)
start += clientRect.width + spacing
})
this.rootTransform = `translate(${(width - start) / 2}, ${height - offset})`
}
}
</script>
<file_sep>/src/components/base/Axis.vue
<template>
<g :class="['axis', vertical ? 'y-axis' : 'x-axis']">
<g class="labels" :transform="labelTransform">
<text v-for="(label, index) in labels" :x="xyLabels[index] && xyLabels[index].x" :y="xyLabels[index] && xyLabels[index].y" ref="labelItems">
<tspan>{{ label }}</tspan>
</text>
</g>
<g class="grid">
<path :d="d" v-for="d in lines"></path>
</g>
</g>
</template>
<script>
import { _space } from '../../config'
export default {
name: 'fish-chart-axis',
props: {
labels: { type: Array, required: true },
vertical: { type: Boolean, default: false },
type: { type: String, default: 'line' }
},
data () {
return {
labelTransform: '',
xyLabels: [],
lines: []
}
},
mounted () {
// console.log('labels:', this.labels)
const { height, width } = this.$parent.$el.getBoundingClientRect()
this.labelTransform = `translate(${_space.left},${height - _space.bottom})`
let step = (width - _space.left - _space.right) / (this.labels.length - (this.type === 'line' ? 1 : 0))
// 如果垂直
if (this.vertical) {
this.labelTransform = `translate(${_space.left},${_space.top})`
step = (height - _space.top - _space.bottom) / (this.labels.length - (this.type === 'line' ? 1 : 0))
}
let start = 0
// 设置label的位置
this.labels.forEach((label, index) => {
this.updateXY(index, start, step)
this.updateLines(index, start, width, height)
start += step
})
if (this.type === 'column') {
this.updateLines(this.labels.length, start, width, height)
}
// this.updateLines(this.labels.length, start, width, height)
},
methods: {
updateXY (index, start, step) {
if (this.vertical) {
this.xyLabels.splice(index, 1, {x: -15, y: start})
} else {
let x = start
if (this.type === 'column') {
const { width } = this.$refs.labelItems[index].getBoundingClientRect()
x += (step - width) / 2 + width / 2
}
this.xyLabels.splice(index, 1, {x: x, y: 15})
}
},
updateLines (index, start, width, height) {
if (this.vertical) {
this.lines.splice(index, 1, `M ${_space.left} ${_space.top + start} L ${width - _space.right} ${_space.top + start}`)
} else {
this.lines.splice(index, 1, `M ${_space.left + start} ${_space.top} L ${_space.left + start} ${height - _space.bottom}`)
}
}
}
}
</script>
<file_sep>/src/components/base/Line.vue
<template>
<g class="line">
<path :d="line" :stroke="color"></path>
<rect v-for="(point, index) in points"
class="point"
:x="point.x - pointSize/2"
:y="point.y - pointSize/2"
:height="pointSize"
:width="pointSize"
:fill="color"
:rx="pointSize/2"
:ry="pointSize/2"></rect>
</g>
</template>
<script>
export default {
name: 'fish-chart-base-line',
props: {
points: { type: Array, required: true },
pointSize: { type: Number, required: true },
color: { type: String, required: true }
},
data () {
return {
line: this.points.map((p, index) => `${index === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join('')
}
}
}
</script>
<file_sep>/src/components/ChartRing.vue
<template>
<svg version="1.1" class="fish chart" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" ref="root">
<fish-chart-title :title="title" :subtitle="subtitle"></fish-chart-title>
<g :transform="transform">
<g class="ring" v-for="shapeGroup in shapeGroups">
<path :d="shapeGroup.path" :fill="shapeGroup.color"></path>
<text :x="shapeGroup.textPoint.x" :y="shapeGroup.textPoint.y" :style="{'text-anchor': shapeGroup.textAnchor}">
<tspan>{{shapeGroup.name}} : {{(shapeGroup.v/vTotal * 100).toFixed(2)}}%</tspan>
</text>
</g>
</g>
</svg>
</template>
<script>
import { _color, _space } from '../config.js'
import FishChartTitle from './base/Title.vue'
export default {
components: {FishChartTitle},
name: 'fish-chart-ring',
props: {
title: { type: String, required: true },
subtitle: { type: String, default: '' },
total: { type: [String, Number] },
margin: { type: Number, default: 10 },
data: { type: Array, required: true } // [{name, v, color}]
},
data () {
let _total = 0.0
this.data.forEach((item) => { _total += item.v })
return {
shapeGroups: [],
vTotal: this.total || _total,
transform: ''
}
},
mounted () {
const { width, height } = this.$refs.root.getBoundingClientRect()
const centerPoint = {x: width / 2, y: (height + _space.top) / 2}
const r = (width > height ? height / 2 - _space.top / 2 : width / 2) - this.margin
const innerR = r - r / 5
this.transform = `translate(${centerPoint.x}, ${centerPoint.y})`
// 弧度起点坐标
let start = {x: 0, y: -r}
let start1 = {x: 0, y: -innerR}
let degree = 0.0
let textDegree = 0.0
this.data.forEach((item, index) => {
let currentDegree = (item.v / this.vTotal) * 360 // 占用多少度
// 计算环位置
degree += currentDegree
let endp = new Circle(r).getPointFromDegree(degree)
let endp1 = new Circle(innerR).getPointFromDegree(degree)
// console.log(endp, ':::', endp1)
let path = ['M', start.x, start.y, 'A', r, r, 0, currentDegree > 180 ? 1 : 0, 1, endp.x, endp.y, 'L', endp1.x, endp1.y, 'A', innerR, innerR, 0, currentDegree > 180 ? 1 : 0, 0, start1.x, start1.y, 'z'].join(' ')
start = endp
start1 = endp1
// 计算文字位置
textDegree += currentDegree / 2
let textAnchor = textDegree > 180 ? 'end' : 'start'
let tendp = new Circle(r + 10).getPointFromDegree(textDegree)
textDegree += currentDegree / 2
this.shapeGroups.push(Object.assign({textPoint: tendp, textAnchor: textAnchor}, item, {path: path, color: item.color || _color.get(index)}))
})
}
}
export class Circle {
constructor (r) {
this.r = r
}
getPointFromDegree (degree) {
let rad = degree * (Math.PI / 180)
return {x: this.r * Math.sin(rad), y: -this.r * Math.cos(rad)}
}
}
</script>
<file_sep>/example/App.vue
<template>
<div id="app">
<div style="width: 1000px; height: 500px; border: 1px solid #ccc; margin-bottom: 10px;">
<fish-chart-line title="每月数据量统计" subtitle="数据来源myliang" :labels="lineLabels" :data="lineData"></fish-chart-line>
</div>
<div style="width: 1000px; height: 500px; border: 1px solid #ccc; margin-bottom: 10px;">
<fish-chart-column title="每月数据量统计" subtitle="数据来源myliang" :labels="columnLabels" :data="columnData"></fish-chart-column>
</div>
<div style="width: 1000px; height: 500px; border: 1px solid #ccc; margin-bottom: 10px;">
<fish-chart-ring title="测试Ring" subtitle="source: myliang" :data="ringData"></fish-chart-ring>
</div>
</div>
</template>
<script>
export default {
name: 'app',
data () {
return {
lineLabels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
lineData: [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}, {
name: 'London',
data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}],
columnLabels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
columnData: [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}, {
name: 'London',
data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}],
ringData: [
{name: 'Firefox', v: 45.0},
{name: 'IE', v: 26.8},
{name: 'Safari', v: 8.5},
{name: 'Opera', v: 6.2},
{name: '其他', v: 0.7}
]
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
<file_sep>/src/components/ChartColumn.vue
<template>
<svg version="1.1" class="fish chart" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" ref="root">
<fish-chart-title :title="title" :subtitle="subtitle"></fish-chart-title>
<fish-chart-axis :labels="labels" type="column"></fish-chart-axis>
<fish-chart-axis :labels="yLabels" type="column" vertical></fish-chart-axis>
<fish-chart-legend :data="legends" :radius="2"></fish-chart-legend>
<g :transform="transform">
<g v-for="shapeGroup in shapeGroups" class="column">
<rect v-for="rect in shapeGroup.rects"
:x="rect.x" :y="rect.y" :height="rect.h" :width="columnWidth"
:fill="shapeGroup.color" :rx="0" :ry="0"></rect>
</g>
</g>
</svg>
</template>
<script>
import { _color, _space } from '../config.js'
import helper from '../helper.js'
import FishChartLegend from './base/Legend.vue'
import FishChartAxis from './base/Axis.vue'
import FishChartTitle from './base/Title.vue'
export default {
components: {
FishChartTitle,
FishChartAxis,
FishChartLegend},
name: 'fish-chart-column',
props: {
title: { type: String, required: true },
subtitle: { type: String, default: '' },
labels: { type: Array, required: true },
columnWidth: { type: Number, default: 8 },
data: { type: Array, required: true } // [{name: '', data: []}]
},
data () {
const { data, columnWidth } = this
return {
legends: data.map((item, index) => { return { name: item.name, color: (item.color || _color.get(index)) } }),
yLabels: getYLabels(data),
shapeGroups: [],
transform: '',
columnSpace: columnWidth / 2
}
},
mounted () {
const { width, height } = this.$refs.root.getBoundingClientRect()
const centerPoint = {x: _space.left, y: (height - _space.bottom) * this.yLabels.indexOf(0) / (this.yLabels.length - 1)}
// 定位到y-axis === 0的位置
this.transform = `translate(${centerPoint.x}, ${centerPoint.y})`
// 每个像素占用的多少刻度
const pixScales = (height - _space.bottom - _space.top) / Math.abs(this.yLabels[this.yLabels.length - 1] - this.yLabels[0])
// console.log(pixScales)
// x axis 间距
let xSpacing = (width - _space.left - _space.right) / this.labels.length
this.data.forEach((item, i) => {
const color = item.color || _color.get(i)
const shapeWidth = this.data.length * this.columnWidth + (this.data.length - 1) * this.columnSpace
const shapeOffset = i * (this.columnSpace + this.columnWidth)
const rects = item.data.map((v, index) => {
return { y: -v * pixScales, x: index * xSpacing + ((xSpacing - shapeWidth) / 2) + shapeOffset, h: Math.abs(-v * pixScales) }
})
this.shapeGroups.push({rects: rects, color: color})
})
}
}
const getYLabels = (data) => {
let min = Math.min(...data.map((item) => Math.min(...item.data)))
let max = Math.max(...data.map((item) => Math.max(...item.data)))
return helper.generateAxisScales(min, max, 8).sort((a, b) => a < b)
}
</script>
<file_sep>/src/components/base/Title.vue
<template>
<g>
<text class="title" ref="title" :transform="titleTransform">{{ title }}</text>
<text class="subtitle" ref="subtitle" :transform="subtitleTransform" v-if="subtitle">{{ subtitle }}</text>
</g>
</template>
<script>
export default {
name: 'fish-chart-title',
props: {
title: { type: String, required: true },
subtitle: { type: String }
},
data () {
return {
titleTransform: '',
subtitleTransform: ''
}
},
mounted () {
const { width } = this.$parent.$el.getBoundingClientRect()
const titleWidth = this.$refs.title.getBoundingClientRect().width
this.titleTransform = `translate(${(width - titleWidth) / 2}, 25)`
if (this.$refs.subtitle) {
const subtitleWidth = this.$refs.subtitle.getBoundingClientRect().width
this.subtitleTransform = `translate(${(width - subtitleWidth) / 2}, 45)`
}
}
}
</script>
<file_sep>/src/helper.js
module.exports = {
generateAxisScales (min, max, num) {
let delta = max - min
if (delta < 1.0) {
max += (1.0 - delta) / 2.0
min -= (1.0 - delta) / 2.0
}
delta = max - min
let exp = parseInt(Math.log(delta) / Math.log(10.0)) - 2
let multiplier = Math.pow(10, exp)
const solutions = [1, 2, 2.5, 5, 10, 20, 25, 50, 100, 200, 250, 500]
let i = 0
for (i = 0; i < solutions.length; i++) {
let multiCal = multiplier * solutions[i]
if (parseInt(delta / multiCal) + 1 <= num) break
}
let interval = multiplier * solutions[i]
let start = (parseInt(Math.ceil(min / interval)) - 1) * interval
let ret = []
for (let j = 0; 1; j++) {
let v = start + interval * j
ret.push(v)
if (v > max) break
}
return ret
}
}
<file_sep>/README.md
# fish-chart
> 一个给予vue2, svg的简单图表组件
## 安装
``` bash
npm install fish-chart
```
## 使用
```
# main.js
import FishChart from 'fish-chart'
Vue.user(FishChart)
```
## 实例
1. 线图
``` xml
<template>
<div style="width: 1000px; height: 500px; border: 1px solid #ccc; margin-bottom: 10px;">
<fish-chart-line title="每月数据量统计" subtitle="数据来源myliang" :labels="lineLabels" :data="lineData"></fish-chart-line>
</div>
</template>
<script>
export default {
data () {
return {
lineLabels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
lineData: [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}, {
name: 'London',
data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]
}
}
}
</script>
```
2. 柱状图
``` xml
<template>
<div style="width: 1000px; height: 500px; border: 1px solid #ccc; margin-bottom: 10px;">
<fish-chart-column title="每月数据量统计" subtitle="数据来源myliang" :labels="columnLabels" :data="columnData"></fish-chart-column>
</div>
</template>
<script>
export default {
data () {
return {
columnLabels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
columnData: [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}, {
name: 'London',
data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]
}
}
}
</script>
```
3. 环图
``` xml
<template>
<div style="width: 1000px; height: 500px; border: 1px solid #ccc; margin-bottom: 10px;">
<fish-chart-ring title="测试Ring" subtitle="source: myliang" :data="ringData"></fish-chart-ring>
</div>
</template>
<script>
export default {
data () {
return {
ringData: [
{name: 'Firefox', v: 45.0},
{name: 'IE', v: 26.8},
{name: 'Safari', v: 8.5},
{name: 'Opera', v: 6.2},
{name: '其他', v: 0.7}
]
}
}
}
</script>
```
## TODOS
* 丰富图表类型
* 优化相关代码
## LICENSE
MIT
<file_sep>/src/index.js
import './chart.css'
import ChartLine from './components/ChartLine.vue'
import ChartColumn from './components/ChartColumn.vue'
import ChartRing from './components/ChartRing.vue'
const components = {
ChartLine,
ChartColumn,
ChartRing
}
const install = function (Vue, opts = {}) {
Object.values(components).forEach((component) => {
// console.log(component.name)
Vue.component(component.name, component)
})
}
// auto install
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue)
}
export default Object.assign({}, components, {install}) // eslint-disable-line no-undef
|
97bb976d308dc8ba086e655c173a87e738226373
|
[
"Markdown",
"Vue",
"JavaScript"
] | 10 |
Markdown
|
skyformat99/fish-chart
|
833c16ba80cda79ab106fa97f7b4cbe535faf288
|
14d528c7b76c55378ea09a12c74c23ee274c9129
|
refs/heads/master
|
<repo_name>concpetosfundamentalesprogramacionaa19/practica080719-2bim-JoanMBQ<file_sep>/Practica080719-2bim/src/potencia/Principal.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package potencia;
/**
*
* @author TIMO
*/
public class Principal {
public static void main(String[] args) {
int potencia = Potencia.get_potencia(2, 4);
System.out.printf("%d\n", potencia);
}
}<file_sep>/Practica080719-2bim/src/arreglo/Principal.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package arreglo;
/**
*
* @author TIMO
*/
public class Principal {
public static void main(String[] args) {
int num[] = {10, 20, 30, 1, 2, 3, 40, 4};
int arreglo = Arreglo.obtenerTamanioArreglo(num, 8);
int arreglo2 = Arreglo.obtenerSumaArreglo(num, 8);
System.out.printf("La suma del metodo 1 es: %s\n"
+ "La suma del metodo 2 es: %s\n", arreglo, arreglo2);
}
}
|
ec2c80f18fb2a944a1e8cc6c0644eb20c0d6c334
|
[
"Java"
] | 2 |
Java
|
concpetosfundamentalesprogramacionaa19/practica080719-2bim-JoanMBQ
|
5da4a767728e08734cac5df8be7d058e92a4f923
|
6cee2b4a05d325dd1cc4896529b00179694c6dd8
|
refs/heads/master
|
<repo_name>Brooke-Paul/Leetcodes<file_sep>/src/main/java/com/learning/Number250/LeetCode276.java
package com.learning.Number250;
import java.util.Map;
/**
* Program Name: leetcodes
* <p>
* Description: 给定一个正整数 n ,你可以做如下操作:
* <p>
* 1. 如果 n 是偶数,则用 n / 2 替换 n 。
* 2. 如果 n 是奇数,则可以用 n + 1 或 n - 1 替换 n 。
* n 变为 1 所需的最小替换次数是多少?
* <p>
* 示例 1:
* <p>
* 输入:
* 8
* <p>
* 输出:
* 3
* <p>
* 解释:
* 8 -> 4 -> 2 -> 1
* <p>
* 示例 2:
* <p>
* 输入:
* 7
* <p>
* 输出:
* 4
* <p>
* 解释:
* 7 -> 8 -> 4 -> 2 -> 1
* 或
* 7 -> 6 -> 3 -> 2 -> 1
* <p>
* Created by xuetao on 2020/2/3
*
* @author xuetao
* @version 1.0
*/
public class LeetCode276 {
public static void main(String[] args) {
int n = 7;
System.out.println(smallestCount(n));
}
private static int smallestCount(int n) {
int count = 0;
while (n > 1) {
count = (n % 2 == 0) ? count : count + 1;
n = (n % 2 == 0) ? n : n - 1;
n = n / 2;
count++;
}
return count;
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode134.java
package com.learning.Number150;
import com.learning.entity.Node;
/**
* @Author xuetao
* @Description: 删除链表中等于给定值 val 的所有节点。
* <p>
* 示例:
* <p>
* 输入: 1->2->6->3->4->5->6, val = 6
* 输出: 1->2->3->4->5
* @Date 2019-10-08
* @Version 1.0
*/
public class LeetCode134 {
public static void main(String[] args) {
Node node = new Node(1, 1, 1, null);
node.next = new Node(2, 2, 2, null);
node.next.next = new Node(3, 3, 3, null);
node.next.next.next = new Node(2, 2, 2, null);
node.next.next.next.next = new Node(3, 3, 3, null);
int target = 3;
Node first = removeNodeI(node, target);
Node second = removeElementII(node, target);
while (first != null) {
System.out.println(first.value);
first = first.next;
}
while (second != null) {
System.out.println(second.value);
second = second.next;
}
}
/**
* 方法一
*
* @param node
* @param target
* @return
*/
private static Node removeNodeI(Node node, int target) {
Node first = new Node(0, 0, 0, null);
first.next = node;
Node prev = first;
Node current = first.next;
while (current != null) {
if ((int) current.value == target) {
prev.next = current.next;
} else {
prev = prev.next;
}
current = current.next;
}
return first.next;
}
/**
* 方法二
*
* @param node
* @param target
* @return
*/
public static Node removeElementII(Node node, int target) {
Node cur = node;
Node result = null;
Node last = null;
while (cur != null) {
if ((int) cur.value != target) {
if (result == null) {
result = cur;
} else {
last.next = cur;
}
last = cur;
}
cur = cur.next;
}
if (last != null) {
last.next = null;
}
return result;
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode151.java
package com.learning.Number200;
import java.util.ArrayList;
import java.util.List;
/**
* @Author xuetao
* @Description: 给定一个无重复元素的有序整数数组,返回数组区间范围的汇总。
* <p>
* 示例 1:
* <p>
* 输入: [0,1,2,4,5,7]
* 输出: ["0->2","4->5","7"]
* 解释: 0,1,2 可组成一个连续的区间; 4,5 可组成一个连续的区间。
* <p>
* 示例 2:
* <p>
* 输入: [0,2,3,4,6,8,9]
* 输出: ["0","2->4","6","8->9"]
* 解释: 2,3,4 可组成一个连续的区间; 8,9 可组成一个连续的区间
* @Date 2019-10-31
* @Version 1.0
*/
public class LeetCode151 {
public static List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
String start = String.valueOf(nums[i]);
int tmpI = i;
while ((i + 1) < nums.length && (nums[i] + 1) == nums[i + 1]) {
i++;
}
if (tmpI == i) {
result.add(start);
} else {
result.add(start + "->" + nums[i]);
}
}
return result;
}
public static void main(String... args) {
int[] nums = new int[]{0, 1, 2, 4, 5, 7};
List<String> result = summaryRanges(nums);
for (String s : result) {
System.out.println(s);
}
}
}
<file_sep>/src/main/java/com/learning/Number250/LeetCode262.java
package com.learning.Number250;
/**
* Program Name: leetcodes
* <p>
* Description: 如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为 摆动序列。 第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。
* <p>
* 例如, [1,7,4,9,2,5] 是一个摆动序列,因为差值 (6,-3,5,-7,3) 是正负交替出现的。相反, [1,4,7,2,5] 和 [1,7,4,5,5] 不是摆动序列,第一个序列是因为它的前两个差值都是正数,第二个序列是因为它的最后一个差值为零。
* <p>
* 给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。
* <p>
* 示例:
* <p>
* 输入: [1,7,4,9,2,5]
* 输出: 6
* 解释: 整个序列就是一个摆动序列。
* <p>
* 输入: [1,17,5,10,13,15,10,5,16,8]
* 输出: 7
* 解释: 它的几个子序列满足摆动序列。其中一个是[1,17,10,13,10,16,8]。
* <p>
* 输入: [1,2,3,4,5,6,7,8,9]
* 输出: 2
* <p>
* 进阶:
* 你能否用 O( n ) 时间复杂度完成此题?
* <p>
* Created by xuetao on 2020/1/14
*
* @author xuetao
* @version 1.0
*/
public class LeetCode262 {
public static void main(String[] args) {
int[] array = {1, 17, 5, 10, 13, 15, 10, 5, 16, 8};
System.out.println(maxLength(array));
}
private static int maxLength(int[] array) {
if (array == null || array.length < 1) {
return 0;
}
int length = array.length;
if (length < 2) {
return length;
}
int preDiff = array[1] - array[0];
int count = 2;
for (int i = 2; i < length; i++) {
int diff = array[i] - array[i - 1];
if ((preDiff > 0 && diff < 0) || (preDiff < 0 && diff > 0)) {
count++;
preDiff = diff;
}
}
return count;
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode115.java
package com.learning.Number150;
import java.util.Arrays;
/**
* @Author xuetao
* @Description: 给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。
* <p>
* 如果数组元素个数小于 2,则返回 0。
* <p>
* 示例 1:
* <p>
* 输入: [3,6,9,1]
* 输出: 3
* 解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。
* <p>
* 示例 2:
* <p>
* 输入: [10]
* 输出: 0
* 解释: 数组元素个数小于 2,因此返回 0。
* <p>
* 说明:
* <p>
* 你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。
* 请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。
* @Date 2019-09-16
* @Version 1.0
*/
public class LeetCode115 {
public static void main(String[] args) {
int[] array = {3, 7, 9, 1, 6, 9, 9};
Arrays.sort(array);
System.out.println(findMaxValue(array));
}
private static int findMaxValue(int[] array) {
long startTime = System.currentTimeMillis();
if (array == null || array.length < 2) {
return 0;
}
int len = array.length;
int max = 0;
for (int i = 1; i < len; i++) {
if (array[i] == array[i - 1]) {
continue;
}
max = Math.max(array[i] - array[i - 1], max);
}
long endTime = System.currentTimeMillis();
System.out.println("cost(" + (endTime - startTime) + ")ms");
return max;
}
}
<file_sep>/src/main/java/com/learning/Number250/LeetCode283.java
package com.learning.Number250;
/**
* Program Name: com.learning.Number250
* Description: 给定一个非负整数数组和一个整数 m ,你需要将这个数组分成 m 个非空的连续子数组。设计一个算法使得这 m 个子数组各自和的最大值最小。
* <p>
* 注意:
* 数组长度 n 满足以下条件:
* <p>
* 1 ≤ n ≤ 1000
* 1 ≤ m ≤ min(50, n )
* 示例:
* <p>
* 输入:
* nums = [7,2,5,10,8]
* m = 2
* <p>
* 输出:
* 18
* <p>
* 解释:
* 一共有四种方法将nums分割为2个子数组。
* 其中最好的方式是将其分为**[7,2,5]** 和 [10,8],
* 因为此时这两个子数组各自的和的最大值为18,在所有情况中最小。
* Created by xuetao on 2020/2/15
*
* @author xuetao
* @version 1.0
*/
public class LeetCode283 {
public static void main(String[] args) {
int[] nums = {7, 2, 5, 10, 8};
int m = 2;
System.out.println(splitArray(nums, m));
}
public static int splitArray(int[] nums, int m) {
int max = 0;
long sum = 0;
for (int num : nums) {
max = Math.max(num, max);
sum += num;
}
if (m == 1) {
return (int) sum;
}
//binary search
long l = max;
long r = sum;
while (l <= r) {
long mid = (l + r) / 2;
if (valid(mid, nums, m)) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return (int) l;
}
public static boolean valid(long target, int[] nums, int m) {
int count = 1;
long total = 0;
for (int num : nums) {
total += num;
if (total > target) {
total = num;
count++;
if (count > m) {
return false;
}
}
}
return true;
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode36.java
package com.learning.Number50;
import java.util.*;
/**
* @Author xuetao
* @Description: 判断一个 9x9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
* <p>
* 数字 1-9 在每一行只能出现一次。
* 数字 1-9 在每一列只能出现一次。
* 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
* <p>
* <p>
* 上图是一个部分填充的有效的数独。
* <p>
* 数独部分空格内已填入了数字,空白格用 '.' 表示。
* <p>
* 示例 1:
* <p>
* 输入:
* [
* ["5","3",".",".","7",".",".",".","."],
* ["6",".",".","1","9","5",".",".","."],
* [".","9","8",".",".",".",".","6","."],
* ["8",".",".",".","6",".",".",".","3"],
* ["4",".",".","8",".","3",".",".","1"],
* ["7",".",".",".","2",".",".",".","6"],
* [".","6",".",".",".",".","2","8","."],
* [".",".",".","4","1","9",".",".","5"],
* [".",".",".",".","8",".",".","7","9"]
* ]
* 输出: true
* <p>
* 示例 2:
* <p>
* 输入:
* [
* ["8","3",".",".","7",".",".",".","."],
* ["6",".",".","1","9","5",".",".","."],
* [".","9","8",".",".",".",".","6","."],
* ["8",".",".",".","6",".",".",".","3"],
* ["4",".",".","8",".","3",".",".","1"],
* ["7",".",".",".","2",".",".",".","6"],
* [".","6",".",".",".",".","2","8","."],
* [".",".",".","4","1","9",".",".","5"],
* [".",".",".",".","8",".",".","7","9"]
* ]
* 输出: false
* 解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。
* 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
* <p>
* 说明:
* <p>
* 一个有效的数独(部分已被填充)不一定是可解的。
* 只需要根据以上规则,验证已经填入的数字是否有效即可。
* 给定数独序列只包含数字 1-9 和字符 '.' 。
* 给定数独永远是 9x9 形式的。
* @Date 2019-06-11
* @Version 1.0
*/
public class LeetCode36 {
/**
* 思考:每一行遍历,接着每一列遍历,最后3*3遍历
*
* @param args
*/
public static void main(String[] args) {
String array[][] = {
{"9", "3", ".", ".", "7", ".", ".", ".", "."},
{"6", ".", ".", "1", "9", "5", ".", ".", "."},
{".", "9", "8", ".", ".", ".", ".", "6", "."},
{"8", ".", ".", ".", "6", ".", ".", ".", "3"},
{"4", ".", ".", "8", ".", "3", ".", ".", "1"},
{"7", ".", ".", ".", "2", ".", ".", ".", "6"},
{".", "6", ".", ".", ".", ".", "2", "8", "."},
{".", ".", ".", "4", "1", "9", ".", ".", "5"},
{".", ".", ".", ".", "8", ".", ".", "7", "9"}
};
System.out.println(isValidSudoku(array));
}
public static boolean isValidSudoku(String[][] array) {
Map[] row = new Map[9];
Map[] col = new Map[9];
Map[] cell = new Map[9];
for (int i = 0; i < 9; i++) {
row[i] = new HashMap(9);
col[i] = new HashMap(9);
cell[i] = new HashMap(9);
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
String str = array[i][j];
int cindex = 3 * (i / 3) + j / 3;
if (".".equals(str)) {
continue;
}
if (row[i].containsValue(str) || col[j].containsValue(str) || cell[cindex].containsValue(str)) {
return false;
} else {
row[i].put(str, str);
col[j].put(str, str);
cell[cindex].put(str, str);
}
}
}
return true;
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode173.java
package com.learning.Number200;
import java.util.*;
/**
* @Author xuetao
* @Description: 给定一个迭代器类的接口,接口包含两个方法: next() 和 hasNext() 。设计并实现一个支持 peek() 操作的顶端迭代器 -- 其本质就是把原本应由 next() 方法返回的元素 peek() 出来。
* <p>
* 示例:
* <p>
* 假设迭代器被初始化为列表 [1,2,3]。
* <p>
* 调用 **next()**返回 1,得到列表中的第一个元素。
* 现在调用 peek() 返回 2,下一个元素。在此之后调用 next() 仍然返回 2。
* 最后一次调用 next() 返回 3,末尾元素。在此之后调用 hasNext() 应该返回 false。
* <p>
* 进阶: 你将如何拓展你的设计?使之变得通用化,从而适应所有的类型,而不只是整数型?
* @Date 2019-11-28
* @Version 1.0
*/
public class LeetCode173 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3);
PeekIterator peekIterator = new PeekIterator(list.iterator());
System.out.println(peekIterator.hasNext());
System.out.println(peekIterator.next());
System.out.println(peekIterator.peek());
System.out.println(peekIterator.hasNext());
System.out.println(peekIterator.next());
System.out.println(peekIterator.peek());
System.out.println(peekIterator.hasNext());
System.out.println(peekIterator.next());
System.out.println(peekIterator.peek());
}
public static class PeekIterator implements Iterator<Integer> {
private Queue<Integer> queue;
public PeekIterator(Iterator<Integer> iterator) {
queue = new LinkedList<>();
while (iterator.hasNext()) {
queue.add(iterator.next());
}
}
public Integer peek() {
return queue.peek();
}
@Override
public boolean hasNext() {
return !queue.isEmpty();
}
@Override
public Integer next() {
return queue.poll();
}
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode38.java
package com.learning.Number50;
/**
* @Author xuetao
* @Description: 报数序列是指一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
* <p>
* 1. 1
* 2. 11
* 3. 21
* 4. 1211
* 5. 111221
* <p>
* 1 被读作 "one 1" ( "一个一" ) , 即 11 。
* 11 被读作 "two 1s" ( "两个一" ), 即 21 。
* 21 被读作 "one 2" , " one 1" ( "一个二" , "一个一" ) , 即 1211 。
* <p>
* 给定一个正整数 n ,输出报数序列的第 n 项。
* <p>
* 注意:整数顺序将表示为一个字符串。
* <p>
* 示例 1:
* <p>
* 输入: 1
* 输出: "1"
* <p>
* 示例 2:
* <p>
* 输入: 4
* 输出: "1211"
* @Date 2019-06-13
* @Version 1.0
*/
public class LeetCode38 {
public static void main(String[] args) {
System.out.println(numberOff(7));
}
/**
* 解决思路:
* 第一个循环用于获取上一次返回的字串
* 第二个循环用于处理上次的字串判断重复count+1,不重复重新计算下标与count
*
* @param num
* @return
*/
public static String numberOff(int num) {
String s = "1";
if (num == 0 || num == 1) {
return s;
}
StringBuffer stringBuffer = new StringBuffer(s);
for (int i = 1; i < num; i++) {
int count = 1;
StringBuffer current = stringBuffer;
stringBuffer = new StringBuffer();
char st = current.charAt(0);
System.out.println(st);
int length = current.length();
for (int j = 1; j < length; j++) {
if (current.charAt(j) == st) {
count++;
} else {
System.out.println("count " + count + "st " + st);
stringBuffer.append(count).append(st);
count = 1;
st = current.charAt(j);
}
}
System.out.println("count " + count + "st " + st);
stringBuffer.append(count).append(st);
System.out.println("count " + count + "st " + st + " stringBuffer " + stringBuffer.toString());
}
return stringBuffer.toString();
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode175.java
package com.learning.Number200;
import java.util.HashMap;
import java.util.Map;
/**
* @Author xuetao
* @Description: 给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循相同的模式。
* <p>
* 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应模式。
* <p>
* 示例1:
* <p>
* 输入: pattern = "abba", str = "dog cat cat dog"
* 输出: true
* <p>
* 示例 2:
* <p>
* **输入:**pattern = "abba", str = "dog cat cat fish"
* 输出: false
* <p>
* 示例 3:
* <p>
* 输入: pattern = "aaaa", str = "dog cat cat dog"
* 输出: false
* <p>
* 示例 4:
* <p>
* 输入: pattern = "abba", str = "dog dog dog dog"
* 输出: false
* <p>
* 说明:
* 你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。
* @Date 2019-12-01
* @Version 1.0
*/
public class LeetCode175 {
public static void main(String[] args) {
String pattern = "abba";
String str = "dog cat cat dog";
System.out.println(hasSameMode(pattern, str));
}
private static boolean hasSameMode(String pattern, String str) {
String[] array = str.split(" ");
int pLen = pattern.length();
int sLen = array.length;
if (pLen != sLen) {
return false;
}
Map<Character, String> map = new HashMap<>();
for (int i = 0; i < pLen; i++) {
if (map.get(pattern.charAt(i)) != null && !map.get(pattern.charAt(i)).equals(array[i])) {
return false;
}
map.putIfAbsent(pattern.charAt(i), array[i]);
}
return true;
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode31.java
package com.learning.Number50;
/**
* @Author xuetao
* @Description: 实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
* <p>
* 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
* <p>
* 必须 原地 修改,只允许使用额外常数空间。
* <p>
* 以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
* 1,2,3 → 1,3,2
* 3,2,1 → 1,2,3
* 1,1,5 → 1,5,1
* @Date 2019-06-04
* @Version 1.0
*/
public class LeetCode31 {
public static void main(String[] args) {
int nums[] = {1, 1, 4, 3, 2};
nextPermutation(nums);
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
}
public static void nextPermutation(int[] nums) {
int length = nums.length;
int i = length - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i >= 0) {
int j = length - 1;
while (j >= 0 && nums[i] >= nums[j]) {
j--;
}
swap(nums, i, j);
}
reverse(nums, i + 1, length);
}
public static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public static void reverse(int[] nums, int start, int length) {
int end = length - 1;
while (start <= end) {
int temp = nums[start];
nums[start++] = nums[end];
nums[end--] = temp;
}
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode186.java
package com.learning.Number200;
/**
* Program Name: leetcodes
* <p>
* Description:初始时有 n 个灯泡关闭。 第 1 轮,你打开所有的灯泡。 第 2 轮,每两个灯泡你关闭一次。 第 3 轮,每三个灯泡切换一次开关(如果关闭则打开,如果打开则关闭)。第 i 轮,你每 i 个灯泡切换一次开关。 对于第 n 轮,你只切换最后一个灯泡的开关。 找出 n 轮后有多少个亮着的灯泡。
* <p>
* 示例:
* <p>
* 输入: 3
* 输出: 1
* 解释:
* 状态off表示灯泡关闭,on表示开启。
* 初始时, 灯泡状态 [off, off, off].
* 第一轮后, 灯泡状态 [on, on, on].
* 第二轮后, 灯泡状态 [on, off, on].
* 第三轮后, 灯泡状态 [on, off, offå].
* <p>
* 你应该返回 1,因为只有一个灯泡还亮着。
* <p>
* Created by xuetao on 2019/12/13
*
* @author xuetao
* @version 1.0
*/
public class LeetCode186 {
public static void main(String[] args) {
int array = 7;
System.out.println(findLightOn(array));
}
private static int findLightOn(int n) {
if (n < 2) {
return n;
}
return (int) Math.sqrt(n);
}
}
<file_sep>/src/main/java/com/learning/Number250/LeetCode263.java
package com.learning.Number250;
/**
* Program Name: leetcodes
* <p>
* Description: 给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。
* <p>
* 示例:
* <p>
* nums = [1, 2, 3]
* target = 4
* <p>
* 所有可能的组合为:
* (1, 1, 1, 1)
* (1, 1, 2)
* (1, 2, 1)
* (1, 3)
* (2, 1, 1)
* (2, 2)
* (3, 1)
* <p>
* 请注意,顺序不同的序列被视作不同的组合。
* <p>
* 因此输出为 7。
* <p>
* 进阶:
* 如果给定的数组中含有负数会怎么样?
* 问题会产生什么变化?
* 我们需要在题目中添加什么限制来允许负数的出现?
* <p>
* 致谢:
* 特别感谢 @pbrother 添加此问题并创建所有测试用例。
* <p>
* Created by xuetao on 2020/1/15
*
* @author xuetao
* @version 1.0
*/
public class LeetCode263 {
private static int count = 0;
public static void main(String[] args) {
int[] array = {1, 2, 3};
int target = 4;
findNumber(array, target);
System.out.println(count);
}
private static void findNumber(int[] nums, int target) {
int length = nums.length;
for (int i = 0; i < length; i++) {
dps(nums, length, target - nums[i]);
}
}
private static void dps(int[] nums, int length, int target) {
if (target == 0) {
count++;
return;
}
for (int j = 0; j < length; j++) {
if (target - nums[j] >= 0) {
dps(nums, length, target - nums[j]);
}
}
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode109.java
package com.learning.Number150;
/**
* @Author xuetao
* @Description: 给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
* <p>
* 示例 1:
* <p>
* 输入: [2,3,-2,4]
* 输出: 6
* 解释: 子数组 [2,3] 有最大乘积 6。
* <p>
* 示例 2:
* <p>
* 输入: [-2,0,-1]
* 输出: 0
* 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
* @Date 2019-09-10
* @Version 1.0
*/
public class LeetCode109 {
public static void main(String[] args) {
int[] array = {2, 3, -2, 4, 8, 9};
System.out.println(maxProduct(array));
}
private static int maxProduct(int[] array) {
int max = 0;
for (int i = 1; i < array.length; i++) {
max = Math.max(max, array[i] * array[i - 1]);
}
return max;
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode176.java
package com.learning.Number200;
/**
* Program Name: leetcodes
* <p>
* Description: 你和你的朋友,两个人一起玩 Nim游戏 :桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。
* <p>
* 你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。
* <p>
* 示例:
* <p>
* 输入: 4
* 输出: false
* 解释: 如果堆中有 4 块石头,那么你永远不会赢得比赛;
* 因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。
* <p>
* Created by xuetao on 2019/12/2
*
* @author xuetao
* @version 1.0
*/
public class LeetCode176 {
public static void main(String[] args) {
int n = 11;
System.out.println(winGame(n));
}
private static boolean winGame(int n) {
return n % 4 != 0;
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode48.java
package com.learning.Number50;
/**
* @Author xuetao
* @Description: 给定一个 n × n 的二维矩阵表示一个图像。
* <p>
* 将图像顺时针旋转 90 度。
* <p>
* 说明:
* <p>
* 你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。 请不要 使用另一个矩阵来旋转图像。
* <p>
* 示例 1:
* <p>
* 给定 matrix =
* [
* [1,2,3],
* [4,5,6],
* [7,8,9]
* ],
* <p>
* 原地旋转输入矩阵,使其变为:
* [
* [7,4,1],
* [8,5,2],
* [9,6,3]
* ]
* <p>
* 示例 2:
* <p>
* 给定 matrix =
* [
* [ 5, 1, 9,11],
* [ 2, 4, 8,10], 3 6
* [13, 3, 6, 7], 4 8
* [15,14,12,16]
* ],
* <p>
* 原地旋转输入矩阵,使其变为:
* [
* [15,13, 2, 5], 00-03 01-13 02-23 03 33
* [14, 3, 4, 1],
* [12, 6, 8, 9],
* [16, 7,10,11]
* ]
* @Date 2019-06-29
* @Version 1.0
*/
public class LeetCode48 {
public static void main(String[] args) {
int[][] array = {{5, 1, 9, 11}, {2, 4, 8, 10}, {3, 3, 6, 7}, {15, 14, 12, 16}};
rotateMatrix(array);
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
public static void rotateMatrix(int[][] array) {
int row = array.length;
int col = array[0].length;
int top = 0;
int bottom = row - 1;
while (top < bottom) {
int[] temp = array[top];
array[top] = array[bottom];
array[bottom] = temp;
top++;
bottom--;
}
for (int i = 0; i < row; i++) {
for (int j = i + 1; j < col; j++) {
int temp = array[i][j];
array[i][j] = array[j][i];
array[j][i] = temp;
}
}
}
}
<file_sep>/src/main/java/com/learning/Number100/LeetCode82.java
package com.learning.Number100;
import com.learning.entity.Node;
/**
* @Author xuetao
* @Description: Given a sorted linked list, delete all duplicates such that each element appear only once.
* <p>
* For example,
* Given 1->1->2, return 1->2.
* Given 1->1->2->3->3, return 1->2->3.
* ---------------------
* @Date 2019-08-10
* @Version 1.0
*/
public class LeetCode82 {
/**
* 上一题简便做法,明日解决
*
* @param args
*/
public static void main(String[] args) {
Node node = new Node(1, 1, 1, null);
node.next = new Node(1, 1, 1, null);
node.next.next = new Node(2, 2, 2, null);
node.next.next.next = new Node(3, 3, 3, null);
node.next.next.next.next = new Node(3, 3, 3, null);
removeDuplicates(node);
}
private static void removeDuplicates(Node node) {
Node first = new Node(0, 0, 0, null);
Node firstTemp = first;
Node temp = node;
int value = 0;
while (temp != null) {
if ((int) temp.value != value) {
firstTemp.next = temp;
firstTemp = firstTemp.next;
} else {
firstTemp.next = null;
}
value = (int) temp.value;
temp = temp.next;
}
node = first.next;
while (node != null) {
System.out.println(node.value);
node = node.next;
}
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode29.java
package com.learning.Number50;
/**
* @Author xuetao
* @Description: 给定两个整数,被除数 dividend 和除数 divisor 。将两数相除,要求不使用乘法、除法和 mod 运算符。
* <p>
* 返回被除数 dividend 除以除数 divisor 得到的商。
* <p>
* 示例 1:
* <p>
* 输入: dividend = 10, divisor = 3
* 输出: 3
* <p>
* 示例 2:
* <p>
* 输入: dividend = 7, divisor = -3
* 输出: -2
* <p>
* 说明:
* <p>
* 被除数和除数均为 32 位有符号整数。
* 除数不为 0。
* 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2 31 , 2 31 − 1]。本题中,如果除法结果溢出,则返回 2 31 − 1。
* @Date 2019-05-31
* @Version 1.0
*/
public class LeetCode29 {
/**
* 使用位运算符
* 判断运算后的符号标志
* 如果 a >= b, b<<2, n+1, 循环执行, 如果 a < 2b, a-b 继续与b比较,直到 循环结束
*
* @param args
*/
public static void main(String[] args) {
System.out.println(divide(8, 3));
}
public static int divide(int dividend, int divisor) {
if (divisor == 0 || (dividend == 1 && divisor == Integer.MIN_VALUE)) {
return Integer.MAX_VALUE;
}
boolean sign = ((dividend > 0) ^ (divisor > 0));
int sum = 0;
while (dividend >= divisor) {
int n = divisor;
int m = 1;
while (dividend >= (n << 1)) {
m = m << 1;
n = n << 1;
}
sum += m;
dividend = dividend - n;
}
return sign ? -sum : sum;
}
}
<file_sep>/src/main/java/com/learning/Number250/LeetCode272.java
package com.learning.Number250;
/**
* Program Name: leetcodes
* <p>
* Description: 给定两个字符串 s 和 t ,它们只包含小写字母。
* <p>
* 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
* <p>
* 请找出在 t 中被添加的字母。
* <p>
* 示例:
* <p>
* 输入:
* s = "abcd"
* t = "abcde"
* <p>
* 输出:
* e
* <p>
* 解释:
* 'e' 是那个被添加的字母。
* <p>
* Created by xuetao on 2020/1/27
*
* @author xuetao
* @version 1.0
*/
public class LeetCode272 {
public static void main(String[] args) {
String s = "abcd";
String t = "abcde";
System.out.println(findUniqueChar(s, t));
}
private static Character findUniqueChar(String s, String t) {
char[] sa = s.toCharArray();
char[] ta = t.toCharArray();
for (char c : ta) {
if (s.indexOf(c) == -1) {
return c;
}
}
return null;
}
}
<file_sep>/src/main/java/com/learning/Number250/LeetCode252.java
package com.learning.Number250;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Program Name: leetcodes
* <p>
* Description: 给定两个数组,写一个方法来计算它们的交集。
* <p>
* 例如:
* 给定 nums1 = [1, 2, 2, 1] , nums2 = [2, 2] , 返回 [2, 2] .
* <p>
* 注意:
* <p>
* 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
* 我们可以不考虑输出结果的顺序。
* 跟进:
* <p>
* 如果给定的数组已经排好序呢?你将如何优化你的算法?
* 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
* 如果 nums2 的元素存储在磁盘上,内存是有限的,你不能一次加载所有的元素到内存中,你该怎么办?
* <p>
* Created by xuetao on 2020/1/2
*
* @author xuetao
* @version 1.0
*/
public class LeetCode252 {
public static void main(String[] args) {
int[] num1 = {1, 2, 2, 1};
int[] num2 = {1, 2};
System.out.println(intersectionArray(num1, num2));
}
private static List<Integer> intersectionArray(int[] num1, int[] num2) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < num1.length; i++) {
map.put(num1[i], map.getOrDefault(num1[i], 0) + 1);
}
List<Integer> al = new ArrayList<Integer>();
for (int i : num2) {
if (map.containsKey(i) && map.get(i) > 0) {
al.add(i);
map.put(i, map.get(i) - 1);
}
}
return al;
}
}
<file_sep>/src/main/java/com/learning/Number100/LeetCode86.java
package com.learning.Number100;
/**
* @Author xuetao
* @Description: 给定两个有序整数数组 nums1 和 nums2 ,将 nums2 合并到 nums1 中 , 使得 num1 成为一个有序数组。
* <p>
* 说明:
* <p>
* 初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。
* 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n )来保存 nums2 中的元素。
* 示例:
* <p>
* 输入:
* nums1 = [1,2,3,0,0,0], m = 3
* nums2 = [2,5,6], n = 3
* <p>
* 输出: [1,2,2,3,5,6]
* @Date 2019-08-17
* @Version 1.0
*/
public class LeetCode86 {
public static void main(String[] args) {
int[] num1 = {4, 5, 6, 0, 0, 0};
int[] num2 = {1, 2, 3};
int m = 3;
int n = 3;
merge(num1, m, num2, n);
for (int i = 0; i < num1.length; i++) {
System.out.println(num1[i]);
}
}
private static void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1;
int j = n - 1;
int k = m + n - 1;
while (i >= 0 && j >= 0) {
if (nums1[i] > nums2[j]) {
nums1[k--] = nums1[i--];
} else {
nums1[k--] = nums2[j--];
}
}
while (j >= 0) {
nums1[k--] = nums2[j--];
}
}
}
<file_sep>/src/main/java/com/learning/Number250/LeetCode287.java
package com.learning.Number250;
/**
* Program Name: com.learning.Number250
* Description: 给定两个字符串形式的非负整数 num1 和 num2 ,计算它们的和。
* <p>
* 注意:
* <p>
* num1 和 num2 的长度都小于 5100.
* num1 和 num2 都只包含数字 0-9 .
* num1 和 num2 都不包含任何前导零。
* 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
* Created by xuetao on 2020/2/20
*
* @author xuetao
* @version 1.0
*/
public class LeetCode287 {
public static void main(String[] args) {
String num1 = "2124";
String num2 = "0126";
System.out.println(transfer(num1) + transfer(num2));
}
private static int transfer(String num) {
int len = num.length();
int n = 0;
for (int i = 0; i < len; i++) {
int x = num.charAt(i) - '0';
n = n * 10 + x;
}
return n;
}
}
<file_sep>/src/main/java/com/learning/Number100/LeetCode99.java
package com.learning.Number100;
import java.util.Arrays;
/**
* @Author xuetao
* @Description: 给定一个未排序的整数数组,找出最长连续序列的长度。
* <p>
* 要求算法的时间复杂度为 O(n) 。
* <p>
* 示例:
* <p>
* 输入: [100, 4, 200, 1, 3, 2]
* 输出: 4
* 解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
* @Date 2019-08-30
* @Version 1.0
*/
public class LeetCode99 {
public static void main(String[] args) {
int[] array = {1,6,9};
// int[] array = {1,3,5,7,6};
Arrays.sort(array);
System.out.println(maxSequence(array));
}
private static int maxSequence(int[] array) {
int length = array.length;
int max = 1;
int x = array[0];
int index = 1;
for (int i = 1; i < length; i++) {
if (array[i] == x + 1) {
index++;
} else {
index = 1;
}
x = array[i];
max = Math.max(max, index);
}
return max;
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode191.java
package com.learning.Number200;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Program Name: leetcodes
* <p>
* Description: 给定一个机票的字符串二维数组 [from, to] ,子数组中的两个成员分别表示飞机出发和降落的机场地点,对该行程进行重新规划排序。所有这些机票都属于一个从JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 出发。
* <p>
* 说明:
* <p>
* 如果存在多种有效的行程,你可以按字符自然排序返回最小的行程组合。例如,行程 ["JFK", "LGA"] 与 ["JFK", "LGB"] 相比就更小,排序更靠前
* 所有的机场都用三个大写字母表示(机场代码)。
* 假定所有机票至少存在一种合理的行程。
* 示例 1:
* <p>
* 输入:
* 示例 2:
* <p>
* 输入:
* <p>
* Created by xuetao on 2019/12/20
*
* @author xuetao
* @version 1.0
*/
public class LeetCode191 {
public static void main(String[] args) {
String[][] array = {{"JFK", "SFO"}, {"JFK", "ATL"}, {"SFO", "ATL"}, {"ATL", "JFK"}, {"ATL", "SFO"}};
System.out.println(findItinerary(array));
}
public static List<String> findItinerary(String[][] tickets) {
List<List<String>> allPossibilities = new ArrayList<>();
List<String[]> JFKStarts = new ArrayList<>();
for (String[] ticket : tickets) {
if (ticket[0].equals("JFK")) {
JFKStarts.add(ticket);
}
}
for (String[] ticket : JFKStarts) {
List<String> thisPossibility = new ArrayList<>();
thisPossibility.add(ticket[0]);
thisPossibility.add(ticket[1]);
dfs(ticket, thisPossibility, tickets, allPossibilities);
}
//sort lexicographically and return the smallest
Collections.sort(allPossibilities, new ListComparator<>());
return allPossibilities.get(0);
}
private static void dfs(String[] thisTicket, List<String> thisPossibility, String[][] tickets, List<List<String>> allPossibilities) {
if (thisPossibility.size() == tickets.length + 1) {
allPossibilities.add(new ArrayList<>(thisPossibility));
return;
}
for (String[] ticket : tickets) {
if (!ticket.equals(thisTicket) && thisPossibility.get(thisPossibility.size() - 1).equals(ticket[0])) {
thisPossibility.add(ticket[1]);
dfs(ticket, thisPossibility, tickets, allPossibilities);
thisPossibility.remove(thisPossibility.size() - 1);
}
}
}
private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> {
@Override
public int compare(List<T> o1, List<T> o2) {
for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) {
int c = o1.get(i).compareTo(o2.get(i));
if (c != 0) {
return c;
}
}
return Integer.compare(o1.size(), o2.size());
}
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode133.java
package com.learning.Number150;
import java.util.HashSet;
import java.util.Set;
/**
* @Author xuetao
* @Description: 编写一个算法来判断一个数是不是“快乐数”。
* <p>
* 一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
* <p>
* 示例:
* <p>
* 输入: 19
* 输出: true
* 解释: 12 + 92 = 82
* 82 + 22 = 68
* 62 + 82 = 100
* 12 + 02 + 02 = 1
* @Date 2019-10-07
* @Version 1.0
*/
public class LeetCode133 {
public static void main(String[] args) {
int num = 19;
System.out.println(isHappy(num));
}
public static boolean isHappy(int n) {
if (n == 1) {
return true;
}
Set<Integer> set = new HashSet();
while (n != 1) {
String str = String.valueOf(n);
n = 0;
for (int i = 0; i < str.length(); i++) {
int temp = Character.getNumericValue(str.charAt(i));
n += temp * temp;
}
if (n == 1) {
return true;
}
if (!set.add(n)) {
return false;
}
}
return false;
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode144.java
package com.learning.Number150;
import java.util.HashMap;
import java.util.Map;
/**
* @Author xuetao
* @Description: 给定一个整数数组,判断是否存在重复元素。
* <p>
* 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
* <p>
* 示例 1:
* <p>
* 输入: [1,2,3,1]
* 输出: true
* <p>
* 示例 2:
* <p>
* 输入: [1,2,3,4]
* 输出: false
* <p>
* 示例 3:
* <p>
* 输入: [1,1,1,3,3,4,3,2,4,2]
* 输出: true
* @Date 2019-10-22
* @Version 1.0
*/
public class LeetCode144 {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4};
System.out.println(isRepeat(array));
}
/**
* 判断数组是否重复
*
* @param array
* @return
*/
private static boolean isRepeat(int[] array) {
if (array == null || array.length == 0) {
return false;
}
int len = array.length;
Map<Integer, Integer> map = new HashMap();
for (int i = 0; i < len; i++) {
if (map.containsKey(array[i])) {
return true;
}
map.put(array[i], array[i]);
}
return false;
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode199.java
package com.learning.Number200;
import java.util.HashSet;
import java.util.Set;
/**
* Program Name: leetcodes
* <p>
* Description:编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
* <p>
* 示例 1:
* 给定 s = "hello", 返回 "holle".
* <p>
* 示例 2:
* 给定 s = "leetcode", 返回 "leotcede".
* <p>
* 注意:
* 元音字母不包括 "y".
* <p>
* Created by xuetao on 2019/12/29
*
* @author xuetao
* @version 1.0
*/
public class LeetCode199 {
public static void main(String[] args) {
String s = "hello";
System.out.println(reverseVowels(s));
}
public static String reverseVowels(String s) {
StringBuilder sb = new StringBuilder(s);
Set<Character> vowels = new HashSet();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
vowels.add('A');
vowels.add('E');
vowels.add('I');
vowels.add('O');
vowels.add('U');
//use two pointers approach would be the fastest
int i = 0;
int j = s.length() - 1;
while (i < j) {
char left = s.charAt(i);
char right = s.charAt(j);
while (i < j && !vowels.contains(left)) {
i++;
left = s.charAt(i);
}
while (i < j && !vowels.contains(right)) {
j--;
right = s.charAt(j);
}
char temp = left;
sb.setCharAt(i, right);
sb.setCharAt(j, temp);
i++;
j--;
}
return sb.toString();
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode177.java
package com.learning.Number200;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* Program Name: leetcodes
* <p>
* Description: 中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。
* <p>
* 例如,
* <p>
* [2,3,4] 的中位数是 3
* <p>
* [2,3] 的中位数是 (2 + 3) / 2 = 2.5
* <p>
* 设计一个支持以下两种操作的数据结构:
* <p>
* void addNum(int num) - 从数据流中添加一个整数到数据结构中。
* double findMedian() - 返回目前所有元素的中位数。
* 示例:
* <p>
* addNum(1)
* addNum(2)
* findMedian() -> 1.5
* addNum(3)
* findMedian() -> 2
* <p>
* Created by xuetao on 2019/12/3
*
* @author xuetao
* @version 1.0
*/
public class LeetCode177 {
private Queue<Long> large;
private Queue<Long> small;
public static void main(String[] args) {
LeetCode177 leetCode177 = new LeetCode177();
leetCode177.addNum(1);
leetCode177.addNum(2);
leetCode177.addNum(3);
System.out.println(leetCode177.findMedian());
leetCode177.addNum(4);
leetCode177.addNum(5);
System.out.println(leetCode177.findMedian());
}
public LeetCode177() {
large = new PriorityQueue<>();
small = new PriorityQueue<>(Collections.reverseOrder());
}
public void addNum(int num) {
large.offer((long) num);
small.offer(large.poll());
if (large.size() < small.size()) {
large.offer(small.poll());
}
}
public double findMedian() {
if (large.size() > small.size()) {
return large.peek();
}
return (large.peek() + small.peek()) / 2.0;
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode9.java
package com.learning.Number50;
/**
* @Author xuetao
* @Description: 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
* <p>
* 示例 1:
* <p>12121
* 输入: 121
* 输出: true
* <p>
* 示例 2:
* <p>
* 输入: -121
* 输出: false
* 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
* <p>
* 示例 3:
* <p>
* 输入: 10
* 输出: false
* 解释: 从右向左读, 为 01 。因此它不是一个回文数。
* <p>
* 进阶:
* <p>
* 你能不将整数转为字符串来解决这个问题吗?
* @Date 2019-05-01
* @Version 1.0
*/
public class LeetCode9 {
public static void main(String[] args) {
System.out.println(isPalindrome1(12121));
System.out.println(isPalindrome2(12121));
}
/**
* 常规解法
*
* @param x
* @return
*/
public static boolean isPalindrome1(int x) {
if (x == 0) {
return true;
}
if (x < 0) {
return false;
}
int temp = 0;
int m = x;
while (m > 0) {
temp = temp * 10 + m % 10;
m = m / 10;
}
return temp == x;
}
/**
* 快速解法
*
* @param x
* @return
*/
public static boolean isPalindrome2(int x) {
if (x == 0) {
return true;
}
if (x < 0) {
return false;
}
int temp = 0;
int m = x;
while (m > temp) {
temp = temp * 10 + m % 10;
m = m / 10;
}
return temp == m || m == temp / 10;
}
}
<file_sep>/src/main/java/com/learning/Number100/LeetCode63.java
package com.learning.Number100;
/**
* @Author xuetao
* @Description: 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
* <p>
* 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
* <p>
* 现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?
* <p>
* <p>
* <p>
* 网格中的障碍物和空位置分别用 1 和 0 来表示。
* <p>
* 说明: m 和 n 的值均不超过 100。
* <p>
* 示例 1:
* <p>
* 输入: [
* [0,0,0],
* [0,1,0],
* [0,0,0]
* ]
* 输出: 2
* 解释:
* 3x3 网格的正中间有一个障碍物。
* 从左上角到右下角一共有 2 条不同的路径:
* 1. 向右 -> 向右 -> 向下 -> 向下
* 2. 向下 -> 向下 -> 向右 -> 向右
* @Date 2019-07-18
* @Version 1.0
*/
public class LeetCode63 {
public static void main(String[] args) {
int m = 3;
int n = 3;
int[][] array = {{0, 0, 0}, {0, 0, 0}, {0, 0, 1}};
int[][] result = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (array[i][j] == 1) {
result[i][j] = 0;
} else if (i == 0 && j == 0) {
result[i][j] = 1;
} else if (i == 0 && j > 0) {
result[i][j] = result[i][j - 1];
} else if (j == 0 && i > 0) {
result[i][j] = result[i - 1][j];
} else {
result[i][j] = result[i - 1][j] + result[i][j - 1];
}
}
}
System.out.println(result[m - 1][n - 1]);
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode35.java
package com.learning.Number50;
/**
* @Author xuetao
* @Description: 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
* <p>
* 你可以假设数组中无重复元素。
* <p>
* 示例 1:
* <p>
* 输入: [1,3,5,6], 5
* 输出: 2
* <p>
* 示例 2:
* <p>
* 输入: [1,3,5,6], 2
* 输出: 1
* <p>
* 示例 3:
* <p>
* 输入: [1,3,5,6], 7
* 输出: 4
* <p>
* 示例 4:
* <p>
* 输入: [1,3,5,6], 0
* 输出: 0
* @Date 2019-06-10
* @Version 1.0
*/
public class LeetCode35 {
public static void main(String[] args) {
int[] array = {1, 3, 5, 6};
int target = 7;
System.out.println(findIndexOne(array, target));
System.out.println(findIndexTwo(array, target));
}
/**
* 方法一 for循环判断索引位置
*
* @param array
* @param target
* @return
*/
public static int findIndexOne(int[] array, int target) {
if (array == null || array.length < 1) {
return -1;
}
int length = array.length - 1;
int index = 0;
for (int i = 0; i <= length; i++) {
if (array[i] == target) {
index = i;
} else if (array[length] <= target) {
index = length + 1;
} else if (array[i] < target && array[i + 1] >= target) {
index = i + 1;
}
}
return index;
}
/**
* 方法二 使用二分查找判断index 下标
*
* @param array
* @param target
* @return
*/
public static int findIndexTwo(int[] array, int target) {
if (array == null || array.length < 1) {
return -1;
}
int left = 0;
int right = array.length - 1;
int index = binarySearch(array, target, left, right);
return index;
}
public static int binarySearch(int[] array, int target, int left, int right) {
if (left > right) {
return left;
}
int mid = (left + right) / 2;
if (array[mid] == target) {
return mid;
} else if (array[mid] > target) {
return binarySearch(array, target, left, mid - 1);
} else {
return binarySearch(array, target, mid + 1, right);
}
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode125.java
package com.learning.Number150;
/**
* @Author xuetao
* @Description: 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
* <p>
* 设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。
* <p>
* 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
* <p>
* 示例 1:
* <p>
* 输入: [2,4,1], k = 2
* 输出: 2
* 解释: 在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。
* <p>
* 示例 2:
* <p>
* 输入: [3,2,6,5,0,3], k = 2
* 输出: 7
* 解释: 在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。
* 随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。
* @Date 2019-09-27
* @Version 1.0
*/
public class LeetCode125 {
public static void main(String[] args) {
int[] array = {3, 2, 7, 5, 9, 0, 3};
int k = 2;
System.out.println(maxStocks(array, k));
}
/**
* k 为 循环的次数, 利用二维数组去累加操作,获取最大值
*
* @param array
* @param k
* @return
*/
private static int maxStocks(int[] array, int k) {
if (array == null || array.length < 2) {
return 0;
}
int length = array.length;
if (k >= length / 2) {
int price = 0;
for (int i = 1; i < length; i++) {
if (array[i] > array[i - 1]) {
price += array[i] - array[i - 1];
}
}
return price;
}
int[][] buy = new int[k + 1][length];
for (int j = 1; j <= k; j++) {
int temp = -array[0];
for (int m = 1; m < length; m++) {
buy[j][m] = Math.max(buy[j][m - 1], array[m] + temp);
System.out.println("j=" + j + ",m=" + m + ",buy=" + buy[j][m]);
temp = Math.max(temp, buy[j - 1][m - 1] - array[m]);
System.out.println("temp=" + temp);
}
}
return buy[k][length - 1];
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode137.java
package com.learning.Number150;
import com.learning.entity.Node;
import java.util.ArrayList;
import java.util.List;
/**
* @Author xuetao
* @Description: 反转一个单链表。
* <p>
* 示例:
* <p>
* 输入: 1->2->3->4->5->NULL
* 输出: 5->4->3->2->1->NULL
* <p>
* 进阶:
* 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
* @Date 2019-10-12
* @Version 1.0
*/
public class LeetCode137 {
public static void main(String[] args) {
Node node = new Node(1, 1, 1, null);
node.next = new Node(2, 2, 2, null);
node.next.next = new Node(3, 3, 3, null);
node.next.next.next = new Node(4, 4, 4, null);
node.next.next.next.next = new Node(5, 5, 5, null);
Node result = reverseLinked(node);
while (result != null) {
System.out.println(result.value);
result = result.next;
}
}
/**
* 反转链表 每次遍历交换当前两个数据位置
*
* @param node
* @return
*/
private static Node reverseLinked(Node node) {
Node result = null;
while (node != null) {
Node next = node.next;
node.next = result;
result = node;
node = next;
}
return result;
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode190.java
package com.learning.Number200;
import com.learning.entity.Node;
/**
* Program Name: leetcodes
* <p>
* Description: 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。
* <p>
* 请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。
* <p>
* 示例 1:
* <p>
* 输入: 1->2->3->4->5->NULL
* 输出: 1->3->5->2->4->NULL
* <p>
* 示例 2:
* <p>
* 输入: 2->1->3->5->6->4->7->NULL
* 输出: 2->3->6->7->1->5->4->NULL
* <p>
* 说明:
* <p>
* 应当保持奇数节点和偶数节点的相对顺序。
* 链表的第一个节点视为奇数节点,第二个节点视为偶数节点,以此类推。
* <p>
* Created by xuetao on 2019/12/18
*
* @author xuetao
* @version 1.0
*/
public class LeetCode190 {
public static void main(String[] args) {
Node node = new Node(1, 1, 1, null);
node.next = new Node(2, 2, 2, null);
node.next.next = new Node(3, 3, 3, null);
node.next.next.next = new Node(4, 4, 4, null);
node.next.next.next.next = new Node(5, 5, 5, null);
node.next.next.next.next.next = new Node(6, 6, 6, null);
node.next.next.next.next.next.next = new Node(7, 7, 7, null);
Node result = sortNode(node);
while (result != null) {
System.out.println(result.value);
result = result.next;
}
}
private static Node sortNode(Node node) {
Node temp = node;
Node first = new Node(0, 0, 0, null);
Node firstTemp = first;
Node second = new Node(0, 0, 0, null);
Node secondTemp = second;
boolean state = true;
while (temp != null) {
if (state) {
firstTemp.next = temp;
firstTemp = firstTemp.next;
state = false;
} else {
secondTemp.next = temp;
secondTemp = secondTemp.next;
state = true;
}
temp = temp.next;
}
if (!state) {
secondTemp.next = null;
}
firstTemp.next = second.next;
return first.next;
}
}
<file_sep>/src/main/java/com/learning/Number250/LeetCode266.java
package com.learning.Number250;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Program Name: leetcodes
* <p>
* Description: 设计一个支持在 平均 时间复杂度 O(1) 下,执行以下操作的数据结构。
* <p>
* insert(val) :当元素 val 不存在时,向集合中插入该项。
* remove(val) :元素 val 存在时,从集合中移除该项。
* getRandom :随机返回现有集合中的一项。每个元素应该有 相同的概率 被返回。
* 示例 :
* <p>
* // 初始化一个空的集合。
* RandomizedSet randomSet = new RandomizedSet();
* <p>
* // 向集合中插入 1 。返回 true 表示 1 被成功地插入。
* randomSet.insert(1);
* <p>
* // 返回 false ,表示集合中不存在 2 。
* randomSet.remove(2);
* <p>
* // 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
* randomSet.insert(2);
* <p>
* // getRandom 应随机返回 1 或 2 。
* randomSet.getRandom();
* <p>
* // 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
* randomSet.remove(1);
* <p>
* // 2 已在集合中,所以返回 false 。
* randomSet.insert(2);
* <p>
* // 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
* randomSet.getRandom();
* <p>
* Created by xuetao on 2020/1/18
*
* @author xuetao
* @version 1.0
*/
public class LeetCode266 {
public static void main(String[] args) {
RandomizedSetII randomSet = new RandomizedSetII();
System.out.println(randomSet.insert(1));
System.out.println(randomSet.insert(1));
System.out.println(randomSet.insert(2));
System.out.println(randomSet.getList());
System.out.println(randomSet.getRandom());
System.out.println(randomSet.remove(1));
System.out.println(randomSet.getRandom());
System.out.println(randomSet.getList());
}
}
class RandomizedSetII {
private List<Integer> list = new ArrayList<>();
private static Random random = new Random();
public boolean insert(int val) {
if (list.contains(val)) {
list.add(val);
return false;
} else {
list.add(val);
return true;
}
}
public boolean remove(Integer val) {
return list.remove(val);
}
public int getRandom() {
return list.get(random.nextInt(list.size()));
}
public List getList() {
return list;
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode10.java
package com.learning.Number50;
/**
* @Author xuetao
* @Description: 给定一个字符串 ( s ) 和一个字符模式 ( p )。实现支持 '.' 和 '*' 的正则表达式匹配。
* <p>
* '.' 匹配任意单个字符。
* '*' 匹配零个或多个前面的元素。
* <p>
* 匹配应该覆盖 整个 字符串 ( s ) ,而不是部分字符串。
* <p>
* 说明:
* <p>
* s 可能为空,且只包含从 a-z 的小写字母。
* p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 * 。
* 示例 1:
* <p>
* 输入:
* s = "aa"
* p = "a"
* 输出: false
* 解释: "a" 无法匹配 "aa" 整个字符串。
* <p>
* 示例 2:
* <p>
* 输入:
* s = "aa"
* p = "a*"
* 输出: true
* 解释: '*' 代表可匹配零个或多个前面的元素, 即可以匹配 'a' 。因此, 重复 'a' 一次, 字符串可变为 "aa"。
* <p>
* 示例 3:
* <p>
* 输入:
* s = "ab"
* p = "."
* 输出: true
* 解释: "." 表示可匹配零个或多个('*')任意字符('.')。
* <p>
* 示例 4:
* <p>
* 输入:
* s = "aab"
* p = "c*a*b"
* 输出: true
* 解释: 'c' 可以不被重复, 'a' 可以被重复一次。因此可以匹配字符串 "aab"。
* <p>
* 示例 5:
* <p>
* 输入:
* s = "mississippi"
* p = "mis*is*p*."
* 输出: false
* @Date 2019-05-05
* @Version 1.0
*/
public class LeetCode10 {
public static boolean isMatch(String text, String pattern) {
//如果都为空则匹配成功
if (pattern.isEmpty()) {
return text.isEmpty();
}
//第一个是否匹配上
boolean first_match = (!text.isEmpty() && (pattern.charAt(0) == text.charAt(0) || pattern.charAt(0) == '.'));
// pattern 包含 * 的情况
if (pattern.length() >= 2 && pattern.charAt(1) == '*') {
return (isMatch(text, pattern.substring(2)) ||
(first_match && isMatch(text.substring(1), pattern)));
} else {
// pattern 不包含 * 的情况,如果第一个字符相等, s和p同时向右移动一位看是否仍然能匹配成功
return first_match && isMatch(text.substring(1), pattern.substring(1));
}
}
public static void main(String[] args) {
System.out.println(isMatch("aab", "..a*b"));
System.out.println(isMatch("mississippi", "mis*is*p*."));
}
}
<file_sep>/src/main/java/com/learning/Number100/LeetCode94.java
package com.learning.Number100;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @Author xuetao
* @Description: 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
* <p>
* 例如,给定三角形:
* <p>
* [
* [2],
* [3,4],
* [6,5,7],
* [4,1,8,3]
* ]
* <p>
* 自顶向下的最小路径和为 11 (即, 2 + 3 + 5 + 1 = 11)。
* <p>
* 说明:
* <p>
* 如果你可以只使用 O ( n ) 的额外空间( n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。
* @Date 2019-08-25
* @Version 1.0
*/
public class LeetCode94 {
public static void main(String[] args) {
List<List<Integer>> list = new ArrayList();
List<Integer> list1 = Arrays.asList(2);
List<Integer> list2 = Arrays.asList(3, 4);
List<Integer> list3 = Arrays.asList(6, 5, 7);
List<Integer> list4 = Arrays.asList(4, 1, 8, 3);
list.add(list1);
list.add(list2);
list.add(list3);
list.add(list4);
System.out.println( minimumTotal(list));
}
private static int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.size();
List<Integer> cache = triangle.get(n - 1);
for (int layer = n - 2; layer >= 0; layer--) {
for (int i = 0; i <= layer; i++) {
int value = Math.min(cache.get(i), cache.get(i + 1)) + triangle.get(layer).get(i);
cache.set(i, value);
}
}
System.out.println(cache);
return cache.get(0);
}
}
<file_sep>/src/main/java/com/learning/Number250/LeetCode251.java
package com.learning.Number250;
import java.util.*;
/**
* Program Name: leetcodes
* <p>
* Description: 给定两个数组,写一个函数来计算它们的交集。
* <p>
* 例子:
* <p>
* 给定 num1 = [1, 2, 2, 1] , nums2 = [2, 2] , 返回 [2] .
* <p>
* 提示:
* <p>
* 每个在结果中的元素必定是唯一的。
* 我们可以不考虑输出结果的顺序。
* <p>
* Created by xuetao on 2020/1/1
*
* @author xuetao
* @version 1.0
*/
public class LeetCode251 {
public static void main(String[] args) {
int[] num1 = {1, 2, 2, 1};
int[] num2 = {1, 2};
System.out.println(intersectionArray(num1, num2));
}
private static List<Integer> intersectionArray(int[] num1, int[] num2) {
Set<Integer> set = new HashSet<>();
if (num1 == null || num1.length == 0) {
return new ArrayList<>();
}
if (num2 == null || num2.length == 0) {
return new ArrayList<>();
}
int len1 = num1.length;
int len2 = num2.length;
for (int i = 0; i < len1; i++) {
if (!set.contains(num1[i])) {
set.add(num1[i]);
}
}
List<Integer> list = new ArrayList<>();
for (int j = 0; j < len2; j++) {
if (set.contains(num2[j])) {
list.add(num2[j]);
}
}
return list;
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode28.java
package com.learning.Number50;
/**
* @Author xuetao
* @Description: 实现 strStr() 函数。
* <p>
* 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1 。
* <p>
* 示例 1:
* <p>
* 输入: haystack = "hello", needle = "ll"
* 输出: 2
* <p>
* 示例 2:
* <p>
* 输入: haystack = "aaaaa", needle = "bba"
* 输出: -1
* <p>
* 说明:
* <p>
* 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
* <p>
* 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
* @Date 2019-05-31
* @Version 1.0
*/
public class LeetCode28 {
public static void main(String[] args) {
System.out.println(findStr("hello", "ll"));
}
/**
* 利用string contains 判断是否包含
* 再去截取字符串比较
*
* @param hasystack
* @param needle
* @return
*/
public static int findStr(String hasystack, String needle) {
if (hasystack == null || hasystack == "") {
return -1;
}
if (needle == null || needle == "") {
return 0;
}
if (!hasystack.contains(needle)) {
return -1;
}
for (int i = 0; i <= hasystack.length() - needle.length(); i++) {
if (hasystack.substring(i, i + needle.length()).equals(needle)) {
return i;
}
}
return -1;
}
}
<file_sep>/src/main/java/com/learning/Number100/LeetCode58.java
package com.learning.Number100;
/**
* @Author xuetao
* @Description: 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
* <p>
* 如果不存在最后一个单词,请返回 0 。
* <p>
* 说明: 一个单词是指由字母组成,但不包含任何空格的字符串。
* <p>
* 示例:
* <p>
* 输入: "Hello World"
* 输出: 5
* @Date 2019-07-13
* @Version 1.0
*/
public class LeetCode58 {
public static void main(String[] args) {
String s = "H elloWorld ";
System.out.println(findLastStringOne(s));
System.out.println(findLastStringTwo(s));
}
/**
* 方法一: split获取字符串数组
*
* @param s
* @return
*/
public static int findLastStringOne(String s) {
if (s == "" || s == null) {
return 0;
}
s = s.trim();
String[] array = s.split(" ");
String lastStr = array.length > 1 ? array[array.length - 1] : "";
System.out.println(lastStr);
return lastStr.length();
}
/**
* 方法二: for循环获取
*
* @param s
* @return
*/
public static int findLastStringTwo(String s) {
if (s == "" || s == null) {
return 0;
}
s = s.trim();
int n = 0;
int length = s.length();
for (int i = length - 1; i >= 0; i--) {
if (s.charAt(i) != ' ') {
n++;
} else {
break;
}
}
return n == length ? 0 : n;
}
}
<file_sep>/src/main/java/com/learning/Number100/LeetCode70.java
package com.learning.Number100;
import java.util.Stack;
/**
* @Author xuetao
* @Description: 给定一个文档 (Unix-style) 的完全路径,请进行路径简化。
* <p>
* 例如,
* path = "/home/" , => "/home"
* path = "/a/./b/../../c/" , => "/c"
* <p>
* 边界情况:
* <p>
* 你是否考虑了 路径 = "/../" 的情况?
* 在这种情况下,你需返回 "/" 。
* 此外,路径中也可能包含多个斜杠 '/' ,如 "/home//foo/" 。
* 在这种情况下,你可忽略多余的斜杠,返回 "/home/foo" 。
* @Date 2019-07-25
* @Version 1.0
*/
public class LeetCode70 {
/**
* 思路: 去掉 .., ., // 中的 /
* 字符串分隔
*
* @param args
*/
public static void main(String[] args) {
String path = "/a/./b/../1/c/";
System.out.println(simplifyPath(path));
}
private static String simplifyPath(String path) {
String[] array = path.split("/");
int length = array.length;
Stack s = new Stack();
StringBuffer res = new StringBuffer();
for (int i = 0; i < length; i++) {
if (array[i].equals("") || array[i].equals(".") || (array[i].equals("..") && s.isEmpty())) {
continue;
} else if (array[i].equals("..") && !s.isEmpty()) {
s.pop();
} else {
s.push(array[i]);
}
}
if (s.isEmpty()) {
return "/";
} else {
Object[] a = s.toArray();
for (int i = 0; i < a.length; i++) {
res.append("/" + a[i].toString());
}
return res.toString();
}
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode153.java
package com.learning.Number200;
import java.util.ArrayList;
import java.util.List;
/**
* @Author xuetao
* @Description: 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
* <p>
* 说明:
* 你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
* <p>
* 示例 1:
* <p>
* 输入: root = [3,1,4,null,2], k = 1
* 输出: 1
* <p>
* 示例 2:
* <p>
* 输入: root = [5,3,6,2,4,null,null,1], k = 3
* 输出: 3
* <p>
* 进阶:
* 如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数?
* @Date 2019-11-03
* @Version 1.0
*/
public class LeetCode153 {
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
root.left = new TreeNode(1);
root.left.right = new TreeNode(2);
root.right = new TreeNode(4);
int k = 1;
List<Integer> list = new ArrayList();
findSmallestK(root, list);
System.out.println(list.get(k - 1));
}
private static void findSmallestK(TreeNode treeNode, List<Integer> list) {
if (treeNode == null) {
return;
}
if (treeNode.left != null) {
findSmallestK(treeNode.left, list);
}
list.add(treeNode.val);
if (treeNode.right != null) {
findSmallestK(treeNode.right, list);
}
}
}
class TreeNode {
TreeNode left;
TreeNode right;
Integer val;
public TreeNode(int val) {
this.val = val;
}
}
<file_sep>/src/main/java/com/learning/Number100/LeetCode61.java
package com.learning.Number100;
import com.learning.entity.Node;
import java.util.Objects;
/**
* @Author xuetao
* @Description: 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
* <p>
* 示例 1:
* <p>
* 输入: 1->2->3->4->5->NULL, k = 2
* 输出: 4->5->1->2->3->NULL
* 解释:
* 向右旋转 1 步: 5->1->2->3->4->NULL
* 向右旋转 2 步: 4->5->1->2->3->NULL
* <p>
* 示例 2:
* <p>
* 输入: 0->1->2->NULL, k = 4
* 输出: 2->0->1->NULL
* 解释:
* 向右旋转 1 步: 2->0->1->NULL
* 向右旋转 2 步: 1->2->0->NULL
* 向右旋转 3 步: 0->1->2->NULL
* 向右旋转 4 步: 2->0->1->NULL
* @Date 2019-07-15
* @Version 1.0
*/
public class LeetCode61 {
public static void main(String[] args) {
Node node = new Node(Objects.hashCode(1), 1, 1, null);
node.next = new Node(Objects.hashCode(2), 2, 2, null);
node.next.next = new Node(Objects.hashCode(3), 3, 3, null);
node.next.next.next = new Node(Objects.hashCode(4), 4, 4, null);
node.next.next.next.next = new Node(Objects.hashCode(5), 5, 5, null);
Node temp = node;
int length = 1;
while (temp.next != null) {
temp = temp.next;
length++;
}
int k = 6;
System.out.println("链表长度" + length);
rotateLink(node, temp, length, k);
}
/**
* 方法一 先形成闭环然后再隔断
*
* @param node
* @param length
*/
private static void rotateLink(Node node, Node temp, int length, int k) {
if (node == null) {
return;
}
Node first = node;
temp.next = node; //形成闭环
// for (int i = length - k % length; i > 1; i--) {
for (int i = 1; i < length - k % length; i++) {
first = first.next;
}
temp = first.next;
first.next = null;
while (temp != null) {
System.out.println("rotateLink " + temp.value);
temp = temp.next;
}
}
}<file_sep>/src/main/java/com/learning/Number250/LeetCode280.java
package com.learning.Number250;
import com.learning.entity.Node;
import com.learning.entity.TreeNode;
/**
* Program Name: leetcodes
* <p>
* Description: 计算给定二叉树的所有左叶子之和。
* <p>
* 示例:
* <p>
* 3
* /
* 9 20
* /
* 15 7
* <p>
* 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
* <p>
* Created by xuetao on 2020/2/10
*
* @author xuetao
* @version 1.0
*/
public class LeetCode280 {
public static void main(String[] args) {
TreeNode treeNode = new TreeNode(1);
treeNode.left = new TreeNode(3);
treeNode.left.left = new TreeNode(4);
treeNode.left.right = new TreeNode(5);
treeNode.right = new TreeNode(6);
treeNode.right.left = new TreeNode(7);
treeNode.right.right = new TreeNode(8);
System.out.println(sumOfLeftLeaves(treeNode));
}
public static int sumOfLeftLeaves(TreeNode root) {
int result = 0;
if (root == null) {
return result;
}
return dfs(root, result, false);
}
private static int dfs(TreeNode root, int result, boolean left) {
if (root.left == null && root.right == null && left) {
result += root.val;
return result;
}
int leftResult = 0;
if (root.left != null) {
left = true;
leftResult = dfs(root.left, result, left);
}
int rightResult = 0;
if (root.right != null) {
left = false;
rightResult = dfs(root.right, result, left);
}
return leftResult + rightResult;
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode146.java
package com.learning.Number150;
/**
* @Author xuetao
* @Description: 给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j ,使得 nums [i] 和 nums [j] 的差的绝对值最大为 t ,并且 i 和 j 之间的差的绝对值最大为 ķ 。
* <p>
* 示例 1:
* <p>
* 输入: nums = [1,2,3,1], k = 3, t = 0
* 输出: true
* <p>
* 示例 2:
* <p>
* 输入: nums = [1,0,1,1], k = 1, t = 2
* 输出: true
* <p>
* 示例 3:
* <p>
* 输入: nums = [1,5,9,1,5,9], k = 2, t = 3
* 输出: false
* @Date 2019-10-24
* @Version 1.0
*/
public class LeetCode146 {
public static void main(String[] args) {
int[] array = {1, 5, 9, 1, 5, 9};
int k = 2;
int t = 3;
System.out.println(containsNearBy(array, k, t));
}
private static boolean containsNearBy(int[] array, int k, int t) {
if (array == null || array.length == 0) {
return false;
}
int len = array.length;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (Math.abs(array[i] - array[j]) <= t && j - i <= k) {
return true;
}
}
}
return false;
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode5.java
package com.learning.Number50;
/**
* @Author xuetao
* @Description: 给定一个字符串s, 找到 s 中最长的回文子串
* 输入:'babad' 输出 'bab' 或者 'aba'
* 输入:'cbbd' 输出 'bb'
* @Date 2019-04-25
* @Version 1.0
*/
public class LeetCode5 {
private int lo, maxLen;
public static void main(String[] args) {
String str = "caba";
LeetCode5 leetCode5 = new LeetCode5();
System.out.println(leetCode5.longgestStr(str));
}
public String longgestStr(String s) {
if (s == null || s.length() < 1) {
return "";
}
int len = s.length();
for (int i = 0; i < len - 1; i++) {
// 判断奇数的情况
extendPalindrome(s, i, i);
// 判断偶数的情况
extendPalindrome(s, i, i + 1);
}
return s.substring(lo, lo + maxLen);
}
private void extendPalindrome(String s, int j, int k) {
while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {
j--;
k++;
}
if (maxLen < k - j - 1) {
lo = j + 1;
maxLen = k - j - 1;
}
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode7.java
package com.learning.Number50;
/**
* @Author xuetao
* @Description: 给定一个 32 位有符号整数,将整数中的数字进行反转。
* 示例 1:
* 输入: 123
* 输出: 321
* 示例 2:
* 输入: -123
* 输出: -321
* 示例 3:
* 输入: 120
* 输出: 21
* 注意:
* 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2^31 , 2^31 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。
* @Date 2019-04-28
* @Version 1.0
*/
public class LeetCode7 {
public static void main(String[] args) {
System.out.println( reverse(-123123131));
}
public static int reverse(int x) {
long s = 0;
while (x != 0) {
s = x % 10 + s * 10;
x = x / 10;
if (s > Integer.MAX_VALUE || s < Integer.MIN_VALUE) {
return 0;
}
}
return (int)s;
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode116.java
package com.learning.Number150;
/**
* @Author xuetao
* @Description: 比较两个版本号 version1 和 version2 。
* 如果 _version1_ > _version2_ 返回 1 ,如果 _version1_ < _version2_ 返回 -1 , 除此之外返回 0 。
* <p>
* 你可以假设版本字符串非空,并且只包含数字和 . 字符。
* <p>
* . 字符不代表小数点,而是用于分隔数字序列。
* <p>
* 例如, 2.5 不是“两个半”,也不是“差一半到三”,而是第二版中的第五个小版本。
* <p>
* 示例 1:
* <p>
* 输入: _version1_ = "0.1", _version2_ = "1.1"
* 输出: -1
* <p>
* 示例 2:
* <p>
* 输入: _version1_ = "1.0.1", _version2_ = "1"
* 输出: 1
* <p>
* 示例 3:
* <p>
* 输入: _version1_ = "7.5.2.4", _version2_ = "7.5.3"
* 输出: -1
* @Date 2019-09-17
* @Version 1.0
*/
public class LeetCode116 {
public static void main(String[] args) {
String target = "7.5.2";
String source = "7.5.2.4.6";
System.out.println(compareVersion(target, source));
}
private static int compareVersion(String target, String source) {
String[] targetArray = target.split("\\.");
String[] sourceArray = source.split("\\.");
int targetLen = targetArray.length;
int sourceLen = sourceArray.length;
int min = Math.min(targetLen, sourceLen);
for (int i = 0; i < min; i++) {
if (Integer.valueOf(targetArray[i]) < Integer.valueOf(sourceArray[i])) {
return -1;
}
if (Integer.valueOf(targetArray[i]) > Integer.valueOf(sourceArray[i])) {
return 1;
}
}
if (targetLen == sourceLen) {
return 0;
}
return targetLen > sourceLen ? 1 : -1;
}
}
<file_sep>/src/main/java/com/learning/Number100/LeetCode56.java
package com.learning.Number100;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* @Author xuetao
* @Description: 给出一个区间的集合,请合并所有重叠的区间。
* <p>
* 示例 1:
* <p>
* 输入: [[1,3],[2,6],[8,10],[15,18]]
* 输出: [[1,6],[8,10],[15,18]]
* 解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
* <p>
* 示例 2:
* <p>
* 输入: [[1,4],[4,5]]
* 输出: [[1,5]]
* 解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
* @Date 2019-07-10
* @Version 1.0
*/
public class LeetCode56 {
public static void main(String[] args) {
List<List<Integer>> list = new ArrayList();
list.add(Arrays.asList(2, 6));
list.add(Arrays.asList(1, 3));
list.add(Arrays.asList(4, 10));
list.add(Arrays.asList(15, 18));
Collections.sort(list, (o1, o2) -> o1.get(0) - o2.get(0));
list.forEach(i -> {
i.forEach(o -> System.out.println(o));
});
List<List<Integer>> mergeList = merge(list);
mergeList.forEach(i -> {
i.forEach(o -> System.out.println(o));
});
}
public static List<List<Integer>> merge(List<List<Integer>> list) {
List<List<Integer>> result = new ArrayList<>();
if (list.size() <= 1) {
return list;
}
int length = list.size();
for (int i = 0; i < length; i++) {
List<Integer> integerList = list.get(i);
int start = integerList.get(0);
int end = integerList.get(1);
while (i < length && list.get(i).get(0) <= end) {
end = Math.max(list.get(i).get(0), end);
i++;
}
result.add(Arrays.asList(start, end));
i--;
}
return result;
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode161.java
package com.learning.Number200;
import com.learning.entity.Node;
import java.util.ArrayList;
import java.util.List;
/**
* @Author xuetao
* @Description: 给定一个二叉树,返回所有从根节点到叶子节点的路径。
* <p>
* 说明: 叶子节点是指没有子节点的节点。
* <p>
* 示例:
* <p>
* 输入:
* <p>
* 1
* /
* 2 3
* <p>
* 5
* <p>
* 输出: ["1->2->5", "1->3"]
* <p>
* 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
* @Date 2019-11-12
* @Version 1.0
*/
public class LeetCode161 {
public static void main(String[] args) {
TreeNode treeNode = new TreeNode(1);
treeNode.left = new TreeNode(2);
treeNode.left.right = new TreeNode(5);
treeNode.right = new TreeNode(3);
List<String> list = new ArrayList<>();
dfs(list, treeNode, "");
list.forEach(i -> System.out.println(i));
}
/**
* 递归遍历
*
* @param strings
* @param treeNode
*/
public static void dfs(List<String> strings, TreeNode treeNode, String data) {
if (treeNode.left == null && treeNode.right == null) {
strings.add(data + treeNode.val + "");
}
if (treeNode.left != null) {
dfs(strings, treeNode.left, data + treeNode.val + "->");
}
if (treeNode.right != null) {
dfs(strings, treeNode.right, data + treeNode.val + "->");
}
}
}
<file_sep>/src/main/java/com/learning/Number250/LeetCode268.java
package com.learning.Number250;
/**
* Program Name: leetcodes
* <p>
* Description: 给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。
* <p>
* (题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。)
* <p>
* 注意:
* <p>
* 你可以假设两个字符串均只含有小写字母。
* <p>
* canConstruct("a", "b") -> false
* canConstruct("aa", "ab") -> false
* canConstruct("aa", "aab") -> true
* <p>
* Created by xuetao on 2020/1/21
*
* @author xuetao
* @version 1.0
*/
public class LeetCode268 {
public static void main(String[] args) {
String a = "aa";
String b = "aab";
System.out.println(canConstruct(a, b));
}
private static boolean canConstruct(String a, String b) {
char[] magazine = b.toCharArray();
int[] mag = new int[256];
for (int i = 0; i < magazine.length; i++) {
mag[magazine[i] - 'a']++;
}
char[] ransom = a.toCharArray();
for (int j = 0; j < ransom.length; j++) {
if (mag[ransom[j] - 'a'] <= 0) {
return false;
}
mag[ransom[j] - 'a']--;
}
return true;
}
}
<file_sep>/src/main/java/com/learning/Number100/LeetCode93.java
package com.learning.Number100;
import java.util.ArrayList;
import java.util.List;
/**
* @Author xuetao
* @Description: 杨辉三角 二 ,返回第 n 列
* @Date 2019-08-24
* @Version 1.0
*/
public class LeetCode93 {
public static void main(String[] args) {
List<Integer> lists = findList(20);
lists.forEach(i -> System.out.println(i));
}
private static List<Integer> findList(int num) {
List<List<Integer>> lists = new ArrayList<>(num);
List list = null;
if (num >= 1) {
list = new ArrayList();
list.add(1);
lists.add(list);
}
int m = 0;
for (int i = 2; i <= num; i++) {
list = new ArrayList(i);
list.add(1);
for (int j = 1; j <= m; j++) {
list.add(lists.get(m).get(j - 1) + lists.get(m).get(j));
}
list.add(1);
lists.add(list);
m++;
}
return lists.get(m);
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode194.java
package com.learning.Number200;
/**
* Program Name: leetcodes
* <p>
* Description: 给定一个非负整数 num 。 对于范围 0 ≤ i ≤ num 中的每个数字 i ,计算其二进制数中的1的数目并将它们作为数组返回。
* <p>
* 示例:
* 比如给定 num = 5 ,应该返回 [0,1,1,2,1,2] .
* <p>
* 进阶:
* <p>
* 给出时间复杂度为 O(n * sizeof(integer)) 的解答非常容易。 但是你可以在线性时间 O(n) 内用一次遍历做到吗?
* 要求算法的空间复杂度为 O(n) 。
* 你能进一步完善解法吗? 在c ++或任何其他语言中不使用任何内置函数(如c++里的 __builtin_popcount )来执行此操作。
* 致谢:
* 特别感谢 @syedee 添加此问题及所有测试用例。
* <p>
* Created by xuetao on 2019/12/23
*
* @author xuetao
* @version 1.0
*/
public class LeetCode194 {
public static void main(String[] args) {
int[] array = countBits(5);
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
private static int[] countBits(int num) {
int[] array = new int[num + 1];
for (int i = 0; i < array.length; i++) {
array[i] = count(i);
}
return array;
}
private static int count(int num) {
int count = 0;
while (num != 0) {
count++;
num &= num - 1;
}
return count;
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode184.java
package com.learning.Number200;
/**
* Program Name: leetcodes
* <p>
* Description: 编写一段程序来查找第 _n_ 个超级丑数。
* <p>
* 超级丑数是指其所有质因数都在长度为 k 的质数列表 primes 中的正整数。
* <p>
* 示例:
* <p>
* 输入: n = 12, primes = [2,7,13,19]
* 输出: 32
* 解释: [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32],是给定长度为 4 的 质数列表 primes = [2,7,13,19]的前 12 个超级丑数。
* <p>
* 说明:
* <p>
* 1 是任何给定 primes 的超级丑数。
* 给定 primes 中的数字以升序排列。
* 0 < k ≤ 100, 0 < n ≤ 10 6 , 0 < primes[i] < 1000 。
* 第 n 个超级丑数确保在 32 位有符整数的范围内。
* <p>
* Created by xuetao on 2019/12/11
*
* @author xuetao
* @version 1.0
*/
public class LeetCode184 {
public static void main(String[] args) {
int[] array = {2, 7, 13, 19};
System.out.println(nthSuperUglyNumber(12, array));
}
public static int nthSuperUglyNumber(int n, int[] primes) {
int[] ret = new int[n];
ret[0] = 1;
int[] indexes = new int[primes.length];
for (int i = 1; i < n; i++) {
ret[i] = Integer.MAX_VALUE;
for (int j = 0; j < primes.length; j++) {
ret[i] = Math.min(ret[i], primes[j] * ret[indexes[j]]);
}
for (int j = 0; j < indexes.length; j++) {
if (ret[i] == primes[j] * ret[indexes[j]]) {
indexes[j]++;
}
}
}
return ret[n - 1];
}
}
<file_sep>/src/main/java/com/learning/Number250/LeetCode279.java
package com.learning.Number250;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Program Name: leetcodes
* <p>
* Description: 一只青蛙想要过河。 假定河流被等分为 x 个单元格,并且在每一个单元格内都有可能放有一石子(也有可能没有)。 青蛙可以跳上石头,但是不可以跳入水中。
* <p>
* 给定石子的位置列表(用单元格序号升序表示), 请判定青蛙能否成功过河 (即能否在最后一步跳至最后一个石子上)。 开始时, 青蛙默认已站在第一个石子上,并可以假定它第一步只能跳跃一个单位(即只能从单元格1跳至单元格2)。
* <p>
* 如果青蛙上一步跳跃了 k 个单位,那么它接下来的跳跃距离只能选择为 k - 1 、 k 或 k + 1 个单位。 另请注意,青蛙只能向前方(终点的方向)跳跃。
* <p>
* 请注意:
* <p>
* 石子的数量 ≥ 2 且 < 1100;
* 每一个石子的位置序号都是一个非负整数,且其 < 2 31 ;
* 第一个石子的位置永远是0。
* 示例 1:
* <p>
* [0,1,3,5,6,8,12,17]
* <p>
* 总共有8个石子。
* 第一个石子处于序号为0的单元格的位置, 第二个石子处于序号为1的单元格的位置,
* 第三个石子在序号为3的单元格的位置, 以此定义整个数组...
* 最后一个石子处于序号为17的单元格的位置。
* <p>
* 返回 true。即青蛙可以成功过河,按照如下方案跳跃:
* 跳1个单位到第2块石子, 然后跳2个单位到第3块石子, 接着
* 跳2个单位到第4块石子, 然后跳3个单位到第6块石子,
* 跳4个单位到第7块石子, 最后,跳5个单位到第8个石子(即最后一块石子)。
* <p>
* 示例 2:
* <p>
* [0,1,2,3,4,8,9,11]
* <p>
* 返回 **false。**青蛙没有办法过河。
* 这是因为第5和第6个石子之间的间距太大,没有可选的方案供青蛙跳跃过去。
* <p>
* Created by xuetao on 2020/2/9
*
* @author xuetao
* @version 1.0
*/
public class LeetCode279 {
public static void main(String[] args) {
int[] stone = {0,1,2,3,4,8,9,11};
System.out.println(canCross(stone));
}
public static boolean canCross(int[] stones) {
if (stones.length == 0) {
return true;
}
Map<Integer, Set<Integer>> map = new HashMap<>(stones.length);
map.put(0, new HashSet<>());
map.get(0).add(1);
for (int i = 1; i < stones.length; i++) {
map.put(stones[i], new HashSet<>());
}
for (int i = 0; i < stones.length; i++) {
int stone = stones[i];
for (int step : map.get(stone)) {
int reach = step + stone;
if (reach == stones[stones.length - 1]) {
return true;
}
Set<Integer> set = map.get(reach);
if (set != null) {
set.add(step);
if (step - 1 > 0) {
set.add(step - 1);
}
set.add(step + 1);
}
}
}
return false;
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode124.java
package com.learning.Number150;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author xuetao
* @Description: 所有 DNA 由一系列缩写为 A,C,G 和 T 的核苷酸组成,例如:“ACGAATTCCG”。在研究 DNA 时,识别 DNA 中的重复序列有时会对研究非常有帮助。
* <p>
* 编写一个函数来查找 DNA 分子中所有出现超多一次的10个字母长的序列(子串)。
* <p>
* 示例:
* <p>
* 输入: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
* <p>
* 输出: ["AAAAACCCCC", "CCCCCAAAAA"]
* @Date 2019-09-26
* @Version 1.0
*/
public class LeetCode124 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
String s = "AAAAACCCCCAABAACCCCCCAAAAAACCCCC";
findSubString(s, map);
List<String> list = new ArrayList<>();
map.forEach((s1, integer) -> {
if (integer > 1) {
list.add(s1);
}
});
System.out.println(list);
}
/**
* 查找字串长度为10并且出现次数大于1次的字串集合
*/
private static void findSubString(String s, Map<String, Integer> map) {
if (s == null) {
return;
}
int length = s.length();
if (length < 11) {
return;
}
for (int i = 0; i < length - 9; i++) {
map.put(s.substring(i, i + 10), map.getOrDefault(s.substring(i, i + 10), 0) + 1);
}
}
}
<file_sep>/src/main/java/com/learning/Number250/LeetCode260.java
package com.learning.Number250;
/**
* Program Name: leetcodes
* <p>
* Description: 我们正在玩一个猜数字游戏。 游戏规则如下:
* 我从 1 到 n 选择一个数字。 你需要猜我选择了哪个数字。
* 每次你猜错了,我会告诉你这个数字是大了还是小了。
* 你调用一个预先定义好的接口 guess(int num) ,它会返回 3 个可能的结果( -1 , 1 或 0 ):
* <p>
* -1 : 我的数字比较小
* 1 : 我的数字比较大
* 0 : 恭喜!你猜对了!
* <p>
* 示例:
* <p>
* n = 10, 我选择 6.
* <p>
* 返回 6.
* <p>
* Created by xuetao on 2020/1/12
*
* @author xuetao
* @version 1.0
*/
public class LeetCode260 {
public static void main(String[] args) {
System.out.println(guessNumber(10));
}
private static int guessNumber(int n) {
int left = 1;
int right = n;
while (left + 1 < right) {
int mid = (left + right) / 2;
int g = guess(mid);
if (g == 0) {
return mid;
} else if (g > 0) {
left = mid;
} else {
right = mid;
}
}
if (guess(left) == 0) {
return left;
}
return right;
}
private static int guess(int num) {
if (num > 6) {
return -1;
} else if (num < 6) {
return 1;
} else {
return 0;
}
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode163.java
package com.learning.Number200;
import java.util.*;
/**
* @Author xuetao
* @Description: 给定一个整数数组 nums ,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。
* <p>
* 示例 :
* <p>
* 输入: [1,2,1,3,2,5]
* 输出: [3,5]
* <p>
* 注意:
* <p>
* 结果输出的顺序并不重要,对于上面的例子, [5, 3] 也是正确答案。
* 你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现?
* @Date 2019-11-15
* @Version 1.0
*/
public class LeetCode163 {
public static void main(String[] args) {
int[] array = {1, 2, 1, 3, 2, 5};
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < array.length; i++) {
map.put(array[i], map.getOrDefault(array[i], 0) + 1);
}
Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, Integer> integerEntry = iterator.next();
if (integerEntry.getValue() <= 1) {
System.out.println(integerEntry.getKey());
}
}
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode166.java
package com.learning.Number200;
import java.util.Arrays;
/**
* @Author xuetao
* @Description: 给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。
* <p>
* 示例 1:
* <p>
* 输入: [3,0,1]
* 输出: 2
* <p>
* 示例 2:
* <p>
* 输入: [9,6,4,2,3,5,7,0,1]
* 输出: 8
* <p>
* 说明:
* 你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?
* @Date 2019-11-18
* @Version 1.0
*/
public class LeetCode166 {
public static void main(String[] args) {
int[] array = {9, 6, 4, 2, 3, 5, 7, 0, 1};
System.out.println(missingNumber(array));
}
private static int missingNumber(int[] array) {
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
if (array[i] != i) {
return i;
}
}
return 0;
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode43.java
package com.learning.Number50;
/**
* @Author xuetao
* @Description: 给定两个以字符串形式表示的非负整数 num1 和 num2 ,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
* <p>
* 示例 1:
* <p>
* 输入: num1 = "2", num2 = "3"
* 输出: "6"
* <p>
* 示例 2:
* <p>
* 输入: num1 = "123", num2 = "456"
* 输出: "56088"
* <p>
* 说明:
* <p>
* num1 和 num2 的长度小于110。
* num1 和 num2 只包含数字 0-9 。
* num1 和 num2 均不以零开头,除非是数字 0 本身。
* 不能使用任何标准库的大数类型(比如 BigInteger) 或 直接将输入转换为整数来处理 。
* @Date 2019-06-20
* @Version 1.0
*/
public class LeetCode43 {
/**
* 解题思路:以第一个数为准,获取每一个字串与后一个串求乘积,然后相加即可得到想要的结果
*
* @param args
*/
public static void main(String[] args) {
String numOne = "41";
String numTwo = "23";
System.out.println(multiplyString(numOne, numTwo));
}
public static String multiplyString(String num1, String num2) {
if (num1.charAt(0) == '0' || num2.charAt(0) == '0') {
return "0";
}
int length1 = num1.length();
int length2 = num2.length();
int[] array = new int[length1];
int m = 0;
for (int j = 0; j < length2; j++) {
m = 10 * m + Integer.valueOf(num2.charAt(j) + "");
}
for (int i = length1 - 1; i >= 0; i--) {
int s = Integer.valueOf(num1.charAt(i) + "");
int k = (int) Math.pow(10, length1 - i - 1);
array[i] = (s * m * k);
}
int result = 0;
for (int q = array.length - 1; q >= 0; q--) {
result += array[q];
}
return String.valueOf(result);
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode183.java
package com.learning.Number200;
/**
* Program Name: leetcodes
* <p>
* Description: 给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。
* <p>
* 设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
* <p>
* 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
* 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
* 示例:
* <p>
* 输入: [1,2,3,0,2]
* 输出: 3
* 解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
* <p>
* Created by xuetao on 2019/12/10
*
* @author xuetao
* @version 1.0
*/
public class LeetCode183 {
public static void main(String[] args) {
int[] array = {1, 2, 3, 0, 2};
System.out.println(maxProfit(array));
}
private static int maxProfit(int[] prices) {
int sell = 0;
int preSell = 0;
int buy = Integer.MIN_VALUE;
int preBuy;
for (int price : prices) {
preBuy = buy;
buy = Math.max(preSell - price, preBuy);
preSell = sell;
sell = Math.max(preBuy + price, preSell);
}
return sell;
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode102.java
package com.learning.Number150;
import java.util.Arrays;
import java.util.List;
/**
* @Author xuetao
* @Description: 给定一个 非空 字符串 s 和一个包含 非空 单词列表的字典 wordDict ,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
* <p>
* 说明:
* <p>
* 拆分时可以重复使用字典中的单词。
* 你可以假设字典中没有重复的单词。
* 示例 1:
* <p>
* 输入: s = "leetcode", wordDict = ["leet", "code"]
* 输出: true
* 解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
* <p>
* 示例 2:
* <p>
* 输入: s = "applepenapple", wordDict = ["apple", "pen"]
* 输出: true
* 解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
* 注意你可以重复使用字典中的单词。
* <p>
* 示例 3:
* <p>
* 输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
* 输出: false
* @Date 2019-09-02
* @Version 1.0
*/
public class LeetCode102 {
public static void main(String[] args) {
String s = "catsandog";
List<String> wordList = Arrays.asList("cats", "dog", "sand", "and", "cat");
System.out.println(splitString(s, wordList));
}
private static boolean splitString(String s, List<String> wordList) {
if (s == null) {
return false;
}
int length = s.length();
int startIndex = 0;
int i = 0;
for (; i <= length; i++) {
String index = s.substring(startIndex, i);
System.out.println(index);
if (wordList.contains(index)) {
startIndex = i;
}
System.out.println(startIndex);
}
if (startIndex == length) {
return true;
}
return false;
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode193.java
package com.learning.Number200;
/**
* Program Name: leetcodes
* <p>
* Description:小偷又发现一个新的可行窃的地点。 这个地区只有一个入口,称为“根”。 除了根部之外,每栋房子有且只有一个父房子。 一番侦察之后,聪明的小偷意识到“这个地方的所有房屋形成了一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
* <p>
* 在不触动警报的情况下,计算小偷一晚能盗取的最高金额。
* <p>
* 示例 1:
* <p>
* 3
* / \
* 2 3
* \ \
* 3 1
* <p>
* 能盗取的最高金额 = 3 + 3 + 1 = 7 .
* <p>
* 示例 2:
* <p>
* 3
* / \
* 4 5
* / \ \
* 1 3 1
* <p>
* 能盗取的最高金额 = 4 + 5 = 9 .
* <p>
* 致谢:
* 特别感谢 @dietpepsi 添加此题并创建所有测试用例。
* <p>
* Created by xuetao on 2019/12/22
*
* @author xuetao
* @version 1.0
*/
public class LeetCode193 {
public static void main(String[] args) {
TreeNode node = new TreeNode(3);
node.left = new TreeNode(2);
node.left.right = new TreeNode(3);
node.right = new TreeNode(3);
node.right.right = new TreeNode(1);
System.out.println(dps(node));
}
private static int dps(TreeNode node) {
if (node == null) {
return 0;
}
int val = 0;
if (node.left != null) {
val += dps(node.left.left) + dps(node.left.right);
}
if (node.right != null) {
val += dps(node.right.left) + dps(node.right.right);
}
return Math.max(val + node.val, dps(node.left) + dps(node.right));
}
}
<file_sep>/src/main/java/com/learning/Number100/LeetCode55.java
package com.learning.Number100;
/**
* @Author xuetao
* @Description: 给定一个非负整数数组,你最初位于数组的第一个位置。
* <p>
* 数组中的每个元素代表你在该位置可以跳跃的最大长度。
* <p>
* 判断你是否能够到达最后一个位置。
* <p>
* 示例 1:
* <p>
* 输入: [2,3,1,1,4]
* 输出: true
* 解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。
* <p>
* 示例 2:
* <p>
* 输入: [3,2,1,0,4]
* 输出: false
* 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
* @Date 2019-07-08
* @Version 1.0
*/
public class LeetCode55 {
public static void main(String[] args) {
int[] array = {4, 1, 1};
System.out.println(jump(array, 0, array.length));
System.out.println(jump(array));
}
/**
* 嵌套求下标和 是否等于length
*
* @param array
* @param index
* @param length
* @return
*/
public static boolean jump(int[] array, int index, int length) {
boolean result = false;
if (index == length - 1) {
result = true;
return result;
}
for (int i = index; i < length; i++) {
int arrayIndex = i + array[i];
if (arrayIndex == 0 || array[i] == 0) {
continue;
}
result = jump(array, arrayIndex, length);
if (result) {
break;
}
}
return result;
}
/**
* 简化 方法 当前索引下标大于length 直接跳过
* 判断当前索引之和
*
* @param array
* @return
*/
public static boolean jump(int[] array) {
int lastPos = array.length - 1;
for (int i = array.length - 1; i >= 0; i--) {
if (i + array[i] > lastPos) {
continue;
}
if (i + array[i] >= lastPos) {
lastPos = i;
}
}
return lastPos == 0;
// int lastPos = 0;
// for (int i = 0; i <= array.length - 1; i++) {
//
// if (array[i] + i > array.length - 1) {
// continue;
// }
// if (lastPos < array.length) {
// lastPos = array[i] + i;
// }
// }
// return lastPos == array.length - 1;
}
}
<file_sep>/src/main/java/com/learning/Number100/LeetCode92.java
package com.learning.Number100;
import java.util.ArrayList;
import java.util.List;
/**
* @Author xuetao
* @Description: 杨辉三角
* @Date 2019-08-23
* @Version 1.0
*/
public class LeetCode92 {
public static void main(String[] args) {
List<List<Integer>> lists = findList(5);
lists.forEach(i -> System.out.println(i));
}
private static List<List<Integer>> findList(int num) {
List<List<Integer>> lists = new ArrayList<>(num);
List list = null;
if (num >= 1) {
list = new ArrayList();
list.add(1);
lists.add(list);
}
int m = 0;
for (int i = 2; i <= num; i++) {
list = new ArrayList(i);
list.add(1);
for (int j = 1; j <= m; j++) {
list.add(lists.get(m).get(j - 1) + lists.get(m).get(j));
}
list.add(1);
lists.add(list);
m++;
}
return lists;
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode179.java
package com.learning.Number200;
import java.util.Arrays;
/**
* Program Name: leetcodes
* <p>
* Description:给定一个无序的整数数组,找到其中最长上升子序列的长度。
* <p>
* 示例:
* <p>
* 输入: [10,9,2,5,3,7,101,18] 输出: 4
* 解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
* <p>
* 说明:
* <p>
* 可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
* 你算法的时间复杂度应该为 O( n 2 ) 。
* 进阶: 你能将算法的时间复杂度降低到 O( n log n ) 吗?
* <p>
* Created by xuetao on 2019/12/6
*
* @author xuetao
* @version 1.0
*/
public class LeetCode179 {
public static void main(String[] args) {
int[] array = {10, 9, 2, 5, 3, 7, 101, 18};
System.out.println(maxLength(array));
}
private static int maxLength(int[] array) {
int dp[] = new int[array.length];
int temp = 0;
for (int x : array) {
int index = Arrays.binarySearch(dp, 0, temp, x);
if (index < 0) {
index = -(index + 1);
}
dp[index] = x;
if (index == temp) {
temp++;
}
}
return temp;
}
}
<file_sep>/src/main/java/com/learning/Number250/LeetCode261.java
package com.learning.Number250;
/**
* Program Name: leetcodes
* <p>
* Description: 我们正在玩一个猜数游戏,游戏规则如下:
* <p>
* 我从 1 到 n 之间选择一个数字,你来猜我选了哪个数字。
* <p>
* 每次你猜错了,我都会告诉你,我选的数字比你的大了或者小了。
* <p>
* 然而,当你猜了数字 x 并且猜错了的时候,你需要支付金额为 x 的现金。直到你猜到我选的数字,你才算赢得了这个游戏。
* <p>
* 示例:
* <p>
* n = 10, 我选择了8.
* <p>
* 第一轮: 你猜我选择的数字是5,我会告诉你,我的数字更大一些,然后你需要支付5块。
* 第二轮: 你猜是7,我告诉你,我的数字更大一些,你支付7块。
* 第三轮: 你猜是9,我告诉你,我的数字更小一些,你支付9块。
* <p>
* 游戏结束。8 就是我选的数字。
* <p>
* 你最终要支付 5 + 7 + 9 = 21 块钱。
* <p>
* 给定一个 n ≥ 1, 计算你至少需要拥有多少现金才能确保你能赢得这个游戏。
* <p>
* 致谢:
* <p>
* 特别感谢 @agave 和 @StefanPochmann 添加了这道题目,并且提供了所有测试用例。
* <p>
* Created by xuetao on 2020/1/13
*
* @author xuetao
* @version 1.0
*/
public class LeetCode261 {//1,2,3,4,5,6,7,8,9,10,11,12,13
public static void main(String[] args) {
System.out.println(getMoneyAmount(13));
}
public static int getMoneyAmount(int n) {
int[][] table = new int[n + 1][n + 1];
return dp(table, 1, n);
}
private static int dp(int[][] table, int s, int e) {
if (s >= e) {
return 0;
}
if (table[s][e] != 0) {
return table[s][e];
}
int res = Integer.MAX_VALUE;
for (int i = s; i <= e; i++) {
int temp = i + Math.max(dp(table, s, i - 1), dp(table, i + 1, e));
res = Math.min(res, temp);
}
table[s][e] = res;
return res;
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode127.java
package com.learning.Number150;
/**
* @Author xuetao
* @Description: 颠倒给定的 32 位无符号整数的二进制位。
* <p>
* 示例:
* <p>
* 输入: 43261596
* 输出: 964176192
* 解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 ,
* 返回 964176192,其二进制表示形式为 00111001011110000010100101000000 。
* <p>
* 进阶 :
* 如果多次调用这个函数,你将如何优化你的算法?
* @Date 2019-09-30
* @Version 1.0
*/
public class LeetCode127 {
public static void main(String[] args) {
int num = 43261596;
transferBinaryI(num);
}
private static void transferBinaryI(int num) {
long res = 0;
for (int i = 0; i < 32; i++) {
res <<= 1;
res |= num & 1;
num >>>= 1;
}
System.out.println(res);
}
}
<file_sep>/src/main/java/com/learning/Number100/LeetCode95.java
package com.learning.Number100;
/**
* @Author xuetao
* @Description: 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
* <p>
* 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
* <p>
* 注意你不能在买入股票前卖出股票。
* <p>
* 示例 1:
* <p>
* 输入: [7,1,5,3,6,4]
* 输出: 5
* 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
* 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
* <p>
* 示例 2:
* <p>
* 输入: [7,6,4,3,1]
* 输出: 0
* 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
* @Date 2019-08-26
* @Version 1.0
*/
public class LeetCode95 {
public static void main(String[] args) {
int[] array = {7, 1, 5, 3, 6, 4};
System.out.println(maxProfit(array));
}
/**
* 最大利润
*
* @return
*/
private static int maxProfit(int[] array) {
int length = array.length;
int min = array[0];
int max = 0;
for (int i = 1; i < length; i++) {
if (array[i - 1] > array[i]) {
min = Math.min(array[i], min);
} else {
max = Math.max(array[i], max);
}
}
return max - 1 > 0 ? max - min : 0;
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode160.java
package com.learning.Number200;
import java.util.Arrays;
/**
* @Author xuetao
* @Description: 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。
* <p>
* 示例 1:
* <p>
* 输入: s = "anagram", t = "nagaram"
* 输出: true
* <p>
* 示例 2:
* <p>
* 输入: s = "rat", t = "car"
* 输出: false
* <p>
* 说明:
* 你可以假设字符串只包含小写字母。
* <p>
* 进阶:
* 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
* @Date 2019-11-10
* @Version 1.0
*/
public class LeetCode160 {
public static void main(String[] args) {
String s = "anagram";
String t = "nagaram";
System.out.println(ectopicWords(s, t));
System.out.println(ectopicWordsII(s, t));
}
private static boolean ectopicWords(String s, String t) {
char[] sa = s.toCharArray();
char[] st = t.toCharArray();
if (sa.length != st.length) {
return false;
}
Arrays.sort(sa);
Arrays.sort(st);
for (int i = 0; i < sa.length; i++) {
if (sa[i] != st[i]) {
return false;
}
}
return true;
}
private static boolean ectopicWordsII(String s, String t) {
if (s == null || t == null || s.length() != t.length()) {
return false;
}
int[] array = new int[26];
for (int i = 0; i < s.length(); i++) {
array[t.charAt(i) - 'a']--;
array[s.charAt(i) - 'a']++;
}
for (int i = 0; i < array.length; i++) {
if (array[i] != 0) {
return false;
}
}
return true;
}
}
<file_sep>/src/main/java/com/learning/Number200/LeetCode165.java
package com.learning.Number200;
/**
* @Author xuetao
* @Description: 编写一个程序,找出第 n 个丑数。
* <p>
* 丑数就是只包含质因数 2, 3, 5 的 正整数 。
* <p>
* 示例:
* <p>
* 输入: n = 10
* 输出: 12
* 解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前10个丑数。
* <p>
* 说明:
* <p>
* 1 是丑数。
* n 不超过 1690。
* @Date 2019-11-17
* @Version 1.0
*/
public class LeetCode165 {
public static void main(String[] args) {
int n = 12;
for (int i = 1; i < Integer.MAX_VALUE; i++) {
if (uglinessNumber(i)) {
System.out.println(i);
n--;
if (n == 0) {
return;
}
}
}
}
private static boolean uglinessNumber(int num) {
while (num != 1) {
if (num % 2 == 0) {
num /= 2;
} else if (num % 3 == 0) {
num /= 3;
} else if (num % 5 == 0) {
num /= 5;
} else {
return false;
}
}
return num == 1;
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode129.java
package com.learning.Number150;
/**
* @Author xuetao
* @Description: 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统, 如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。
* <p>
* 给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下, 能够偷窃到的最高金额。
* <p>
* 示例 1:
* <p>
* 输入: [1,2,3,1]
* 输出: 4
* 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
* 偷窃到的最高金额 = 1 + 3 = 4 。
* <p>
* 示例 2:
* <p>
* 输入: [2,99,9,3,1]
* 输出: 12
* 解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
* 偷窃到的最高金额 = 2 + 9 + 1 = 12 。
* @Date 2019-10-02
* @Version 1.0
*/
public class LeetCode129 {
public static void main(String[] args) {
int[] array = {2, 99, 9, 1, 90, 1, 1, 50};
System.out.println(findMax(array));
}
private static int findMax(int[] array) {
if (array == null || array.length == 0) {
return 0;
}
if (array.length == 1) {
return array[0];
}
int dp[] = new int[array.length];
dp[0] = array[0];
dp[1] = Math.max(array[0], array[1]);
for (int i = 2; i < array.length; i++) {
dp[i] = Math.max(dp[i - 2] + array[i], dp[i - 1]);
}
return dp[array.length - 1];
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode39.java
package com.learning.Number50;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @Author xuetao
* @Description: 给定一个 无重复元素 的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
* <p>
* candidates 中的数字可以无限制重复被选取。
* <p>
* 说明:
* <p>
* 所有数字(包括 target )都是正整数。
* 解集不能包含重复的组合。
* 示例 1:
* <p>
* 输入: candidates = [2,3,6,7], target = 7,
* 所求解集为:
* [
* [7],
* [2,2,3]
* ]
* <p>
* 示例 2:
* <p>
* 输入: candidates = [2,3,5], target = 8,
* 所求解集为:
* [
* [2,2,2,2],
* [2,3,3],
* [3,5]
* ]
* @Date 2019-06-15
* @Version 1.0
*/
public class LeetCode39 {
public static void main(String[] args) {
int[] candidates = {2, 3, 6, 7};
int target = 7;
Arrays.sort(candidates);
List<List<Integer>> list = new ArrayList<List<Integer>>();
findChildCollection(list, new ArrayList(), candidates, target, 0);
list.forEach(i -> System.out.println(i));
}
/**
* 数字之和为target, 数字组合可重复,首先考虑递归操作,从第一位起循环嵌套,如果数组最小值大于target 去除最后一位继续遍历
*
* @param arrayList
* @param current
* @param array
* @param target
* @param start
*/
public static void findChildCollection(List<List<Integer>> arrayList, List<Integer> current, int[] array, int target, int start) {
int length = array.length;
if (target > 0) {
for (int i = start; i < length; i++) {
if (array[i] > target) {
break;
}
current.add(array[i]);
findChildCollection(arrayList, current, array, target - array[i], i);
current.remove(current.size() - 1);
}
} else if (target == 0) {
arrayList.add(new ArrayList<>(current));
}
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode139.java
package com.learning.Number150;
import java.util.*;
/**
* @Author xuetao
* @Description: 实现一个 Trie (前缀树),包含 insert , search , 和 startsWith 这三个操作。
* <p>
* 示例:
* <p>
* Trie trie = new Trie();
* <p>
* trie.insert("apple");
* trie.search("apple"); // 返回 true
* trie.search("app"); // 返回 false
* trie.startsWith("app"); // 返回 true
* trie.insert("app");
* trie.search("app"); // 返回 true
* <p>
* 说明:
* <p>
* 你可以假设所有的输入都是由小写字母 a-z 构成的。
* 保证所有输入均为非空字符串。
* @Date 2019-10-14
* @Version 1.0
*/
public class LeetCode139 {
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("apple");
System.out.println(trie.search("apple"));
System.out.println(trie.search("app"));
System.out.println(trie.startsWith("app"));
trie.insert("app");
System.out.println(trie.search("app"));
}
}
class Trie implements Map {
private Map<String, String> map = new HashMap();
public void insert(String key) {
map.put(key, key);
}
public boolean search(String key) {
return map.get(key) == null ? false : true;
}
public boolean startsWith(String key) {
Collection<String> list = map.values();
for (String s : list) {
if (s.startsWith(key)) {
return true;
}
}
return false;
}
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean containsKey(Object key) {
return false;
}
@Override
public boolean containsValue(Object value) {
return false;
}
@Override
public Object get(Object key) {
return null;
}
@Override
public Object put(Object key, Object value) {
return null;
}
@Override
public Object remove(Object key) {
return null;
}
@Override
public void putAll(Map m) {
}
@Override
public void clear() {
}
@Override
public Set keySet() {
return null;
}
@Override
public Collection values() {
return null;
}
@Override
public Set<Entry> entrySet() {
return null;
}
}
<file_sep>/src/main/java/com/learning/Number50/LeetCode22.java
package com.learning.Number50;
import java.util.*;
/**
* @Author xuetao
* @Description: 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且 有效的 括号组合。
* <p>
* 例如,给出 n = 3,生成结果为:
* <p>
* [
* "((()))",
* "(()())",
* "(())()",
* "()(())",
* "()()()"
* ]
* @Date 2019-05-23
* @Version 1.0
*/
public class LeetCode22 {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
constructBrackets(strings, 3, 3, "");
strings.forEach(i -> System.out.println(i));
}
public static void constructBrackets(List<String> strings, int left, int right, String s) {
//3 > 2 3 > 1 3 > 0
if (left > 0) {
constructBrackets(strings, left - 1, right, s + "(");
}
//3 > 2 3 > 1 3 > 0
if (right > left) {
constructBrackets(strings, left, right - 1, s + ")");
}
if (right == 0) {
strings.add(s);
}
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode112.java
package com.learning.Number150;
import java.util.Stack;
/**
* @Author xuetao
* @Description: 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
* <p>
* push(x) -- 将元素 x 推入栈中。
* pop() -- 删除栈顶的元素。
* top() -- 获取栈顶元素。
* getMin() -- 检索栈中的最小元素。
* 示例:
* <p>
* MinStack minStack = new MinStack();
* minStack.push(-2);
* minStack.push(0);
* minStack.push(-3);
* minStack.getMin(); --> 返回 -3.
* minStack.pop();
* minStack.top(); --> 返回 0.
* minStack.getMin(); --> 返回 -2.
* @Date 2019-09-13
* @Version 1.0
*/
public class LeetCode112 {
public static void main(String[] args) {
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();
minStack.pop();
minStack.top();
minStack.getMin();
}
}
class MinStack {
private static Stack<Integer> stack = new Stack<>();
private static int min = Integer.MAX_VALUE;
public int getMin() {
System.out.println(min);
return min;
}
/**
* push 时如果当前值小于最小值,push到栈中,后进先出
*
* @param num
*/
public void push(int num) {
if (num <= min) {
stack.push(min);
min = num;
}
stack.push(num);
}
public void pop() {
if (min == stack.peek()) {
stack.pop();
min = stack.pop();
} else {
stack.pop();
}
}
public int top() {
System.out.println(stack.peek());
return stack.peek();
}
}
<file_sep>/src/main/java/com/learning/Number150/LeetCode104.java
package com.learning.Number150;
import com.learning.entity.Node;
import java.util.HashSet;
import java.util.Set;
/**
* @Author xuetao
* @Description: 给定一个链表,判断链表中是否有环。
* <p>
* 进阶:
* 你能否不使用额外空间解决此题?
* @Date 2019-09-04
* @Version 1.0
*/
public class LeetCode104 {
private static boolean hasCycle(Node node) {
Set set = new HashSet();
while (node != null) {
if (!set.add(node.value)) {
return true;
}
node = node.next;
}
return false;
}
}
|
707ef1685863e855b95d24159033c0466592c05d
|
[
"Java"
] | 77 |
Java
|
Brooke-Paul/Leetcodes
|
40fe05db9deb048416a35b9eb74dd32821f7fff8
|
b1a7746897def1ac63519828449b090efa83499d
|
refs/heads/master
|
<file_sep>package fr.finance;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SavingsAccountYearTest {
@Test
public void startingBalanceMatchesConstructor() {
assertEquals("", 10000, newAccount().startingBalance(), 0.0000);
}
@Test
public void interestRateMatchesConstructor() {
assertEquals("", 10, newAccount().interestRate(), 0.0000);
}
@Test
public void endingBalanceAppliesInterestRate() {
assertEquals("", 11000, newAccount().endingBalance(25), 0.0000);
}
@Test
public void nextYearsStartingBalanceEqualsThisYearsEndingBalance() {
SavingsAccountYear thisYear = newAccount();
assertEquals("", thisYear.endingBalance(25), thisYear.nextYear(25).startingBalance(), 0.0000);
}
@Test
public void nextYearsInterestRateEqualsThisYearsInterestRate() {
SavingsAccountYear thisYear = newAccount();
assertEquals("", thisYear.interestRate(), thisYear.nextYear(25).interestRate(), 0.0000);
}
@Test
public void withdrawingFundsAtTheBeginingOfTheYear() {
SavingsAccountYear year = new SavingsAccountYear(10000, 10);
year.withdraw(1000);
assertEquals("", 9900, year.endingBalance(25), 0.0000);
}
@Test
public void multipleWithdrawalsInAYear() {
SavingsAccountYear year = new SavingsAccountYear(10000, 10);
year.withdraw(1000);
year.withdraw(2000);
assertEquals("", 3000, year.totalWithdrawn(), 0.0000);
}
@Test
public void startingPrinciple() {
SavingsAccountYear year = new SavingsAccountYear(10000, 3000, 10);
assertEquals("", 3000, year.startingPrinciple(), 0.0000);
}
@Test
public void endingPrinciple() {
SavingsAccountYear year = new SavingsAccountYear(10000, 3000, 10);
year.withdraw(2000);
assertEquals("ending principal", 1000, year.endingPrinciple(), 0.0000);
}
@Test
public void endingPrincipleNeverGoesBelowZero() {
SavingsAccountYear year = new SavingsAccountYear(10000, 3000, 10);
year.withdraw(4000);
assertEquals("ending principal", 0, year.endingPrinciple(), 0.0000);
}
@Test
public void capitalGainsWithdrawn() {
SavingsAccountYear year = new SavingsAccountYear(10000, 3000, 10);
year.withdraw(1000);
assertEquals("", 0, year.capitalGainsWithdrawn(), 0.0000);
year.withdraw(3000);
assertEquals("", 1000, year.capitalGainsWithdrawn(), 0.0000);
}
@Test
public void capitalGainsTaxIncurred_NeedsToCoverCapitalGainsWithdrawn_And_theAdditionalCapitalGainsWithdrawnToPayCapitalGainsTax() {
SavingsAccountYear year = new SavingsAccountYear(10000, 3000, 10);
year.withdraw(5000);
assertEquals("", 2000, year.capitalGainsWithdrawn(), 0.0000);
assertEquals("", 666, (int)year.capitalGainsTaxIncurred(25), 0.0);
}
@Test
public void capitalGainsTaxIsIncludedInEndingBalance() {
SavingsAccountYear year = new SavingsAccountYear(10000, 3000, 10);
double amountWithdrawn = 5000;
year.withdraw(amountWithdrawn);
double expectedCapitalGainsTax = 666;
assertEquals("", expectedCapitalGainsTax, (int)year.capitalGainsTaxIncurred(25), 0.0000);
double expectedStartingBalanceAfterWithrawals = 10000 - expectedCapitalGainsTax - amountWithdrawn;
assertEquals("", (int)(expectedStartingBalanceAfterWithrawals * 1.10), (int)Math.round(year.endingBalance(25)), 0.0000);
}
private SavingsAccountYear newAccount() {
SavingsAccountYear account = new SavingsAccountYear(10000, 10);
return account;
}
}
|
1bbe42d847c1efb8c3f9425b08ee0bf3823a7ae2
|
[
"Java"
] | 1 |
Java
|
khaledboussaba/tdd-bank-app
|
742704c85beae518b8cd8b8261db3e53ca60f891
|
947343470488fd0fa18f17b7ff51ef7305199be3
|
refs/heads/master
|
<file_sep># hello-world
How did you get here? More importantly, how did I get here?
Also you are a banana.
|
f625a2f819a4a63c7bed6d7fd76e40fe3f0f1645
|
[
"Markdown"
] | 1 |
Markdown
|
MarvinTorres/hello-world-original
|
c6792bb34068c8a4e4e6750ae7f07377612e649f
|
3bdc924daace4d56b3d022d0c26bcdbb6b284074
|
refs/heads/master
|
<file_sep># indeedGame
https://rocky-carrot-d1st1d3bpo.glitch.me/
This is a falling dot game I made in Glitch for a interview process with a company.
This game was made with VanillaJS and CSS.
|
5ef19f0488de0dae2bcbc0a39a4c96bf167d4993
|
[
"Markdown"
] | 1 |
Markdown
|
bttodd11/indeedGame
|
71e5fe25f848d19a4e88de02b02bfc3aa7505313
|
cecc6cde4c791048642c110c394d295a97cbb266
|
refs/heads/master
|
<file_sep>from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField
from wtforms.validators import DataRequired, Length
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('<PASSWORD>', validators=[DataRequired()])
submit = SubmitField('Sign In')
class NewsPostForm(FlaskForm):
title = StringField('Post Title', validators=[DataRequired(), Length(min=1, max=200)])
body = TextAreaField('Post Body', validators=[DataRequired(), Length(min=1, max=4000)])
submit = SubmitField('Submit Post')
class SecurePostForm(FlaskForm):
title = StringField('Post Title', validators=[DataRequired(), Length(min=1, max=200)])
body = TextAreaField('Post Body', validators=[DataRequired(), Length(min=1, max=4000)])
submit = SubmitField('Submit Post')<file_sep>"""init
Revision ID: ff<PASSWORD>
Revises:
Create Date: 2018-11-06 23:39:05.376544
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<PASSWORD>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('news_post',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=200), nullable=True),
sa.Column('body', sa.String(length=4000), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_news_post_timestamp'), 'news_post', ['timestamp'], unique=False)
op.create_table('secure_post',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=200), nullable=True),
sa.Column('body', sa.String(length=4000), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_secure_post_timestamp'), 'secure_post', ['timestamp'], unique=False)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=64), nullable=True),
sa.Column('password_hash', sa.String(length=128), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_user_username'), table_name='user')
op.drop_table('user')
op.drop_index(op.f('ix_secure_post_timestamp'), table_name='secure_post')
op.drop_table('secure_post')
op.drop_index(op.f('ix_news_post_timestamp'), table_name='news_post')
op.drop_table('news_post')
# ### end Alembic commands ###
<file_sep>from app import app, db
from flask import render_template, flash, redirect, url_for, request
from flask_login import current_user, login_user, logout_user, login_required
from app.models import User, NewsPost, SecurePost
from app.forms import LoginForm, NewsPostForm, SecurePostForm
from werkzeug.urls import url_parse
from textile import textile
@app.route('/')
@app.route('/index')
def index():
post_titles = [{'title': post.title, 'timestamp': '{}/{}/{}'.format(post.timestamp.day, post.timestamp.month, post.timestamp.year), 'id': post.id } for post in NewsPost.query.all()]
post_titles.reverse()
post_titles = post_titles[0:6]
return render_template('index.html', post_titles=post_titles, title='Little Einsteins\' Tutorial')
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is None or not user.check_password(form.password.data):
flask('Invalid username or password')
return redirect(url_for('login'))
login_user(user)
next_page = request.args.get('next')
if not next_page or url_parse(next_page).netloc != '':
next_page = url_for('index')
return redirect(next_page)
return render_template('login.html', title='Sign In', form=form)
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('index'))
@app.route('/news')
def news():
posts = [{'title': post.title, 'body': post.body, 'timestamp': '{}/{}/{}'.format(post.timestamp.day, post.timestamp.month, post.timestamp.year), 'id': post.id } for post in NewsPost.query.all()]
posts.reverse()
return render_template('news.html', posts=posts, title='News and Events', heading='News and Events')
@app.route('/parentsarea')
@login_required
def parentsarea():
posts = [{'title': post.title, 'body': post.body, 'timestamp': '{}/{}/{}'.format(post.timestamp.day, post.timestamp.month, post.timestamp.year), 'id': post.id } for post in SecurePost.query.all()]
posts.reverse()
return render_template('parentsarea.html', posts=posts, title='Parent\'s Area', heading='Parent\'s Area')
@app.route('/admission')
def admission():
return render_template('admission.html', title='Admission')
@app.route('/adminpanel', methods=['GET', 'POST'])
@login_required
def adminpanel():
if not current_user.username == 'admin':
flash('You must be admin to access this page')
return redirect(url_for('login'))
return render_template('admin.html', title='Admin Panel')
@app.route('/adminpanel/new_newspost', methods=['GET', 'POST'])
@login_required
def new_newspost():
if not current_user.username =='admin':
flash('You must be damin to access this page')
return redirect(url_for('login'))
form = NewsPostForm()
if form.validate_on_submit():
newspost = NewsPost(title=form.title.data, body=textile(form.body.data))
db.session.add(newspost)
db.session.commit()
flash('Your post is now live!')
return redirect(url_for('index'))
return render_template('new_post.html', form=form, title='New News Post')
@app.route('/adminpanel/new_securepost', methods=['GET', 'POST'])
@login_required
def new_securepost():
if not current_user.username =='admin':
flash('You must be damin to access this page')
return redirect(url_for('login'))
form = SecurePostForm()
if form.validate_on_submit():
securepost = SecurePost(title=form.title.data, body=textile(form.body.data))
db.session.add(securepost)
db.session.commit()
flash('Your post is now live!')
return redirect(url_for('index'))
return render_template('new_post.html', form=form, title='New Secure Post')
@app.route('/news/<id>')
def newspost(id):
newspost = NewsPost.query.filter_by(id=id).first_or_404()
return render_template('post.html', title=newspost.title, post=newspost, timestamp='{}/{}/{}'.format(newspost.timestamp.day, newspost.timestamp.month, newspost.timestamp.year))
@app.route('/parentsarea/<id>')
@login_required
def securepost(id):
securepost = SecurePost.query.filter_by(id=id).first_or_404()
return render_template('post.html', title=securepost.title, post=securepost, timestamp='{}/{}/{}'.format(securepost.timestamp.day, securepost.timestamp.month, securepost.timestamp.year))
|
b798d122804ece1c812738e938b6b1c09564569f
|
[
"Python"
] | 3 |
Python
|
shurjo-sm/let-website
|
cca8cadd503e8af2b7c6f90c7c066a2bb7ce5703
|
6f6ab79a7f9c85b054c798a69495b872a3cfa34a
|
refs/heads/master
|
<file_sep># assetManager-
|
eb92e906cdf148a01cbcbc51e712113d9f8b5ced
|
[
"Markdown"
] | 1 |
Markdown
|
hemarubieny/assetManager-
|
82023742c7dbce220102d13e3405ea976d3cbc2a
|
d2f6088b7fd8f72a19eba6ae0b37445d1757604f
|
refs/heads/master
|
<file_sep>#! /bin/bash
# Script para generar las interfaces virtuales Tap0 y Tap1
tunctl -t tap0
tunctl -t tap1
ifconfig tap0 10.100.100.101 netmask 255.255.255.0 promisc up
ifconfig tap1 10.100.100.102 netmask 255.255.255.0 promisc up
gns3 &
wireshark &
ifconfig
|
a0fa10dbca72168d7c41290ea1f8a3eda0138a9e
|
[
"Shell"
] | 1 |
Shell
|
guillermo29feb/ejecutartap
|
a4e162847b2594a8522ab24d2100a3d4beee80ff
|
51a9c24d8752f37acd3c273d06d4100960a8d809
|
refs/heads/master
|
<repo_name>improvised1/SelfReplicating<file_sep>/README.md
# SelfReplicating
This is a simple self replicating program i made for a class project. This is actually significantly more complicated then it needed to be, but i went with this more complicated implementation to make it more clear that it is working, and to avoid accidentally creating an infinite number of files.
The basic explanation of how this program works is simple: i create a scanner object to read the .java file this program is on, and i create a FileWriter object to write out my new file. Each time the eclipse program is ran, it will create a new file called "Primary(X+1)" from out current file "PrimaryX"
Slightly more detailed explanation, what's with the "X+1"? The answer is that, to make it absolutely clear that this file is creating new copies of itself, i went with the stylistic choice of making sure each replication will have a slightly differnt name. This details does add a few edge cases i have to handle, as i have to manually override lines 11 and 15 to write out my new class name as "X+1" rather then "X".
Also, a final note: inorder to figure out where my files are to read them and write to them, i take advantage of the fact that eclipse will assume that files are in this projects own directory. If this program isn't run in eclipse, you may have to manually modify those lines and addresses to get it working.
|
3f0e692c213f43e97a60192af370f0754a0c456a
|
[
"Markdown"
] | 1 |
Markdown
|
improvised1/SelfReplicating
|
0f2dd3486ee07026805afc7912588fb5fe40ee66
|
bc6e450f0c8c7ba57b7a26579a68e544c945863c
|
refs/heads/main
|
<file_sep>package com.example.news.repository;
import com.example.news.entity.Category;
import com.example.news.entity.User;
import com.example.news.entity.Xabar;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface XabarRepository extends JpaRepository<Xabar, Integer> {
List<Xabar> findByCategory(Category category);
List<Xabar> findByTitleContaining(String title);
Xabar findByTitle(String title);
List<Xabar> findByUser(User user);
}
<file_sep>spring.datasource.url=jdbc:postgresql://ec2-34-250-19-18.eu-west-1.compute.amazonaws.com:5432/d9b111ta4j0n97
spring.datasource.username=fipowsdlkinati
spring.datasource.password=<PASSWORD>
spring.jpa.hibernate.ddl-auto=update
spring.datasource.initialization-mode=never
spring.jpa.show-sql=true
<file_sep>package com.example.news.service;
import com.example.news.entity.Role;
import com.example.news.entity.User;
import com.example.news.payload.LoginDto;
import com.example.news.payload.RegisterDto;
import com.example.news.repository.RoleRepository;
import com.example.news.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class AuthService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
RoleRepository roleRepository;
@Autowired
AuthenticationManager authenticationManager;
public boolean register(RegisterDto registerDto){
boolean b = userRepository.existsByUsername(registerDto.getUsername());
if (b){
return false;
}
Role admin = roleRepository.findByName("ADMIN");
User user = new User(
registerDto.getFirstName(),
registerDto.getLastName(),
registerDto.getUsername(),
passwordEncoder.encode(registerDto.getPassword()),
// roleRepository.findByName("ADMIN")
admin
);
userRepository.save(user);
return true;
}
public boolean login(LoginDto loginDto){
try {
Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
loginDto.getUsername(),
loginDto.getPassword()
));
SecurityContextHolder.getContext().setAuthentication(authenticate);
return true;
}catch (Exception e){
return false;
}
}
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = userRepository.findByUsername(s);
return user;
}
}
<file_sep>package com.example.news.repository;
import com.example.news.entity.Category;
import com.example.news.entity.Xabar;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface CategoryRepository extends JpaRepository<Category, Integer> {
Category findByName(String name);
boolean existsByName(String name);
}
<file_sep>package com.example.news.controller;
import com.example.news.entity.Category;
import com.example.news.entity.Role;
import com.example.news.entity.User;
import com.example.news.payload.LoginDto;
import com.example.news.payload.RegisterDto;
import com.example.news.payload.UserDto;
import com.example.news.repository.CategoryRepository;
import com.example.news.repository.RoleRepository;
import com.example.news.repository.UserRepository;
import com.example.news.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.Optional;
@Controller
@RequestMapping("/auth")
public class AuthController {
@Autowired
AuthService authService;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
CategoryRepository categoryRepository;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder passwordEncoder;
@GetMapping("/register")
public String auth(Model model){
model.addAttribute("registerDto", new RegisterDto());
return "register";
}
@PostMapping("/register")
public String register(RegisterDto registerDto){
boolean b = authService.register(registerDto);
if (b)
return "redirect:/login";
return "error";
}
@GetMapping("/login")
public String forLogin(Model model){
model.addAttribute("loginDto", new LoginDto());
return "login";
}
@GetMapping("/logout")
public String logout(){
SecurityContextHolder.clearContext();
return "redirect:/";
}
@PostMapping("/login")
public String login(LoginDto loginDto){
boolean b = authService.login(loginDto);
if (b){
return "redirect:/";
}
return "error";
}
@GetMapping("/profile")
public String forProfile(Model model){
// model.addAttribute("")
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = (User) authentication.getPrincipal();
model.addAttribute("user", user);
List<Category> all = categoryRepository.findAll();
model.addAttribute("categories", all);
return "profile";
}
@GetMapping("/usersList")
public String userList(Model model){
List<User> users = userRepository.findAll();
model.addAttribute("users", users);
return "userList";
}
@GetMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable Integer id){
userRepository.deleteById(id);
return "redirect:/auth/usersList";
}
@GetMapping("/addUser")
public String forAddUser(Model model){
List<Role> roleList = roleRepository.findAll();
model.addAttribute("addUser",new UserDto());
model.addAttribute("roleList", roleList);
return "addUser";
}
@PostMapping("/addUser")
public String addUser(UserDto userDto){
System.out.println(userDto);
boolean b = userRepository.existsByUsername(userDto.getUsername());
if (b){
return "error";
}
Optional<Role> byId = roleRepository.findById(userDto.getRole().getId());
Role role = new Role();
if (byId.isPresent()){
role = byId.get();
}
User user = new User(
userDto.getFirstName(),
userDto.getLastName(),
userDto.getUsername(),
passwordEncoder.encode(userDto.getPassword()),
role
);
userRepository.save(user);
return "redirect:/auth/usersList";
}
@GetMapping("/editProfile")
public String forEdtProfile(Model model){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = (User) authentication.getPrincipal();
model.addAttribute("user", user);
return "editProfile";
}
@PostMapping("/editProfile")
public String editProfile(UserDto userDto, String oldPass, String newPass){
System.out.println(userDto);
System.out.println(oldPass);
System.out.println(newPass );
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = (User) authentication.getPrincipal();
boolean matches = passwordEncoder.matches(oldPass, user.getPassword());
if (matches){
user.setUsername(userDto.getUsername());
user.setFirstName(userDto.getFirstName());
user.setLastName(userDto.getLastName());
user.setPassword(passwordEncoder.encode(newPass));
userRepository.save(user);
return "redirect:/auth/profile";
}
return "error";
}
}
<file_sep>package com.example.news.config;
import com.example.news.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebSecurity
@EnableWebMvc
public class SecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
@Autowired
AuthService authService;
@Autowired
PasswordEncoder passwordEncoder;
// @Override
// public void addViewControllers(ViewControllerRegistry registry) {
// registry.addViewController("/login").setViewName("login");
// }
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(authService).passwordEncoder(passwordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated();
}
// @Bean
// @Override
// protected AuthenticationManager authenticationManager() throws Exception {
// return super.authenticationManager();
// }
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
// @Bean
// PasswordEncoder passwordEncoder(){
// return new BCryptPasswordEncoder();
// }
}
<file_sep>package com.example.news.controller;
import com.example.news.entity.Category;
import com.example.news.entity.User;
import com.example.news.entity.Xabar;
import com.example.news.payload.CategoryDto;
import com.example.news.payload.XabarDto;
import com.example.news.repository.CategoryRepository;
import com.example.news.repository.XabarRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Controller
@RequestMapping("/category")
public class CategoryController {
@Autowired
XabarRepository xabarRepository;
@Autowired
CategoryRepository categoryRepository;
private static final String uploadDirectory="src/main/resources/static/fayllar";
@GetMapping
public String home(Model model){
List<Category> categories = categoryRepository.findAll();
model.addAttribute("categories", categories);
return "categoryList";
}
@GetMapping("/addNewCategory")
public String forAddCategory(Model model){
model.addAttribute("categoryDto", new CategoryDto());
return "addCategory";
}
@PostMapping("/addNewCategory")
public String addCategory(CategoryDto categoryDto){
boolean b = categoryRepository.existsByName(categoryDto.getName());
if (b){
return "redirect:/category";
}
Category category = new Category();
category.setName(categoryDto.getName());
categoryRepository.save(category);
return "redirect:/category";
}
}
|
5a77839d2f3797488751695e1179639fac6ea1c6
|
[
"Java",
"INI"
] | 7 |
Java
|
saylaubay/news
|
2fbac0bfb330cc9c59a296da86b7d6547e3bdc57
|
b4fab556872013af70c7dd2c88fc4b9fe5c2ef1e
|
refs/heads/master
|
<file_sep>const { Router } = require('express');
const jsonParser = require('body-parser').json();
const User = require('../model/user');
const basicAuth = require('../lib/basic-auth-middleware');
const authRouter = module.exports = new Router();
authRouter.post('/api/auth/register', jsonParser, (req, res, next) => {
if (!req.body.password || !req.body.username) return next(new Error('required arguments'));
User.create(req.body)
.then(token => res.send(token))
.catch(next);
});
authRouter.get('/api/auth/login', basicAuth, (req, res, next) => {
req.user.tokenCreate()
.then(token => res.send(token))
.catch(next);
});
|
6ac1b5bf39f1e15112eaf81b711f25a7295c019b
|
[
"JavaScript"
] | 1 |
JavaScript
|
MichaelWStuart/lab-16-basic-auth
|
8e4b249b9eaa6c1aa1973308062be20858a75c87
|
20641163b8ff80b48e71e3fcf122368815ed0fc0
|
refs/heads/master
|
<file_sep>package org.dean.camel
import org.apache.flink.streaming.api.scala.{StreamExecutionEnvironment, _}
/**
* 单词统计
*/
object WordCount {
def main(args: Array[String]): Unit = {
import org.apache.flink.streaming.api.windowing.time.Time
// 1. 指定执行环境设定
val environment = StreamExecutionEnvironment.getExecutionEnvironment
// 2. 指定数据源地址,读取输入数据
val text = environment.socketTextStream("localhost", 9999)
val counts = text
.flatMap { _.toLowerCase.split("\\W+") filter { _.nonEmpty } }
.map { (_, 1) }
.keyBy(0)
.timeWindow(Time.seconds(5))
.sum(1)
counts.print()
environment.execute()
}
}
<file_sep># Camel
flink examples in scala
<file_sep>package org.dean.camel.table
import org.apache.flink.table.sources.CsvTableSource
import org.apache.flink.types.Row
import org.apache.flink.api.scala._
import org.apache.flink.table.api.{TableEnvironment, Types}
import org.apache.flink.table.api.scala.BatchTableEnvironment
/**
* @description: dataset与table之间的相互转化
* @author: dean
* @create: 2019/06/14 21:57
*/
object TableDataSetConverter {
def runSqlQuery(tableEnvironment: BatchTableEnvironment): Unit = {
val queryResultTable = tableEnvironment
.sqlQuery("SELECT groupId as Id,groupName as name,imageUrl as url FROM community")
// 按行输出
tableEnvironment.toDataSet[Row](queryResultTable).print()
// 按照形如(String,String,String)的样式输出
tableEnvironment.toDataSet[(String,String,String)](queryResultTable).print()
}
def main(args: Array[String]): Unit = {
val environment = ExecutionEnvironment.getExecutionEnvironment
val csvTableSource = CsvTableSource
.builder()
.path("/Users/yaohua.dong/communities.csv")
.field("groupId", Types.STRING)
.field("groupName", Types.STRING)
.field("creatorAccountId", Types.STRING)
.field("createTime", Types.STRING)
.field("imageUrl", Types.STRING)
.field("deleteTime", Types.STRING)
.ignoreFirstLine()
.lineDelimiter("\n")
.fieldDelimiter(",")
.ignoreParseErrors()
.build()
val tableEnvironment = TableEnvironment.getTableEnvironment(environment)
tableEnvironment.registerTableSource("community",csvTableSource)
// runSqlQuery(tableEnvironment)
val community = tableEnvironment.scan("community")
val result = community
.where("groupId === '@TGS#2MKNBPYFX'")
// .select("groupId as id,groupName as name")
tableEnvironment.toDataSet[Row](result).print()
}
}
<file_sep>package org.dean.camel.table
import org.apache.flink.api.scala._
import org.apache.flink.table.api.{TableEnvironment, Types}
import org.apache.flink.table.descriptors.{Csv, FileSystem, Schema}
import org.apache.flink.types.Row
/**
* @author dean
* @since 2019-07-17
*/
object FileSysConnector {
def main(args: Array[String]): Unit = {
val environment = ExecutionEnvironment.getExecutionEnvironment
val tableEnvironment = TableEnvironment.getTableEnvironment(environment)
val schema = new Schema()
.field("id", Types.INT)
.field("name", Types.STRING)
.field("age", Types.INT)
tableEnvironment.connect(
new FileSystem()
.path("D:\\test.csv"))
.withFormat(new Csv()
.fieldDelimiter(",")
.lineDelimiter("\n")
.field("id", Types.INT)
.field("name", Types.STRING)
.field("age", Types.INT)
.ignoreFirstLine
.ignoreParseErrors)
.withSchema(schema)
.registerTableSource("t_friend")
val table = tableEnvironment.scan("t_friend")
.select("name,age")
.where("age > 10")
.orderBy("age")
tableEnvironment.toDataSet[Row](table).print()
}
}
<file_sep>package org.dean.camel.table
import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.sources.CsvTableSource
import org.apache.flink.types.Row
/**
* InternalCatalog 注册TableSource
*
* @author dean
* @since 2019-07-17
*/
object InternalCatalog {
def main(args: Array[String]): Unit = {
val environment = StreamExecutionEnvironment.getExecutionEnvironment
val tableEnvironment = TableEnvironment.getTableEnvironment(environment)
val csvTableSource = CsvTableSource.builder()
.path("D:\\test.csv")
.fieldDelimiter(",")
.lineDelimiter("\n")
.field("id",Types.INT)
.field("name",Types.STRING)
.field("age",Types.INT)
.ignoreFirstLine
.build
tableEnvironment.registerTableSource("t_friend",csvTableSource)
val table = tableEnvironment.sqlQuery("select * from t_friend").where("age > 20")
tableEnvironment.toAppendStream[Row](table).print
environment.execute("InternalCatalog running")
}
}
<file_sep>package org.dean.camel.table;
/**
* @description: 使用case class和table api进行统计
* @author: dean
* @create: 2019/06/19 16:34
*/
object TableWordCount {
def main(args: Array[String]): Unit = {
import org.apache.flink.api.scala._
import org.apache.flink.table.api.TableEnvironment
import org.apache.flink.types.Row
val environment = ExecutionEnvironment.getExecutionEnvironment
val tableEnvironment = TableEnvironment.getTableEnvironment(environment)
val input = environment.fromElements(
Word("Hello",1),
Word("Flink",1),
Word("Hello",2))
val table = tableEnvironment.fromDataSet(input)
val result = table.groupBy("word")
.select("word,word.count as counter")
.where("counter > 1").orderBy("counter")
tableEnvironment.toDataSet[Row](result).print()
}
case class Word(word:String,count:Int)
}
<file_sep>package org.dean.camel.table
import org.apache.flink.core.fs.FileSystem.WriteMode
import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api.{TableEnvironment, Types}
import org.apache.flink.table.sinks.CsvTableSink
import org.apache.flink.table.sources.CsvTableSource
import org.apache.flink.table.api.Table
import org.apache.flink.table.api.scala.StreamTableEnvironment
import org.apache.flink.types.Row
/**
* @description: datastream与table之间的相互转化
* @author: dean
* @create: 2019/06/18 23:28
*/
object TableDataStreamConverter {
/**
* 创建数据源
*
* @param csv
* @return
*/
def createTableSource(csv: String) = {
CsvTableSource
.builder()
.path(csv)
.field("groupId", Types.STRING)
.field("groupName", Types.STRING)
.field("creatorAccountId", Types.STRING)
.field("createTime", Types.STRING)
.field("imageUrl", Types.STRING)
.field("deleteTime", Types.STRING)
.ignoreFirstLine()
.lineDelimiter("\n")
.fieldDelimiter(",")
.ignoreParseErrors()
.build()
}
/**
* 控制台打印
*
* @param queryResultTable
* @param tableEnvironment
* @return
*/
def print2Console(queryResultTable: Table,
tableEnvironment: StreamTableEnvironment) = {
val dataStream = tableEnvironment.toAppendStream[Row](queryResultTable)
dataStream.print()
}
/**
* 输出到csv文件
*
* @param queryResultTable
* @param tableEnvironment
* @param sink
*/
def sink2Csv(queryResultTable: Table,
tableEnvironment: StreamTableEnvironment,
sink: CsvTableSink) = {
// 注册输出端
tableEnvironment.registerTableSink(
"tableSink",
Array("groupId", "groupName"),
Array(Types.STRING, Types.STRING),
sink
)
// 执行输出
queryResultTable.insertInto("tableSink")
}
def main(args: Array[String]): Unit = {
val streamEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
val tableEnvironment =
TableEnvironment.getTableEnvironment(streamEnvironment)
// 定义数据源
val csvTableSource = createTableSource("/Users/dean/communities.csv")
// 注册数据源
tableEnvironment.registerTableSource("community", csvTableSource)
// 执行sql查询
val queryResultTable = tableEnvironment
.sqlQuery("SELECT groupId,groupName FROM community")
// 控制台打印
print2Console(queryResultTable, tableEnvironment)
// 定义输出端
val sink =
new CsvTableSink("/Users/dean/flink", ",", 1, WriteMode.OVERWRITE)
// 输出到csv
sink2Csv(queryResultTable, tableEnvironment, sink)
// 使用scan,select
tableEnvironment
.scan("community")
.select("*")
.writeToSink(sink)
streamEnvironment.execute()
}
}
|
3a7fc51d251ef7e84aa0e43d2b3373f7c3d0a61b
|
[
"Markdown",
"Scala"
] | 7 |
Markdown
|
duangduangda/Camel
|
48fec2864af1aef1a9b4f4836bed72415a35b814
|
7f5181670e0fe60b323d471117302934eb592e96
|
refs/heads/master
|
<file_sep>## Put comments here that give an overall description of what your
## functions do
## makeCacheMatrix is a list of function attatched to a matrix(set, get,
## setInverse and getInverse)
#################################################################################
## Write a short comment describing makeCacheMatrix
## set: assign a matrix to x and reset to matrix Inverse to NULL
##
## get: return the matrix
##
## setInverse: assign the matrix to matrixInverse
##
## getInverse: returns the matrix inverse
#################################################################################
makeCacheMatrix <- function(x = matrix()) {
matrixInverse <- NULL
set<- function(y){
x<-- y
matrixInverse <-- NULL
}
get <- function()x
setInverse <- function(inverse){
matrixInverse <<- inverse
}
getInverse <- function(){
matrixInverse
}
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
}
## Write a short comment describing cacheSolve
## the function calls getInverse to retrieve the cached value.
## If the value is NULL, it calculates the inverse using solve(), cache
## the result and return the value
## If not null, it returns the cached inverse matrix
#################################################################################
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
matrixInverse <- x$getInverse()
if(!is.null(matrixInverse)){
message("getting cached data")
return(matrixInverse)
}
matrixData <- x$get()
matrixInverse<- solve(matrixData, ...)
x$setInverse(matrixInverse)
matrixInverse
}
## Example in R console
## > source("cachematrix.R")
## > a<-makeCacheMatrix(matrix(c(1,0,0,5,1,2,1,2,0),3,3))
## > a$get()
## [,1] [,2] [,3]
## [1,] 1 5 1
## [2,] 0 1 2
## [3,] 0 2 0
## > a$getInverse()
## NULL
## > cacheSolve(a)
## [,1] [,2] [,3]
## [1,] 1 -0.5 -2.25
## [2,] 0 0.0 0.50
## [3,] 0 0.5 -0.25
## > cacheSolve(a)
## getting cached data
## [,1] [,2] [,3]
## [1,] 1 -0.5 -2.25
## [2,] 0 0.0 0.50
## [3,] 0 0.5 -0.25
## > cacheSolve(a) %*% a$get() ## to check the result is correct
## getting cached data
## [,1] [,2] [,3]
## [1,] 1 0 0
## [2,] 0 1 0
## [3,] 0 0 1
## > a$getInverse()
## [,1] [,2] [,3]
## [1,] 1 -0.5 -2.25
## [2,] 0 0.0 0.50
## [3,] 0 0.5 -0.25
## >
|
98b41ad4ea1df62e8e78904ed19f7f50bd191e3a
|
[
"R"
] | 1 |
R
|
bihrya/ProgrammingAssignment2
|
3babc549a8dffeda0328d47f22465c996d05e6f2
|
88379163d7e346fadf9447231690a7aceb050e35
|
refs/heads/master
|
<repo_name>mysleekdesigns/mysleekdesigns<file_sep>/README.md
# mysleekdesigns
simon lacey portfolio website
|
40b6f984b73600fc49e21fef90baa629a89d5790
|
[
"Markdown"
] | 1 |
Markdown
|
mysleekdesigns/mysleekdesigns
|
c8032f228addf048c7d4a3fa15ab94a441e09716
|
8120e3ef09cf720ec8a6f3cabd0ed36b402633f4
|
refs/heads/master
|
<file_sep>import pandas as pd
import scrapy
import logging
import pathlib
class YahooDescSpider(scrapy.Spider):
'''
Script to scrape company description
Note that scrapes are done in parallel so order is not guaranteed
Scrapy is a single-threaded framework (and does not support multithreading),
but is asynchronous (parallel requests = multiprocessing)
Time Taken: 108.6s
** DELETE PREVIOUS CSV FILE BEFORE RUNNING AS SCRAPY APPENDS TO EXISTING FILE INSTEAD OF OVERWRITING **
'''
name = "yahoo_desc"
INDEX = 'russell'
NUM_INVALID_TICKERS = 0
INVALID_URLS = []
ticker_df = pd.read_csv('data_in/%s_tickers_df.csv' %INDEX)
tickers = ticker_df.Ticker
# start_url is scrapy naming convention, dont change
# (dont need to implement start_requests with this)
start_urls = ['https://finance.yahoo.com/quote/'+ticker+'/profile?p='+ticker
for ticker in tickers]
custom_settings = {
'LOG_LEVEL': logging.WARNING, # Scrapy logs alot of stuff at a lower setting
'FEEDS': {pathlib.Path('data_out/%s_desc_%s.csv' %(INDEX, name[:-5])): {'format': 'csv'}}, # When writing to this file, the additional scrapes will be appended not overwritten
'FEED_EXPORT_ENCODING': 'utf-8-sig' # not utf-8 so as to force csv to open in utf-8, if not will have wierd characters
}
@staticmethod
def get_ticker_from_url(url):
return url.split('=')[-1]
def parse(self, response):
url = response.request.url
ticker = self.get_ticker_from_url(url)
desc = response.xpath('//*[@id="Col1-0-Profile-Proxy"]/section/section[2]/p/text()').extract()
desc = [s.replace('\n', ' ') for s in desc]
sec = response.xpath('//*[@id="Col1-0-Profile-Proxy"]/section/div[1]/div/div/p[2]/span[2]/text()').extract()
ind = response.xpath('//*[@id="Col1-0-Profile-Proxy"]/section/div[1]/div/div/p[2]/span[4]/text()').extract()
if not sec:
self.NUM_INVALID_TICKERS +=1
self.INVALID_URLS.append(url)
print('SECTOR AND DESC MISSING: %s'%url)
elif not desc:
self.NUM_INVALID_TICKERS +=1
self.INVALID_URLS.append(url)
print('DESC MISSING: %s'%url)
else:
print('VALID: %s'%ticker)
yield {
'Ticker': ticker,
'Description': desc,
'Sector': sec,
'SubIndustry': ind
}
<file_sep>import pandas as pd
import scrapy
import logging
import pathlib
class BloombergDescSpider(scrapy.Spider):
'''
DOSENT WORK: Bloomberg has captcha
Script to scrape company description
Time Taken: -
** DELETE PREVIOUS CSV FILE BEFORE RUNNING AS SCRAPY APPENDS TO EXISTING FILE INSTEAD OF OVERWRITING **
'''
name = "bloomberg_desc"
INDEX = 'snp'
NUM_INVALID_TICKERS = 0
INVALID_URLS = []
ticker_df = pd.read_csv('data_in/%s_tickers_df.csv' %INDEX).head()
tickers = ticker_df.Ticker
# start_url is scrapy naming convention, dont change
# (dont need to implement start_requests with this)
start_urls = ['https://www.bloomberg.com/profile/company/'+ticker+':US'
for ticker in tickers]
custom_settings = {
'LOG_LEVEL': logging.WARNING, # Scrapy logs alot of stuff at a lower setting
'FEEDS': {pathlib.Path('data_out/%s_desc_%s.csv' %(INDEX, name[:-5])): {'format': 'csv'}}, # When writing to this file, the additional scrapes will be appended not overwritten
'FEED_EXPORT_ENCODING': 'utf-8-sig' # not utf-8 so as to force csv to open in utf-8, if not will have wierd characters
}
@staticmethod
def get_ticker_from_url(url):
return url.split('/')[-1][:-3]
def parse(self, response):
def evaluate(s, response):
# to return None if element cant be found
try:
return eval(s)
except:
return None
print(response.request.url)
ticker = self.get_ticker_from_url(response.request.url)
print(ticker)
yield {
'Ticker': ticker,
'Description': evaluate(
'''response.xpath('//*[@id="root"]/div/section/div[2]/section/section[1]/div/text()').extract()''', response)
}
<file_sep>aiohttp==3.7.2
argon2-cffi==20.1.0
async-generator==1.10
async-timeout==3.0.1
atomicwrites==1.4.0
attrs==20.3.0
backcall==0.2.0
beautifulsoup4==4.9.3
bleach==3.2.1
bs4==0.0.1
certifi==2020.11.8
cffi==1.14.3
chardet==3.0.4
click==7.1.2
colorama==0.4.4
cycler==0.10.0
Cython==0.29.14
dataframe-image==0.1.1
decorator==4.4.2
defusedxml==0.6.0
entrypoints==0.3
funcy==1.15
future==0.18.2
gensim==3.8.3
idna==2.10
idna-ssl==1.1.0
importlib-metadata==2.0.0
iniconfig==1.1.1
ipykernel==5.3.4
ipython==7.16.1
ipython-genutils==0.2.0
ipywidgets==7.5.1
jedi==0.17.2
Jinja2==2.11.2
joblib==0.17.0
jsonschema==3.2.0
jupyter-client==6.1.7
jupyter-core==4.6.3
jupyterlab-pygments==0.1.2
kiwisolver==1.3.1
lxml==4.6.1
MarkupSafe==1.1.1
matplotlib==3.3.2
mistune==0.8.4
multidict==5.0.0
multitasking==0.0.9
nbclient==0.5.1
nbconvert==6.0.7
nbformat==5.0.8
nest-asyncio==1.4.2
nltk==3.5
notebook==6.1.5
numexpr==2.7.1
numpy==1.19.3
packaging==20.4
pandas==1.1.4
pandocfilters==1.4.3
parso==0.7.1
pickleshare==0.7.5
Pillow==8.0.1
playsound==1.2.2
pluggy==0.13.1
prometheus-client==0.8.0
prompt-toolkit==3.0.8
py==1.9.0
pyclustering==0.10.0.1
pycparser==2.20
Pygments==2.7.2
pyLDAvis==2.1.2
pyparsing==2.4.7
pyrsistent==0.17.3
pytest==6.1.2
python-dateutil==2.8.1
pytz==2020.4
pywin32==228
pywinpty==0.5.7
pyzmq==19.0.2
regex==2020.10.28
requests==2.24.0
scikit-learn==0.23.2
scipy==1.5.4
seaborn==0.11.0
selenium==3.141.0
Send2Trash==1.5.0
six==1.15.0
sklearn==0.0
smart-open==3.0.0
soupsieve==2.0.1
tabula==1.0.5
terminado==0.9.1
testpath==0.4.4
threadpoolctl==2.1.0
toml==0.10.2
tornado==6.1
tqdm==4.51.0
traitlets==4.3.3
typing-extensions==3.7.4.3
urllib3==1.25.11
wcwidth==0.2.5
webencodings==0.5.1
widgetsnbextension==3.5.1
wikipedia==1.4.0
yarl==1.6.2
yfinance==0.1.55
zipp==3.4.0
<file_sep>import pandas as pd
import scrapy
import logging
import pathlib
class MorningStarDescSpider(scrapy.Spider):
'''
Script to scrape company description
Time Taken: 176.8s
** DELETE PREVIOUS CSV FILE BEFORE RUNNING AS SCRAPY APPENDS TO EXISTING FILE INSTEAD OF OVERWRITING **
Need to consider multiple exchanges for morning star scraping
'''
name = "morningstar_desc"
INDEX = 'snp'
NUM_INVALID_TICKERS = 0
INVALID_URLS = []
ticker_df = pd.read_csv('data_in/%s_tickers_df.csv' %INDEX)
tickers = ticker_df.Ticker.str.replace('-', '.')
# start_url is scrapy naming convention, dont change
# (dont need to implement start_requests with this)
# xnas - NASDAQ, xnys - NEW YORK STOCK EXCHANGE, bats - BATS GLOBAL MARKETS
start_urls = ['https://www.morningstar.com/stocks/xnas/'+ticker+'/quote'
for ticker in tickers]
# This variable ensures 404 pages are handled
handle_httpstatus_list = [404]
custom_settings = {
'LOG_LEVEL': logging.WARNING, # Scrapy logs alot of stuff at a lower setting
'FEEDS': {pathlib.Path('data_out/%s_desc_%s.csv' %(INDEX, name[:-5])): {'format': 'csv'}}, # When writing to this file, the additional scrapes will be appended not overwritten
'FEED_EXPORT_ENCODING': 'utf-8-sig' # not utf-8 so as to force csv to open in utf-8, if not will have wierd characters
}
@staticmethod
def get_ticker_from_url(url):
return url.split('/')[-2]
@staticmethod
def get_exchange_from_url(url):
return url.split('/')[-3]
def parse(self, response):
url = response.request.url
ticker = self.get_ticker_from_url(url)
exchange = self.get_exchange_from_url(url)
if response.status == 404:
if exchange == 'xnas':
new_url = 'https://www.morningstar.com/stocks/xnys/'+ticker+'/quote'
yield scrapy.Request(url=new_url, callback=self.parse)
elif exchange == 'xnys':
new_url = 'https://www.morningstar.com/stocks/bats/'+ticker+'/quote'
yield scrapy.Request(url=new_url, callback=self.parse)
else:
self.NUM_INVALID_TICKERS +=1
self.INVALID_URLS.append(url)
print('INVALID TICKER: %s'%url)
yield {
'Ticker': ticker,
'Description': None
}
if response.status == 200:
desc = response.xpath('//*[@id="__layout"]/div/div[2]/div[3]/main/div[2]/div/div/div[1]/div[1]/div/div[1]/p/text()').extract()
desc = [s.strip().replace('\n', ' ') for s in desc]
if desc == ['—']:
print('TICKER WITHOUT DESC: %s (%s)'%(url, exchange))
yield {
'Ticker': ticker,
'Description': None
}
else:
print('DONE: %s (%s)'%(ticker, exchange))
yield {
'Ticker': ticker,
'Description': desc
}
<file_sep>import pandas as pd
# df = pd.read_csv('data_out/yahoo_price.csv')
<file_sep>import pandas as pd
import scrapy
import logging
import pathlib
from datetime import datetime
class YahooPriceSpider(scrapy.Spider):
'''
Script to scrape company Price
Dont use this as this cant interact with the webpage
Time Takes: 230.9s
'''
name = "yahoo_price"
custom_settings = {
'LOG_LEVEL': logging.WARNING, # Scrapy logs alot of stuff at a lower setting
'FEEDS': {pathlib.Path('data_out/yahoo_price.csv'): {'format': 'csv'}}, # When writing to this file, the additional scrapes will be appended not overwritten
'FEED_EXPORT_ENCODING': 'utf-8-sig' # not utf-8 so as to force csv to open in utf-8, if not will have wierd characters
}
def start_requests(self):
# Not sure why but start_urls gives problems for this scrape
ticker_df = pd.read_csv('data_in/snp_tickers_df.csv')
tickers = ticker_df.Ticker
d1 = datetime.strptime('20200102', "%Y%m%d")
d2 = datetime.strptime('20200401', "%Y%m%d")
time_str1 = str(int(datetime.timestamp(d1)))
time_str2 = str(int(datetime.timestamp(d2)))
urls = ['https://finance.yahoo.com/quote/'+ ticker +'/history?period1='+time_str1+'&period2='+time_str2+'&interval=1d&filter=history&frequency=1d'
for ticker in tickers]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
@staticmethod
def get_ticker_from_url(url):
return url.split('/')[4]
def parse(self, response):
url = response.request.url
try:
ticker = self.get_ticker_from_url(url)
except:
# means url form changed to https://finance.yahoo.com/lookup?s=BDX
ticker = url.split('=')[-1]
print('BAD TICKER: %s' %ticker)
item = {'Ticker' : ticker}
yield item
print(ticker)
item = {'Ticker' : ticker}
prices = response.xpath('//*[@id="Col1-1-HistoricalDataTable-Proxy"]/section/div[2]/table/tbody/tr/td[5]//text()').extract()
for i in range(len(prices)):
item[i] = prices[i]
yield item
<file_sep>import pandas as pd
import scrapy
import logging
import pathlib
class ReutersDescSpider(scrapy.Spider):
'''
Script to scrape company description
Time Taken: 108.6s
** DELETE PREVIOUS CSV FILE BEFORE RUNNING AS SCRAPY APPENDS TO EXISTING FILE INSTEAD OF OVERWRITING **
'''
name = "reuters_desc"
INDEX = 'snp'
NUM_INVALID_TICKERS = 0
INVALID_URLS = []
ticker_df = pd.read_csv('data_in/%s_tickers_df.csv' %INDEX)
tickers = ticker_df.Ticker.str.replace('-', '')
# start_url is scrapy naming convention, dont change
# (dont need to implement start_requests with this)
start_urls = ['https://www.reuters.com/companies/'+ticker
for ticker in tickers]
custom_settings = {
'LOG_LEVEL': logging.WARNING, # Scrapy logs alot of stuff at a lower setting
'FEEDS': {pathlib.Path('data_out/%s_desc_%s.csv' %(INDEX, name[:-5])): {'format': 'csv'}}, # When writing to this file, the additional scrapes will be appended not overwritten
'FEED_EXPORT_ENCODING': 'utf-8-sig' # not utf-8 so as to force csv to open in utf-8, if not will have wierd characters
}
@staticmethod
def get_ticker_and_market_from_url(url):
s = url.split('/')[-1]
if '.' in s:
ticker, market = s.split('.')
else:
ticker, market = s, None
return ticker, market
def parse(self, response):
url = response.request.url
ticker, market = self.get_ticker_and_market_from_url(url)
desc = response.xpath('//*[@id="__next"]/div/div[4]/div[1]/div/div/div/div[4]/div[1]/p/text()').extract() or \
response.xpath('//*[@id="__next"]/div/div[4]/div[1]/div/div/div/div[3]/div[1]/p/text()').extract()
desc = [s.strip().replace('\n', ' ') for s in desc]
if desc:
print('VALID: %s (%s)'%(ticker, market))
yield {
'Ticker': ticker,
'Description': desc
}
elif not market:
# try NASDAQ
new_url = 'https://www.reuters.com/companies/'+ticker+'.OQ'
yield scrapy.Request(url=new_url, callback=self.parse)
elif market == 'OQ':
# try NEW YORK STOCK EXCHANGE
new_url = 'https://www.reuters.com/companies/'+ticker+'.N'
yield scrapy.Request(url=new_url, callback=self.parse)
else:
self.NUM_INVALID_TICKERS +=1
self.INVALID_URLS.append([ticker, url])
print('INVALID TICKER: %s'%url)
yield {
'Ticker': ticker,
'Description': None
}
<file_sep># Text-based Industry Classification
The goal of this project is to use NLP techniques to classify companies according to their descriptions and compare it with the current industry standard, Global Industry Classification Standard (GICS). The SnP500 and Russell 3000 Indexes are specifically studied in this project. Several Sources of description, topic modelling techniques, clustering techniques are used as listed:
* Descriptions used:
1. EDGAR 10-K reports (from 2020 and 2015)
1. Yahoo Finance
1. Wikipedia
1. Morning Star
1. Reuters
1. Reuters India
1. Bloomberg
* Topic Modelling Techniques:
1. Latent Semantic Indexing (LSI)
1. Latent Dirichlet Allocation (LDA)
1. Non Negative Matrix Factorization (NMF)
1. Principal Component Analysis (PCA)
* Clustering Techniques
1. K-means
1. K-medioids
1. Gaussian Mixture Model
1. Hierarchical Clustering
## Results
### Main Results
1. Text-based Industry Classification has comparable performance to standard GICS Industry classification
* Training on Russell 3000 stock business descriptions, best model performs 0.8% better than GICS R2 score (0.305) (Fig 1)
* Even though it may not be significant, we know that it at least is perform as good as GICS classification, since model is able to cosistently able to perform in a +-1% range of the GICS R2 score for topic sizes from 100-250 (Fig 1)
* Also, Ratio Variation (RV) scores are better in ratios: profit margin, ROA and ROE, but slightly worse in pb_ratio and beta. But all percentage differences are in a band of 10%, and we conclude that Text-based Industry Classification is able to perform as well as GICS (Fig 2)
||
|:--:|
| *Figure 1* |
||
|:--:|
| *Figure 2* |
1. Text-based Industry Classification performs better for lower market-cap stocks compared to high market-cap stocks relative to GICS Industry classification
* When filtering classification of Russell 3000 stocks to 2 sections: SnP500 stocks (approximately top 500 capitalisation stocks) and Russell2 stocks (which we difine as the bottom 500 market capitalisation stocks in Russell 3000), and evluating we get the following results
* Note: we dont train on sub-universe index individually to reduce bias
* For SnP500, best model performs 1.5% better than the GICS R2 score (0.449) (Fig 3)
* For Russell2, best model performs 4.0% better than the GICS R2 score (0.131) (Fig 5)
* In terms of RV score, the percentage change relative to GICS score for all ratios are in a margin of 5% within each other for both Snp and Russell2 (Fig 4&6)
* Given that the R2 is a stronger metric of industry classification, we conclude that text-based industry classification performs better for lower market-cap stocks compared to high market-cap stocks relative to GICS Industry classification
* This may be due to classification of smaller companies not being updated frequently
||
|:--:|
| *Figure 3* |
||
|:--:|
| *Figure 4* |
||
|:--:|
| *Figure 5* |
||
|:--:|
| *Figure 6* |
1. Similarity of Text-based Industry Classification to GICS
* Generally the similarity to GICS is about 50% (Fig 9)
* Fig 7 shows the Similarity probability of each GICS industry to the classification model with best R2 score output trained on Russell 3000 tickers
* We see that Utilities generally are able to be classified well
||
|:--:|
| *Figure 7* |
### Minor Results
1. Data Sources which are most informative about classification based on the order of R2 metrics are (Fig 8):
1. 10-K report Business Description
1. Reuters India
1. Yahoo (worst wiki)
* Its noteworthy that 10-K reports from 2015 and 2020 do not show a significant difference in R2 scores
||
|:--:|
| *Figure 8 : Run again...maybe cos unnormlalised?* |
1. For more general classifications, Text-based Classification performs worse than the GICS standard
* For Russell 3000 with sector classification, best model performs 2.22% worse than GICS Sector R2 (0.266) (Fig 9)
||
|:--:|
| *Figure 9: Russell Classification by Sector* |
1. Topic modelling
* LSI and PCA are the techniques which produce better R2 performance compared to NMF and LDA (Fig 10)
* Usually num_topics in the range [50, 200] gives best R2 results (Fig 10)
* Interestingly, LDA classifications are more similar to GICS, although it performs the worse in terms of R2 (Fig 11)
||
|:--:|
| *Figure 10* |
||
|:--:|
| *Figure 11* |
1. Clustering Algo
* Agglomerative Clustering seems to constantly perform well, followed by K-means and GMM (Fig 10)
* K-Medioids consistantly does not perform well (Fig 10)
1. Pre-processing
* Normalising (samplewise L2 scaling) or using the raw DTM after topic modelling does not cause a significat difference in R2 scores
* Best model for Russell was 0.29% and 0.80% better than GICS respectively
* Standardizing is gives poor results
* Best model for Russell was 0.21% worse than GICS
## Usage
### Viewing/Running Text-based Industry Classification
1. Install requirements for project using:
```
pip install -r requirements.txt
```
2. Refer to **LSI Word Embedding.ipynb**
* Set variables under *Global Vars* section according to preference
* Some data is not available on github as files are too big (eg. 10K reports and other business descriptions). Method to retrive them is detailed below
### Data Extraction and Cleaning
This section shows how to extract and clean data used for this project
* 2,3,4 : Data to extract which is not included
* 5,6 : Not compulsory
* 1,7 : Data is included
1. Extract Index Tickers
* Refer to **Data Extraction and Cleaning.ipynb** under header *Scrape Index Tickers*
* This set of tickers will be used when scraping business descriptions from the various sources
1. Extract 10-K Reports
* Clone [SEC-EDGAR-text](https://github.com/alions7000/SEC-EDGAR-text) project
* Modify **document_group_section_search.json** file to only include Section 1A parts of 10-K filings (simply delete all other parts of JSON file)
* Run program using:
```
python SEC-EDGAR-text
```
* With default settings, this outputs 10K filings of SnP500 companies from current date to one year prior. Filter from output (`output_files_examples/batch_xx/`) all filenames ending with `excerpt.txt` (using OS search functionality)(should be slightly less than half the total files) and transfer all these .txt files into `data_out/10-K/XX` folder in this project
* Start and end date can be adjusted when program is run (as done in this project for 2015 and 2020 reports)
* For this project, reports are scraped for a 1 year timeframe (to get data from as many companies as possible) and then filter the latest filing for each company (this filtering is done in the next step)
* Note that SnP500 ticker list used by the project can be outdated, so follow this procedure to extract data for a specific set of tickers (i.e. latest set of SnP/Russell Tickers):
* Run code section in **Data Extraction and Cleaning.ipynb** under header *Scrape Ticker CIKs*, copy output (`data_out/scrapping_ticker_ciks.txt`) to companies_list.txt file in SEC-EDGAR-text project, and run it. Transfer filtered output to a new folder (e.g. `data_out/10-K/Russell/`)
* Takes ~ 8hrs to run for Russell tickers
* After `data_out/10-K/(index_name)/` folder has been populated, run code section in **Data Extraction and Cleaning.ipynb** under header *Merge 10K reports* (setting input and output folder and files accordingly)
1. Scrape Business Descriptions from multiple web-sources
* Scrapy Framework used due to its much faster performance than other scraping tools (like selenium)
* Business Description Sources:
* Yahoo Finance
* Business Insider
* Morning Star
* Reuters
* Reuters India
* Bloomberg
* Ensure that you have saved the required index tickers into `scrapy_spiders/data_in/` folder by following step 1
* `cd` to `scrapy_spiders/` folder and run spider for required data source with:
```
scrapy crawl XXX_desc
```
where XXX is either yahoo, businessinsider, morningstar, reuters, reutersindia or csimarket
* This populates `scrapy_spiders/data_out/` folder with a .csv file of scraped descriptions
* If .csv file you are writing to exists, delete before re-running (as Scrapy appends to files instead of overwriting if the file to write to exists)
* Edit `INDEX` parameter each spider accordingly to scrape data from respective index (e.g. snp, russell)
* Note that xpaths of descriptions and other scraping information change frequently (due to change in format of website of the scraping site), so do ensure that you are retrieving the right information, else edit scrapy script accordingly (usually just need to change xpath)
* Note: Although spiders are saved in directory `scrapy_spiders/yahoo_spiders/` the subfolder yahoo_spiders does not mean only yahoo spiders are in the directory (directory name is left unchanged as it was initialted as such and is difficult to rename now)
1. Extract Wikipedia Descriptions
* Refer to **Data Extraction and Cleaning.ipynb** under header *Scrape Wikipedia description*
1. Extract [Yahoo Finance](https://sg.finance.yahoo.com/) Descriptions (Method 2)
* Refer to **Data Extraction and Cleaning.ipynb** under header *Scrape Yahoo Description, Price, Ratios*
* This script mainly uses selenium (some parts use yfinance) and thus takes a long time, so it is better to use the scrapy framework
* Download chromedriver.exe [here](https://chromedriver.chromium.org/downloads) and put driver in project folder
1. Scrape Yahoo Prices and Market Ratios
* Similar to above procedure, but with the commands:
```
scrapy crawl yahoo_price
scrapy crawl yahoo_ratios
```
* This method is better than scrapy method as we are able to adjust start_date and end_date to longer periods (thanks to seleniums interactivity)
1. Other Data Extraction and Cleaning processes (Refer to **Data Extraction and Cleaning.ipynb** for details)
* Scrape GICS industry code to name map
* Clean Ticker to GICS map
* Clean Market Ratios
## Data used and Sources (in `data_in/` folder or APIs used or websites scraped)
* Company Business Description Data (MSFT is used as example in all the links)
* [Yahoo](https://sg.finance.yahoo.com/quote/MSFT/profile?p=MSFT)
* [Business Insider](https://markets.businessinsider.com/stocks/msft-stock)
* [CNN](https://money.cnn.com/quote/profile/profile.html?symb=MSFT)
* Same description as Business Insider
* [Morning Star](https://www.morningstar.com/stocks/xnas/msft/quote)
* [Reuters](https://www.reuters.com/companies/MSFT.O)
* [Investing.com](https://www.investing.com/equities/microsoft-corp-company-profile)
* Same description as Reuters
* [Reuters India](https://in.reuters.com/finance/stocks/company-profile/MSFT.DF)
* Medium length descriptions
* [CSIMarket.com](https://csimarket.com/stocks/amzn-Business-Description.html)
* Descriptions used are probably from 10K report
* About 30% tickers do not have business description
* [Bloomberg](https://www.bloomberg.com/profile/company/MSFT:US)
* Unable to scrape as it has captcha
* russell_price.csv
* price of all tickers in Russell 3000 index from Jan 2015 to May 2020 (from past project)
* russell_ratio.csv
* 6 ratios (mkt_cap, pb_ratio, beta, profit_m, roa, roe) of all Russell 3000 index companies
* from past project
* Russell3000.pdf
* list of all comanies in Russell 3000, updated 31 Mar 2020, however ticker name not provided
* from [FTSE Russell](https://www.ftserussell.com/analytics/factsheets/home/constituentsweights)
* list Russell 3000 tickers
* from 3rd party source but claims last updated on 21 Sep 2020
* http://www.kibot.com/Historical_Data/Russell_3000_Historical_Intraday_Data.aspx
* list of STI tickers
* https://en.wikipedia.org/wiki/Straits_Times_Index
* list of SnP tickers
* http://en.wikipedia.org/wiki/List_of_S%26P_500_companies
* Ticker-CIK map
* https://www.sec.gov/include/ticker.txt
* ticker_to_gics.csv
* ticker-GICS map for all tickers in Russell 3000
* from prof (also found in past project)
* GICS classification of SnP stocks
* from bloomberg (from prof)
* Stop Words List (for financial use)
* https://sraf.nd.edu/textual-analysis/resources/#StopWords
Explored but not used (might be useful)
* API for CIK to ticker mapping
* https://medium.com/@jan_5421/cik-to-ticker-mapping-bb22194b5cc0
* cik_ticker.csv
* cik-ticker map for 13000+ tickers<file_sep>import pandas as pd
import scrapy
import logging
import pathlib
class ReutersIndiaDescSpider(scrapy.Spider):
'''
Script to scrape company description
Time Taken: 108.6s
** DELETE PREVIOUS CSV FILE BEFORE RUNNING AS SCRAPY APPENDS TO EXISTING FILE INSTEAD OF OVERWRITING **
- website autochanges url according to exchange
'''
name = "reutersindia_desc"
INDEX = 'snp'
NUM_INVALID_TICKERS = 0
INVALID_URLS = []
ticker_df = pd.read_csv('data_in/%s_tickers_df.csv' %INDEX)
tickers = ticker_df.Ticker.str.replace('-', '')
# start_url is scrapy naming convention, dont change
# (dont need to implement start_requests with this)
start_urls = ['https://in.reuters.com/finance/stocks/company-profile/'+ticker
for ticker in tickers]
custom_settings = {
'LOG_LEVEL': logging.WARNING, # Scrapy logs alot of stuff at a lower setting
'FEEDS': {pathlib.Path('data_out/%s_desc_%s.csv' %(INDEX, name[:-5])): {'format': 'csv'}}, # When writing to this file, the additional scrapes will be appended not overwritten
'FEED_EXPORT_ENCODING': 'utf-8-sig' # not utf-8 so as to force csv to open in utf-8, if not will have wierd characters
}
@staticmethod
def get_ticker_and_market_from_url(url):
if 'lookup?' in url: #invalid search
s = url.split('=')[-1]
ticker, market = s, None
else:
s = url.split('/')[-1]
if '.' in s:
ticker, market = s.split('.')
else:
ticker, market = s, None
return ticker, market
def parse(self, response):
url = response.request.url
ticker, market = self.get_ticker_and_market_from_url(url)
desc = response.xpath('//*[@id="companyNews"]/div/div[2]/p/text()').extract()
if not desc:
desc = response.xpath('//*[@id="companyNews"]/div/div[2]/text()').extract()
if len(desc)>0 and desc[0].strip() == 'NA':
desc = []
desc = [s.replace('\n', ' ') for s in desc]
if (ticker == 'WTTR' and market == 'N'): # not sure why but this symbol gets repeated
pass
elif desc:
print('VALID: %s (%s)'%(ticker, market))
if market and len(market)>3:
print('----------------------------------------------------------------------------------')
print(url)
yield {
'Ticker': ticker,
'Description': desc # note that desc is a list but it is concatenated when put in csv
}
else:
desc = response.xpath('//*[@id="companyNews"]/div/div[2]/text()').extract()
self.NUM_INVALID_TICKERS +=1
self.INVALID_URLS.append(url)
print('INVALID TICKER: %s'%url)
yield {
'Ticker': ticker,
'Description': None # note that desc is a list but it is concatenated when put in csv
}
<file_sep># Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
# from itemadapter import ItemAdapter
from scrapy.exporters import CsvItemExporter
import time
class YahooSpidersPipeline:
'''
Adds Timer
'''
def process_item(self, item, spider):
return item
def open_spider(self, spider):
self.start = time.time()
print('START TIME: %s' %self.start)
def close_spider(self, spider):
if hasattr(spider, 'NUM_INVALID_TICKERS'):
print('NUM_INVALID_TICKERS: %s'%spider.NUM_INVALID_TICKERS)
if hasattr(spider, 'INVALID_URLS'):
[print(url) for url in spider.INVALID_URLS]
self.end = time.time()
print('END TIME: %s' %self.end)
diff = self.end - self.start
print('TOTAL TIME: %s' %diff)
class YahooSpidersPipeline2:
'''
Currently not used.Everything is done in spider files
'''
def __init__(self):
# self.filename = 'pages.csv'
pass
def open_spider(self, spider):
self.filename = 'data_out/%s.csv' %spider.name
self.csvfile = open(self.filename, 'wb')
self.exporter = CsvItemExporter(self.csvfile, include_headers_line=True)
self.exporter.start_exporting()
def close_spider(self, spider):
self.exporter.finish_exporting()
self.csvfile.close()
def process_item(self, item, spider):
if spider.name == 'yahoo_price':
new_item = {'Ticker' : item['Ticker']}
i = 0
for price in item['Prices']:
new_item[i] = price
i += 1
self.exporter.export_item(new_item)
print(new_item)
return new_item
else:
self.exporter.export_item(item)
return item<file_sep>import pandas as pd
import scrapy
import logging
import pathlib
class YahooDescSpider(scrapy.Spider):
'''
Script to scrape company description
Note that scrapes are done in parallel so order is not guaranteed
Scrapy is a single-threaded framework (and does not support multithreading),
but is asynchronous (parallel requests = multiprocessing)
Time Taken: 102.2
'''
name = "yahoo_ratios"
ticker_df = pd.read_csv('data_in/snp_tickers_df.csv')
tickers = ticker_df.Ticker
# symbols = ['MMM', 'ABT']
# start_url is scrapy naming convention, dont change
# (dont need to implement start_requests with this)
start_urls = ['https://finance.yahoo.com/quote/'+ticker+'/key-statistics?p='+ticker
for ticker in tickers]
custom_settings = {
'LOG_LEVEL': logging.WARNING, # Scrapy logs alot of stuff at a lower setting
'FEEDS': {pathlib.Path('data_out/yahoo_ratios.csv'): {'format': 'csv'}}, # When writing to this file, the additional scrapes will be appended not overwritten
'FEED_EXPORT_ENCODING': 'utf-8-sig' # not utf-8 so as to force csv to open in utf-8, if not will have wierd characters
}
@staticmethod
def get_ticker_from_url(url):
return url.split('=')[-1]
def parse(self, response):
ticker = self.get_ticker_from_url(response.request.url)
print(ticker)
yield {
'Ticker': ticker,
'mkt_cap' : response.xpath('//*[@id="Col1-0-KeyStatistics-Proxy"]/section/div[3]/div[1]/div[2]/div/div[1]/div[1]/table/tbody/tr[1]/td[3]//text()').extract(),
'pb_ratio' : response.xpath('//*[@id="Col1-0-KeyStatistics-Proxy"]/section/div[3]/div[1]/div[2]/div/div[1]/div[1]/table/tbody/tr[7]/td[3]//text()').extract(),
'beta' : response.xpath('//*[@id="Col1-0-KeyStatistics-Proxy"]/section/div[3]/div[2]/div/div[1]/div/div/table/tbody/tr[1]/td[2]//text()').extract(),
'profit_margin' : response.xpath('//*[@id="Col1-0-KeyStatistics-Proxy"]/section/div[3]/div[3]/div/div[2]/div/div/table/tbody/tr[1]/td[2]//text()').extract(),
'roa' : response.xpath('//*[@id="Col1-0-KeyStatistics-Proxy"]/section/div[3]/div[3]/div/div[3]/div/div/table/tbody/tr[1]/td[2]//text()').extract(),
'roe' : response.xpath('//*[@id="Col1-0-KeyStatistics-Proxy"]/section/div[3]/div[3]/div/div[3]/div/div/table/tbody/tr[2]/td[2]//text()').extract()
}
<file_sep>import pandas as pd
import scrapy
import logging
import pathlib
class CsimarketDescSpider(scrapy.Spider):
'''
Script to scrape company description
Time Taken: 108.6s
** DELETE PREVIOUS CSV FILE BEFORE RUNNING AS SCRAPY APPENDS TO EXISTING FILE INSTEAD OF OVERWRITING **
- website autochanges url according to exchange
- missing information for many tickers
'''
name = "csimarket_desc"
INDEX = 'russell'
NUM_INVALID_TICKERS = 0
INVALID_URLS = []
# start_url is scrapy naming convention, dont change
# (dont need to implement start_requests with this)
# start_urls =
custom_settings = {
'LOG_LEVEL': logging.WARNING, # Scrapy logs alot of stuff at a lower setting
'FEEDS': {pathlib.Path('data_out/%s_desc_%s.csv' %(INDEX, name[:-5])): {'format': 'csv'}}, # When writing to this file, the additional scrapes will be appended not overwritten
'FEED_EXPORT_ENCODING': 'utf-8-sig' # not utf-8 so as to force csv to open in utf-8, if not will have wierd characters
}
def start_requests(self):
ticker_df = pd.read_csv('data_in/%s_tickers_df.csv' %self.INDEX)
tickers = ticker_df.Ticker.str.replace('-', '')
# do it this way as the urls change for invalid tickers, making it impossible to get back the ticker from the url
for ticker in tickers:
url = 'https://csimarket.com/stocks/'+ticker+'-Business-Description.html'
yield scrapy.Request(url=url, meta={'ticker':ticker}, callback=self.parse)
def parse(self, response):
url = response.request.url
ticker = response.meta['ticker']# self.get_ticker_from_url(url)
desc = response.xpath('//*[@id="glavno_polje"]/table[3]/tr/td[1]/div/p/text() | //*[@id="glavno_polje"]/table[3]/tr/td[1]/div/text()').extract()
desc = [s.strip().replace('\n', ' ') for s in desc]
if desc:
print('VALID: %s'%ticker)
yield {
'Ticker': ticker,
'Description': desc # note that desc is a list but it is concatenated when put in csv
}
else:
self.NUM_INVALID_TICKERS +=1
self.INVALID_URLS.append([ticker, url])
print('INVALID TICKER: %s'%ticker, url)
yield {
'Ticker': ticker,
'Description': None # note that desc is a list but it is concatenated when put in csv
}
|
15cb08ed00d3151b006c79cef7fbaa939ef6c06c
|
[
"Markdown",
"Text",
"Python"
] | 12 |
Markdown
|
Sivalavida/Text-based-Industry-Classification
|
eea37c5c2cb60256e61c357eadbd3a8a66546320
|
3d27f0165e96dda0c70357c4f23bcdb85c1ad660
|
refs/heads/master
|
<file_sep>import json
from pathlib import Path
import tldextract
from tqdm import tqdm
import numpy as np
import h5py
from collections import Counter
from utils.helper import iter_partitions
def store_labels(model_path, labels_dict, override=False):
"""
model_path (Path) - model folder path
labels_dict (dict) - labels stored in dict
"""
for i, value in enumerate(iter_partitions(model_path)):
partition, count = value
print("Partition: {}..".format(i))
labels = np.zeros(count, dtype=int)
links = model_path / "entity_names_link_{}.json".format(i)
with open(links, "rt") as tf:
entities_list = json.load(tf)
for pos, value in enumerate(tqdm(entities_list)):
labels[pos] = labels_dict[int(value)]
# save labels vector
# TODO: infer the CORRECT name of embeddings
h5_path = model_path / 'embeddings_link_{}.v50.h5'.format(i)
try:
h5f = h5py.File(h5_path, 'a')
h5f.create_dataset('labels', data=labels, dtype=int)
except RuntimeError:
print("Labels already stored!")
if override:
print("Overwriting new labels..")
h5f = h5py.File(h5_path, 'r+')
data = h5f['labels']
data[...] = labels
h5f.close()
def assign_labels(basename, data_folder=Path("/data"), verbose=False):
"""
Function to assign labels to nodes in {basename} based on the url domain.
Input:
basename (str)
data_folder (Path)
verbose (bool)
"""
urls_path = data_folder / "graphs" / basename / (basename + ".urls")
assert urls_path.exists(), "Urls file not found!"
# check if labels dict already existing
labels_path = data_folder / "models" / basename / ("labels.json")
if labels_path.exists():
print("Labels json already existing.")
else:
print("Building labels json..")
# count number of lines in file
num_lines = sum(1 for line in urls_path.open())
labels_array = [0] * num_lines
with urls_path.open() as f:
clusters_count = Counter()
labels = dict()
class_index = 0
for pos, line in enumerate(tqdm(f, total=num_lines)):
# extract the TLD
complete_domain = tldextract.extract(line).suffix
# we only need the country domain now
domain = complete_domain.split(".")[-1]
# if domain unseen add it to class indices
if domain not in labels:
class_index += 1
labels[domain] = class_index
# assign label and add it to array
y = labels[domain]
labels_array[pos] = y
clusters_count[domain] += 1
labels_data = dict()
# labels_data['labels'] = labels # do we really need this?
labels_data['labels'] = {int(v): k for k, v in labels.items()}
labels_data['count'] = clusters_count
labels_data['array'] = labels_array
if verbose:
print("Found following labels:")
print(labels)
with open(labels_path, 'w', encoding='utf-8') as outfile:
json.dump(labels_data, outfile, ensure_ascii=False, indent=4)
return labels_path
def main(basename):
"""
TODO: add argparse
"""
model = Path("/data/models") / basename
# retrieve labels
print("Assigning labels..")
labels_path = assign_labels(basename, data_folder=Path("/data"),
verbose=True)
with labels_path.open() as f:
labels = json.load(f)
# save labels in h5 embedding files
print("Associating labels to embeddings..")
store_labels(model, labels["array"], override=True)
if __name__ == "__main__":
basename = "indochina-2004"
main(basename)
<file_sep>import numpy as np
import faiss
import json
import argparse
from pathlib import Path
from utils.helper import load_data, iter_partitions, train_search
from sklearn import metrics
from sklearn.cluster import KMeans
from check_result import check
def bench_k_means(estimator, name, data, labels):
estimator.fit(data)
print(name)
print("homogeneity score: {}".format(
metrics.homogeneity_score(labels, estimator.labels_)))
print("completeness score: {}".format(
metrics.completeness_score(labels, estimator.labels_)))
print("v measure score: {}".format(
metrics.v_measure_score(labels, estimator.labels_)))
print("adjusted rand score: {}".format(
metrics.adjusted_rand_score(labels, estimator.labels_)))
print("adjusted mutual info score: {}".format(
metrics.adjusted_mutual_info_score(labels, estimator.labels_),
average_method='arithmetic'))
print("silhouette score: {}".format(
metrics.silhouette_score(data, estimator.labels_,
metric='euclidean',
sample_size=300)))
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Use Kmeans on given graph embeddings.')
parser.add_argument('-b', '--basename', type=str, default='indochina-2004',
help='name of the graph to use')
parser.add_argument('-n', type=int, default=5,
help='number of centroids')
parser.add_argument('-it', type=int, default=50,
help="number of iterations")
parser.add_argument('-v', "--verbose", default=True,
help="verbosity")
parser.add_argument("-k", "--knearest", type=int, default=20,
help="k centroids nearest neighbours")
args = parser.parse_args()
basename = args.basename
ncentroids = args.n
niter = args.it
verbose = args.verbose
k = args.knearest
model_path = Path("/data/models") / basename
print("Loading data..")
X, Y = load_data(model_path)
classes = len(np.unique(Y))
print("X shape: {}".format(X.shape))
print("{} classes.".format(classes))
score = metrics.silhouette_score(X, Y, metric='euclidean',
sample_size=1000)
print("silhouette_score: {}".format(score))
print("")
d = X.shape[1]
kmeans = faiss.Kmeans(d, ncentroids, niter=niter, verbose=verbose)
kmeans.train(X)
# algo = KMeans(init='k-means++', n_clusters=classes, n_init=10,
# max_iter=1000)
# bench_k_means(algo, "k-means++", X, Y)
# print("")
# algo = KMeans(init='random', n_clusters=classes, n_init=10,
# max_iter=1000)
# bench_k_means(algo, "random", X, Y)
entities_list = []
for json_f, _ in iter_partitions(model_path, names=True):
with open(json_f, "rt") as f:
entities = json.load(f)
entities_list += [i for i in entities]
urls_file = Path('/data/graphs/', basename, (basename + '.urls'))
idx = train_search(X)
check(kmeans.centroids, k, X, idx, urls_file.as_posix(), entities_list)
<file_sep>import random
import attr
import argparse
from pathlib import Path
from torchbiggraph.converters.import_from_tsv import convert_input_data
from torchbiggraph.config import add_to_sys_path, ConfigFileLoader
from torchbiggraph.eval import do_eval
from torchbiggraph.train import train
from torchbiggraph.util import (
set_logging_verbosity,
setup_logging,
SubprocessInitializer,
)
def random_split_file(fpath, train_frac=0.9, shuffle=False):
train_file = fpath.parent / 'train.txt'
test_file = fpath.parent / 'test.txt'
if train_file.exists() and test_file.exists():
print("Found some files that indicate that the input data "
"has already been shuffled and split, not doing it again.")
print("These files are: {} and {}".format(
train_file, test_file))
else:
print('Shuffling and splitting train/test file. \
This may take a while.')
print("Reading data from file: {}".format(fpath))
with fpath.open("rt") as in_tf:
lines = in_tf.readlines()
if shuffle:
print('Shuffling data')
random.shuffle(lines)
split_len = int(len(lines) * train_frac)
print('Splitting to train and test files')
with train_file.open("wt") as out_tf_train:
for line in lines[:split_len]:
out_tf_train.write(line)
with test_file.open("wt") as out_tf_test:
for line in lines[split_len:]:
out_tf_test.write(line)
return train_file, test_file
def run_train_eval(data_dir, config_path, basename, eval_=False):
tab_graph = data_dir / basename / (basename + '.tab')
assert tab_graph.exists(), "graph tab file not found."
train_f, test_f = random_split_file(tab_graph)
loader = ConfigFileLoader()
config = loader.load_config(config_path, None)
set_logging_verbosity(config.verbose)
subprocess_init = SubprocessInitializer()
subprocess_init.register(setup_logging, config.verbose)
subprocess_init.register(add_to_sys_path, loader.config_dir.name)
input_edge_paths = [train_f, test_f]
output_train_path, output_test_path = config.edge_paths
convert_input_data(
config.entities,
config.relations,
config.entity_path,
config.edge_paths,
input_edge_paths,
lhs_col=0,
rhs_col=1,
rel_col=None,
dynamic_relations=False,
)
# update the config edge_paths and train
train_config = attr.evolve(config, edge_paths=[output_train_path])
train(train_config, subprocess_init=subprocess_init)
print("Trained!")
if eval_:
relations = [attr.evolve(r, all_negs=True) for r in config.relations]
eval_config = attr.evolve(
config, edge_paths=[output_test_path],
relations=relations,
num_uniform_negs=0)
do_eval(eval_config, subprocess_init=subprocess_init)
def main():
setup_logging()
parser = argparse.ArgumentParser(
description='Generate embeddings on given graph.')
parser.add_argument('--data_dir', type=Path, default='/data/graphs',
help='where to find data')
parser.add_argument('--basename', type=str, default='cnr-2000',
help='name of the graph to use')
args = parser.parse_args()
basename = args.basename
config_path = Path("config") / (basename + ".py")
data_dir = args.data_dir
run_train_eval(data_dir, config_path, basename, eval_=True)
if __name__ == "__main__":
main()
<file_sep>import numpy as np
import argparse
from utils.data_utils import *
from utils.faiss_utils import train_search
from tqdm import tqdm
def load_XY(basename):
"""
Load embeddings (X) and possibly the
labels (Y) of the graph {basename}.
"""
model_path = Path("/data/models") / basename
print("Loading data..")
X, Y = load_data(model_path)
classes = len(np.unique(Y))
print("X shape: {}".format(X.shape))
print("{} classes".format(classes))
return X, Y
def precision_score(node_ranking, neighs):
"""
Compute the precision score as explained in
https://dawn.cs.stanford.edu/2018/03/19/hyperbolics/
Input:
- node_ranking (np.array)
- neighs (list)
Output:
- precision score (float)
"""
# note: positions starting from 1 --> add 1
neighs_ranks = np.in1d(node_ranking, neighs).nonzero()[0] + 1
neighs_card = np.arange(len(neighs_ranks)) + 1
node_score = neighs_card / neighs_ranks
return node_score.sum() / len(neighs)
def map_score(X, nodes, ind, neigh_num=50):
"""
Compute the map score of the given embedding.
If the number of neighbours of the current node
is bigger than the one given as input, returns
the current node as an outlier.
Input:
- X (np.array), embeddings
- nodes (list[list]), neighbours of each node
- ind (faiss index), index used to compute L2
distances for the embeddings
- neigh_num (int), number of neighbours considered
Output:
- score (float), map score
- outliers (list)
- singleton, number of singleton nodes
"""
outliers = []
score = 0
singleton = 0
_, ranking = ind.search(X, neigh_num)
for node, neighs in enumerate(nodes):
Na = len(neighs)
if Na == 0:
singleton += 1
elif Na > neigh_num // 2:
outliers.append(node)
else:
# start from index=1 to not consider the node itself
Ra = ranking[node, 1:]
score += precision_score(Ra, neighs)
return score, outliers, singleton
def dataset_map(X, out_nodes, neighs=50):
"""
Compute the MAP score on all the embeddings
given as input.
"""
ind = train_search(X)
if len(X) > 10000:
n = 10000
iters = len(X) // n
splits = np.array_split(X, iters)
out_node_split = np.array_split(out_nodes, iters)
else:
iters = 1
splits = X
out_node_split = out_nodes
score = 0
singleton = 0
for data, nodes in tqdm(zip(splits, out_node_split), total=iters):
split_score, outliers, sing = map_score(
data, nodes, ind, neigh_num=neighs)
singleton += sing
score += split_score
while len(outliers) > 0:
neighs *= 2
split_score, outliers, _ = map_score(
data[outliers], nodes[outliers], ind, neigh_num=neighs)
score += split_score
return score / (len(X) - singleton)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Measure mean average precision of produced embeddings.')
parser.add_argument('-b', '--basename', type=str, default='indochina-2004',
help='name of the graph to use')
args = parser.parse_args()
basename = args.basename
embeddings = load_XY(basename)
X = embeddings[0]
ent_list = get_entities_list(basename)
ent_list = np.array(ent_list)
perm = np.argsort(ent_list)
X = X[perm]
out_nodes = nodes_from_ascii(basename)
out_nodes = [out_nodes[i] for i in ent_list[perm]]
assert len(X) == len(out_nodes)
ind = train_search(X)
score = dataset_map(X, out_nodes)
print("MAP score on {}: {}".format(basename, score))
<file_sep>import json
import h5py
import numpy as np
from pathlib import Path
from tqdm import trange
def iter_embeddings(model_path, h5=True):
"""
updated version of iter_partitions
NOTICE: returns objects NOT ordered
"""
temp = []
if h5:
for h5_file in model_path.glob('embeddings_link*.h5'):
temp.append(h5_file)
else:
for json_file in model_path.glob('entity_names_link_*.json'):
temp.append(json_file)
temp = sorted(temp)
for i in temp:
yield i
def load_data(model_path):
"""
Load data saved in model_path.
Input:
- model_path (Path)
Output:
- X (np.array), embeddings
- Y (np.array), labels (if possible)
otherwise array of zeros.
"""
x_arrays = []
y_arrays = []
for partition in iter_embeddings(model_path):
h5f = h5py.File(partition, 'r')
X = h5f["embeddings"][:]
x_arrays.append(X)
try:
Y = h5f["labels"][:]
y_arrays.append(Y)
except KeyError:
print("Labels not defined")
if len(y_arrays) > 0:
X = np.vstack(x_arrays)
Y = np.hstack(y_arrays)
return X, Y
else:
X = np.vstack(x_arrays)
Y = np.zeros(len(X))
return X, Y
def get_entities_list(basename):
entities_list = []
model_path = Path("/data/models") / basename
for json_f in iter_embeddings(model_path, h5=False):
with json_f.open() as f:
entities = json.load(f)
entities_list += [int(i) for i in entities]
return entities_list
def nodes_from_ascii(basename, in_nodes=False):
"""
Read nodes from ascii file.
Input:
- basename (str), name of the graph
- in_nodes (bool), if True return in_nodes
Output:
nodes (list), list of out_nodes
(in_nodes) if in_nodes=True
"""
ascii_path = Path("/data/graphs") / basename / ("ascii.graph-txt")
assert ascii_path.exists(), "Graph not found!"
with ascii_path.open() as f:
line = f.readline()
V = int(line.split()[0])
print("{} vertices".format(V))
print("reading..")
nodes = [list() for i in range(V)]
singleton = 0
for i in trange(V):
line = f.readline()
if line[0] == "\n":
singleton += 1
else:
if in_nodes:
for node in line.split():
nodes[int(node)].append(i)
else:
nodes[i] = [int(j) for j in line.split()]
print("Found {} singleton nodes".format(singleton))
return nodes
def edges_from_ascii(basename, rm_singleton=False):
"""
Input:
basename (str) - name of the graph
rm_singleton (bool) - whether to remove singleton nodes
Output:
out_nodes (list) - list of numpy arrays containing
the out nodes of every node in the graph
in_nodes (list) - list of numpy arrays containing
the in nodes of every node in the graph
out_degree - list of out degrees of nodes
in_degree - list of in degrees of nodes
TODO: remove nodes with no links?
"""
ascii_path = Path("/data/graphs") / basename / ("ascii.graph-txt")
assert ascii_path.exists(), "Graph not found!"
with ascii_path.open() as f:
line = f.readline()
line_tot = int(line.split()[0])
print("{} lines".format(line_tot))
print("reading..")
out_nodes = [0] * line_tot
in_nodes = [0] * line_tot
out_degree = [0] * line_tot
for i in trange(line_tot):
line = f.readline()
if line[0] == '\n' and not rm_singleton:
# don't remove singleton
# assume node is linked to itself
in_ = np.array([i])
out_ = np.array([i])
else:
in_ = np.fromstring(line, dtype=int, sep=' ')
out_ = np.ones(len(in_), dtype=int) * i
out_nodes[i] = out_
in_nodes[i] = in_
out_degree[i] = len(out_)
print("finished reading, now preprocessing..")
out_nodes = np.hstack(out_nodes)
in_nodes = np.hstack(in_nodes)
unique_elements, in_degree_temp = np.unique(in_nodes, return_counts=True)
# some nodes might have in_degree = 0
in_degree = np.zeros(len(out_degree))
in_degree[unique_elements] = in_degree_temp
return out_nodes, in_nodes, out_degree, in_degree
<file_sep>from os.path import join
BASENAME = "reddit"
def get_torchbiggraph_config():
model = join("/data/models", BASENAME)
graphs = join("data/graphs", BASENAME)
config = dict(
# I/O data
entity_path=model,
# where to store learnt edges
edge_paths=[
join(graphs, "train_partitioned"),
join(graphs, "test_partitioned"),
],
checkpoint_path=model,
# Graph structure
entities={
'link': {'num_partitions': 1},
},
relations=[{
'name': 'follow',
'lhs': 'link',
'rhs': 'link',
'operator': 'none',
}],
verbose=True,
dynamic_relations=False,
# Scoring model
dimension=64,
global_emb=False,
# Training
num_epochs=50,
num_uniform_negs=50,
loss_fn='softmax',
lr=0.01,
# Misc
hogwild_delay=2,
)
return config
<file_sep># Biggraph
To train an embedding, modify the *config.py* file.
Data should be located in the folder *"/data/graphs/"*.
Input graphs should be stored in tab separated values. To generate such a graph, you can use for example [webgraph](http://webgraph.di.unimi.it) with the following command
java -cp "webgraph/*" -server it.unimi.dsi.webgraph.ArcListASCIIGraph graphs/cnr-2000/cnr-2000 graphs/cnr-2000/cnr-2000.tab
<file_sep>FROM biggraph
WORKDIR /workspace
RUN git clone https://github.com/Nicolaus93/biggraph.git
WORKDIR /workspace/biggraph<file_sep>import faiss
import linecache
from pathlib import Path
from utils.data_utils import get_entities_list
def train_search(data):
"""train similarity search model
as explained in faiss tutorial.
"""
nb, d = data.shape
index = faiss.IndexFlatL2(d) # build the index
print("Index trained: {}".format(index.is_trained))
index.add(data) # add vectors to the index
print("Index total: {}".format(index.ntotal))
return index
def kmeans(X, n_cent=5, niter=50, verbose=True):
"""
Use k-means algorithm from faiss.
"""
d = X.shape[1]
ncentroids = n_cent
algo = faiss.Kmeans(d, ncentroids, niter=niter, verbose=verbose)
algo.train(X)
return algo
def PCA(X, out=2):
"""
Use PCA algorithm from faiss.
"""
d = X.shape[1]
mat = faiss.PCAMatrix(d, out)
mat.train(X)
assert mat.is_trained
tr = mat.apply_py(X)
return tr
def centroid_neigh(basename, k_means, X, entities, n=15):
"""
Find the n-nearest neighbours to k-means
cluster centroids.
"""
d = X.shape[1]
index = faiss.IndexFlatL2(d)
index.add(X)
D, Ind = index.search(k_means.centroids, n)
find_neighbours(basename, Ind, entities)
def find_neighbours(basename, idx, ent_list):
"""
Helper function for centroid_neigh.
"""
ids_file = Path('/data/graphs/') / basename / (basename + '.urls')
if not ids_file.exists():
ids_file = Path('/data/graphs/') / basename / (basename + '.ids')
assert ids_file.exists(), "File not found!"
f = ids_file.as_posix()
for pos, cluster in enumerate(idx):
print("\x1b[0;35;43m Cluster {} \x1b[0m".format(pos))
for node in cluster:
line = ent_list[node]
print(linecache.getline(f, line + 1))
<file_sep>import numpy as np
import linecache
import json
import h5py
import argparse
from pathlib import Path
from utils.faiss_utils import train_search
def check(nodes, k, idx, f, ent_list):
"""
nodes - 2d array of nodes we want to check
k - nearest neighbours
ind - index built with faiss
f - file containing urls
ent_list - list of entities id
read https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python
how to print with different colours
"""
if len(nodes) == 1:
dist, ind = idx.search(nodes.reshape(1, -1), k)
else:
dist, ind = idx.search(nodes, k)
for row in ind:
source = int(ent_list[row[0]])
print('\x1b[0;35;43m' + '{} nearest neighbours of node {}'.format(
k - 1, source) + '\x1b[0m')
print('\x1b[0;35;43m' + linecache.getline(f, source + 1) + '\x1b[0m')
for node in row[1:]:
neighbor = int(ent_list[node])
print(" node {}, {}".format(
node, linecache.getline(f, neighbor + 1)))
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Generate embeddings on given graph.')
parser.add_argument('basename', help='name of the graph to use')
parser.add_argument('format', help='file format storing original data.')
args = parser.parse_args()
basename = args.basename
f_format = args.format
assert f_format == 'ids' or f_format == 'urls', "not the right format!"
model_path = Path("/data/models") / basename
assert model_path.is_dir(), "model directory not found"
with (model_path / "entity_names_link_0.json").open() as tf:
entities_list = json.load(tf)
hf_path = list(model_path.glob("embeddings_link_0*.h5"))[0]
hf = h5py.File(hf_path)
x = hf["embeddings"][:]
idx = train_search(x)
nodes_id = np.random.randint(len(x), size=5)
nodes = x[nodes_id, :]
k = 6
ids_file = Path("/data/graphs") / basename / (basename + '.' + f_format)
try:
check(nodes, k, idx, str(ids_file), entities_list)
except Exception as e:
print("e")
print("urls file not found!")
|
936cca95dee45380148ebc92e47fe7517f3f45a7
|
[
"Markdown",
"Dockerfile",
"Python"
] | 10 |
Markdown
|
Nicolaus93/biggraph
|
5e8c7330d81490fa9079b16bc91ee147bbd3a3ba
|
cb1692a18c7a0d01c9b9ae4d10d6a76ac640e6f7
|
refs/heads/master
|
<file_sep>@REM use a variable as sketch name
@set SKETCH_NAME=Processing_print
@FOR /F %%A IN ('WMIC OS GET LocalDateTime ^| FINDSTR \.') DO @SET B=%%A
@set FORMAT_DATE=%B:~0,4%-%B:~4,2%-%B:~6,2%
@set FORMAT_TIME=%TIME:~0,2%-%TIME:~3,2%-%TIME:~6,2%
cd application.windows32
%SKETCH_NAME% >> "%~dp0\Win_log_both_stdout_stderr_on_%FORMAT_DATE%_%FORMAT_TIME%.txt" 2>&1
<file_sep># Catch output of exported Processing sketch
##Mac OS
Prior to Mountain Lion, stdout and stderr (where println goes to) is forwarded to system log, which can be seen in Console app. So we need to manually forward those standard streams to log file so we can debug sketchs.
###Folder structure of Mac OS Processing application
The exported application has a executable file in "Contents/MacOS/". The application can be opened by executing that file.

When that file is executed in terminal. You should see all it's print and error in terminal.

There is a "Mac_merge_stdout_stderr.command" file redirect stdout and stderr to a text file. For more info refer to http://en.wikipedia.org/wiki/Redirection_(computing)
###Add execution permission
If you see something like this when you double click .command file: (The file “Mac_merge_stdout_stderr.command” could not be executed because you do not have appropriate access privileges)

You need to add "x" permission to the .command file.
Open terminal window and type "chmod +x " and drag the .command file in,

You should see like "chmod +x /Volumes/Mac_storage/github/Catch-output-of-exported-Processing-sketch/Processing_print/Mac_merge_stdout_stderr.command
" in you terminal.
Press return to finish this step.
###Get output
Double click the .command file and you should see a text file with output.

##Windows
The standard streams works the same way. Double click the bat file will do the trick.

<file_sep>#!/bin/bash
#following lines is used to switch to current path when executed in Finder
PROGPATH=$(dirname $_)
cd $PROGPATH
#use a variable as sketch name
SKETCH_NAME=Processing_print
CURRENT_TIME=$(date "+%Y_%m_%d-%H_%M_%S")
./application.macosx/$SKETCH_NAME.app/Contents/MacOS/$SKETCH_NAME >>Mac_log_both_stdout_stderr_on-$CURRENT_TIME.txt 2>&1
<file_sep>int counter=0;
void setup() {
frameRate(1/2.0);
}
void draw() {
System.out.println("Output "+counter);
System.err.println("ERR output "+counter);
counter++;
if (counter == 5) { //let's have an exception
throw new RuntimeException("Testing unhandled exception processing.");
}
}
|
6c0d68ac7286df7c6023c1084f2dd9e923ca9b50
|
[
"Processing",
"Markdown",
"Batchfile",
"Shell"
] | 4 |
Processing
|
DeqingSun/Catch-output-of-exported-Processing-sketch
|
8dde479674d80f0b7c10f547d304e5ad89d5fa62
|
4d8f2fdcaf40c8f12dae1a4204407aa8e6cc78c8
|
refs/heads/master
|
<repo_name>fercalderonayala/github-para-desarrolladores<file_sep>/README.md
# Bienvenido al curso de github para desarrolladores
github para desarrolladores
[Visita mi blog] (https://www.facebook.com/fernando.calderonayala)
|
ec39fa3e067dd687f7dab54e1d698c4241e5915f
|
[
"Markdown"
] | 1 |
Markdown
|
fercalderonayala/github-para-desarrolladores
|
eda042e9b446619be830b0f5bc66be54efba4546
|
c6f57ac2e2bf6fde9c33db53d66fff9d0409abde
|
refs/heads/master
|
<repo_name>zs-kaide/parsetsv_python3<file_sep>/parsetsv_multitask_p3.py
#!/usr/bin/env python3
# coding:utf-8
import signal
import sys
import os
import glob
import logging
import logging.handlers
import datetime
import click
import pickle
import struct
import tempfile
import shutil
import math
import concurrent.futures
import errno
class SignalException(Exception):
def __init__(self, message):
super(SignalException, self).__init__(message)
def do_exit(sig, stack):
raise SignalException("Exiting")
# ファイルを分割し、index、offset、offset + lengthを返す。
def tsv_separate_generator(inputf):
CHUNK_SIZE = 1024 * 1024 * 100
with open(inputf, 'rb') as f:
f_size = os.stat(f.fileno()).st_size
split_count = math.ceil(f_size / CHUNK_SIZE)
start_offset = len(f.readline())
for split_idx in range(split_count):
offset = CHUNK_SIZE * (split_idx + 1) - 1
f.seek(offset)
last_line_len = len(f.readline())
if offset < f_size:
end_offset = offset + last_line_len
else:
end_offset = f_size
yield (
split_idx,
start_offset,
end_offset,
)
if end_offset >= f_size or last_line_len == 0:
break
start_offset = end_offset
def sum_file(self, files):
with tempfile.NamedTemporaryFile(delete=False, dir='/var/tmp/',) as f:
s = 0
for file in self.files:
with open(file) as f1:
os.sendfile(f.fileno(), f1.fileno(), s)
s += os.stat(file).st_size
return f.name
class ReadTsvGenerator(object):
def __init__(self, inputf, iterable):
self.inputf = inputf
self.iterable = iterable
def read_tsv(self):
with open(self.inputf, "rb") as f:
start_offset = self.iterable[1],
end_offset = self.iterable[2],
f.seek(start_offset[0])
start = start_offset[0]
while start < end_offset[0]:
row = f.readline()
start += len(row)
row = [
i.decode(
'utf-8'
) for i in row.strip(b'\n').split(b'\t')
]
row = (
int(row[0]),
int(row[1]),
int(row[2]),
float(row[3]),
int(row[4]),
row[5],
row[6],
row[7],
row[8],
)
yield row
class ParseTsvGenerator(object):
def __init__(self, iterable):
self.iterable = iterable
def pickle_tsv(self):
lines = self.iterable
next(lines)
for record in lines:
yield pickle.dumps(record)
def struct_tsv(self):
lines = self.iterable
next(lines)
for record in lines:
s = struct.Struct(
'i h l d ? %ds %ds %ds %ds' % (
len(record[5]), len(record[6]),
len(record[7]), len(record[8]),
)
)
yield s.pack(*record)
class ParseRowsTsv(object):
def __init__(self, file, inputf, outputf):
self.file = file
self.inputf = os.path.abspath(os.path.expanduser(inputf))
self.outputf = os.path.abspath(os.path.expanduser(outputf))
# 単一タスク
def dotask(self, rule):
parsetsv = ParseTsvGenerator(
ReadTsvGenerator(self.inputf, rule).read_tsv())
if self.file == 'pickle':
w = parsetsv.pickle_tsv()
elif self.file == 'struct':
w = parsetsv.struct_tsv()
with tempfile.NamedTemporaryFile(
delete=False, dir='/var/tmp', suffix='_dotask', prefix='tmp_',
) as f:
for row in w:
f.write(row)
return f.name
# マルチプロセス
def multi_do_task(self):
with concurrent.futures.ProcessPoolExecutor() as executor:
future_to_tsv = {
executor.submit(
self.dotask, rule
): rule for rule in tsv_separate_generator(self.inputf)}
with tempfile.TemporaryDirectory(
suffix='_tsv', prefix='tmp_', dir='/var/tmp') as temp_dir:
with tempfile.NamedTemporaryFile(
suffix='_tsv', prefix='tmp_',
delete=False, dir=temp_dir,) as f:
s = 0
for future in concurrent.futures.as_completed(
future_to_tsv):
chunk = future_to_tsv[future][2] - \
future_to_tsv[future][1]
with open(future.result()) as separatefile:
os.sendfile(
f.fileno(), separatefile.fileno(), s, chunk)
s += os.stat(separatefile.fileno()).st_size
try:
os.remove(separatefile.name)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
shutil.move(f.name, self.outputf)
@click.command()
@click.option(
'--file', type=click.Choice(['pickle', 'struct']),
default='pickle')
@click.option('-i', '--inputf', default='~/kadai_1.tsv')
@click.option('-o', '--outputf', default='~/zone/kadai_2v3.p')
def cmd(file, inputf, outputf):
s = datetime.datetime.now()
print(s + datetime.timedelta(0, 0, 0, 0, 0, 9))
# シグナル
signal.signal(signal.SIGINT, do_exit)
signal.signal(signal.SIGHUP, do_exit)
signal.signal(signal.SIGTERM, do_exit)
# ログハンドラーを設定する
LOG_MANYROWSTSV = 'logging_warning.out'
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.WARNING)
handler = logging.handlers.RotatingFileHandler(
LOG_MANYROWSTSV, maxBytes=2000, backupCount=5,)
my_logger.addHandler(handler)
parser = ParseRowsTsv(file, inputf, outputf)
try:
parser.multi_do_task()
except SignalException as e1:
my_logger.warning('%s: %s' % (e1, datetime.datetime.now()))
logfiles = glob.glob('%s*' % LOG_MANYROWSTSV)
print(logfiles)
sys.exit(1)
finally:
e = datetime.datetime.now()
print(str(e-s))
def main():
cmd()
if __name__ == '__main__':
main()
<file_sep>/parsetsv_p3.py
#!/usr/bin/env python3
# coding:utf-8
import signal
import sys
import os
import glob
import logging
import logging.handlers
import csv
import datetime
import click
import pickle
import struct
import tempfile
import shutil
class SignalException(Exception):
def __init__(self, message):
super(SignalException, self).__init__(message)
def do_exit(sig, stack):
raise SignalException("Exiting")
class IterToFile(object):
def __init__(self, iterable, output_filename):
self.iterable = iterable
self.output_filename = output_filename
def write_file(self):
with tempfile.TemporaryDirectory(
suffix='_tsv', prefix='tmp_', dir='/var/tmp') as temp_dir:
fname = self.write_str_into_file(temp_dir)
shutil.move(fname, self.output_filename)
def write_str_into_file(self, dir_name):
with tempfile.NamedTemporaryFile(delete=False, dir=dir_name,) as f:
for row in self.iterable:
f.write(row)
return f.name
class ReadTsvGenerator(object):
def __init__(self, inputf):
self.inputf = inputf
def read_tsv(self):
with open(self.inputf, "r") as f:
reader = csv.reader(f, delimiter="\t", lineterminator='\n')
yield next(reader)
for row in reader:
row = (
int(row[0]),
int(row[1]),
int(row[2]),
float(row[3]),
int(row[4]),
row[5],
row[6],
row[7],
row[8],
)
yield row
class ParseTsvGenerator(object):
def __init__(self, iterable):
self.iterable = iterable
def pickle_tsv(self):
for record in self.iterable:
yield pickle.dumps(record)
def struct_tsv(self):
lines = self.iterable
line = lines.next()
inits = struct.Struct(
's '.join(
[str(len(line[i])) for i in range(9)]) + 's')
yield inits.pack(*line)
for record in lines:
s = struct.Struct(
'i h l d ? %ds %ds %ds %ds' % (
len(record[5]), len(record[6]),
len(record[7]), len(record[8]),
)
)
yield s.pack(*record)
class ParseRowsTsv(object):
def __init__(self, file, inputf, outputf):
self.file = file
self.inputf = os.path.abspath(os.path.expanduser(inputf))
self.outputf = os.path.abspath(os.path.expanduser(outputf))
def write_into_file(self):
parsetsv = ParseTsvGenerator(ReadTsvGenerator(self.inputf).read_tsv())
if self.file == 'pickle':
IterToFile(parsetsv.pickle_tsv(), self.outputf).write_file()
elif self.file == 'struct':
IterToFile(parsetsv.struct_tsv(), self.outputf).write_file()
@click.command()
@click.option(
'--file', type=click.Choice(['pickle', 'struct']),
default='pickle')
@click.option('-i', '--inputf', default='~/kadai_1.tsv')
@click.option('-o', '--outputf', default='~/zone/kadai_2v3.p')
def cmd(file, inputf, outputf):
s = datetime.datetime.now()
print(s + datetime.timedelta(0, 0, 0, 0, 0, 9))
# シグナル
signal.signal(signal.SIGINT, do_exit)
signal.signal(signal.SIGHUP, do_exit)
signal.signal(signal.SIGTERM, do_exit)
# ログハンドラーを設定する
LOG_MANYROWSTSV = 'logging_warning.out'
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.WARNING)
handler = logging.handlers.RotatingFileHandler(
LOG_MANYROWSTSV, maxBytes=2000, backupCount=5,)
my_logger.addHandler(handler)
parser = ParseRowsTsv(file, inputf, outputf)
try:
parser.write_into_file()
except SignalException as e1:
my_logger.warning('%s: %s' % (e1, datetime.datetime.now()))
logfiles = glob.glob('%s*' % LOG_MANYROWSTSV)
print(logfiles)
sys.exit(1)
finally:
e = datetime.datetime.now()
print(str(e-s))
def main():
cmd()
if __name__ == '__main__':
main()
|
6fb0bc264711e599ecfe920f09f509d59ddfd492
|
[
"Python"
] | 2 |
Python
|
zs-kaide/parsetsv_python3
|
3e7847b451b4979d603c6e421cb1b79c010a10db
|
26f315091027f9adfa17e6c92a8aeb26fad3b960
|
refs/heads/master
|
<file_sep>if __name__ == "__main__":
def add():
one = input("Number One:")
two = input("Number Two:")
print( int(one) + int(two))
def multiply():
three = input("Number three:")
four = input("Number four:")
m = int(three) * int(four)
print(m)
addormultiply = input("Wuld you like to add or multiply?(add/multiply):")
if addormultiply != "add" or addormultiply != "multiply":
print("Wrong Input!")
#addormultiply = input("Wuld you like to add or multiply?(add/multiply):")
multiply()
elif addormultiply == "multiply":
multiply()
elif addormultiply == "add":
add()
|
f1abab88657a872148e01cc12b6a74e4d97883c6
|
[
"Python"
] | 1 |
Python
|
nirbheeksetia/pythonPrograms
|
eab4cc6580ebcba9c4eac134e8e49e4d62e384d7
|
c98bfb7535c5f9aba6a931976e8cbd9ab97d7722
|
refs/heads/main
|
<repo_name>helab207/3D-MASNet<file_sep>/util/predict_funcs.py
import numpy as np
import tensorflow as tf
import keras.backend as K
def calculateIdx1D(vol_length, cube_length, stride):
one_dim_pos = np.arange(0, vol_length-cube_length+1, stride)
if (vol_length - cube_length) % stride != 0:
one_dim_pos = np.concatenate([one_dim_pos, [vol_length-cube_length]])
return one_dim_pos
def calculateIdx3D(vol_size, cube_size, strides):
x_idx, y_idx, z_idx = [calculateIdx1D(vol_size[i], cube_size[i], strides[i]) for i in range(3)]
return x_idx, y_idx, z_idx
def idx2pos(idx, vol_size):
"""
Given a flatten idx, return the position (x, y, z) in the 3D image space.
Args:
idx(int): index into flattened 3D volume
vol_size(list or tuple of 3 int): size of 3D volume
"""
assert len(vol_size) == 3, 'length of vol_size must be 3, but got {}'.format(len(vol_size))
pos_x = idx / (vol_size[1] * vol_size[2])
idx_yz = idx % (vol_size[1] * vol_size[2])
pos_y = idx_yz / vol_size[2]
pos_z = idx_yz % vol_size[2]
return np.array([pos_x, pos_y, pos_z], np.int16) # shape of [3, ]
def pos2idx(pos, vol_size):
"""
Given a position (x, y, z) in the 3D image space, return a flattened idx.
Args:
pos (list or tuple of 3 int): Position in 3D volume
vol_size (list or tuple of 3 int): Size of 3D volume
"""
assert len(pos) == 3, 'length of pos must be 3, but got {}'.format(len(pos))
assert len(vol_size) == 3, 'length of vol_size must be 3, but got {}'.format(len(vol_size))
return (pos[0] * vol_size[1] * vol_size[2]) + (pos[1] * vol_size[2]) + pos[2]
def calculateCubeIdx3D(cube_size, vol_size, strides):
"""
Calculating the idx of all the patches in 3D image space.
Args:
cube_size (list or tuple of 3 int):
vol_size (list or tuple of 3 int):
strides (list or tuple of 3 int): crop stride in 3 direction
"""
x_idx, y_idx, z_idx = calculateIdx3D(vol_size, cube_size, strides)
pos_idx_flat = np.zeros(x_idx.shape[0] * y_idx.shape[0] * z_idx.shape[0])
flat_idx = 0
for x in x_idx:
for y in y_idx:
for z in z_idx:
pos_3d = [x, y, z]
pos_idx_flat[flat_idx] = pos2idx(pos_3d, vol_size)
flat_idx += 1
return pos_idx_flat
def predict_segmentation(input_dict, batch_size, cube_size, strides, net, gpu_num):
"""
Calculating the Segmentation Probability Map.
Args:
input_dict (dict):
"t1w": image with shape of [*vol_size, 1]
"t2w": image with shape of [*vol_size, 1]
batch_size (int):
cube_size (list or tuple of 3 int):
strides (list or tuple of 3 int):
net (keras.Model): the trained model
"""
assert len(cube_size) == 3, 'length of cube_size must be 3, but got {}'.format(len(cube_size))
assert len(strides) == 3, 'length of strides must be 3, but got {}'.format(len(strides))
t1w = input_dict['t1w']
t2w = input_dict['t2w']
vol_size = t1w.shape[0:3]
mask = np.array((t1w > 0), np.int8)
flat_idx = calculateCubeIdx3D(cube_size, vol_size, strides)
# flat_idx_select stores non-zero cubes' idx.
flat_idx_select = np.zeros(flat_idx.shape)
# remove the background cubes
for cube_idx in range(0, flat_idx.shape[0]):
cube_pos = idx2pos(flat_idx[cube_idx], vol_size)
mask_cube = mask[cube_pos[0]:cube_pos[0]+cube_size[0], cube_pos[1]:cube_pos[1]+cube_size[1], cube_pos[2]:cube_pos[2]+cube_size[2]]
if np.sum(mask_cube) != 0:
flat_idx_select[cube_idx] = 1
flat_idx_select = np.array(flat_idx_select, np.bool)
flat_idx = flat_idx[flat_idx_select]
print("Valid cube number is: ", flat_idx.shape[0])
"""
reset the batch_size according to the number of gpus
"""
cubes_num = flat_idx.shape[0]
if cubes_num % batch_size < gpu_num:
batch_size = batch_size - 1
segmentation_predict = np.zeros(shape=(1, *vol_size, 4))
segmentation_count = np.zeros(shape=(1, *vol_size, 1))
batch_idx = 0
while batch_idx < flat_idx.shape[0]:
t1w_cubes = []
t2w_cubes = []
if batch_idx + batch_size < flat_idx.shape[0]:
cur_batch_size = batch_size
else:
cur_batch_size = flat_idx.shape[0] - batch_idx
for slices in range(0, cur_batch_size):
cube_pos = idx2pos(flat_idx[batch_idx+slices], vol_size)
t1w_cube = np.expand_dims(t1w[cube_pos[0]:cube_pos[0]+cube_size[0],
cube_pos[1]:cube_pos[1]+cube_size[1],
cube_pos[2]:cube_pos[2]+cube_size[2], :], axis=0)
t2w_cube = np.expand_dims(t2w[cube_pos[0]:cube_pos[0]+cube_size[0],
cube_pos[1]:cube_pos[1]+cube_size[1],
cube_pos[2]:cube_pos[2]+cube_size[2], :], axis=0)
t1w_cubes.append(t1w_cube)
t2w_cubes.append(t2w_cube)
t1w_cubes = np.concatenate(t1w_cubes, axis=0)
t2w_cubes = np.concatenate(t2w_cubes, axis=0)
input_cubes = np.concatenate([t1w_cubes, t2w_cubes], axis=-1)
res_cubes = net.predict_on_batch(input_cubes)
for slices in range(0, cur_batch_size):
cube_pos = idx2pos(flat_idx[batch_idx+slices], vol_size)
segmentation_predict[:,cube_pos[0]:cube_pos[0]+cube_size[0],
cube_pos[1]:cube_pos[1]+cube_size[1],
cube_pos[2]:cube_pos[2]+cube_size[2], :] +=res_cubes[slices]
segmentation_count[:, cube_pos[0]:cube_pos[0]+cube_size[0],
cube_pos[1]:cube_pos[1]+cube_size[1],
cube_pos[2]:cube_pos[2]+cube_size[2], :] += 1.0
batch_idx += cur_batch_size
# remove 0 count areas
segmentation_count += (segmentation_count == 0)
segmentation_predict = segmentation_predict / segmentation_count
return segmentation_predict[0]
<file_sep>/client/run.py
import sys
import json
class Params(object):
def __init__(self, param):
if not isinstance(param, dict):
raise ValueError("Wrong value type, expected `dict`, but got {}".format(type(param)))
self.param = param
def __getattr__(self, name):
return self.param[name]
if __name__ == "__main__":
with open(sys.argv[1], 'r') as f:
params = Params(json.load(f))
if params.task == 'train':
from .train import main as train_main
train_main(params)
elif params.task == 'predict':
from .predict import main as predict_main
predict_main(params)
elif params.task == 'deploy':
from .deploy import main as deploy_main
deploy_main(params)
else:
raise ValueError("Wrong params `task`, expected `train` or `predict`, but got `{}`".format(params.task))<file_sep>/models/ac_layer.py
import tensorflow as tf
import math
import numpy as np
import keras
import keras.backend as K
from keras.layers import BatchNormalization, Conv3D, Add, ZeroPadding3D, Lambda, concatenate
def ACBlock(input_tensor, name=None, filters=None, ksize=None, strides=(1, 1),
momentum=0.99, epsilon=0.001, moving_mean_initializer='zeros', moving_variance_initializer='ones',
kernel_initializer='glorot_uniform', kernel_regularizer=None, beta_initializer='zeros', gamma_initializer='ones', deploy=False):
if name == None:
raise Exception("Please set the name of this convolution layer")
if filters == None:
raise Exception('Please set the number of filters this convolution layer')
if ksize == None:
raise Exception('Please set the kernel size of this convolution layer')
if not isinstance(ksize, int):
raise Exception('kernel size must be an integer')
pad_size = ksize // 2
if deploy:
outs_fusion = ZeroPadding3D(padding=(pad_size, pad_size, pad_size), name=name+'.fused_pad')(input_tensor)
outs_fusion = Conv3D(filters=filters, kernel_size=(ksize, ksize, ksize), strides=strides, padding='valid', kernel_initializer=kernel_initializer,
kernel_regularizer=kernel_regularizer, use_bias=True, name=name+'.fused_conv')(outs_fusion)
return outs_fusion
else:
outs_nxnxn = ZeroPadding3D(padding=(pad_size, pad_size, pad_size), name=name+'.pad_nxnxn')(input_tensor)
outs_1xnxn = ZeroPadding3D(padding=(0, pad_size, pad_size), name=name+'.pad_1xnxn')(input_tensor)
outs_nx1xn = ZeroPadding3D(padding=(pad_size, 0, pad_size), name=name+'.pad_nx1xn')(input_tensor)
outs_nxnx1 = ZeroPadding3D(padding=(pad_size, pad_size, 0), name=name+'_pad_nxnx1')(input_tensor)
outs_nxnxn = Conv3D(filters=filters, kernel_size=(ksize, ksize, ksize), strides=strides, padding='valid', kernel_initializer=kernel_initializer,
kernel_regularizer=kernel_regularizer, use_bias=False, name=name+'.conv_nxnxn')(outs_nxnxn)
outs_1xnxn = Conv3D(filters=filters, kernel_size=(1, ksize, ksize), strides=strides, padding='valid', kernel_initializer=kernel_initializer,
kernel_regularizer=kernel_regularizer, use_bias=False, name=name+'.conv_1xnxn')(outs_1xnxn)
outs_nx1xn = Conv3D(filters=filters, kernel_size=(ksize, 1, ksize), strides=strides, padding='valid', kernel_initializer=kernel_initializer,
kernel_regularizer=kernel_regularizer, use_bias=False, name=name+'.conv_nx1xn')(outs_nx1xn)
outs_nxnx1 = Conv3D(filters=filters, kernel_size=(ksize, ksize, 1), strides=strides, padding='valid', kernel_initializer=kernel_initializer,
kernel_regularizer=kernel_regularizer, use_bias=False, name=name+'.conv_nxnx1')(outs_nxnx1)
outs_nxnxn = BatchNormalization(momentum=momentum, epsilon=epsilon, beta_initializer=beta_initializer,
gamma_initializer=gamma_initializer, moving_mean_initializer=moving_mean_initializer,
moving_variance_initializer=moving_variance_initializer, name=name+'.bn_nxnxn')(outs_nxnxn)
outs_1xnxn = BatchNormalization(momentum=momentum, epsilon=epsilon, beta_initializer=beta_initializer,
gamma_initializer=gamma_initializer, moving_mean_initializer=moving_mean_initializer,
moving_variance_initializer=moving_variance_initializer, name=name+'.bn_1xnxn')(outs_1xnxn)
outs_nx1xn = BatchNormalization(momentum=momentum, epsilon=epsilon, beta_initializer=beta_initializer,
gamma_initializer=gamma_initializer, moving_mean_initializer=moving_mean_initializer,
moving_variance_initializer=moving_variance_initializer, name=name+'.bn_nx1xn')(outs_nx1xn)
outs_nxnx1 = BatchNormalization(momentum=momentum, epsilon=epsilon, beta_initializer=beta_initializer,
gamma_initializer=gamma_initializer, moving_mean_initializer=moving_mean_initializer,
moving_variance_initializer=moving_variance_initializer, name=name+'.bn_nxnx1')(outs_nxnx1)
added = Add(name = name+'.add')([outs_nxnxn, outs_1xnxn, outs_nx1xn, outs_nxnx1])
return added
# this is the MixACB function, which is originally named pyramidACB.
def pyramidACBlock(input_tensor, name=None, in_channels_ratio=[3, 1], out_channels_ratio=[3, 1], out_channels=16, ksize=[3, 5], strides=1,
kernel_initializer='glorot_uniform', kernel_regularizer=None, deploy=False):
in_channels = input_tensor.get_shape()[-1].value
in_channels_for_conv3 = in_channels // np.sum(in_channels_ratio) * in_channels_ratio[0]
out_channels_for_conv3 = out_channels // np.sum(out_channels_ratio) * out_channels_ratio[0]
out_channels_for_conv5 = out_channels - out_channels_for_conv3
input_tensor_for_conv3 = Lambda(lambda x: x[:,:,:,:,0:in_channels_for_conv3])(input_tensor)
output_tensor_for_conv3 = ACBlock(input_tensor_for_conv3, name=name+'.pyacb_3', filters=out_channels_for_conv3, ksize=ksize[0], strides=strides,
kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer, deploy=deploy)
input_tensor_for_conv5 = Lambda(lambda x: x[:,:,:,:,in_channels_for_conv3:])(input_tensor)
output_tensor_for_conv5 = ACBlock(input_tensor_for_conv5, name=name+'.pyacb_5', filters=out_channels_for_conv5, ksize=ksize[1], strides=strides,
kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer, deploy=deploy)
outputs = concatenate([output_tensor_for_conv3, output_tensor_for_conv5], axis=-1, name=name+'.concat_3_5')
return outputs
<file_sep>/client/deploy.py
import sys
import os
from models.dunet import DUNetMixACB
from util.model_fusion import deploy
from util.prep import maybe_mkdir_p
def main(params):
ori_model = params.ori_model
net = DUNetMixACB(deploy=False)
model = net.build_model()
net.switch_to_deploy()
deploy_model = net.build_model()
print("Total {} model(s) need to be fused.".format(len(ori_model)))
for i in range(len(ori_model)):
model_i_path = os.path.abspath(ori_model[i])
print("Fusing model: {} ...".format(model_i_path))
deploy_path = model_i_path.replace(".h5", "_deploy.h5")
deploy(model, deploy_model, model_i_path, deploy_path, 1e-3)
print("Fused model has been stored in {}".format(deploy_path))
<file_sep>/util/metrics.py
import numpy as np
import scipy.ndimage
from numpy.core.umath_tests import inner1d
import nibabel as nib
def dice(img1, img2, idx=None):
"""Calculate the dice coeficient between two images of a specific class.
Args:
img1: numpy array
img2: numpy array
idx: the label class. In iSeg dataset, 0,1,2,3 represent background, CSF, GM and WM, respectively.
"""
if idx:
img1 = img1 == idx
img2 = img2 == idx
img1 = np.asarray(img1).astype(np.bool)
img2 = np.asarray(img2).astype(np.bool)
if img1.shape != img2.shape:
raise ValueError("Shape missmatch: img1 and img2 must got same shape. But got {} for img1 and {} for img2".format(img1.shape, img2.shape))
intersection = np.logical_and(img1, img2)
dsc = 2.0 * intersection.sum() / (img1.sum() + img2.sum())
return dsc
def ModHausdorffDist(A,B):
"""
borrow from: https://github.com/zhengyang-wang/3D-Unet--Tensorflow/blob/master/utils/HausdorffDistance.py
This function computes the Modified Hausdorff Distance (MHD) which is
proven to function better than the directed HD as per Dubuisson et al.
in the following work:
<NAME> and <NAME>. A Modified Hausdorff distance for object
matching. In ICPR94, pages A:566-568, Jerusalem, Israel, 1994.
http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=576361
The function computed the forward and reverse distances and outputs the
maximum/minimum of both.
Optionally, the function can return forward and reverse distance.
Format for calling function:
[MHD,FHD,RHD] = ModHausdorffDist(A,B);
where
MHD = Modified Hausdorff Distance.
FHD = Forward Hausdorff Distance: minimum distance from all points of B
to a point in A, averaged for all A
RHD = Reverse Hausdorff Distance: minimum distance from all points of A
to a point in B, averaged for all B
A -> Point set 1, [row as observations, and col as dimensions]
B -> Point set 2, [row as observations, and col as dimensions]
No. of samples of each point set may be different but the dimension of
the points must be the same.
<NAME> Stanford University; 06/17/2014
"""
# Find pairwise distance
D_mat = np.sqrt(inner1d(A,A)[np.newaxis].T + inner1d(B,B)-2*(np.dot(A,B.T)))
# Calculating the forward HD: mean(min(each col))
FHD = np.mean(np.min(D_mat,axis=1))
# Calculating the reverse HD: mean(min(each row))
RHD = np.mean(np.min(D_mat,axis=0))
# Calculating mhd
MHD = np.max(np.array([FHD, RHD]))
return(MHD, FHD, RHD)
def MHD(pred, label):
'''Compute 3D MHD for a single class.
Args:
pred: An array of size [Depth, Height, Width], with only 0 or 1 values
label: An array of size [Depth, Height, Width], with only 0 or 1 values
Returns:
3D MHD for a single class
'''
D, H, W = label.shape
pred_d = np.array([pred[:, i, j] for i in range(H) for j in range(W)])
pred_h = np.array([pred[i, :, j] for i in range(D) for j in range(W)])
pred_w = np.array([pred[i, j, :] for i in range(D) for j in range(H)])
label_d = np.array([label[:, i, j] for i in range(H) for j in range(W)])
label_h = np.array([label[i, :, j] for i in range(D) for j in range(W)])
label_w = np.array([label[i, j, :] for i in range(D) for j in range(H)])
MHD_d = ModHausdorffDist(pred_d, label_d)[0]
MHD_h = ModHausdorffDist(pred_h, label_h)[0]
MHD_w = ModHausdorffDist(pred_w, label_w)[0]
ret = np.mean([MHD_d, MHD_h, MHD_w])
return ret
<file_sep>/util/data.py
import math
import os
import numpy as np
import nibabel as nib
from random import random
from util.prep import image_norm, make_onehot_label
class DataGen(object):
def __init__(self, file_path, id_list=[1,2,3,4,5,6,7]):
self.batch_size = 16
self.cube_size = 32
self.file_list = []
for ids in id_list:
datas = {}
subject_name = 'subject-{}-'.format(ids)
print("load image file: {}".format(subject_name))
T1 = os.path.join(file_path, subject_name + 'T1.hdr')
T2 = os.path.join(file_path, subject_name + 'T2.hdr')
label = os.path.join(file_path, subject_name + 'label.hdr')
t1_data = nib.load(T1).get_data()
t2_data = nib.load(T2).get_data()
mask = np.array(t1_data > 0, dtype=np.int8)
label_data = make_onehot_label(nib.load(label).get_data(), 4)
t1_data = image_norm(t1_data)
t2_data = image_norm(t2_data)
datas['images'] = np.concatenate([t1_data, t2_data], axis=-1)
datas['label'] = label_data
datas['mask'] = mask
self.file_list.append(datas)
def make_gen(self):
while True:
curr_batch_idx = 0
images_cubes = []
label_cubes = []
while curr_batch_idx < self.batch_size:
file_idx = np.random.randint(0, len(self.file_list))
random_file = self.file_list[file_idx]
h, w, d, _ = random_file['images'].shape
while True:
random_hidx = np.random.randint(0, h-self.cube_size)
random_widx = np.random.randint(0, w-self.cube_size)
random_didx = np.random.randint(0, d-self.cube_size)
mask_cube = random_file['mask'][random_hidx:random_hidx+self.cube_size,
random_widx:random_widx+self.cube_size,
random_didx:random_didx+self.cube_size, :]
if np.sum(mask_cube) != 0:
break
random_images_cube = np.expand_dims(random_file['images'][random_hidx:random_hidx+self.cube_size,
random_widx:random_widx+self.cube_size,
random_didx:random_didx+self.cube_size, :], axis=0)
random_label_cube = np.expand_dims(random_file['label'][random_hidx:random_hidx+self.cube_size,
random_widx:random_widx+self.cube_size,
random_didx:random_didx+self.cube_size, :], axis=0)
images_cubes.append(random_images_cube)
label_cubes.append(random_label_cube)
curr_batch_idx += 1
images_cubes = np.concatenate(images_cubes, axis=0)
label_cubes = np.concatenate(label_cubes, axis=0)
yield (
{'input': images_cubes},
{'output': label_cubes}
)
<file_sep>/client/train.py
import os
from functools import partial
import keras
import numpy as np
import tensorflow as tf
from keras.backend import clear_session, set_session
from keras.optimizers import Adam
from keras.utils import multi_gpu_model
from models.dunet import DUNetMixACB, cross_entropy
from util.callbacks import ModelCheckpointParallel
from util.data import DataGen
from util.prep import maybe_mkdir_p
from util.misc import save_params, cosine_annealing
def main(params):
# ======================================
# Set Environment Variable #
# ======================================
work_path = os.path.abspath('./workdir')
save_path = os.path.join(work_path, 'save', params.name)
maybe_mkdir_p(save_path)
save_file_name = os.path.join(
save_path, '{epoch:02d}.h5')
save_params(params, os.path.join(save_path, 'train.json'))
# ======================================
# Close Useless Information #
# ======================================
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.environ['TF_ENABLE_AUTO_MIXED_PRECISION'] = '1'
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
clear_session()
# ==============================================================
# Set GPU Environment And Initialize Networks #
# ==============================================================
gpu_nums = len(params.gpu.split(','))
os.environ["CUDA_VISIBLE_DEVICES"] = params.gpu
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.allow_soft_placement = True
set_session(tf.Session(config=config))
model = DUNetMixACB().build_model()
if params.load_model_file is not None:
print('loadding ', params.load_model_file)
model.load_weights(params.load_model_file)
if gpu_nums > 1:
print('MultiGpus: {}'.format(gpu_nums))
save_schedule = ModelCheckpointParallel(filepath=save_file_name, period=10)
mg_model = multi_gpu_model(model, gpus=gpu_nums)
else:
print('Single device.')
save_schedule = keras.callbacks.ModelCheckpoint(filepath=save_file_name, period=10)
mg_model = model
# ===================================================================
# Set Training Callbacks and Initialize Data Generator #
# ===================================================================
train_gen = DataGen(params.train_dir, params.train_ids).make_gen()
lr_schedule_fn = partial(cosine_annealing, lr_init=params.lr_init, lr_min=params.lr_min)
lr_schedule = keras.callbacks.LearningRateScheduler(lr_schedule_fn)
call_backs = [lr_schedule, save_schedule]
mg_model.compile(optimizer=Adam(lr=params.lr_init), loss=cross_entropy)
history = mg_model.fit_generator(train_gen,
steps_per_epoch=params.train_nums_per_epoch//params.batch_size,
epochs=params.epochs, callbacks=call_backs)
<file_sep>/util/prep.py
import numpy as np
import os
def maybe_mkdir_p(directory):
splits = directory.split("/")[1:]
for i in range(0, len(splits)):
if not os.path.isdir(os.path.join("/", *splits[:i+1])):
try:
os.mkdir(os.path.join("/", *splits[:i+1]))
except FileExistsError:
# this can sometimes happen when two jobs try to create the same directory at the same time,
# especially on network drives.
print("WARNING: Folder %s already existed and does not need to be created" % directory)
def make_onehot_label(label, num_classes):
onehot_encoding = []
for c in range(num_classes):
onehot_encoding.append(label == c)
onehot_encoding = np.concatenate(onehot_encoding, axis=-1)
onehot_encoding = np.array(onehot_encoding, dtype=np.int16)
return onehot_encoding
def _calIdx1D(vol_length, cube_length, stride):
one_dim_pos = np.arange(0, vol_length-cube_length+1, stride)
if (vol_length - cube_length) % stride != 0:
one_dim_pos = np.concatenate([one_dim_pos, [vol_length-cube_length]])
return one_dim_pos
def _calIdx3D(vol_size, cube_size, strides):
x_idx, y_idx, z_idx = [_calIdx1D(vol_size[i], cube_size[i], strides[i]) for i in range(3)]
return x_idx, y_idx, z_idx
def crop(data, x, y, z, cube_size):
assert len(cube_size) == 3
return data[:, x:x+cube_size[0],
y:y+cube_size[1],
z:z+cube_size[2], :]
def image_norm(img):
mask = (img > 0)
mean = np.mean(img[mask])
std = np.std(img[mask])
return ((img - mean) / std) * mask
# return (img - mean) / std
def cut_edge(data, keep_margin):
'''
function that cuts zero edge
# Ricardo: calculating the margin number of non-zero area.
'''
D, H, W, _ = data.shape
# print(D, H, W)
D_s, D_e = 0, D - 1
H_s, H_e = 0, H - 1
W_s, W_e = 0, W - 1
while D_s < D:
if data[D_s].sum() != 0:
D_s -= 1
break
D_s += 1
while D_e > D_s:
if data[D_e].sum() != 0:
D_e += 1
break
D_e -= 1
while H_s < H:
if data[:, H_s].sum() != 0:
H_s -= 1
break
H_s += 1
while H_e > H_s:
if data[:, H_e].sum() != 0:
H_e += 1
break
H_e -= 1
while W_s < W:
if data[:, :, W_s].sum() != 0:
W_s -= 1
break
W_s += 1
while W_e > W_s:
if data[:, :, W_e].sum() != 0:
W_e += 1
break
W_e -= 1
if keep_margin != 0:
D_s = max(0, D_s - keep_margin)
D_e = min(D - 1, D_e + keep_margin)
H_s = max(0, H_s - keep_margin)
H_e = min(H - 1, H_e + keep_margin)
W_s = max(0, W_s - keep_margin)
W_e = min(W - 1, W_e + keep_margin)
return int(D_s), int(D_e), int(H_s), int(H_e), int(W_s), int(W_e)
def vote(segmentation_sets):
onehot_segmentation_sets = [make_onehot_label(seg, 4) for seg in segmentation_sets]
vote_seg = np.argmax(sum(onehot_segmentation_sets), axis=-1)
vote_seg = np.array(np.expand_dims(vote_seg, axis=-1), dtype=np.uint8)
return vote_seg
<file_sep>/models/dunet.py
import keras
import tensorflow as tf
from keras import backend as K
from keras.layers import (BatchNormalization, Conv3D, Conv3DTranspose, Dropout,
Input, Layer, ReLU, Reshape, Softmax, concatenate,
merge)
from keras.losses import categorical_crossentropy
from .ac_layer import pyramidACBlock
def cross_entropy(y_true, y_pred):
ce_loss = categorical_crossentropy(y_true, y_pred)
return ce_loss
class DUNetMixACB(object):
def __init__(self, deploy=False):
super().__init__()
self.deploy = deploy
self.bn_size = 4
self.dense_conv = 3
self.growth_rate = 16
self.dropout_rate = 0.1
self.compress_rate = 0.5
self.num_init_features = 32
self.conv_size = 3
self.weight_decay = 0.0005
self.images = Input(shape=[32,32,32,2], name='input')
self.num_classes = 4
def switch_to_deploy(self):
self.deploy = True
def encoder(self, input_img):
img = Conv3D(filters=self.num_init_features, kernel_size=3, strides=1, padding='same',
kernel_initializer=keras.initializers.he_normal(),
kernel_regularizer=keras.regularizers.l2(l=self.weight_decay), name='feature_conv')(input_img)
img = BatchNormalization(name='feature_bn')(img)
img = ReLU(name='feature_relu')(img)
# encode path
dense1 = self.dense_block(img, 'dense1') # 80 32*32*32
trans1 = self.transition_down(dense1, 'trans1') # 40
dense2 = self.dense_block(trans1, 'dense2') # 88 16*16*16
trans2 = self.transition_down(dense2, 'trans2') # 44
dense3 = self.dense_block(trans2, 'dense3') # 92 8*8*8
trans3 = self.transition_down(dense3, 'trans3') # 46
dense4 = self.dense_block(trans3, 'dense4') # 94 4*4*4
return dense1, dense2, dense3, dense4
def decoder(self, dense1, dense2, dense3, dense4):
trans4 = self.transition_up(dense4, 'trans4') ## 47
# decode path
concat1 = self.SkipConn(dense3, trans4, 'concat1')
dense5 = self.dense_block(concat1, 'dense5') # 187
trans5 = self.transition_up(dense5, 'trans5') # 94
concat2 = self.SkipConn(dense2, trans5, 'concat2')
dense6 = self.dense_block(concat2, 'dense6') # 229
trans6 = self.transition_up(dense6, 'trans6') # 115
concat3 = self.SkipConn(dense1, trans6, 'concat3')
dense7 = self.dense_block(concat3, 'dense7') # 242
return dense7
def build_model(self):
enc = self.encoder(self.images)
dec = self.decoder(*enc)
seg = Conv3D(filters=self.num_classes, kernel_size=1, strides=1,
padding='same', dilation_rate=1, use_bias=False,
name='seg_conv')(dec)
seg = Softmax(name='output')(seg)
model = keras.Model(inputs=self.images, outputs=seg, name='deploy' if self.deploy else 'enrich')
return model
def bottle_layer(self, x_in, out_channel, padding='same', use_bias=True, name='bottle'):
x = Conv3D(filters=out_channel, kernel_size=1, strides=1,
padding=padding, use_bias=use_bias,
kernel_initializer=keras.initializers.he_normal(),
kernel_regularizer=keras.regularizers.l2(l=self.weight_decay), name=name+'.conv0')(x_in)
x = BatchNormalization(name=name+'.bn0')(x)
x = ReLU(name=name+'.relu0')(x)
return x
def dense_layer(self, f_in, name):
x = self.bottle_layer(f_in, self.bn_size*self.growth_rate, name=name+'.bottle')
x = self._aconv(x, self.growth_rate, 1, name=name+'.aconv')
x = Dropout(rate=self.dropout_rate, name=name+'.drop')(x)
x = concatenate([f_in, x], name=name+'.cat')
return x
def dense_block(self, f_in, name='dense_block0'):
x = f_in
for i in range(self.dense_conv):
x = self.dense_layer(x, name=name+'.denselayer{}'.format(i))
return x
def _aconv(self, x_in, out_channel, stride=1, name=None):
x = pyramidACBlock(x_in, name+'.pyacb', out_channels=out_channel, strides=stride,
kernel_initializer=keras.initializers.he_normal(),
kernel_regularizer=keras.regularizers.l2(self.weight_decay),
deploy=self.deploy)
x = ReLU(name=name+'.relu')(x)
return x
def _deconv(self, x_in, out_channel, padding='same', name=None):
x = Conv3DTranspose(filters=out_channel, kernel_size=self.conv_size, strides=2, padding=padding,
kernel_initializer=keras.initializers.he_normal(),
kernel_regularizer=keras.regularizers.l2(l=self.weight_decay), name=name+'.convtrans')(x_in)
x = BatchNormalization(name=name+'.bn')(x)
x = ReLU(name=name+'.relu')(x)
return x
def transition_down(self, f_in, name='trans_down'):
channels = f_in.get_shape()[-1].value
x = self._aconv(f_in, int(channels * self.compress_rate), 1, name=name+'.conv0')
x = self._aconv(x, x.get_shape()[-1].value, 2, name=name+'.conv1')
return x
def transition_up(self, f_in, name='trans_up'):
channels = f_in.get_shape()[-1].value
x = self._deconv(f_in, int(channels * self.compress_rate), name=name+'.deconv')
return x
def SkipConn(self, enc_f, dec_f, name='skip'):
"""
f_in_1: the feature map from the encoder path
f_in_2: the feature map from the decoder path
"""
return concatenate([enc_f, dec_f], name=name)
<file_sep>/README.md
# 3D-MASNet
This repository provides the experimental code for our paper "3D-MASNet: 3D Mixed-scale Asymmetric Convolutional Segmentation Network for 6-month-old Infant Brain MR Images".
Created by <NAME> at Beijing Normal University.
**For any questions, please contact <EMAIL> or <EMAIL>**
## Contents
- [Publication](#publication)
- [Dataset](#dataset)
- [Requirements](#requirements)
- [Runing the code](#runing-the-code)
- [Training](#training)
- [Model Fusion](#model-fusion)
- [Testing](#testing)
- [Results](#results)
## Publication
If you find that this work is useful for your research, please consider citing our paper.
## Dataset
The dataset used for model training and validation is from [iSeg-2019](http://iseg2019.web.unc.edu/). The iSeg organizers provide 10 infant subjects with labels for model training, and 13 infant subjects without labels for model validation. Each subject consists of T1 and T2 images for segmentation.
## Requirements
- python 3.5+
- tensorflow-gpu 1.7+
- Keras
- nibabel
## Runing the code
The process of **training**, **model fusion** and **testing** are all completed by configuring JSON files.
### Training
An example of JSON file for the training process shown in [train.json](/settings/train.json).
- "task": This parameter need to set to `"train"`, which means that we're going to train the model.
- "name": The name of this training process.
- "gpu": For example, if you have 3 gpus, but you want to use the 1st and 3rd gpu, you should write here as `"0,2"`
- "train_dir": The path to your training dataset.
- "train_ids": The list of ids of your training subjects.
- "lr_init": The maximum learning rate.
- "lr_min": The minimum learning rate.
- "epochs": The total training epochs.
- "train_nums_per_epoch": The total training cubes extracted in one epoch.
- "load_model_file": The path to pretrain model to be loaded. If not model file to be loade, you should set here as `null`.
Once you have configured your JSON file for training, you need run this command like this:
```
python -m client.run ./settings/train.json
```
### Model Fusion
Once your training process is over, you could configure your JSON file to fuse your model's parameters. An example of JSON file for the model fusion process shown in [deploy.json](/settings/deploy.json).
- "task": This parameter need to set to `"deploy"`, which means that we're going to fuse the model's parameters.
- "ori_model": List of pathes to models which are not fused.
Once you have configured your JSON file for model fusion, you need run this command like this:
```
python -m client.run ./settings/deploy.json
```
### Testing
Once your training or model fusion process is over, you can configure your JSON file to segment subjects' brain images. An example of JSON file for the model prediction shown in [predict.json](/settings/predict_undeploy.json).
- "task": This parameter need to set to `"predict"`, which means that we're going to make model prediction.
- "gpu_id": The id of the GPU which you want to use. For example, you want to use the second gpu, you should write `"1"`.
- "save_folder": The path to the folder of the saved segmentation results.
- "data_path": The path to the images to be segmented.
- Notice!! If you want to use a different dataset here with T1 and T2 images, you dataset should be organized like this:
```
├── subject-1-label.hdr
├── subject-1-label.img
├── subject-1-T1.hdr
├── subject-1-T1.img
├── subject-1-T2.hdr
├── subject-1-T2.img
├── subject-2-label.hdr
├── subject-2-label.img
├── subject-2-T1.hdr
├── subject-2-T1.img
├── subject-2-T2.hdr
├── subject-2-T2.img
├── ...
```
- "subjects": The list of ids of subjects to be segmented.
- "predict_mode": two optional choice —— `"evaluation"` and `"prediction"`
- `"evaluation"`: If you have labels, you can set this option and evaluate the model's accuracy.
- `"prediction"`: If you do not have labels, you need to set this.
- "model_files": The list of model files to be loaded for model prediction.
- If there is only one model file's path in this parameter, the program will output one segmentation result predicted by this model file.
- If there are multiple model files' pathes in this parameter, the program will adopt the majority voting strategy to combine these models' segmentation results.
- "deploy": If the model file to be loaded has fused parameters, you should set this parameter as `true`; otherwise, you need to set here as `false`.
We provide the pretrained model as example
- if you have run the command list in [Model Fusion](#model-fusion), you could run command like this:
```
python -m client.run ./settings/predict_example.json
```
- We also provide the pretrained models used for the iSeg-2019 competition, if you want to obatin the same results as we provided to the iSeg organizers, you could run command like this:
```
python -m client.run ./settings/predict_ensemble.json
```
- We also release the quantitative evaluation results of iSeg-2019 competition: `evaluation_result_sw_bnu.xlsx`.
## Results
**Comparison of segmentation performance on the 13 validation infants of iSeg-2019 between the proposed method and the methods of the top 4 ranked teams.**
- DICE
|Team | CSF | GM | WM | Average
|:----------:|:----------:|:-----------:|:-----:|:--------------:|
|Brain_Tech|0.961|0.928|0.911|0.933|
|FightAutism|0.960|0.929|0.911|0.933|
|OxfordIBME|0.960|0.927|0.907|0.931|
|QL111111|0.959|0.926|0.908|0.931|
|Our|**0.961**|**0.931**|**0.912**|**0.935**|
- MHD
|Team | CSF | GM | WM | Average
|:----------:|:----------:|:-----------:|:-----:|:--------------:|
|Brain_Tech|8.873|5.724|7.114|7.237|
|FightAutism|9.233|5.678|**6.678**|7.196|
|OxfordIBME|**8.560**|**5.495**|6.759|**6.938**|
|QL111111|9.484|5.601|7.028|7.371|
|Our|9.293|5.741|7.111|7.382|
- ASD
|Team | CSF | GM | WM | Average
|:----------:|:----------:|:-----------:|:-----:|:--------------:|
|Brain_Tech|0.108|0.300|0.347|0.252|
|FightAutism|0.110|0.300|0.341|0.250|
|OxfordIBME|0.112|0.307|0.353|0.257|
|QL111111|0.114|0.307|0.353|0.258|
|Our|**0.107**|**0.292**|**0.332**|**0.244**|
<file_sep>/util/misc.py
import json
import numpy as np
def cosine_annealing(epoch, lr_init, lr_min):
return ((lr_init-lr_min)/2)*(np.cos(np.pi*(np.mod(epoch-1,50)/50))+1)+lr_min
class Params(object):
def __init__(self, param):
if not isinstance(param, dict):
raise ValueError("Wrong value type, expected `dict`, but got {}".format(type(param)))
self.param = param
def __getattr__(self, name):
return self.param[name]
def save_params(params: Params, path):
param_dict = params.param
param_dict = json.dumps(param_dict)
f = open(path, 'w')
f.write(param_dict)
f.close()
<file_sep>/client/predict.py
import argparse
import os
import time
import keras.backend as K
import nibabel as nib
import numpy as np
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
from models.dunet import DUNetMixACB
from util.metrics import dice
from util.predict_funcs import predict_segmentation
from util.prep import image_norm, maybe_mkdir_p, vote
from util.timer import Clock
def save(t1_path, save_path, segmentation):
t1_affine = nib.load(t1_path).get_affine()
segmentation = np.array(segmentation, dtype=np.uint8)
seg = nib.AnalyzeImage(segmentation, t1_affine)
nib.save(seg, save_path)
def analyze_score(dsc_score):
csf = []
gm = []
wm = []
for i in range(len(dsc_score)):
csf.append(dsc_score[i][0])
gm.append(dsc_score[i][1])
wm.append(dsc_score[i][2])
print('%s | %2.2f | %2.2f | %2.2f | %2.2f |' % ('Avg Dice', np.mean(csf), np.mean(
gm), np.mean(wm), np.mean([np.mean(csf), np.mean(gm), np.mean(wm)])))
def cal_acc(label, pred):
dsc = []
print('------------------------------------------')
for i in range(1, 4):
dsc_i = dice(pred, label, i)
dsc_i = round(dsc_i*100, 2)
dsc.append(dsc_i)
print('Data | CSF | GM | WM | Avg. |')
print('%s | %2.2f | %2.2f | %2.2f | %2.2f |' %
('Dice', dsc[0], dsc[1], dsc[2], np.mean(dsc)))
return dsc
def predict(path_dict, model, cube_size, strides):
affine = nib.load(path_dict['t1w']).get_affine()
t1_data = nib.load(path_dict['t1w']).get_data()
t2_data = nib.load(path_dict['t2w']).get_data()
vol_size = t1_data.shape[0:3]
mask = (t1_data > 0)
t1_data_norm = image_norm(t1_data)
t2_data_norm = image_norm(t2_data)
subject_data = {'t1w': t1_data_norm, 't2w': t2_data_norm}
segmentation = predict_segmentation(
subject_data, 30, cube_size, strides, model, 1)
segmentation = np.expand_dims(np.argmax(segmentation, axis=-1), axis=-1)
if 'label' in path_dict.keys():
label_data = nib.load(path_dict['label']).get_data()
cal_acc(label_data, segmentation)
return segmentation
def main(params):
gpu_id = params.gpu_id
save_folder = params.save_folder
data_path = params.data_path
cube_size = [32] * 3
strides = [28] * 3
clock = Clock()
maybe_mkdir_p(os.path.abspath(save_folder))
# close useless warning information
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
if gpu_id is not None:
gpu = '/gpu:' + str(gpu_id)
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.allow_soft_placement = True
set_session(tf.Session(config=config))
else:
gpu = '/cpu:0'
with tf.device(gpu):
normal_model = DUNetMixACB(deploy=params.deploy).build_model()
dice_score = []
for i in params.subjects:
print("preprocess subject: {}".format(i))
t1_path = os.path.join(data_path, 'subject-' + str(i) + '-T1.img')
t2_path = os.path.join(data_path, 'subject-' + str(i) + '-T2.img')
save_seg_path = os.path.join(
save_folder, 'subject-' + str(i) + '-label.img')
input_dict = {'t1w': t1_path, 't2w': t2_path}
segmentation_sets = []
if params.predict_mode == 'evaluation':
input_dict['label'] = os.path.join(
data_path, 'subject-' + str(i) + '-label.img')
for j in range(len(params.model_files)):
print("subj {}, j {}".format(i, j))
normal_model.load_weights(params.model_files[j])
clock.tic()
seg = predict(input_dict, normal_model, cube_size, strides)
segmentation_sets.append(seg)
final_seg = vote(segmentation_sets)
save(t1_path, save_seg_path, final_seg)
clock.toc()
if params.predict_mode == 'evaluation':
print("The ensemble result is :")
label_data = nib.load(input_dict['label']).get_data()
dsc = cal_acc(label_data, final_seg)
dice_score.append(dsc)
print("The average time is {}.".format(clock.average_time/60))
if params.predict_mode == 'evaluation':
analyze_score(dice_score)
<file_sep>/util/timer.py
''' A collection of general python utilities '''
import time
import datetime
class Timer(object):
"""
modified from:
http://stackoverflow.com/questions/5849800/tic-toc-functions-analog-in-python
a helper class for timing
use:
with Timer('foo_stuff'):
# do some foo
# do some stuff
as an alternative to
t = time.time()
# do stuff
elapsed = time.time() - t
"""
def __init__(self, name=None, verbose=True):
self.name = name
self.verbose = verbose
def __enter__(self):
self.tstart = time.time()
def __exit__(self, type, value, traceback):
if self.verbose:
if self.name:
print('[%s]' % self.name, end="")
print('Elapsed: %6.4s' % (time.time() - self.tstart))
class Clock(object):
'''
A simple timer.
'''
def __init__(self):
self.init_time = time.time()
self.total_time = 0.
self.calls = 0
self.start_time = 0.
self.diff = 0.
self.average_time = 0.
self.remain_time = 0.
def tic(self):
# using time.time instead of time.clock because time time.clock
# does not normalize for multithreading
self.start_time = time.time()
def toc(self, average=True):
self.diff = time.time() - self.start_time
self.total_time += self.diff
self.calls += 1
self.average_time = self.total_time / self.calls
if average:
return self.average_time
else:
return self.diff
def remain(self, iters, max_iters):
if iters == 0:
self.remain_time = 0
else:
self.remain_time = (time.time() - self.init_time) * \
(max_iters - iters) / iters
return str(datetime.timedelta(seconds=int(self.remain_time)))
<file_sep>/util/model_fusion.py
import numpy as np
import keras
CUBE_KERNEL_KEYWORD = '.conv_nxnxn'
def _fuse_kernel(kernel, gamma, std, eps=1e-5):
b_gamma = np.reshape(gamma, (1, 1, 1, 1, kernel.shape[-1]))
b_gamma = np.tile(b_gamma, (kernel.shape[0], kernel.shape[1], kernel.shape[2], kernel.shape[3], 1))
b_std = np.reshape(std, (1, 1, 1, 1, kernel.shape[-1]))
b_std = np.tile(std, (kernel.shape[0], kernel.shape[1], kernel.shape[2], kernel.shape[3], 1))
return kernel * b_gamma / b_std
def kernel_fusion(kernels):
# list of parameters in the order of [nxnxn, 1xnxn, nx1xn, nxnx1]
ksize = kernels[0].shape[0]
kernel_nxnxn = kernels[0]
kernel_1xnxn = kernels[1]
kernel_nx1xn = kernels[2]
kernel_nxnx1 = kernels[3]
kernel_nxnxn[ksize//2:ksize//2+1, 0:ksize, 0:ksize, :, :] += kernel_1xnxn
kernel_nxnxn[0:ksize, ksize//2:ksize//2+1, 0:ksize, :, :] += kernel_nx1xn
kernel_nxnxn[0:ksize, 0:ksize, ksize//2:ksize//2+1, :, :] += kernel_nxnx1
return kernel_nxnxn
def deploy(original_model, deploy_model, weights_path, fused_weights_path, eps=1e-5):
original_model.load_weights(weights_path)
layer_names = [layer.name for layer in original_model.layers]
conv_nxnxn_var_names = [name for name in layer_names if CUBE_KERNEL_KEYWORD in name]
flag = True
for conv_nxnxn_name in conv_nxnxn_var_names:
print(conv_nxnxn_name)
conv_nxnxn_kernel = original_model.get_layer(conv_nxnxn_name).get_weights()[0]
conv_1xnxn_kernel = original_model.get_layer(conv_nxnxn_name.replace(CUBE_KERNEL_KEYWORD, '.conv_1xnxn')).get_weights()[0]
conv_nx1xn_kernel = original_model.get_layer(conv_nxnxn_name.replace(CUBE_KERNEL_KEYWORD, '.conv_nx1xn')).get_weights()[0]
conv_nxnx1_kernel = original_model.get_layer(conv_nxnxn_name.replace(CUBE_KERNEL_KEYWORD, '.conv_nxnx1')).get_weights()[0]
bn_nxnxn = original_model.get_layer(conv_nxnxn_name.replace(CUBE_KERNEL_KEYWORD, '.bn_nxnxn')).get_weights()
bn_1xnxn = original_model.get_layer(conv_nxnxn_name.replace(CUBE_KERNEL_KEYWORD, '.bn_1xnxn')).get_weights()
bn_nx1xn = original_model.get_layer(conv_nxnxn_name.replace(CUBE_KERNEL_KEYWORD, '.bn_nx1xn')).get_weights()
bn_nxnx1 = original_model.get_layer(conv_nxnxn_name.replace(CUBE_KERNEL_KEYWORD, '.bn_nxnx1')).get_weights()
kernels = [conv_nxnxn_kernel, conv_1xnxn_kernel, conv_nx1xn_kernel, conv_nxnx1_kernel]
gammas = [bn_nxnxn[0], bn_1xnxn[0], bn_nx1xn[0], bn_nxnx1[0]]
betas = [bn_nxnxn[1], bn_1xnxn[1], bn_nx1xn[1], bn_nxnx1[1]]
means = [bn_nxnxn[2], bn_1xnxn[2], bn_nx1xn[2], bn_nxnx1[2]]
vars = [bn_nxnxn[3], bn_1xnxn[3], bn_nx1xn[3], bn_nxnx1[3]]
if flag:
print(kernels[0].dtype, vars[0].dtype)
flag = False
stds = [np.sqrt(var + eps) for var in vars]
fused_bias = betas[0] + betas[1] + betas[2] + betas[3] - means[0] * gammas[0] / stds[0] - means[1] * gammas[1] / stds[1] \
- means[2] * gammas[2] / stds[2] - means[3] * gammas[3] / stds[3]
fused_kernels = [_fuse_kernel(kernels[i], gammas[i], stds[i], eps) for i in range(4)]
fused_weights = kernel_fusion(fused_kernels)
# fused_weights, fused_b = kernel_fusion(kernels, gammas, betas, means, vars)
total_weights = [fused_weights, fused_bias]
deploy_model.get_layer(conv_nxnxn_name.replace(CUBE_KERNEL_KEYWORD, '.fused_conv')).set_weights(total_weights)
for name in layer_names:
if '_nxnxn' not in name and '_1xnxn' not in name and '_nx1xn' not in name and '_nxnx1' not in name and '.add' not in name and 'lambda' not in name and 'concatenate' not in name:
print(name)
deploy_model.get_layer(name).set_weights(original_model.get_layer(name).get_weights())
deploy_model.save_weights(fused_weights_path)
|
cbc2be65ad431ab7439bf2dccb7014878d7070d3
|
[
"Markdown",
"Python"
] | 14 |
Markdown
|
helab207/3D-MASNet
|
ff9fbb7d7ac13eb8082ce4cd3923a45dfb21fad6
|
019a6a727e12dc07f44a1a37e596cb6b797e96d3
|
refs/heads/master
|
<file_sep>cvtheque
========
CVthèque
|
be43bca0aa91419aef001867482761c48edbad9b
|
[
"Markdown"
] | 1 |
Markdown
|
franzz0/cvtheque
|
a87bcf2ade15ffc5d26bbeddb362f803aa735ab0
|
de2395770da1b3e57cb88285ffe33c33bd867184
|
refs/heads/master
|
<repo_name>yangchuhua/scRNAseq_workflow_benchmark<file_sep>/code/scrnaseq_workflow_DE.R
#####################################################
#
# scRNASeq pipeline functions
#
# PART VII: Differential expression analysis
# _______________________
#
# This script contains wrapper functions to different differential expression analysis methods.
#
# Authors:
# <NAME> (<EMAIL>)
# <NAME> (<EMAIL>)
####################################################
##########################################
# Finding marker genes
#########################################
# Inputs for the different functions:
# - sce = the SCESet after QC or after normalization
# - cl_id : the name of the grouping (e.g. "mclust") used in the comparison. Must be
# a column name of pData(sce)
# - cl_ref: the entry in pData(sce)$cl_id that should be used as the reference,
# i.e. against which all the rest of the cells are compared
# - alpha = false discovery rate cutoff, default = 0.05
# - fc_cutoff = log2 fold change cutoff, default = 0.5
#______________________________________________
# Wilcoxon test
# Additional input: pseudocount = a constant added to each expression value
# This is only used for calculating fold changes. It wil shrink the fold change
# for very low expressed genes and prevent getting ridiculous values due to division by very
# small numbers. The default is 2, meaning that it will mostly affect genes having
# mean log-transformed expression values below 1.
#______________________________________________
run_wilcoxon_test = function(sce,cl_id,cl_ref,
alpha=0.05,fc_cutoff=0.5,pseudocount=NULL){
if(!is.null(pseudocount)){warning("The pseudocount argument is deprecated and will be removed!")}
ignore = is.na(pData(sce)[,cl_id])
sce = sce[,!ignore]
in_clust = pData(sce)[,cl_id] %in% cl_ref
pvals = apply(norm_exprs(sce),1,
function(x) wilcox.test(x=x[in_clust],y=x[!in_clust])$p.value)
fc = apply(norm_exprs(sce),1,
function(x) mean(x[in_clust])-mean(x[!in_clust]))
#log2((mean(2^x[in_clust]-1)+pseudocount)/(mean(2^x[!in_clust]-1)+pseudocount))
out = data.table(gene_id = rownames(sce), pval = pvals, log2fc = fc)
out[,adj_pval:=p.adjust(pval,method="fdr")]
out[,DE_flag:=(adj_pval<alpha & abs(log2fc)>fc_cutoff)]
return(out)
}
#_________________________
# limma (can be unreliable with zero-inflated data)
# as input for limma-voom, the raw, non-logged counts are provided along with the size factros.
# The voom transformation then uses tehse to normalize internally.
# as input for limma-trend, log2(CPM+1) are used as recommended by the authors
#____________________
#
run_limma = function(sce,cl_id,cl_ref,
alpha=0.05,fc_cutoff=0.5,count_thr=1,pct=50, method = "trend"){
if(!method %in% c("voom","trend")){
stop("Method has to be either \"voom\" or \"trend\".")
}
ignore = is.na(pData(sce)[,cl_id])
sce = sce[,!ignore]
res = as.factor(pData(sce)[,cl_id] %in% cl_ref)
design = model.matrix(~0+res)
colnames(design) = c("Rest","Cluster")
rownames(design) = colnames(sce)
# filter out genes not detected at a count of count-thr in at least
# 50% of cells in at least one cluster. Outlier cells (clusters with only one cell) are ignored.
clust_sizes = table(pData(sce)[,cl_id])
clusts = names(clust_sizes[which(clust_sizes>1)])
keep_mat = matrix(rep(NA,dim(sce)[1]*length(clusts)),ncol = length(clusts))
for(i in seq(length(clusts))){
keep_mat[,i] = rowSums(counts(sce)[,pData(sce)[,cl_id]==clusts[i]]>=count_thr)>=pct/100*length(which(pData(sce)[,cl_id]==clusts[i]))
}
keep = apply(keep_mat, 1, function(x) any(x))
#convert to DGEList and filter
dge = convertTo(sce[keep,],"edgeR")
contrast_matrix = limma::makeContrasts(Cluster-Rest, levels = design)
if(method == "voom"){
# transforming counts
voomt = limma::voom(dge,plot=T,design = design)
#do differential expression analysis on voom transformed data
fit = limma::lmFit(voomt, design)
fit2 = limma::contrasts.fit(fit,contrast_matrix)
fit2 = limma::eBayes(fit2)
} else {
logCPM = edgeR::cpm(dge, log=TRUE, prior.count=1)
fit = limma::lmFit(logCPM, design)
fit2 = limma::contrasts.fit(fit,contrast_matrix)
fit2 = limma::eBayes(fit2, trend = T)
}
diff_exp = limma::topTable(fit2,adjust="BH",number = dim(dge)[1])
out = data.table(gene_id = rownames(diff_exp),diff_exp)
out[,DE_flag:=as.factor(adj.P.Val < alpha & abs(logFC) > fc_cutoff)]
return(out)
}
#______________________________________________________________________
# MAST
# as input, use either the raw counts as log2(counts+1), stored in the exprs slot
# or the normalized counts on log scale, stored in the norm_exprs slot
#_______________________________________________________________________
run_MAST = function(sce,cl_id,cl_ref,n_cores = 8,nbins=10,min_per_bin=30,
alpha=0.05,fc_cutoff=0.5,norm=F,set_thresh=T){
library(MAST)
ignore = is.na(pData(sce)[,cl_id])
sce = sce[,!ignore]
options(mc.cores = n_cores)
if(norm){
sca = FromMatrix(norm_exprs(sce), pData(sce), fData(sce))} else {
sca = FromMatrix(log2(counts(sce)+1), pData(sce), fData(sce))
}
# adaptive thresholding
# note how the threshold moves with median expression
if(set_thresh){
message("Calculating expression thresholds...\n
Check the MAST_theresholds plot. If there are no clear bimodal\n
distributions, the thresholds are likely to be nonsense.\n
If that is the case, re-run this function setting set_thresh = F")
thres = thresholdSCRNACountMatrix(assay(sca), nbins = nbins, min_per_bin = min_per_bin)
if(!any(thres$cutpoint!=0)){message("All cut points are zero. Try using a different
value of nbins and min_per_bin or set set_thresh=FALSE")}
par(mfrow=c(nbins%%4+1,4))
plot(thres)
dev.copy2pdf(file = file.path(plotdir,"MAST_thresholds.pdf"),width=8,height=3*(nbins%%4+1))
par(mfrow=c(1,1))
assays(sca) = list(thresh=thres$counts_threshold, counts=assay(sca))
}
cond=factor(colData(sca)[,cl_id]==cl_ref)
cond=relevel(cond,"FALSE")
colData(sca)$condition=cond
# calculate the cellular detection rate as no. detected features / no. total features
# and center it
colData(sca)$cngeneson = scale(pData(sce)$total_features/dim(sce)[1],scale=F)
# fit model (note that this will take time for large datasets!!)
message("Fitting models...")
zlmCond = zlm(~condition + cngeneson, sca)
summaryCond = summary(zlmCond, doLRT='conditionTRUE')
#extract the results as a data.table
summaryDt = summaryCond$datatable
fcHurdle = merge(summaryDt[contrast=='conditionTRUE' & component=='H',.(primerid, `Pr(>Chisq)`)], #hurdle P values
summaryDt[contrast=='conditionTRUE' & component=='logFC', .(primerid, coef, ci.hi, ci.lo)], by='primerid') #logFC coefficients
fcHurdle[,fdr:=p.adjust(`Pr(>Chisq)`, 'fdr')]
names(fcHurdle)[1:3] = c("gene_id","pval","log2FC")
fcHurdle[,DE_flag:=as.factor(fdr<alpha & abs(log2FC)>fc_cutoff)]
return(fcHurdle)
}
<file_sep>/code/scrnaseq_workflow_Setup.R
#####################################################
#
# scRNASeq pipeline functions
#
# PART I: Setup
# _______________________
#
# This script contains heleper fucntions for reading data, gene annotation and loading required libraries.
#
# Authors:
# <NAME> (<EMAIL>)
# <NAME> (<EMAIL>)
####################################################
################
# Library Calls
################
# note that these are only what is needed throughout the analysis
# as some of the other packages load a LOT of depndencies, you might have
# to unload them / restart R after using them and before being able to
# load any new packages
library_calls = function(){
library(Rtsne)
library(ggplot2)
library(data.table)
library(scater)
library(scran)
library(RColorBrewer)
}
################################
# Reading data & Gene annotation
################################
# Helper function to read count matrix from csv.
read_data = function(infile,experiment_id){
counts = read.delim(infile, header=T, stringsAsFactors=FALSE)
# matrix count format
rownames(counts) = counts$Gene.Id
counts = counts[,-1]
colnames(counts) = paste0(experiment_id,"_C",seq(dim(counts)[2]),sep="")
return(counts)
}
#----------------------------------
# Annotating genes using ensembldb (the advantage is that it is faster than biomaRt, will
# return exactly one entry per gene including non-coding ones, and uses always
# the same version (regardless of bioconductor version), so this is used
# by default)
get_gene_annotations = function(gene_list,v=F,get_descriptions=T,organism = "human"){
library(ensembldb)
if(organism == "human"){
library(EnsDb.Hsapiens.v79)
edb = EnsDb.Hsapiens.v79
} else if(organism == "mouse"){
library(EnsDb.Mmusculus.v75)
edb = EnsDb.Mmusculus.v75
} else {stop("Currently, annotation is only available for organisms human or mouse.")}
my_get = function(x,db,v){
out = tryCatch({get(x,db)[1]},
error = function(cond){
if(v) {message(cond)}
return("")},
finally = {})
return(out)
}
gene_info = ensembldb::genes(edb,filter = list(GeneIdFilter(gene_list)))
gene_info_dt = data.table(gene_id = names(gene_info),
chr = as.character(seqnames(gene_info)),
symbol = make.unique(gene_info$symbol),
gene_biotype = gene_info$gene_biotype)
geneName = data.table(gene_id = gene_list)
geneName = merge(geneName,gene_info_dt,by="gene_id",all=T)
if(get_descriptions & organism == "human"){
library(org.Hs.eg.db)
geneName[,eg:=my_get(gene_id,db=org.Hs.egENSEMBL2EG,v),by="gene_id"]
geneName[,description:=my_get(eg,db=org.Hs.egGENENAME,v),by="eg"]
} else if(get_descriptions){
library(org.Mm.eg.db)
geneName[,eg:=my_get(gene_id,db=org.Mm.egENSEMBL2EG,v),by="gene_id"]
geneName[,description:=my_get(eg,db=org.Mm.egGENENAME,v),by="eg"]
}
return(geneName)
}
#-----------------------------------
# Annotating genes using biomaRt
get_gene_annotations_biomart = function(gene_list){
library(biomaRt)
# Load the organism-specific biomart
ensembl = biomaRt::useEnsembl(
biomart = 'ensembl',
dataset = paste0('hsapiens', '_gene_ensembl'),
version = 83
)
#
geneName = biomaRt::getBM(attributes = c('ensembl_gene_id','hgnc_symbol',
"entrezgene", "description","chromosome_name"),
filters = 'ensembl_gene_id',
values = gene_list,
mart = ensembl)
description = lapply(seq(length(geneName$description)),function(i){
strsplit(geneName$description[i],"[[]")[[1]][1]
})
description = (unlist(description))
geneName$description = description
colnames(geneName) = c('gene_id','symbol','eg','description','chr')
geneName = data.table(geneName)
setkey(geneName,'gene_id')
geneName = unique(geneName) #remove duplicate entrez gene identifiers
geneName[,symbol:=make.unique(symbol)]
#save(geneName,file="data/output/geneName.RData")
return(geneName)
}
<file_sep>/code/scRNASeq_pipeline_functions.R
###############################################
# scRNASeq workflow - Functions
#
# This script sources all parts of the scRNASeq workflow.
###############################################
source(file.path(code_dir, "scrnaseq_workflow_Setup.R"))
source(file.path(code_dir, "scrnaseq_workflow_QC.R"))
source(file.path(code_dir, "scrnaseq_workflow_Normalization.R"))
source(file.path(code_dir, "scrnaseq_workflow_Feature_Selection.R"))
source(file.path(code_dir, "scrnaseq_workflow_Clustering.R"))
source(file.path(code_dir, "scrnaseq_workflow_CellSIUS.R"))
source(file.path(code_dir, "scrnaseq_workflow_DE.R"))
source(file.path(code_dir, "scrnaseq_workflow_Plotting.R"))
<file_sep>/code/scrnaseq_workflow_CellSIUS.R
#####################################################
#
# scRNASeq pipeline functions
#
# PART VI: Cell subtype identification using CellSIUS
# _______________________
#
# This implements the CellSIUS method. Note that this can also be used with a custom workflow, as long as you provide
# your data as an SCESet that contains all relevant fields in pData and fData.
#
# Authors:
# <NAME> (<EMAIL>)
# <NAME> (<EMAIL>)
####################################################
#-----------------------------------------------
# LICENSE
#-----------------------------------------------
#Copyright 2018 Novartis Institutes for BioMedical Research 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 "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.
# limitations under the License.
#########################################
# Identifying rare cell types
#########################################
cellsius_main = function(sce,group_id,min_n_cells=10,verbose = T, min_fc = 2,
organism = "human", corr_cutoff = NULL, iter=0, max_perc_cells = 50,
fc_between_cutoff = 1, mcl_path = "/da/dmp/cb/prog/mcl-14-137/bin/mcl"){
library(Ckmeans.1d.dp)
expr_dt = data.table(gene_id = rownames(sce),norm_exprs(sce))
expr_dt_melt = melt(expr_dt,id.vars="gene_id",val="expr",var="cell_idx")
expr_dt_melt = merge(expr_dt_melt,
data.table(cell_idx=colnames(sce),main_cluster=as.character(pData(sce)[,group_id])),
by="cell_idx")
#Identify genes with significant bimodal distribution
expr_dt_melt[,c("N_cells","within_p","pos0","pos1","Dpos"):=cellsius_find_bimodal_genes(expr,min_n_cells = min_n_cells, max_perc_cells = max_perc_cells),by=c('gene_id','main_cluster')]
expr_dt_melt[,sig := within_p<100 & Dpos > min_fc]
expr_dt_melt[sig==T, within_adj_p:=p.adjust(within_p),by=c('cell_idx')] #correct for multiple testing, only consider genes where test has actually been run
expr_dt_melt[,sig:=within_adj_p<0.1]
expr_dt_melt = expr_dt_melt[gene_id %in% expr_dt_melt[!is.na(sig) & sig==T]$gene_id]
# If no bimodal gene were found, exit and return NA
if(dim(expr_dt_melt)[1] == 0){
print("No genes with bimodal distribution found, returning NA.")
return(NA)
}
# Check whether these genes are specific to the subcluster
for(clust in unique(expr_dt_melt$main_cluster)){
expr_dt_melt = expr_dt_melt[,paste0(clust,"_",c("p_between","fc")):=cellsius_test_cluster_specificity(
expr,main_cluster,clust, fc_between_cutoff = fc_between_cutoff),by="gene_id"]
expr_dt_melt[main_cluster==clust,keep:=(expr_dt_melt[main_cluster==clust][[paste0(clust,"_p_between")]] < 0.1)]
}
expr_dt_melt = expr_dt_melt[keep==TRUE & !is.na(sig)]
# If there are still non-specific genes, discard them (this can happen for
# very high expressed genes like mitochondrial genes)
expr_dt_melt[,n_clust_per_gene:=length(unique(main_cluster)),by='gene_id']
expr_dt_melt = expr_dt_melt[n_clust_per_gene==1]
expr_dt_melt[,n_clust_per_gene:=NULL]
# Identify correlated gene sets with MCL
expr_dt_melt = expr_dt_melt[,gene_cluster:=0]
expr_dt_melt = cellsius_find_gene_sets(expr_dt_melt, corr_cutoff = corr_cutoff, mcl_path=mcl_path)
# discard gene sets that only contain one gene (those are assigned to cluster 0)
expr_dt_melt = expr_dt_melt[gene_cluster !=0 ]
if(dim(expr_dt_melt)[1] == 0){
print("No subclusters found, returning NA.")
return(NA)
}
# Extract cell subclusters
expr_dt_melt[,sub_cluster:=main_cluster]
expr_dt_melt[,mean_expr := mean(expr), by = c('main_cluster','gene_cluster','cell_idx')]
expr_dt_melt[,sub_cluster:=cellsius_sub_cluster(mean_expr,sub_cluster,gene_cluster, iter=iter),by=c('main_cluster','gene_cluster')]
# Check how many cells belong to the subgroup relative to the total cluster size.
# If a sub cluster contains more than max_perc_cells cells, discard it.
clust_list = expr_dt_melt[,list(sub = length(unique(cell_idx))) ,by=c('sub_cluster','main_cluster')]
clust_list[,tot := sum(sub)/(length(sub_cluster)/2), by= 'main_cluster']
clust_list = clust_list[grep('_1$',sub_cluster)]
clust_list[,perc:=sub/tot*100]
discard_sub_clust = clust_list[perc > max_perc_cells]$sub_cluster
discard_sub_clust = append(discard_sub_clust,gsub('_1$','_0',discard_sub_clust))
expr_dt_melt = expr_dt_melt[!sub_cluster%in%discard_sub_clust]
# If verbose is TRUE, print a summary of the results
if(verbose){
# annotate genes (only if verbose)
gene_info = get_gene_annotations(unique(expr_dt_melt$gene_id),get_descriptions = T,
organism = organism)
expr_dt_melt = merge(expr_dt_melt,gene_info, by = 'gene_id')
cellsius_print_summary(expr_dt_melt)
}
return(expr_dt_melt)
}
##################################################
# STEP 1: Identify genes with bimodal distribution
##################################################
cellsius_find_bimodal_genes = function(expr, min_n_cells, max_perc_cells){
#skip genes with 0 expression
if(sum(expr)==0){
return(list(-1,100,-1,-1,-1))
}
# run k-means
k1d = Ckmeans.1d.dp(expr,k=2)
# check if a cluster with more than n cells exists
indx = which(k1d$size>min_n_cells)
if(length(indx)>1 ){
# do statistic only if in pos2 cells are less than max_perc_cells% of the total cells in the cluster
if(k1d$size[2] < round(length(expr)*max_perc_cells/100)){
t1=tryCatch({t.test(expr[which(k1d$cluster==2)],y=expr[which(k1d$cluster==1)])},
error = function(cond){return(0)},
finally={}
)
if(!is.numeric(t1)){
p1=t1$p.value
N0=k1d$size[1] # number of cells where the gene is downregulated
N1=k1d$size[2] # number of cells where the gene is upregulated
pos0=k1d$centers[1]
pos1=k1d$centers[2]
Dpos=pos1-pos0
return(list(N1,p1,pos0,pos1,Dpos))
} #else {print(paste("ttest failed, dpos = ",pos1-pos0))} # for testing
}
}
# if no cluster was found, return a list of dummy values
return(list(-1,100,-1,-1,-1))
}
##################################################
# STEP 2: Check whether these genes are specific to one cell subgroup
###################################################
cellsius_test_cluster_specificity = function(exprs, cluster, current_cluster, fc_between_cutoff){
in_clust = which(cluster == current_cluster)
k1d = Ckmeans.1d.dp(exprs[in_clust],k=2)
in_subclust = in_clust[which(k1d$cluster==2)]
mean_in = mean(exprs[in_subclust])
mean_out = mean(exprs[-in_subclust])
mean_out_nozero = mean(exprs[-in_subclust][exprs[-in_subclust]>0])
# If there are subclusters, but all cells outside the subcluster express 0,
# set mean_out_nozero to 0
if(length(in_subclust>0) && !any(exprs[-in_subclust]>0)){mean_out_nozero=0}
fc = mean_in - mean_out
ts = tryCatch({t.test(exprs[in_subclust],exprs[-in_clust])},
error = function(cond){ return(0)})
if(!is.numeric(ts)){pv = ts$p.value} else {
#print(paste("ttest failed, fc = ",mean_in-mean_out_nozero)) #for testing only
pv=999}
if(!is.nan(mean_out_nozero) && (mean_in-mean_out_nozero < fc_between_cutoff)) pv = 999
return(list(pv,fc))
}
#####################################################
# STEP 3: MCL clustering to find correlated gene sets
#####################################################
cellsius_find_gene_sets = function(expr_dt_melt, corr_cutoff = NULL, min_corr = 0.35, max_corr = 0.5,
mcl_path = "/da/dmp/cb/prog/mcl-14-137/bin/mcl"){
library(igraph)
for(clust in unique(expr_dt_melt$main_cluster)){
if(length(unique(expr_dt_melt[main_cluster == clust]$gene_id))==1) { next }
mat = dcast.data.table(expr_dt_melt[main_cluster==clust], gene_id ~ cell_idx,
value.var = 'expr')
mat = mat[rowSums(mat[,-1,with=F])!=0,]
corr.mat = cor(t(mat[,-1,with=F]))
dimnames(corr.mat) = list(mat$gene_id,mat$gene_id)
if(is.null(corr_cutoff)){
corr_cutoff = max(quantile(corr.mat[corr.mat!=1],0.95),min_corr)
corr_cutoff = min(corr_cutoff, max_corr)}
adj.corr = corr.mat
adj.corr[adj.corr<corr_cutoff] = 0
adj.corr[adj.corr>=corr_cutoff] = 1
diag(adj.corr) = 0 # no self-loop for MCL
graphs = get.data.frame( graph_from_adjacency_matrix(adj.corr), what = "edges") # gene connection for graphs
# if a graph has no edges (i.e. all genes are uncorrelated),
# assign all genes to cluster "0" and go to next iteration
if(dim(graphs)[1]==0){
expr_dt_melt = expr_dt_melt[main_cluster == clust, gene_cluster := 0]
next
}
graphs = data.frame(graphs,CORR=sapply(seq(dim(graphs)[1]), function(i) corr.mat[graphs$from[i],graphs$to[i]] -corr_cutoff))
write.table(graphs, file = "tmp.mcl.inp",row.names=F,col.names=F,sep = " ")
system(paste0(mcl_path, " tmp.mcl.inp --abc -o tmp.mcl.out"))
x = scan("tmp.mcl.out", what="", sep="\n")
y = strsplit(x, "[[:space:]]+")
y = lapply(seq(length(y)), function(i){
tmp = sapply(seq(length(y[[i]])),function(j){
gsub('\"','',y[[i]][j])
})
})
for(i in seq(length(y))){
if(length(y[[i]] > 1)){
expr_dt_melt = expr_dt_melt[main_cluster==clust & gene_id %in% y[[i]],gene_cluster:=i]
}
}
}
return(expr_dt_melt)
}
############################################
# Step 4: Assign cells to subgroups
############################################
cellsius_sub_cluster = function(mean_expr,sub_cluster,gene_cluster, iter = 0){
k1d = Ckmeans.1d.dp(mean_expr,k=2)$cluster
cells_sub = (k1d==2)
if(iter == 0){return(paste0(sub_cluster,"_",gene_cluster,"_",as.numeric(cells_sub)))}
# if iter is set higher than 0, a second step of kmeans clustering.
# This will remove the lowest peak and can sometimes help to get a more
# accurate classification.
k1d = Ckmeans.1d.dp(mean_expr[cells_sub],k=2)$cluster
if (max(k1d)>1) {
cells_sub[cells_sub] = (k1d==2)
return(paste0(sub_cluster,"_",gene_cluster,"_",as.numeric(cells_sub)))
}
return(paste0(sub_cluster,"_",gene_cluster,"_",0))
}
#######################################
# Step 5: Print summary
#######################################
cellsius_print_summary = function(expr_dt_melt){
cat('--------------------------------------------------------\n',
'Summary of rare cell types\n',
'--------------------------------------------------------\n\n')
for(clust in unique(expr_dt_melt$main_cluster)){
if(!any(expr_dt_melt[main_cluster==clust]$gene_cluster!=0)){
next
}
cat('Main cluster: ', clust, '\n', '---------------\n')
subclusts = unique(expr_dt_melt[main_cluster==clust & gene_cluster!=0][order(gene_cluster)]$gene_cluster)
for(subclust in subclusts){
cat('Subcluster: ', subclust, '\n',
'Number of cells: ',
length(unique(expr_dt_melt[main_cluster==clust &
sub_cluster == paste(clust,subclust,1,sep="_")]$cell_idx)),
'\n Marker genes: \n')
print(unique(expr_dt_melt[main_cluster==clust & gene_cluster == subclust][,c("gene_id","symbol","description")]))
cat('\n\n')
}
}
}
############################################
# OPTIONAL: Final assignment to unique clusters
# Note: This is different from the previous subcluster asignemnt, where a cell can potentially be
# a member of multiple subgroups.
############################################
cellsius_final_cluster_assignment = function(rare, sce, group_id, min_n_genes = 3){
rare[,n_genes:=length(unique(gene_id)),by='sub_cluster']
assignments = data.table(cell_idx = colnames(sce), pData(sce)[,group_id])
names(assignments) = c('cell_idx', 'group')
assignments$group = as.character(assignments$group)
assignments = merge(assignments, rare[n_genes>=min_n_genes,c('cell_idx','main_cluster','sub_cluster')],by='cell_idx',all=T)
assignments = unique(assignments)
final_assignment = function(main_cluster,sub_cluster){
if(length(sub_cluster)==1){
if(is.na(sub_cluster) || grepl("0$",sub_cluster)){
out = main_cluster
} else {
out = gsub('_\\d$','',sub_cluster)
}
} else {
subclusts = gsub('_\\d$', '',sub_cluster[grepl("1$",sub_cluster)])
out = paste(subclusts,collapse='-')
if(out == ''){out = main_cluster}
}
return(out)
}
assignments[,final:=final_assignment(group,sub_cluster),by="cell_idx"]
assignments = unique(assignments[,c('cell_idx','final')])
out = data.frame(cluster = as.character(assignments$final), row.names = assignments$cell_idx)
out = out[colnames(sce),,drop=F]
return(out)
}
# Visualize output of CellSIUS on tSNE map
# tsne = RTsne object
# rare = output of the rare cell types algorithm (a data.table)
plot_rare_cells = function(tsne,rare){
tsne_dt = data.table(tSNE1 = tsne$Y[,1], tSNE2 = tsne$Y[,2], cell_idx = rownames(tsne$Y))
tsne_dt = merge(tsne_dt, rare[,c('cell_idx','main_cluster','sub_cluster')],
by = c('cell_idx'), all = T)
tsne_dt[is.na(main_cluster),main_cluster:='Other']
tsne_dt[main_cluster == 'Other',sub_cluster:='none']
tsne_dt[grepl('_0$',sub_cluster),sub_cluster:= 'none']
setkey(tsne_dt, 'cell_idx')
tsne_dt = unique(tsne_dt)
rc_cols = brewer.pal(10,"Spectral")[rep(c(1,9,7,2,6,10,3,8),3)]
p = ggplot(tsne_dt, aes(x = tSNE1, y= tSNE2)) +
geom_point(color = "darkgray", alpha = 0.5, size = 1.5)+
theme_bw() + theme(text = element_text(size = 15))
p = p + geom_point(data = tsne_dt[sub_cluster!='none'], aes(x=tSNE1, y=tSNE2, color = sub_cluster))+
scale_color_manual(values = rc_cols) + guides(color = guide_legend(title = 'Subcluster'))
return(p)
}
# legacy support
rare_cell_type_identifier = function(sce,group_id,min_n_cells=10,verbose = T, min_fc = 2,
organism = "human", corr_cutoff = NULL, iter=0, max_perc_cells = 50,
fc_between_cutoff = 1){
return(cellsius_main(sce, group_id, min_n_cells, verbose, min_fc, organism, corr_cutoff, iter,
max_perc_cells, fc_between_cutoff))
}
<file_sep>/code/scrnaseq_workflow_Clustering.R
#####################################################
#
# scRNASeq pipeline functions
#
# PART V: Clustering
# _______________________
#
# This script contains wrapper functions to different clustering methods.
#
# Authors:
# <NAME> (<EMAIL>)
# <NAME> (<EMAIL>)
####################################################
#######################################
# Clustering
#######################################
dist.gen = function(x,method="euclidean", ...) if ( method %in% c("spearman","pearson","kendall") ) as.dist( (1 - cor(t(x),method=method,...))/2 ) else dist(x,method=method,...)
#________________________________
# MCL
# Note that this needs the mcl binary installed externally
# MCL can be found here:http://micans.org/mcl/
# Input:
# - mat = matrix of normalized expression values on log scale (i.e. norm_exprs slot
# of the SCESet) or a similarity matrix, id is_similarity = TRUE
#_______________________________
build_adjacency_matrix = function(mat,cutoff="auto", is_similarity = F){
library(Ckmeans.1d.dp)
if(!is_similarity){
message("Computing cell Pearson correlation coefficient")
corr.cells = cor(mat,method="pearson")
} else {corr.cells = mat}
adj.corr = corr.cells
if(cutoff=="auto"){
# we find the best correlation cutoff by looking for a "valley"
# in the histogram of correlations. This function attempts to set the
# cutoff automatically, but might not always succeed...
# if there are more than 500 cells, randomly sample 500 correlations
if(dim(corr.cells)[1]>500){
idx = sample(seq(dim(corr.cells)[1]),size=500)
} else {idx = seq(dim(corr.cells)[1])}
freqs = hist(corr.cells[idx,idx],breaks=dim(corr.cells[idx,idx])[1]/10)
k1d = Ckmeans.1d.dp(corr.cells,k=2)
cutoff = max(as.vector(corr.cells)[which(k1d$cluster==1)])
abline(v=cutoff,col="red")
} else if (is.numeric(cutoff)){cutoff=cutoff} else {
stop("Please provide a numeric value for corr.cutoff or set to \"auto\"")
}
message("Building the adjacency matrix")
adj.corr[adj.corr<cutoff]=0
adj.corr[adj.corr>0] = 1
return(list(adj=adj.corr,cor=corr.cells,cutoff=cutoff))
}
MCLcell.clust=function(adj_list,selfloop=T,mcl_path = "/da/dmp/cb/prog/mcl-14-137/bin/mcl"){
library(igraph)
adj = adj_list$adj
corr.cells = adj_list$cor
corr.cutoff = adj_list$cutoff
if(!selfloop) diag(adj)=0 # no self-loop for MCL
message("Building Graph")
graphs = get.data.frame( graph.adjacency(adj), what = "edges") # gene connection for graphs
graphs = data.frame(graphs,CORR=sapply(seq(dim(graphs)[1]), function(i) corr.cells[graphs$from[i],graphs$to[i]] -corr.cutoff))
write.table(graphs, file = "tmp.mcl.inp",row.names=F,col.names=F,sep = " ")
message("Running MCL")
system(paste0(mcl_path, " tmp.mcl.inp --abc -o tmp.mcl.out"))
x = scan("tmp.mcl.out", what="", sep="\n")
MCL.cells = strsplit(x, "[[:space:]]+")
MCL.cells = lapply(seq(length(MCL.cells)), function(i){
tmp = sapply(seq(length(MCL.cells[[i]])),function(j){
gsub('\"','',MCL.cells[[i]][j])
})
})
system("rm tmp.mcl.inp tmp.mcl.out")
groups.MCL = matrix(rep(-1,dim(corr.cells)[2]),ncol=1)
rownames(groups.MCL) = colnames(corr.cells)
for(i in seq(length(MCL.cells))) groups.MCL[MCL.cells[[i]],]=i
#if necessary, collapse all clusters containing only 1 cell to a big "unassigned"
groups.MCL[groups.MCL %in% names(table(groups.MCL)[which(table(groups.MCL)==1)])] = 0
return(groups.MCL)
}
#___________________________________________________
# DBSCAN
# Note that this has issues in high-dimensional space
# You should therefore use as input"
# - dist = the cell-to-cell distance in PCA space
# - min_pts should be set to number of used PCs +1 (don't use more than ~10 PCs)
# - eps is the y value where the elbow on the knn_plot is. Set it to "auto" if you
# want the function to automatically determine eps
#_________________________________________________
run_dbscan = function(dist,eps="auto",min_pts,tol=0.01){
library(dbscan)
#automatic determination of eps (the "elbow" in the kNNdistplot)
if(eps=="auto"){
kNNdist = sort(kNNdist(dist,min_pts))
i = seq(1,length(kNNdist),as.integer(0.001*length(kNNdist)))
slope_prev = 100
for(indx in i){
slope = kNNdist[indx]/indx
if(slope_prev>=slope-tol*slope){
slope_prev = slope
} else {
elbow = indx
break
}
}
eps = kNNdist[elbow]
print(paste("Epsilon: ",eps))
} else if(!is.numeric(eps)){
stop("Please provide a value for eps or set it to \"auto\"")} else {eps=eps}
kNNdistplot(dist,k=min_pts)
abline(h=eps,col="red")
res = dbscan(dist,eps = eps,minPts = min_pts)
return(res$cluster)
}
#__________________________________________
# Mclust
#__________________________________________
gmm_main = function(norm_exprs=NULL,pc_scores=NULL,n_comp=10,do_crossval=T, model_type = "VVI",
best_k=NULL,tolerance = 1.96,k=1:10,n_cores = 4, return_model = F){
library(mclust)
library(parallel)
if(is.null(pc_scores)){
if(is.null(norm_exprs)){
stop("Missing expression values. Please provide either a matrix of normalized counts or pre-computed PCA scores.")
}
print("Running PCA...")
pca = pca_stuff(norm_exprs)
top_pc_scores = pca$x[,1:n_comp]
} else {
top_pc_scores = pc_scores[,1:n_comp]
}
if(do_crossval){
#fit models with k-fold crossvalidation
folds = 1:10
n_folds = length(folds)
# this randomly determines which samples should be excluded from
# model fitting during each fold of the cross-validation.
idx = sample(rep(1:n_folds, length.out = nrow(top_pc_scores)))
#Set up parallel processing
library(parallel)
cl = makeCluster(n_cores)
funs = as.character(lsf.str(envir=parent.frame())) #let clusters know about functions in workspace
clusterExport(cl,funs)
#benchmark
#time = system.time(parSapply(cl,folds,cross_val,data=testset,idx=idx,structure='VVI',components=k))
print("Determining number of clusters...")
likes = parSapply(cl,folds,cross_val,data=top_pc_scores,idx=idx,structure=model_type,components=k)
stopCluster(cl)
mean_likes = apply(likes,1,function(x) sum(x[which(is.finite(x))])/length(which(x!=0 & is.finite(x))))
sd_likes = apply(likes,1,function(x) sd(x[which(x!=0 & is.finite(x))]))
sd_likes = sd_likes[which(!is.na(sd_likes))]
mean_likes = mean_likes[which(!is.na(sd_likes))]
best_idx = which(mean_likes==max(mean_likes))
ci_likes = mean_likes[best_idx]-tolerance*sd_likes[best_idx]
best_k_idx = min(which(mean_likes>=ci_likes)) #smallest numebr of components that
#fit reasonably well
best_k = k[best_k_idx]
mean_likes[best_k_idx]
col=rep(1,n_folds)
col[best_k_idx] = 33
# Plot likelihood vs number of clusters
# This should look like a ROC curve ideally. The best model should have
# a high likelihood with the smallest no. of clusters, i.e. be the one
# where the slope decreases. If there is no clear decrease in the
# slope, this means that pretty much any model fits equally well/bad and that
# most likely the clustering produces a nonsensical result
like_dt = data.table(cluster=k,color=as.factor(col),likes)
like_dt_melt = melt(like_dt,id.vars=c("cluster","color"),val="log-Likelihood",var="fold")
p = ggplot(like_dt_melt[`log-Likelihood`!=0 & is.finite(`log-Likelihood`)],aes(x=as.factor(cluster),y=`log-Likelihood`,fill=color)) +
geom_boxplot() + labs(x = "Number of clusters",
title = paste0("No. clusters v.s. log-likelihood, ",n_folds,"-fold crossvalidation"),
subtitle = paste0(n_comp," principal components used to calcualte model")) +
theme_bw() +scale_fill_manual(values=c("white","red"),guide=F)
#ggsave(p,file=file.path(plotdir,paste0("mclust_crossval_",n_comp,".pdf")),height=5,width=7)
print(p)
print(paste0("Found ",best_k," clusters."))
} else {best_k = best_k}
if(is.null(best_k)){
stop("Please provide a value for best_k or set do_crossval = TRUE")
}
print("Assigning cells to clusters...")
#assignments of cells to clusters
model = calc_model(top_pc_scores,best_k,model_type)
cluster_assignments = model$classification
if(return_model){
return(model)
} else {
return(cluster_assignments)}
}
##################################################################################
#Functions called by gmm_main
##################################################################################
#setup paths and stuff
#do pca
pca_stuff = function(log_data_hv,scale_pca=T,center_pca=T){
pca = prcomp(t(log_data_hv[,-1,with=F]),scale=scale_pca,center=center_pca)
return(pca)
}
#Fitting GMM with mclust:
##############################################################################
# function to calculate different models
# k = number of compnents
# structure = model structure / constraints. See mclustModelNames for details.
calc_model = function(data,k,structure){
return(Mclust(data,G=k,modelNames = structure,initialization=
list(subset=sample(1:nrow(data),size=as.integer(nrow(data)*4/5)))))
}
#############################################################################
#Functions to calculate log-likelihood out of what mclust returns
# Probability density function for a Gaussian mixture
# Presumes the mixture object has the structure used by mclust
dnormalmix = function(x,mixture,log=FALSE) {
lambda = mixture$parameters$pro
k = length(lambda)
# Calculate share of likelihood for all data for one component
like_component = function(x, component) {
lambda[component] * dmvnorm(
x,
mean = mixture$parameters$mean[,component],
sigma = mixture$parameters$variance$sigma[,,component]
)
}
# Create array with likelihood shares from all components over all data
likes = sapply(1:k, like_component ,x = x)
# Add up contributions from components
d = rowSums(likes)
if (log) {
d = log(d)
}
return(d)
}
# Log likelihood function for a Gaussian mixture, potentially on new data
loglike_normalmix = function(x,mixture) {
loglike = dnormalmix(x, mixture, log = TRUE)
return(sum(loglike))
}
###############################################################################
#Cross validation things
#Cross validation
#data = input data
#idx = a random sample of folds (e.g. 11432...)
#fold = the current fold
#structure = model structure for mclust (e.g. 'VVI)
#components = a vector containing the numebr of components for which to test models
cross_val = function(fold,data,idx,structure,components){
#library(mclust,lib.loc = .libPaths()[[2]]) #for the VM
library(mclust)
library(mvtnorm)
like_test = c()
for(k in components){
out = tryCatch(
{
calc_model(data[which(idx!=fold),],k,structure)
},
error=function(cond){
#try to find another model
out2 = 0
counter = 0
while(out2 == 0 && counter<=5){
out2 = tryCatch(
{
calc_model(data[which(idx!=fold),],k,structure)
},
error = return(0),
warning=return(0),
finally= {counter = counter +1}
)
}
message('There was an error: \n')
message(cond)
write.csv(cond,'gmm.log',append=TRUE)
return(out2)
},
warning=function(cond){
#try to find another model
out2 = 0
counter = 0
while(out2 == 0 && counter<=10){
out2 = tryCatch(
{
calc_model(data[which(idx!=fold),],k,structure)
},
error = return(0),
warning=return(0),
finally={counter = counter +1}
)
}
message('There was a warning: \n')
message(cond)
write.csv(cond,'gmm.log',append=TRUE)
return(out2)
},
finally={
message('\n done.')
}
)
if(class(out)=='Mclust'){
like_test = append(like_test,loglike_normalmix(data[which(idx==fold),],out))
}
else{
like_test = append(like_test,0)
}
}
return(like_test)
}
#___________________________________________
# SEURAT
#___________________________________________
seurat_clustering = function(sce,vars.to.regress=NULL,res=0.6,n_comp=10){
library(Seurat)
#make SEURAT object, scale and optionally regress out confounders
tmp_seurat = CreateSeuratObject(raw.data = counts(sce))
tmp_seurat@data = norm_exprs(sce) #add the normalized values
# This next step is a bit of cheating. Seurat expects us to run the complete
# workflow on the same object and checks whether data have been normalized
# by checking if object@calc.params$NormalizeData$normalization.method exists.
# Since we provided normalized values, and do not want to re-run normalization,
# we just put a dummy value in that slot.
tmp_seurat@calc.params$NormalizeData = list(normalization.method ="dummy")
if(!is.null(vars.to.regress)){
if(any(!vars.to.regress%in%names(pData(sce)))){
stop("Variables to regress out have to be column names in pData(sce)")
}
tmp_seurat = AddMetadata(object = tmp_seurat, metadata = pData(sce)[,vars.to.regress])
tmp_seurat = ScaleData(object = tmp_seurat,vars.to.regress=vars.to.regress)
} else {
tmp_seurat = ScaleData(object = tmp_seurat)
}
tmp_seurat = RunPCA(object = tmp_seurat, pc.genes = rownames(sce), do.print = FALSE)
tmp_seurat = FindClusters(object = tmp_seurat, reduction.type = "pca", dims.use = 1:n_comp,
resolution = res, print.output = 0, save.SNN = TRUE)
seurat_assignment = tmp_seurat@ident
return(seurat_assignment)
}
<file_sep>/code/scrnaseq_workflow_QC.R
#####################################################
#
# scRNASeq pipeline functions
#
# PART II: Quality control
# _______________________
#
# This script contains all functions called from the Quality Control section of the workflow.
#
# Authors:
# <NAME> (<EMAIL>)
# <NAME> (<EMAIL>)
####################################################
######################
# Quality Control
######################
#_____________
# Gene filters
#___________
# Filtering out genes that are not expressed at a minimum of min_counts in at least n_th cells
gene_filter_by_feature_count = function(counts, n_th , min_counts = 1){
discard = rowSums(counts>=min_counts) <= n_th
message(paste('Flagged', length(which(discard)), 'genes.'))
return(discard)
}
#______________
# Cell filters
#______________
# Filtering out cells with fewer than n_th detected features
cell_filter_by_feature_count = function(counts, n_th){
discard = colSums(counts>0) <= n_th
message(paste('Flagged', length(which(discard)), 'cells.'))
return(discard)
}
# Filtering out cells with fewer than n_th total UMI counts
cell_filter_by_total_UMI = function(counts, n_th){
discard = colSums(counts) <= n_th
message(paste('Flagged', length(which(discard)), 'cells.'))
return(discard)
}
# Filtering out cells with high mitochondrial gene content
calc_mt_content = function(counts, geneName){
mt = rownames(counts[rownames(counts) %in% rownames(geneName[geneName$chromosome_name=="MT",]),])
mt_not = setdiff(rownames(counts),rownames(counts[mt,]))
counts_mt = counts[mt,]
mt_genes.amount = 100/colSums(counts)*colSums(counts[mt,])
return(mt_genes.amount)
}
cell_filter_by_mt_content = function(mt_genes.amount, t){
discard = mt_genes.amount > t
message(paste('Flagged', length(which(discard)),'cells.'))
return(discard)
}
#__________________
# Cell cycle phase annotation
#__________________
#using the scran package, which internally calls cyclone (default)
annotate_cell_cycle = function(sce, organism = "human", gene.names = rownames(sce)){
if(organism == "human"){
hs.pairs = readRDS(system.file("exdata", "human_cycle_markers.rds", package="scran"))
assigned = cyclone(sce, pairs=hs.pairs, gene.names = gene.names)} else if (organism == "mouse"){
mm.pairs = readRDS(system.file("exdata", "mouse_cycle_markers.rds", package="scran"))
assigned = cyclone(sce, pairs=mm.pairs, gene.names = gene.names)
} else {stop("Organism has to be human or mouse.")}
return(assigned)
}
# using annotations from cyclebase (provided as cell.cycle.gene.RData)
# note that this is based on mean expression, so it might be a bad
# idea to use it on un-normalized data
annotate_cell_cycle_custom = function(log2_counts, organism = "human", input_dir = file.path(code_dir, "input_files")){
# Load list of cell-cycle genes from cyclebase
load(file.path(input_dir,"cell.cycle.gene.RData"))
head(cell.cycle.gene)
#plot(sort(cell.cycle.gene$periodicity_pvalue))
cc = cell.cycle.gene[which(cell.cycle.gene$periodicity_pvalue<.05),]
# 220/361 genes are a subset of the variable gene list of our dataset
if(organism == "human"){
cc = cc[cc$Ensembl.Gene.ID %in% rownames(log2_counts),]
# selecting genes associetes with cell-cycle phase
G1.genes = cc[which(cc$peaktime>0 & cc$peaktime<47 ),]$Ensembl.Gene.ID
S.genes = cc[which(cc$peaktime>47 & cc$peaktime<70 ),]$Ensembl.Gene.ID
G2.genes = cc[which(cc$peaktime>70 & cc$peaktime<90 ),]$Ensembl.Gene.ID
M.genes = cc[which(cc$peaktime>90 & cc$peaktime<100 ),]$Ensembl.Gene.ID
G1_S.genes = cc[which(cc$peaktime>40 & cc$peaktime<50 ),]$Ensembl.Gene.ID
S_G2.genes = cc[which(cc$peaktime>60 & cc$peaktime<70 ),]$Ensembl.Gene.ID
G2_M.genes = cc[which(cc$peaktime>80 & cc$peaktime<90 ),]$Ensembl.Gene.ID
} else if(organism == "mouse"){
cc = cc[cc$Ensembl.Gene.ID.1 %in% rownames(log2_counts),]
# selecting genes associetes with cell-cycle phase
G1.genes = cc[which(cc$peaktime>0 & cc$peaktime<47 ),]$Ensembl.Gene.ID.1
S.genes = cc[which(cc$peaktime>47 & cc$peaktime<70 ),]$Ensembl.Gene.ID.1
G2.genes = cc[which(cc$peaktime>70 & cc$peaktime<90 ),]$Ensembl.Gene.ID.1
M.genes = cc[which(cc$peaktime>90 & cc$peaktime<100 ),]$Ensembl.Gene.ID.1
G1_S.genes = cc[which(cc$peaktime>40 & cc$peaktime<50 ),]$Ensembl.Gene.ID.1
S_G2.genes = cc[which(cc$peaktime>60 & cc$peaktime<70 ),]$Ensembl.Gene.ID.1
G2_M.genes = cc[which(cc$peaktime>80 & cc$peaktime<90 ),]$Ensembl.Gene.ID.1
} else { stop ("Organism has to be either human or mouse")}
# Compute the smean of genes associated with each cell-phase
G1.sum = apply(log2_counts[G1.genes,colnames(log2_counts)],2,mean)
S.sum = apply(log2_counts[S.genes,colnames(log2_counts)],2,mean)
G2.sum = apply(log2_counts[G2.genes,colnames(log2_counts)],2,mean)
M.sum = apply(log2_counts[M.genes,colnames(log2_counts)],2,mean)
G1_S.sum = apply(log2_counts[G1_S.genes,colnames(log2_counts)],2,mean)
S_G2.sum = apply(log2_counts[S_G2.genes,colnames(log2_counts)],2,mean)
G2_M.sum = apply(log2_counts[G2_M.genes,colnames(log2_counts)],2,mean)
# Create a matrix with the sum of genes associated with each cell-cycle pahse per cells
G1.S.G2.M = rbind(G1.sum[names(sort(G1.sum))],S.sum[names(sort(G1.sum))],
G2.sum[names(sort(G1.sum))] ,
M.sum[names(sort(G1.sum))],G1_S.sum[names(sort(G1.sum))],
S_G2.sum[names(sort(G1.sum))],G2_M.sum[names(sort(G1.sum))])
rownames(G1.S.G2.M) = c("G1","S","G2","M","G1_S","S_G2","G2_M")
# compute a cell cycle score (divide by totl expression)
# note that this is biased by expression differences in cc genes,
# better to use correlations as in Seurat or scran
cell.phase = do.call(cbind,
lapply(seq(dim(G1.S.G2.M)[2]),function(i){
res = G1.S.G2.M[,i]/sum(G1.S.G2.M[,i])
}))
colnames(cell.phase) = colnames(G1.S.G2.M)
cell.phase = t(cell.phase)
cell.phase = as.data.frame(cell.phase)
cell.phase = as.data.frame(t(cell.phase),stringsAsFactors = F)
return(cell.phase)
}
#___________
# QC visualization
#___________
# Plotting QC based on RNA amount detected per cell
plot_RNA_QC = function(input_sce, min_genes, min_UMI){
par(mfrow=c(1,3))
hist(log2(input_sce$total_features),xlab="log2[ # detected genes per cell]", main='', cex.axis=1.5,n=100)
abline(v=min_genes,col=2)
hist(log2(input_sce$total_counts),xlab="log2 [# of UMIs per cell]", main='', cex.axis=1.5,n=100)
abline(v=min_UMI,col=2)
plot(log2(input_sce$total_features),log2(input_sce$total_counts),xlab="log2[ # detected features per cell]",ylab="log2 [total counts per cell]", cex.axis=1.5)
abline(v=min_genes,col=2)
abline(h=min_UMI,col=2)
}
# Plotting mitochondrial gene QC
plot_MT_QC = function(sce, t){
par(mfrow=c(1,1))
mt_genes.amount = sce$pct_counts_feature_controls_MT
#mt gene content per cell
plot(seq(length(mt_genes.amount)),(mt_genes.amount),pch=10,cex=1.5,col="gray",main=""
, cex.axis=2,cex.lab=1.5,xlab="cell index",ylab="Ratio of MT-genes[%]")
points(seq(length(mt_genes.amount))[mt_genes.amount<t],mt_genes.amount[mt_genes.amount<t],pch=10,cex=1.5)
abline(h=t,col="red",lty=2,cex=5)
#UMI vs no. genes colored by mt gene content
plotPhenoData(sce, aes_string(x = "log2(total_features)",
y = "log2(total_counts)",
colour = "pct_counts_feature_controls_MT"))+
xlab("Total detected features [log2]") + ylab("Total counts [log2]")+
ggtitle("Total features vs. total counts, colored by MT content")
}
<file_sep>/code/scrnaseq_workflow_Normalization.R
#####################################################
#
# scRNASeq pipeline functions
#
# PART III: Normalization
# _______________________
#
# This script contains a wrapper function to different normalizations, based on the scran R package.
#
# Authors:
# <NAME> (<EMAIL>)
# <NAME> (<EMAIL>)
####################################################
#########################################
# Normalizations
# Input:
# - sce = an SCESet
# - method = the method you want to use to normalize. Choices are:
# TC = total count normalization (multiply this by 10^6 to get CPMs)
# UQ = upperquartile
# RLE = relative log-expression, as in DESeq2
# TMM = trimmed mean of M-values, as in edgeR
# scran (default) = Lun sum factors, implemented in scran package
# Output:
# - the normalized expression values in the norm_exprs slot of the SCESet
#########################################
normalize_counts = function(sce,method = "scran"){
#calculate size factors according to method
switch(method,
"TC" ={sce = normalizeExprs(sce, method="none",return_norm_as_exprs=T)},
"RLE" = {sce = normalizeExprs(sce, method="RLE",return_norm_as_exprs=T)},
"TMM" = {sce = normalizeExprs(sce, method="TMM",return_norm_as_exprs=T)},
"UQ" = {sce = normalizeExprs(sce, method="upperquartile",return_norm_as_exprs=T)},
"scran" = {clusters = quickCluster(sce)
sizes = seq(20,100,5)
if(min(table(clusters))>max(sizes)){
sce = computeSumFactors(sce,clusters = clusters,sizes=sizes)
} else{
message("Clustering of cells failed, using global scaling factors")
sce = computeSumFactors(sce)
if(any(sizeFactors(sce) < 0)) {
warning("Negative size factors generated. Most likely, this is due to some cells having very low total feature counts. Consider using more stringent QC cutoffs.")
}
}
sce = scater::normalize(sce, return_norm_as_exprs=T)}
)
return(sce)
}
<file_sep>/code/workflow_vignette.R
##################################################################################################
# scRNAseq workflow - main file
#
# This file contains all the code (without explanation) that is displayed in the html vignette.
# It might be easier for you to run the workflow from the .Rmd file in the vignettes folder,
# because this contains both the code and extensive documentation.
#
# Author: <NAME> and <NAME>
#############################################################################################
#-----------------------------------------------
# LICENSE
#-----------------------------------------------
# Copyright 2018 Novartis Institutes for BioMedical Research 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 "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.
# limitations under the License.
## ------------------------------------------------------------------------
#source("https://bioconductor.org/biocLite.R")
## ---- eval = F-----------------------------------------------------------
## install.packages("devtools")
## ---- eval=F-------------------------------------------------------------
## # from CRAN
## install.packages("Rtsne") #Rtsne v. 0.13
## install.packages("ggplot2") # ggplot2 v. 2.2.1
## install.packages("data.table") # data.table v. 1.10.4
## install.packages("RColorBrewer") # RColorBrewer v. 1.1-2
## install.packages("mvoutlier") # mvoutlier 2.0.8, required by some functions from scater
##
## devtools::install_github("bwlewis/irlba") # irlba 2.3.2, optional. Make sure you use irlba > 2.3.1, older versions contain a bug that results in unreliable output!
##
## # rom Bioconductor
## biocLite("scater") # scater v. 1.4.0
## biocLite("scran") # scran v. 1.4.5
## ---- eval=F-------------------------------------------------------------
## # ensembldb 2.0.4 and EnsDb.Hsapiens.v79 2.1.0
## biocLite(c("ensembldb","EnsDb.Hsapiens.v79"))
## # org.Hs.eg.db v. 3.4.1
## biocLite("org.Hs.eg.db")
## ---- eval=F-------------------------------------------------------------
## # ensembldb 2.0.4 and EnsDb.Mmusculus 2.1.0
## biocLite(c("ensembldb","EnsDb.Mmusculus.v75"))
## # org.Mm.eg.db v. 3.4.1
## biocLite("org.Mm.eg.db")
## ----eval = F------------------------------------------------------------
## # M3Drop version 3.05.00 (Note: This is still under active development, please let me know if a new version breaks my functions...)
## devtools::install_github("tallulandrews/M3D")
## ---- eval = F-----------------------------------------------------------
## install.packages("cluster") # cluster v. 2.0.6
## install.packages("dendextend") # dendextend v. 1.5.2
## install.packages("Ckmeans.1d.dp") # Ckmeans.1d.dp v. 4.2.1
## install.packages("dbscan") # DBSCAN v. 1.1-1
## install.packages(c("mclust","mvtnorm")) # mclust v. 5.4 and mvtnorm 1.0.6
## install.packages("dynamicTreeCut") # dynamicTreeCut v. 1.63-1
##
## biocLite("SC3") # SC3 v. 1.4.2
## devtools::install_github("satijalab/seurat") #Seurat 2.0.1
## devtools::install_github('JustinaZ/pcaReduce') #pcaReduce 1.68.0
## ----eval = F------------------------------------------------------------
## biocLite("limma") # limma v. 3.32.5
## biocLite("MAST") # MAST v. 1.2.1
## ---- message = FALSE----------------------------------------------------
rm(list=ls())
graphics.off()
wd = ".."
#Directory where input files are stored
input_dir = file.path(wd,"example_data")
#Directory where code is stored
code_dir = file.path(wd,"code")
#where to save the output data?
out_data_dir = file.path(wd,"example_output")
if(!dir.exists(out_data_dir)) {dir.create(out_data_dir)}
#where to save the produced plots?
plotdir = file.path(wd,"example_plots")
if(!dir.exists(plotdir)) {dir.create(plotdir)}
set.seed(17) #to make tSNE plots reproducible
source(file.path(code_dir,"scRNASeq_pipeline_functions.R"))
# loading the libraries that are required throughout the analysis
library_calls()
## ----message=F,eval=F----------------------------------------------------
## # Read the dataset
## counts = read.delim(file.path(input_dir,"pbmc_example_counts.txt"),sep="\t")
##
## # if we have genes that are not expressed in any cell, discard them
## keep_feature = !gene_filter_by_feature_count(counts,0)
## counts = counts[keep_feature,]
##
## # make a table of metadata (e.g. batch, cell type annotation,treatment,...)
## # Here, we do not have any such information, so we just give each cell a name
## # Note that the rownames of this table have to correspond to the column names
## # of the count matrix.
## annot = data.frame(cell_idx=paste0("pbmc_C",seq(dim(counts)[2])))
## rownames(annot) = colnames(counts)
## pd = new("AnnotatedDataFrame", data=annot)
##
## # get gene annotations from ensembldb
## # optional: get gene descriptions from org.Hs.eg.db (slows down the process a lot!)
## # NOTE: the output of get_gene_annotations is a data.table sorted by gene identifier.
## # This means the genes are no longer in the same order as in the count matrix!
## geneName = get_gene_annotations(rownames(counts),organism = "human",get_descriptions = F)
##
## # convert this to feature metadata
## fd_table = as.data.frame(geneName)
## rownames(fd_table) = geneName$gene_id
## fd_table = fd_table[rownames(counts),]
## fd = new("AnnotatedDataFrame",data=fd_table)
##
## #construct SCESet
## sce = newSCESet(countData = counts, phenoData=pd,featureData = fd)
##
## ----eval=F--------------------------------------------------------------
## #calculate QC metrics
## sce = calculateQCMetrics(sce,feature_controls = list(MT=which(fData(sce)$chr=="MT")))
##
## # assign cell cycle phase (based on the method from scran)
## # because PBMCs are post-mitotic, most cells should be assigned to G0/G1 phase
## cc = annotate_cell_cycle(sce)
## sce$cell_cycle_phase = cc$phases
## sce$cc_scores = cc$scores
##
## #save the SCESet
## save(sce,file=file.path(out_data_dir,"sce_raw.RData"))
## ------------------------------------------------------------------------
load(file.path(out_data_dir,"sce_raw.RData"))
p1 = plotQC(sce, type="high",feature_names_to_plot = "symbol")
print(p1)
## ------------------------------------------------------------------------
p1.2 = custom_plotHighestExprs(sce,feature_names_to_plot = "symbol")
p1.2 = p1.2 + xlab("Expression [raw counts, log2]")
print(p1.2)
# to save a plot, use the ggsave function:
ggsave(p1.2, file = "saved_example_plot.pdf",height=7,width=7)
## ----warning=F-----------------------------------------------------------
p2 = plotQC(sce, type = "exprs-freq-vs-mean")
p2 = p2+xlab("Mean expression [raw counts, log2]")+ggtitle("Mean expression versus detection rate")
print(p2)
# Check total number of zeroes
t = table(counts(sce)==0)
print(t/sum(t)*100)
## ------------------------------------------------------------------------
p3 = plotQC(sce, type="find", variable="total_features")
print(p3 + ggtitle("Correlation of principal components with total detected features."))
## ------------------------------------------------------------------------
p3.2 = plotQC(sce, type="find", variable="cell_cycle_phase")
print(p3.2+ggtitle("Correlation of principal components with cell cycle phase."))
## ------------------------------------------------------------------------
vars = c("total_counts","total_features","cell_cycle_phase")
p4 = plotQC(sce, type="expl", variables=vars)
print(p4 + ggtitle("Percentage of explained variance"))
## ------------------------------------------------------------------------
min_genes = 9.0 #minimum number of features (genes) per cell [log2]
min_UMI = 10.5 #minimum total UMIs / cell [log2]
mt_threshold = 9 #Maximum percentage of mitochondrial genes
## ------------------------------------------------------------------------
plot_RNA_QC(sce, min_genes = min_genes, min_UMI = min_UMI)
plot_MT_QC(sce,mt_threshold)
## ------------------------------------------------------------------------
sce$keep_manual = ( !cell_filter_by_feature_count(counts(sce),2^min_genes) &
!cell_filter_by_total_UMI(counts(sce),2^min_UMI) & !cell_filter_by_mt_content(sce$pct_counts_feature_controls_MT,mt_threshold))
table(sce$keep_manual)
sce_clean = sce[,sce$keep_manual]
## ------------------------------------------------------------------------
n_th = 1
min_counts = 2
keep_feature = !(gene_filter_by_feature_count(counts(sce_clean),n_th, min_counts))
sce_clean = sce_clean[keep_feature,]
## ------------------------------------------------------------------------
sce_clean = calculateQCMetrics(sce_clean,feature_controls = list(MT=which(fData(sce_clean)$chr=="MT")))
# The variables used to detect outliers
vars = c( "pct_counts_top_100_features",
"total_features", "pct_counts_feature_controls",
"log10_counts_endogenous_features",
"log10_counts_feature_controls")
sce_clean = plotPCA(sce_clean,
size_by = "total_features",
pca_data_input = "pdata",
selected_variables = vars,
detect_outliers = TRUE,
return_SCESet = TRUE)
table(sce_clean$outlier)
#here, we remove the outliers
sce_clean = sce_clean[,!sce_clean$outlier]
# Finally, we again remove genes that are not expressed
keep_feature = !(gene_filter_by_feature_count(counts(sce_clean),n_th,min_counts))
sce_clean = sce_clean[keep_feature,]
save(sce_clean, file = file.path(out_data_dir,"sce_clean.RData"))
## ------------------------------------------------------------------------
p = my_plot_PCA(counts = log2(counts(sce_clean)+1),
scale_pca = T, center_pca = T, return_pca = F, use_irlba=F,
color = pData(sce_clean)[,"total_features",drop=F])
p = p+ggtitle("PCA on raw log2(counts)")
print(p)
## ------------------------------------------------------------------------
p = my_plot_tSNE(counts = log2(counts(sce_clean)+1),
is_distance = F, scale_pca = F, n_comp = 50, return_tsne=F,
color = pData(sce_clean)[,"total_features",drop=F])
p = p+ggtitle("t-SNE on raw log2(counts)")
print(p)
## ----message=F-----------------------------------------------------------
# normalize data
sce_clean = normalize_counts(sce_clean,method = "scran")
# normalized values are automatically log2-transformed and
# stored in the norm_exprs slot of the SCESet
norm_exprs(sce_clean)[1:5,1:5]
save(sce_clean, file = file.path(out_data_dir,"sce_clean.RData"))
## ------------------------------------------------------------------------
# PCA of normalized values
sum_norm = data.frame(sum_expression = colSums(norm_exprs(sce_clean)))
p1 = my_plot_PCA(counts = norm_exprs(sce_clean),
color=sum_norm,
return_pca = F, scale_pca = T, center_pca = T)
p1 = p1+ggtitle("PCA on normalized counts")
print(p1)
#tSNE of normalized values
p2 = my_plot_tSNE(counts = norm_exprs(sce_clean),
color=sum_norm,
return_tsne = F, is_distance = F)
p2 = p2 + ggtitle("t-SNE (50 PCs) on normalized counts")
print(p2)
## ----message=F-----------------------------------------------------------
cd20 = t(norm_exprs(sce_clean["ENSG00000156738",]))
colnames(cd20) = "CD20"
go_id = "GO:0002376"
ens_go = GO_to_gene(go_id)
info_GO = rownames(sce_clean)%in%ens_go
table(info_GO)
p = my_plot_PCA(counts = norm_exprs(sce_clean[info_GO,]),
return_pca = F, scale_pca = T, center_pca = T,
title = "PCA - GO:0002376 features",
color = cd20)
print(p)
## ------------------------------------------------------------------------
info_HVG = info.genes(2^norm_exprs(sce_clean)-1,PLOT=T,qcv=0.25,pv=.1,q=.5,minBiolDisp = 0)
table(info_HVG)
p = my_plot_PCA(counts = norm_exprs(sce_clean[info_HVG,]),
return_pca = F, scale_pca = T, center_pca = T,
title = "PCA - HVG features",
color = cd20)
print(p)
## ------------------------------------------------------------------------
info_NBdrop = run_DANB(counts(sce_clean),method = "NBDrop",save_plot=F, cutoff = 0.1)
info_NBdisp = run_DANB(counts(sce_clean),method = "NBDisp",save_plot=F, perc_genes = 10)
table(info_NBdrop,info_NBdisp)
p = my_plot_PCA(counts = norm_exprs(sce_clean[info_NBdrop,]),
return_pca = F, scale_pca = T, center_pca = T,
title = "PCA - NBDrop features",
color = cd20)
print(p)
p = my_plot_PCA(counts = norm_exprs(sce_clean[info_NBdisp,]),
return_pca = F, scale_pca = T, center_pca = T,
title = "PCA - NBDisp features",
color = cd20)
print(p)
## ---- eval=F-------------------------------------------------------------
## sce_info = sce_clean[info_NBdrop,]
## dim(sce_info)
##
## # tSNE map of the cleaned data
## # note that by setting return_tsne = T, we can obtain the t-SNE object for later use
## tsne_info = my_plot_tSNE(counts = norm_exprs(sce_info),
## scale_pca = F, n_comp = 50, return_tsne=T)$tsne
## ----eval=F--------------------------------------------------------------
## save(sce_info, file = file.path(out_data_dir,"sce_info.RData"))
## save(tsne_info,file = file.path(out_data_dir,"tsne_info.RData"))
## ------------------------------------------------------------------------
#load the data we need
load(file.path(out_data_dir,"sce_info.RData"))
load(file.path(out_data_dir,"tsne_info.RData"))
## ---- fig.align='center', fig.width=12, fig.height=8---------------------
b_cell = t(norm_exprs(sce_info["ENSG00000156738",]))
colnames(b_cell) = "B-cell"
monocyte = data.frame(Monocyte = colSums(norm_exprs(sce_info)[which(fData(sce_info)$symbol %in% c('CD14','LYZ','FCGR3A','MS4A7')),]))
t_cell = data.frame(`T-cell` = colSums(norm_exprs(sce_info)[which(fData(sce_info)$symbol %in% c('CD3E','CD3D','CD3G')),]))
nk_cell = data.frame(`NK cell` = colSums(norm_exprs(sce_info)[which(fData(sce_info)$symbol %in% c('GNLY','NKG7')),]))
# Make plots
# Note that by providing the tsne input variable instead of counts,
# we can use an existing t-SNE calculation for plotting
p1 = my_plot_tSNE(tsne = tsne_info, color = b_cell, title = "B-cell marker expression")
p2 = my_plot_tSNE(tsne = tsne_info, color = monocyte, title = "Monocyte marker expression")
p3 = my_plot_tSNE(tsne = tsne_info, color = t_cell, title = "T-cell marker expression")
p4 = my_plot_tSNE(tsne = tsne_info, color = nk_cell, title = " NK cell marker expression")
ggmultiplot(p1,p2,p3,p4,cols=2)
## ------------------------------------------------------------------------
assignment = data.table(tsne1 = tsne_info$Y[,1], tsne2 = tsne_info$Y[,2],cell_type = 'T-cell')
assignment[tsne1 < -10 ,cell_type:='B-cell']
assignment[tsne1 > 5 ,cell_type:='Monocyte']
assignment[tsne2 < -17 & tsne1 > -1,cell_type:='NK Cell']
sce_info$cell_type = assignment$cell_type
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"cell_type",drop=F])
print(p+labs(title="t-SNE on informative genes",subtitle = "Colored by manual cell annotation"))
## ---- echo=F-------------------------------------------------------------
library(SC3)
## ----eval=F--------------------------------------------------------------
## library(SC3)
## sce_info = sc3_prepare(sce_info, ks = 2:10, n_cores = 4)
## ----eval=F--------------------------------------------------------------
## sce_info = sc3_estimate_k(sce_info)
## sce_info@sc3$k_estimation
## ----eval=F--------------------------------------------------------------
## sce_info = sc3(sce_info, ks = 6, biology = TRUE, n_cores = 4)
## ---- eval = F-----------------------------------------------------------
## sce_info = sc3(sce_info, ks = 6, biology = F, n_cores = 8)
## sce_info = sc3_run_svm(sce_info)
##
## sce_info@sc3$svm_train_inds = NULL
## sce_info = sc3_calc_biology(sce_info, k=c(8,13), regime = "marker")
##
## # to visualize the markers, use my modified fuction:
##
## # change the plotted gene names to symbol for better readability
## plot_sce = sce_info
## rownames(plot_sce) = fData(plot_sce)$symbol
## custom_sc3_plot_markers(plot_sce, k=6, p.val = 0.01, auroc = 0.90)
##
## rm(plot_sce)
## ---- out.width="110%",fig.height=4--------------------------------------
sc3_plot_consensus(sce_info, k=6)
## ---- out.width="110%",fig.height=4--------------------------------------
sc3_plot_expression(sce_info, k = 6, show_pdata = c("cell_type"))
## ---- out.width="110%",fig.height=6--------------------------------------
# change the plotted gene names to symbol for better readability
plot_sce = sce_info
rownames(plot_sce) = fData(plot_sce)$symbol
sc3_plot_markers(plot_sce, k=6, p.val = 0.01, auroc = 0.90, show_pdata = c("cell_type"))
# for hybrid SVM approach:
# custom_sc3_plot_markers(plot_sce, k=6, p.val = 0.01, auroc = 0.90)
## ------------------------------------------------------------------------
assignment = data.table(clust = sce_info$sc3_6_clusters, cell_type = sce_info$cell_type)
assignment[clust == 1, cell_type:= 'T helper cell']
assignment[clust == 2, cell_type:= 'Monocyte']
assignment[clust==3,cell_type:='?']
assignment[clust==4,cell_type:='CD8+ T-cell']
assignment[clust==5,cell_type:='NK cell']
assignment[clust == 6, cell_type:= 'B-cell']
sce_info$SC3_assignment = assignment$cell_type
p = my_plot_tSNE(tsne = tsne_info,
color = pData(sce_info)[,"SC3_assignment",drop=F],
shape = pData(sce_info)[,"cell_type",drop=F],
title = "SC3 assignment",
show_proportions = T)
print(p)
save(sce_info,file = file.path(out_data_dir,"sce_info.RData"))
## ------------------------------------------------------------------------
pca = my_plot_PCA(counts = norm_exprs(sce_info),return_pca=T)$pca
screeplot(pca,type = 'lines')
## ------------------------------------------------------------------------
dist_eucl = dist.gen(pca$x[,1:6],method='euclidean')
hfit = hclust(dist_eucl,method="average")
plot(hfit, labels = F, main = "hclust on euclidean distance in PCA space")
## ---- message =F---------------------------------------------------------
library(dynamicTreeCut)
groups_hclust_eucl = cutreeDynamic(hfit, distM = as.matrix(dist_eucl), deepSplit = 0, minClusterSize = 5, maxCoreScatter = 0.70, minGap = 0.25)
## ------------------------------------------------------------------------
library(cluster)
si = silhouette(groups_hclust_eucl,dist_eucl)
plot(si, col = "darkgray", border=NA, main = "Silhouette plot for hclust (euclidean in PCA space)")
## ------------------------------------------------------------------------
sce_info$hclust_sil = si[,3]
p = my_plot_tSNE(tsne = tsne_info,
color = pData(sce_info)[,"hclust_sil",drop=F],
shape = pData(sce_info)[,"cell_type",drop=F],
title = "tSNE colored by silhouette width")
print(p+scale_color_distiller(type="div", palette = "RdBu"))
## ------------------------------------------------------------------------
sce_info$hclust_eucl = as.factor(groups_hclust_eucl)
table(sce_info$SC3_assignment,sce_info$hclust_eucl)
## ------------------------------------------------------------------------
# change the plotted gene names to symbol for better readability
plot_sce = sce_info
rownames(plot_sce) = fData(plot_sce)$symbol
monocyte_markers = which(fData(sce_info)$symbol %in% c('CD14','LYZ','FCGR3A','MS4A7'))
p = plotExpression(plot_sce,features = monocyte_markers, x="hclust_eucl",
colour_by = "hclust_eucl")
print(p)
## ----fig.width = 8-------------------------------------------------------
sce_info$hclust_eucl = factor(sce_info$hclust_eucl, levels = levels(sce_info$hclust_eucl), labels = c("T-helper cell","CD14++/CD16- Monocyte","B-cell","CD8+ T-cell","NK cell","CD14+/CD16++ Monocyte"))
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"hclust_eucl",drop=F],
shape = pData(sce_info)[,"cell_type",drop=F],
title = "hclust (euclidean) assignment",
show_proportions = T)
print(p)
## ------------------------------------------------------------------------
library(dendextend)
dist_pearson = dist.gen(t(norm_exprs(sce_info)),method = "pearson")
hfit = hclust(dist_pearson,method="average")
groups_hclust_pearson = cutree(hfit, k=6)
sce_info$hclust_pearson = as.factor(groups_hclust_pearson)
hfit2 = color_branches(hfit, k=6)
hfit2 = hfit2 %>% set("labels", rep("",dim(sce_info)[2]))
plot(hfit2, main = "hclust on Pearson correlation")
## ----fig.width=8---------------------------------------------------------
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"hclust_pearson",drop=F],
shape = pData(sce_info)[,"cell_type",drop=F],
title = "hclust (Pearson) assignment",
show_proportions = T)
print(p)
## ------------------------------------------------------------------------
library(pcaReduce)
expr_mat_info = t(norm_exprs(sce_info))
assignment_info = PCAreduce(expr_mat_info, nbt = 5, q = 6, method = "M")
## ----fig.width=12,fig.height=6-------------------------------------------
table(assignment_info[[1]][,4])
plots = list()
for(i in 1:5){
df = data.frame(apply(assignment_info[[i]],c(1,2),as.factor))
p = my_plot_tSNE(tsne=tsne_info, color = df[,'cl_id.2',drop=F],
shape = pData(sce_info)[,"cell_type",drop=F],
title = paste0("pcaReduce, run ", i))
plots[[i]] = p
}
ggmultiplot(plots[[1]],plots[[2]],plots[[3]],plots[[4]],plots[[5]],cols=3)
## ---- message = F--------------------------------------------------------
sim = 1-as.matrix(dist_eucl)/max(dist_eucl)
adj_corr = build_adjacency_matrix(mat = sim,cutoff="auto",is_similarity=T)
## ---- message = F--------------------------------------------------------
groups_MCL = MCLcell.clust(adj_corr,mcl_path = "/da/dmp/cb/prog/mcl-14-137/bin/mcl")
sce_info$MCL = as.factor(groups_MCL)
table(sce_info$MCL,sce_info$hclust_eucl)
## ---- fig.width = 8------------------------------------------------------
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"MCL",drop=F],
shape = pData(sce_info)[,"hclust_eucl",drop=F],
title = "MCL (cutoff=auto) assignment",
show_proportions = T)
print(p)
## ----fig.height=6,fig.width = 9------------------------------------------
adj_corr = build_adjacency_matrix(mat = sim,cutoff=0.8,is_similarity=T)
groups_MCL = MCLcell.clust(adj_corr,mcl_path = "/da/dmp/cb/prog/mcl-14-137/bin/mcl")
sce_info$MCL2 = as.factor(groups_MCL)
table(sce_info$MCL2,sce_info$hclust_eucl)
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"MCL2",drop=F],
shape = pData(sce_info)[,"hclust_eucl",drop=F],
title = "MCL (cutoff=0.7) assignment",
show_proportions = T)
p = p + scale_color_manual(values = brewer.pal(10,"Paired"))
print(p)
## ----eval = F------------------------------------------------------------
## library(Seurat)
## seurat_assignments = seurat_clustering(sce_info,vars.to.regress=NULL,res=1.2)
## sce_info$seurat = as.factor(seurat_assignments)
## ----fig.width=8, eval = F-----------------------------------------------
## table(sce_info$seurat,sce_info$hclust_eucl)
## p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"seurat",drop=F],
## shape = pData(sce_info)[,"hclust_eucl",drop=F],
## title = "Seurat assignment",show_proportions = T)
## print(p)
## ------------------------------------------------------------------------
DBSCAN_groups = run_dbscan(dist_eucl,eps="auto",min_pts=7,tol=0.005)
## ----fig.height=6,fig.width=8--------------------------------------------
sce_info$DBSCAN = as.factor(DBSCAN_groups)
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"DBSCAN",drop=F],
shape = pData(sce_info)[,"hclust_eucl",drop=F],
title = "DBSCAN assignment",show_proportions = T)
print(p)
## ----fig.width=7,fig.height=6--------------------------------------------
si = silhouette(DBSCAN_groups, dist_eucl)
plot(si, col = "darkgray", border=NA, main = "Silhouette plot for dbscan (euclidean in PCA space)")
## ------------------------------------------------------------------------
boot = fpc::clusterboot(data = dist_eucl, clustermethod = fpc::dbscanCBI, eps = 5.53,
MinPts = 7,B = 100, distances = T, count=F, method = "dist",
bootmethod = "boot")
dt = melt(data.table(cluster = c(0:4), boot$bootresult),id.vars="cluster",val="jaccard index",var="boot number")
dt = dt[cluster!=0]
p = ggplot(dt, aes(x=as.factor(cluster),y=`jaccard index`)) + geom_boxplot() +theme_bw()
print(p + ggtitle("Jaccard similarity between cluster assignment on the full data and on 100 bootstrap samples"))
## ------------------------------------------------------------------------
library(mclust)
mclust_assignment = gmm_main(pc_scores = pca$x,n_comp=6, k=1:8,n_cores=1)
## ------------------------------------------------------------------------
sce_info$mclust = as.factor(mclust_assignment)
table(sce_info$mclust,sce_info$hclust_eucl)
## ---- fig.width = 8------------------------------------------------------
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"mclust",drop=F],
shape = pData(sce_info)[,"hclust_eucl",drop=F],
title = "Mclust assignment",show_proportions = T)
print(p)
## ---- fig.width=8--------------------------------------------------------
mclust_model = gmm_main(pc_scores = pca$x,n_comp=6,do_crossval = F, best_k = 6, return_model = TRUE)
sce_info$mclust_forced = as.factor(mclust_model$classification)
table(sce_info$mclust_forced,sce_info$hclust_eucl)
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"mclust_forced",drop=F],
shape = pData(sce_info)[,"hclust_eucl",drop=F],
title = "Mclust assignment")
print(p)
## ----message=F,results="hide"--------------------------------------------
mclust_boot = MclustBootstrap(mclust_model, nboot=500)
## ------------------------------------------------------------------------
summary(mclust_boot, what = "ci")
## ----fig.width=8, fig.height = 4-----------------------------------------
par(mfrow=c(1,6))
plot(mclust_boot, what = "pro")
## ---- fig.width=8,fig.height=12------------------------------------------
par(mfrow=c(6,6))
plot(mclust_boot, what = "mean")
par(mfrow=c(6,6))
plot(mclust_boot, what = "var")
par(mfrow=c(1,1))
## ---- eval = F-----------------------------------------------------------
## save(sce_info,file = file.path(out_data_dir,"sce_info.RData"))
## ---- warning=F----------------------------------------------------------
sce_clean$cell_type = sce_info$cell_type
cellsius_out = cellsius_main(sce_clean, group_id = "cell_type", min_n_cells = 5,
verbose =T, min_fc = 2, organism = "human", iter=0,
max_perc_cells = 50, fc_between_cutoff = 1)
## ------------------------------------------------------------------------
cellsius_out
## ------------------------------------------------------------------------
unique(cellsius_out[cell_idx=="AAAGCAAGTCAAGCGA"]$sub_cluster)
## ------------------------------------------------------------------------
unique(cellsius_out[sub_cluster == "T-cell_1_1"][,c('gene_id','symbol','description')])
## ------------------------------------------------------------------------
cellsius_out[,length(unique(cell_idx)),by="sub_cluster"]
## ------------------------------------------------------------------------
plot_rare_cells(rare=cellsius_out, tsne=tsne_info)
## ------------------------------------------------------------------------
plot_rare_cells(rare=cellsius_out[main_cluster=="T-cell"], tsne=tsne_info)
## ------------------------------------------------------------------------
plot_rare_cells(rare=cellsius_out[sub_cluster=="T-cell_1_1"], tsne=tsne_info)
## ---- fig.width=8,fig.height=6-------------------------------------------
marker_idx = which(rownames(sce_clean)%in%cellsius_out[sub_cluster=='T-cell_1_1']$gene_id)
plotlist = list()
colors = t(norm_exprs(sce_clean)[marker_idx,,drop=F])
colnames(colors) = fData(sce_clean)$symbol[marker_idx]
for(i in seq(dim(colors)[2])){
plotlist[[i]] = my_plot_tSNE(tsne = tsne_info,
color = colors[,i,drop=F],
alpha = 0.8, title = colnames(colors)[i]) + scale_color_distiller(palette = 'RdYlBu')
}
ggmultiplot(plotlist[[1]],plotlist[[2]],plotlist[[3]], plotlist[[4]],cols = 2)
## ---- eval = F-----------------------------------------------------------
## library(shiny)
## launch_marker_vis_app(tsne = tsne_info, sce=sce_clean, marker_idx = marker_idx)
## ------------------------------------------------------------------------
final_clusters = cellsius_final_cluster_assignment(cellsius_out, sce_clean, group_id = "cell_type", min_n_genes=3)
table(final_clusters$cluster)
p = my_plot_tSNE(tsne = tsne_info, color = final_clusters, title = "CellSIUS cluster assignment")
print(p)
## ------------------------------------------------------------------------
sce_clean$SC3_assignment = sce_info$SC3_assignment
sce_clean$hclust_eucl = sce_info$hclust_eucl
## ------------------------------------------------------------------------
de_wilcox = run_wilcoxon_test(sce_clean, cl_id = "hclust_eucl", cl_ref = "B-cell",
fc_cutoff = 1, alpha = 0.05)
dim(de_wilcox)
head(de_wilcox)
## ------------------------------------------------------------------------
table(de_wilcox$DE_flag)
## ------------------------------------------------------------------------
mean_exprs_dt = data.table(gene_id = rownames(sce_clean),mean_exprs = fData(sce_clean)$mean_exprs)
de_wilcox = merge(de_wilcox,mean_exprs_dt, by = "gene_id")
names(de_wilcox)
## ------------------------------------------------------------------------
p = generic_scatterplot(de_wilcox, x_col = "mean_exprs", y_col = "log2fc",
color = "DE_flag")
print(p+ggtitle('MA plot for Wilcoxon test'))
## ------------------------------------------------------------------------
de_wilcox[,log10_pval:=-log10(adj_pval)]
p = generic_scatterplot(de_wilcox, x_col = "log2fc", y_col = "log10_pval",
color = "DE_flag")
print(p+ggtitle('Volcano plot for Wilcoxon test'))
## ----message=F-----------------------------------------------------------
library(DT)
top_DE = de_wilcox[DE_flag==TRUE][order(log2fc,decreasing = T)]$gene_id[1:20]
gene_table = get_gene_annotations(top_DE,get_descriptions = T)
datatable(gene_table, caption = "Top 20 upregulated genes in B-cells")
## ------------------------------------------------------------------------
de_limma_voom = run_limma(sce_clean, cl_id = "hclust_eucl", cl_ref = "B-cell",
method = "voom", fc_cutoff = 1, alpha = 0.05, count_thr = 1,pct=50)
## ------------------------------------------------------------------------
dim(de_limma_voom)
names(de_limma_voom)
## ------------------------------------------------------------------------
table(de_limma_voom$DE_flag)
table(de_wilcox[de_limma_voom$gene_id,on="gene_id"]$DE_flag,de_limma_voom$DE_flag)
## ------------------------------------------------------------------------
de_limma_voom = merge(de_limma_voom,mean_exprs_dt, by = "gene_id")
names(de_limma_voom)
p = generic_scatterplot(de_limma_voom, x_col = "mean_exprs", y_col = "logFC",
color = "DE_flag")
print(p+ggtitle('MA plot for limma-voom'))
## ------------------------------------------------------------------------
voom_no_filt = run_limma(sce_clean, cl_id = "hclust_eucl", cl_ref = "B-cell",
method = "voom", fc_cutoff = 1, alpha = 0.05, count_thr = 0)
voom_no_filt = merge(voom_no_filt, mean_exprs_dt)
p = generic_scatterplot(voom_no_filt, x_col = "mean_exprs", y_col = "logFC",
color = "DE_flag")
print(p+ggtitle("MA plot for limma-voom, no filtering"))
table(voom_no_filt[DE_flag==TRUE]$gene_id%in%de_limma_voom[DE_flag==TRUE]$gene_id)
## ------------------------------------------------------------------------
example_dt = copy(voom_no_filt)
example_dt[,logFC:=logFC-1*1/(mean_exprs+1)]
example_dt[,DE_flag := adj.P.Val < 0.05 & abs(logFC)>1]
p = generic_scatterplot(example_dt, x_col = "mean_exprs", y_col = "logFC",
color = "DE_flag") + geom_hline(yintercept = 0)
print(p+ggtitle("An example of an MA plot for limma gone wrong"))
## ------------------------------------------------------------------------
de_limma_trend = run_limma(sce_clean, cl_id = "hclust_eucl", cl_ref = "B-cell",
method = "trend", fc_cutoff = 1, alpha = 0.05, count_thr = 1, pct=50)
de_limma_trend = merge(de_limma_trend, mean_exprs_dt)
de_limma_trend[,voom_overlap:=de_limma_trend$DE_flag == de_limma_voom$DE_flag]
p = generic_scatterplot(de_limma_trend, x_col = "mean_exprs", y_col = "logFC",
color = "DE_flag", shape = "voom_overlap")
print(p + ggtitle("MA plot for limma-trend"))
table(de_limma_trend$DE_flag,de_limma_voom$DE_flag)
table(de_wilcox[de_limma_trend$gene_id,on="gene_id"]$DE_flag,de_limma_trend$DE_flag)
# Compare p-values between Wilcoxon test and limma
ggplot(data.table(wilcox = de_wilcox[de_limma_trend$gene_id,on="gene_id"]$pval,
limmatrend = de_limma_trend$P.Val),
aes(x=-log10(wilcox),y=-log10(limmatrend)))+geom_point()+theme_bw()+
ggtitle('Comparison of p-values between limmatrend and Wilcoxon test')
## ---- message = F--------------------------------------------------------
de_MAST = run_MAST(sce_clean,cl_id = "hclust_eucl",cl_ref = "B-cell",norm=T,
set_thresh=T,fc_cutoff = 1, alpha=0.05)
## ---- message = F--------------------------------------------------------
de_MAST = run_MAST(sce_clean,cl_id = "hclust_eucl",cl_ref = "B-cell",norm=T,
set_thresh=F,fc_cutoff = 1, alpha=0.5)
## ----fig.width=10--------------------------------------------------------
de_MAST = merge(de_MAST, mean_exprs_dt)
p = generic_scatterplot(de_MAST, x_col = "mean_exprs", y_col = "log2FC",
color = "DE_flag")
print(p+ggtitle("MA plot for MAST"))
table(de_MAST$DE_flag)
table(de_MAST[de_limma_trend$gene_id,]$DE_flag,de_limma_trend$DE_flag)
# Compare p-values between MAST and limma
ggplot(data.table(MAST = de_MAST[de_limma_trend$gene_id,on="gene_id"]$pval,
limmatrend = de_limma_trend$P.Val),
aes(x=-log10(MAST),y=-log10(limmatrend)))+geom_point()+theme_bw()+
ggtitle('Comparison of p-values between limmatrend and MAST')
## ----fig.width=10, eval = T----------------------------------------------
merged = merge(de_MAST,
de_limma_trend[, c("gene_id","DE_flag"),with=F],
by = "gene_id",all=T)
merged = merge(merged, de_wilcox[,c("gene_id","DE_flag"),with=F],by="gene_id",all=T)
setnames(merged,which(grepl("DE_flag",names(merged))),paste0("DE_flag_",c(1:3)))
merged[,overlap:=factor(DE_flag_1==T & DE_flag_2==T & DE_flag_3==T, labels =c("Not DE or not found by all methods","Overlap of all methods"))]
p = generic_scatterplot(merged, x_col = "mean_exprs", y_col = "log2FC", color = "overlap" )
print(p+ggtitle("Overlap between all methods tested") + ylab("log2FC (MAST)"))
## ---- eval = T, message = F----------------------------------------------
library(SC3)
# add the slots the calc biology function checks
dummy = list(`0`=0)
sce_clean@sc3$consensus = dummy
sce_clean@sc3$n_cores = 4
fData(sce_clean)$sc3_gene_filter = rep(TRUE,dim(sce_clean)[1]) #do not filter out any genes
# add whatever clustering assignment you want to the sc3_0_clusters slot
sce_clean$sc3_0_clusters = as.factor(sce_info$cell_type)
sce_clean = sc3_calc_biology(sce_clean, k = 0)
## ---- out.width="110%",fig.height=6--------------------------------------
# change the plotted gene names to symbol for better readability
plot_sce = sce_clean[!is.na(fData(sce_clean)$symbol),]
rownames(plot_sce) = fData(plot_sce)$symbol
custom_sc3_plot_markers(plot_sce, k=0, p.val = 0.01, auroc = 0.90, show_pdata='sc3_0_clusters')
<file_sep>/vignettes/workflow_vignette.Rmd
---
title: "scRNASeq workflow - Vignette"
author: "<NAME>"
date: "`r format(Sys.time(), '%B %d, %Y')`"
output:
html_document:
toc: true
---
## LICENSE
Copyright 2018 Novartis Institutes for BioMedical Research 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 "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.
## Setting up your environment
### System requirements
Some of the bioconductor packages used in this workflow changed drastically between different versions, so that newer versions are no longer compatible with tho old ones. Therfore, please make sure your **R version is 3.4.1** and your **Bioconductor version is 3.5**.
```{r, eval = F}
source("https://bioconductor.org/biocLite.R")
# to install a specific version of bioconductor, use this instead:
install.packages("BiocInstaller", repos="http://bioconductor.org/packages/3.5/bioc")
library(BiocInstaller)
```
Some packages depend on `Rcpp` and `RcppArmadillo`, which require relatively recent versions of C/C++ compilers. This should in general not be an issue, but keep it in mind if you stumble upon errors involving those packages or any other C/C++ compilation related errors.
Lastly, installing packages from github requires the devtools package:
```{r, eval = F}
install.packages("devtools")
```
### Required packages
In this section, all packages needed to run this vignette are listed in the order that they are loaded. Note that because sometimes, major changes happen between diffrent versions of a package, make sure you are installing the versions provided below.
#### Packages that are required throughout the analysis
```{r, eval=F}
# from CRAN
install.packages("Rtsne") #Rtsne v. 0.13
install.packages("ggplot2") # ggplot2 v. 2.2.1
install.packages("data.table") # data.table v. 1.10.4
install.packages("RColorBrewer") # RColorBrewer v. 1.1-2
install.packages("mvoutlier") # mvoutlier 2.0.8, required by some functions from scater
devtools::install_github("bwlewis/irlba") # irlba 2.3.2, optional. Make sure you use irlba > 2.3.1, older versions contain a bug that results in unreliable output!
# rom Bioconductor
biocLite("scater") # scater v. 1.4.0
biocLite("scran") # scran v. 1.4.5
```
#### Genome annotation (human)
```{r, eval=F}
# ensembldb 2.0.4 and EnsDb.Hsapiens.v79 2.1.0
biocLite(c("ensembldb","EnsDb.Hsapiens.v79"))
# org.Hs.eg.db v. 3.4.1
biocLite("org.Hs.eg.db")
```
#### Genome annotation (mouse)
```{r, eval=F}
# ensembldb 2.0.4 and EnsDb.Mmusculus 2.1.0
biocLite(c("ensembldb","EnsDb.Mmusculus.v75"))
# org.Mm.eg.db v. 3.4.1
biocLite("org.Mm.eg.db")
```
#### Feature selection
```{r,eval = F}
# M3Drop version 3.05.00 (Note: This is still under active development, please let me know if a new version breaks my functions...)
devtools::install_github("tallulandrews/M3D")
```
#### Clustering
```{r, eval = F}
install.packages("cluster") # cluster v. 2.0.6
install.packages("dendextend") # dendextend v. 1.5.2
install.packages("Ckmeans.1d.dp") # Ckmeans.1d.dp v. 4.2.1
install.packages("dbscan") # DBSCAN v. 1.1-1
install.packages(c("mclust","mvtnorm")) # mclust v. 5.4 and mvtnorm 1.0.6
install.packages("dynamicTreeCut") # dynamicTreeCut v. 1.63-1
biocLite("SC3") # SC3 v. 1.4.2
devtools::install_github("satijalab/seurat") #Seurat 2.0.1
devtools::install_github('JustinaZ/pcaReduce') #pcaReduce 1.68.0
```
In addition, an external installation of MCL is required which can be found [here](https://micans.org/mcl/).
#### Differential expression analysis
```{r,eval = F}
biocLite("limma") # limma v. 3.32.5
biocLite("MAST") # MAST v. 1.2.1
```
### Setting up paths for loading and saving data
**Note: You have to change these so that they match your directories!**
This example assumes your working directory is the scRNASeq_workflow/vignettes directory, thus `wd` is the path to the scRNASeq_workflow directory.
```{r, message = FALSE}
rm(list=ls())
graphics.off()
wd = ".."
#Directory where input files are stored
input_dir = file.path(wd,"example_data")
#Directory where code is stored
code_dir = file.path(wd,"code")
#where to save the output data?
out_data_dir = file.path(wd,"example_output")
if(!dir.exists(out_data_dir)) {dir.create(out_data_dir)}
#where to save the produced plots?
plotdir = file.path(wd,"example_plots")
if(!dir.exists(plotdir)) {dir.create(plotdir)}
set.seed(17) #to make tSNE plots reproducible
source(file.path(code_dir,"scRNASeq_pipeline_functions.R"))
# loading the libraries that are required throughout the analysis
library_calls()
```
## A note on gene expression units
Before we start, a brief but important note on units: RNA-Seq is inherently a method for relative quantification of gene expression. While UMI counts can be interpreted as "number of transcripts per cell", this unit is arbitrary and differs between each experiment and platform. Normalizing counts yields "normalized transcripts per cell", or, if scaled to the total number of counts per cell, "normalized counts per million total counts (CPMs)". However, **NONE of these units are comparable across different samples and even less so across different platforms!**. If you want to compare gene expression between different samples, you can do so only after appropriate between-sample normalization.
## Terminology
* Features: The term "features" refers to the things that were measured. In the context of scRNASeq, "features" means "genes", or, more accurately, "transcripts".
* Feature controls: This is a set of features we use for quality control. Here, the feature controls correspond to mitochondrial genes.
* Counts: Counts are the number of unique molecular identifiers (UMIs) mapped to each transcript.
* Expression: The term "expression" refers to gene expression level [arbitrary units!]. Usually, we use the log2-transformed normalized counts as a measure of gene expression.
* Dropout: This is an observation of a zero count for a feature. Dropouts can be either true zeros (i.e., the gene is really not expressed), or technical artifacts (i.e. a transcript was not captured or failed to amplify).
## Preparing the data
For this example, we will use a subset of a publicly available dataset from 10X genomics. The original dataset contains ~4500 Peripheral Blood Mononuclear Cells (PBMCs). The raw data can be downloaded [here](http://cf.10xgenomics.com/samples/cell-exp/2.0.1/pbmc4k/pbmc4k_raw_gene_bc_matrices.tar.gz). To make this vignette run in a reasonable amount of time, the example dataset (example_data/pbmc_example_counts.txt) was created from the raw data by randomly sampling 400 cells.
In this first part, we will read the count matrix, annotate the cells and genes, and construct an SCESet that contains the count data as well as all the metadata:
```{r,message=F,eval=F}
# Read the dataset
counts = read.delim(file.path(input_dir,"pbmc_example_counts.txt"),sep="\t")
# if we have genes that are not expressed in any cell, discard them
keep_feature = !gene_filter_by_feature_count(counts,0)
counts = counts[keep_feature,]
# make a table of metadata (e.g. batch, cell type annotation,treatment,...)
# Here, we do not have any such information, so we just give each cell a name
# Note that the rownames of this table have to correspond to the column names
# of the count matrix.
annot = data.frame(cell_idx=paste0("pbmc_C",seq(dim(counts)[2])))
rownames(annot) = colnames(counts)
pd = new("AnnotatedDataFrame", data=annot)
# get gene annotations from ensembldb
# optional: get gene descriptions from org.Hs.eg.db (slows down the process a lot!)
# NOTE: the output of get_gene_annotations is a data.table sorted by gene identifier.
# This means the genes are no longer in the same order as in the count matrix!
geneName = get_gene_annotations(rownames(counts),organism = "human",get_descriptions = F)
# convert this to feature metadata
fd_table = as.data.frame(geneName)
rownames(fd_table) = geneName$gene_id
fd_table = fd_table[rownames(counts),]
fd = new("AnnotatedDataFrame",data=fd_table)
#construct SCESet
sce = newSCESet(countData = counts, phenoData=pd,featureData = fd)
```
Note that the `get_gene_annotations` function expects the gene identifiers to be ensembl IDs. Also, currently, only annotations for human and mouse genes are supported.
## Quality control
We will use scater to calculate various QC metrics. See the [package vignette](https://bioconductor.org/packages/release/bioc/vignettes/scater/inst/doc/vignette.html) for details. Then, we use the cyclone function in scran to assign cell cycle phases. Since this takes fairly long, we save the SCESet afterwards so we can just load it and continue the analysis at some later time.
```{r,eval=F}
#calculate QC metrics
sce = calculateQCMetrics(sce,feature_controls = list(MT=which(fData(sce)$chr=="MT")))
# assign cell cycle phase (based on the method from scran)
# because PBMCs are post-mitotic, most cells should be assigned to G0/G1 phase
cc = annotate_cell_cycle(sce)
sce$cell_cycle_phase = cc$phases
sce$cc_scores = cc$scores
#save the SCESet
save(sce,file=file.path(out_data_dir,"sce_raw.RData"))
```
### Visualizing gene-level QC metrics
We can use scater to plot various QC metrics. All of these plots are returned as ggplot objects, so it's very easy to modify them (e.g. add titles, change axis labels, ...). Saving plots is most convenient using `ggsave`.
For example, we can visualize the relative expression (percentage of total counts) of the top 50 expressed genes in each cell:
```{r}
load(file.path(out_data_dir,"sce_raw.RData"))
p1 = plotQC(sce, type="high",feature_names_to_plot = "symbol")
print(p1)
```
As expected, we mostly find ribosomal proteins and core metabolic genes among the top 50 genes.
Using a slightly modified version of the scater function, we can also make a similar plot for the absolute raw expression values per gene:
```{r}
p1.2 = custom_plotHighestExprs(sce,feature_names_to_plot = "symbol")
p1.2 = p1.2 + xlab("Expression [raw counts, log2]")
print(p1.2)
# to save a plot, use the ggsave function:
ggsave(p1.2, file = "saved_example_plot.pdf",height=7,width=7)
```
In general, this picks up similar genes than the previous plot. Exceptions are genes that are expressed extremely high, but only in few cells, where the ranking according to percentage of total counts is much lower than the one according to mean expression.
Next, we can plot the detection rate v.s. mean expression for each gene. This gives a general idea of the quality of our data, i.e. how many genes were detected, what was the dropout rate etc.
```{r,warning=F}
p2 = plotQC(sce, type = "exprs-freq-vs-mean")
p2 = p2+xlab("Mean expression [raw counts, log2]")+ggtitle("Mean expression versus detection rate")
print(p2)
# Check total number of zeroes
t = table(counts(sce)==0)
print(t/sum(t)*100)
```
From these three plots, we can see that the data are very sparse. We find a high number of dropouts and even for the most highly expressed genes, there are still some cells having zero counts. Moreover, only very few genes are expressed in more than 50% of all cells.
If we check for the total number of zero counts, we see that over 90% of all counts are zeroes, which indicates that probably sequencing depth was not very high for this dataset or the cells had rather low RNA content.
### Identifying confounders
Scater also includes some functions that help to identify possible confounding factors. For example, a known widespread bias in scRNASeq experiments is the total number of features detected per cell:
```{r}
p3 = plotQC(sce, type="find", variable="total_features")
print(p3 + ggtitle("Correlation of principal components with total detected features."))
```
Or maybe there is some bias from cell cycle phase:
```{r}
p3.2 = plotQC(sce, type="find", variable="cell_cycle_phase")
print(p3.2+ggtitle("Correlation of principal components with cell cycle phase."))
```
Lastly, scater includes a function that determines the amount of variance explained by possible confounding factors:
```{r}
vars = c("total_counts","total_features","cell_cycle_phase")
p4 = plotQC(sce, type="expl", variables=vars)
print(p4 + ggtitle("Percentage of explained variance"))
```
Here, none of the factors contribute significantly to the observed variance and we conclude that there are no major confounders present.
### Filtering low-quality cells
As a first step, we set manual thresholds for the following QC metrics:
* the total number of detected features (min_genes, on log2 scale)
* the total number of UMIs ("counts") per cell (min_UMI, on log2 scale)
* the percentage of counts attributed to mitochondrial genes (mt_threshold)
```{r}
min_genes = 9.0 #minimum number of features (genes) per cell [log2]
min_UMI = 10.5 #minimum total UMIs / cell [log2]
mt_threshold = 9 #Maximum percentage of mitochondrial genes
```
We can check whether those thresholds make sense by calling the `plot_RNA_QC` and `plot_MT_QC` functions. For the RNA content, we would like to get rid of the left-hand tails of the distributions. For the mitochondrial genes, we remove outliers. On the second plot of the MT QC, we can see that most cells with very high mitochondrial gene content have overall poor coverage.
```{r}
plot_RNA_QC(sce, min_genes = min_genes, min_UMI = min_UMI)
plot_MT_QC(sce,mt_threshold)
```
Now that we are happy with the thresholding, we can filter the cells:
```{r}
sce$keep_manual = ( !cell_filter_by_feature_count(counts(sce),2^min_genes) &
!cell_filter_by_total_UMI(counts(sce),2^min_UMI) & !cell_filter_by_mt_content(sce$pct_counts_feature_controls_MT,mt_threshold))
table(sce$keep_manual)
sce_clean = sce[,sce$keep_manual]
```
Note that all filtering functions return logical vectors. It is therefore also possible to just flag the cells as outliers, but keep them in the analysis.
Next, we filter the genes. There are two parameters to set:
* n_th: The minimum number of cells
* min_counts: The minimum number of counts
The filter will then remove any gene not having at least `min_counts` counts in at least `n_th` cells.
Here, we want to remove all genes that do not have at least 2 counts in at least 1 cell.
```{r}
n_th = 1
min_counts = 2
keep_feature = !(gene_filter_by_feature_count(counts(sce_clean),n_th, min_counts))
sce_clean = sce_clean[keep_feature,]
```
Finally, we use scaters automatic outlier detection feature to flag and/or remove any additional outlier cells:
```{r}
sce_clean = calculateQCMetrics(sce_clean,feature_controls = list(MT=which(fData(sce_clean)$chr=="MT")))
# The variables used to detect outliers
vars = c( "pct_counts_top_100_features",
"total_features", "pct_counts_feature_controls",
"log10_counts_endogenous_features",
"log10_counts_feature_controls")
sce_clean = plotPCA(sce_clean,
size_by = "total_features",
pca_data_input = "pdata",
selected_variables = vars,
detect_outliers = TRUE,
return_SCESet = TRUE)
table(sce_clean$outlier)
#here, we remove the outliers
sce_clean = sce_clean[,!sce_clean$outlier]
# Finally, we again remove genes that are not expressed
keep_feature = !(gene_filter_by_feature_count(counts(sce_clean),n_th,min_counts))
sce_clean = sce_clean[keep_feature,]
save(sce_clean, file = file.path(out_data_dir,"sce_clean.RData"))
```
In this case, PC1 can be interpreted as "RNA content", whereas PC2 is dominated by metrics describing diversity.
To visualize the raw data, we can make a PCA plot using `my_plot_PCA`. For a detailed description of all parameters of this function, check the [function documentation](## Functions). For very large datasets, it is a good idea to set `use_irlba=TRUE`. This will then use `prcomp_irlba` to perform an approximate calculation of the first couple of principal components, which is much faster than PCA.
Because the counts are spread over several orders of magnitude, it is generally a good idea to log-transform them before running PCA:
```{r}
p = my_plot_PCA(counts = log2(counts(sce_clean)+1),
scale_pca = T, center_pca = T, return_pca = F, use_irlba=F,
color = pData(sce_clean)[,"total_features",drop=F])
p = p+ggtitle("PCA on raw log2(counts)")
print(p)
```
Coloring the PCA by the total number of features detected shows that the first principal component primarily separates cells by the total number of features detected. This is expected for raw data and we will see this trend disappear after normalization.
Alternatively, we can make a tSNE projection of the log2-transformed counts using `my_plot_tSNE`:
```{r}
p = my_plot_tSNE(counts = log2(counts(sce_clean)+1),
is_distance = F, scale_pca = F, n_comp = 50, return_tsne=F,
color = pData(sce_clean)[,"total_features",drop=F])
p = p+ggtitle("t-SNE on raw log2(counts)")
print(p)
```
Here, we also see some separation according to the number of total detected features, but less strongly than in the PCA. In addition, we start to see 3 distinct clusters. This is what we would expect as there are 3 most abundant cell types among PBMCs (B-cells, T-cells/NK cells and monocytes).
## Normalization
Normalizing the data is required to remove systematic differences between cells that arise from different RNA capture efficiency, sequencing depth, or differences in RNA content between cells. The function `normalize_counts` adds the normalized expression data (on a log2 scale) to the `norm_exprs` slot of the SCESet. We can choose between different normalization methods (see function documentation). In general, they perform very similar to each other. However, because we have very sparse data and methods originally developed for bulk RNA-Seq data (TMM, RLE, TC) often have issues handling many zeroes, we use the method implemented in the scran package which was specifically designed to work on sparse data.
```{r,message=F}
# normalize data
sce_clean = normalize_counts(sce_clean,method = "scran")
# normalized values are automatically log2-transformed and
# stored in the norm_exprs slot of the SCESet
norm_exprs(sce_clean)[1:5,1:5]
save(sce_clean, file = file.path(out_data_dir,"sce_clean.RData"))
```
We can again visualize the data using PCA and tSNE:
```{r}
# PCA of normalized values
sum_norm = data.frame(sum_expression = colSums(norm_exprs(sce_clean)))
p1 = my_plot_PCA(counts = norm_exprs(sce_clean),
color=sum_norm,
return_pca = F, scale_pca = T, center_pca = T)
p1 = p1+ggtitle("PCA on normalized counts")
print(p1)
#tSNE of normalized values
p2 = my_plot_tSNE(counts = norm_exprs(sce_clean),
color=sum_norm,
return_tsne = F, is_distance = F)
p2 = p2 + ggtitle("t-SNE (50 PCs) on normalized counts")
print(p2)
```
As expected, after normalization, the first principal component is no longer separating cells by how many genes they express and we now find 3 distinct clusters, similar to what we saw in the initial tSNE projection.
## Feature selection
Feature selection is a crucial part of this workflow, because by selecting the most informative genes, we can greatly improve the signal/noise ratio. The workflow includes multiple ways of selecting interesting genes:
1. Using prior knowledge: select all the genes that are annotated with some GO term of interest. Here, we will use GO:0002376 (immune system process) as an example.
2. Based on sample variance: This method is described by [Brennecke et. al, 2013](http://www.nature.com/nmeth/journal/v10/n11/full/nmeth.2645.html?foxtrotcallback=true). Informative genes are those with higher than expected sample variance.
3. Based on a mean-dispersion fit using a depth-adjusted negative binomial model (DANB): This method is implemented in versions > 2.0 of M3Drop (Andrews and Hemberg, pre-print can be found [here](https://www.biorxiv.org/content/early/2016/10/20/065094))
In the following, we will use the different approaches and see how they affect our PCA plot. To make sure we actually see true cell type clusters, we color the PCA by the expression of a known B-cell marker (ENSG00000156738, i.e. CD20).
For a detailed description of each function used in this section, check the [Function documentation](#feature-selection-2)
### Feature selection based on GO annotation
```{r,message=F}
cd20 = t(norm_exprs(sce_clean["ENSG00000156738",]))
colnames(cd20) = "CD20"
go_id = "GO:0002376"
ens_go = GO_to_gene(go_id)
info_GO = rownames(sce_clean)%in%ens_go
table(info_GO)
p = my_plot_PCA(counts = norm_exprs(sce_clean[info_GO,]),
return_pca = F, scale_pca = T, center_pca = T,
title = "PCA - GO:0002376 features",
color = cd20)
print(p)
```
### Feature selection using highly-variable genes method
```{r}
info_HVG = info.genes(2^norm_exprs(sce_clean)-1,PLOT=T,qcv=0.25,pv=.1,q=.5,minBiolDisp = 0)
table(info_HVG)
p = my_plot_PCA(counts = norm_exprs(sce_clean[info_HVG,]),
return_pca = F, scale_pca = T, center_pca = T,
title = "PCA - HVG features",
color = cd20)
print(p)
```
### Feature selection using DANB
The `run_DANB` function is a wrapper to both NBDrop and NBDisp methods that are implemented in newer versions (>2.0) of the M3Drop package. Briefly, NBDrop selects genes with unexpected dropout rates while NBDisp selects informative genes based on higher than expected dispersions. In general, NBDrop is less prone to selecting very low expressed genes, but on the downside, if the the total number of features detected per cell is a confounder, NBDrop can enhance this effect. Note that DANB requires raw counts as input.
To modify the number of genes selected, you can either set the `cutoff` variable, which is a p-value cutoff for NBDrop, or set `perc_genes`, in which case the top `perc_genes` percentage of genes will be chosen.
```{r}
info_NBdrop = run_DANB(counts(sce_clean),method = "NBDrop",save_plot=F, cutoff = 0.1)
info_NBdisp = run_DANB(counts(sce_clean),method = "NBDisp",save_plot=F, perc_genes = 10)
table(info_NBdrop,info_NBdisp)
p = my_plot_PCA(counts = norm_exprs(sce_clean[info_NBdrop,]),
return_pca = F, scale_pca = T, center_pca = T,
title = "PCA - NBDrop features",
color = cd20)
print(p)
p = my_plot_PCA(counts = norm_exprs(sce_clean[info_NBdisp,]),
return_pca = F, scale_pca = T, center_pca = T,
title = "PCA - NBDisp features",
color = cd20)
print(p)
```
### Feature selection - Conclusion
In conclusion, we see that by selecting a biological process that we know affects the expected cell types, we can increase the variation between the three observed clusters while cells belonging to the same cluster move closer together. Also, note how the variation explained by the first two principal components increases drastically when we select a small number of informative genes. A similar result is obtained when using DANB with either the NBDisp or NBDrop method, with NBDrop in this case outperforming NBDisp. The HVG method fails to improve this signal/noise ratio. This is most likely because it was originally developed for fluidigm C1 data (no UMIs). On our type of data, it tends to be biased towards low expressed genes as the underlying mean-dispersion model is not fitting well.
I suggest to exclusively use DANB in the future. Which version of this method is best depends on your data:
* The NBDrop version works very well if you expect your highly variable genes to have a binary expression pattern (expressed in one cell type but not expressed at all in others). If there are (technical or biological) differences in dropout rates between cell types, however, NBDrop selects genes that only separate cells according to dropout rate.
* NBDisp selects genes based on dispersion, which is dependent on variance. NBDisp is therefore slightly more biased towards low-expressed genes. In general, this is not really a problem and I found NBDisp to perform very well on all datasets tested.
In the following, we will use only the genes selected by NBDrop.
```{r, eval=F}
sce_info = sce_clean[info_NBdrop,]
dim(sce_info)
# tSNE map of the cleaned data
# note that by setting return_tsne = T, we can obtain the t-SNE object for later use
tsne_info = my_plot_tSNE(counts = norm_exprs(sce_info),
scale_pca = F, n_comp = 50, return_tsne=T)$tsne
```
We will save the SCESet and the t-SNE map for later use:
```{r,eval=F}
save(sce_info, file = file.path(out_data_dir,"sce_info.RData"))
save(tsne_info,file = file.path(out_data_dir,"tsne_info.RData"))
```
```{r}
#load the data we need
load(file.path(out_data_dir,"sce_info.RData"))
load(file.path(out_data_dir,"tsne_info.RData"))
```
## Clustering
The workflow contains different types of clustering approaches. Which one is most appropriate depends on your data. As a rule of thumb, if your data contains clearly separated clusters, all algorithms should produce a similar result. If you get very different results, maybe there really are no clear clusters and you might be better off using an approach tailored to more continuous cell type changes (e.g. monocle, SLICER). A good overview of the different decisions required when carrying out cluster analysis can be found in [this](https://arxiv.org/pdf/1503.02059.pdf) paper by <NAME>. al.
For a detailed description of the functions used in this section, see [Function documentation](#clustering-2)
Before we try any of the methods, we do a quick and dirty annotation of the four major cell types based on marker expression. We use CD20 expression to identify B-cells, the sum of CD14, LYZ, FCGR3A and MS4A7 for any type of Monocyte, CD3 for T-cells and the sum of GNLY and NKG7 for natural killer cells.
```{r, fig.align='center', fig.width=12, fig.height=8}
b_cell = t(norm_exprs(sce_info["ENSG00000156738",]))
colnames(b_cell) = "B-cell"
monocyte = data.frame(Monocyte = colSums(norm_exprs(sce_info)[which(fData(sce_info)$symbol %in% c('CD14','LYZ','FCGR3A','MS4A7')),]))
t_cell = data.frame(`T-cell` = colSums(norm_exprs(sce_info)[which(fData(sce_info)$symbol %in% c('CD3E','CD3D','CD3G')),]))
nk_cell = data.frame(`NK cell` = colSums(norm_exprs(sce_info)[which(fData(sce_info)$symbol %in% c('GNLY','NKG7')),]))
# Make plots
# Note that by providing the tsne input variable instead of counts,
# we can use an existing t-SNE calculation for plotting
p1 = my_plot_tSNE(tsne = tsne_info, color = b_cell, title = "B-cell marker expression")
p2 = my_plot_tSNE(tsne = tsne_info, color = monocyte, title = "Monocyte marker expression")
p3 = my_plot_tSNE(tsne = tsne_info, color = t_cell, title = "T-cell marker expression")
p4 = my_plot_tSNE(tsne = tsne_info, color = nk_cell, title = " NK cell marker expression")
ggmultiplot(p1,p2,p3,p4,cols=2)
```
```{r}
assignment = data.table(tsne1 = tsne_info$Y[,1], tsne2 = tsne_info$Y[,2],cell_type = 'T-cell')
assignment[tsne1 < -10 ,cell_type:='B-cell']
assignment[tsne1 > 5 ,cell_type:='Monocyte']
assignment[tsne2 < -17 & tsne1 > -1,cell_type:='NK Cell']
sce_info$cell_type = assignment$cell_type
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"cell_type",drop=F])
print(p+labs(title="t-SNE on informative genes",subtitle = "Colored by manual cell annotation"))
```
### Single-cell consensus clustering (SC3)
SC3 ([Kiselev et. al, 2016](http://www.nature.com/nmeth/journal/v14/n5/full/nmeth.4236.html?foxtrotcallback=true)) is a tool for unsupervised clustering that integrates multiple clustering approaches and constructs a consensus clustering from them. In a nutshell, different distance measures and transformations are considered and for each combination, a k-means clustering is run. From this, a consensus matrix is constructed that summarizes how often each cell is in the same cluster with each other cell. The final clustering otput is obtained by hierarchical clustering of the consensus matrix.
The advantages of SC3 are that it is more robust to clustering inputs and parameter selection than other methods. Moreover, it was developed to work together with scater and therefore is very easy to use in combination with the rest of this workflow.
The downside of SC3 is that the many clusterings that are generated take some time. According to the authors, SC3 takes ~20 min to run on a dataset with 2000 cells. Another thing to keep in mind is that SC3 uses k-means clustering, which in turn assumes all clusters are equaly sized spheres. In cases where this assumption does not hold, k-means will either split big clusters in a lot of tiny ones or, if forced to use a smaller number of clusters, fail completely.
To run SC3 with the default settings, we just need one function, `sc3()`. Here, we will manually run the individual steps of SC3 to make the analysis a bit more transparent.
First, we prepare the SCESet for the analyisis. This will add all the relevant parameters to the sc3 slot of the object. The parameters we set are
* ks: the number of clusters we would like to test
* n_cores = number of cores used in parallel computing. NOTE: if you do not set this parameter, the function will use the number of available cores -1, which is a really bad idea on a server!
```{r, echo=F}
library(SC3)
```
```{r,eval=F}
library(SC3)
sce_info = sc3_prepare(sce_info, ks = 2:10, n_cores = 4)
```
Next, we let SC3 determine the best number of clusters to use. For a detailed description on how the number of clusters is chosen, see the methods section of the [paper](http://www.nature.com/nmeth/journal/v14/n5/full/nmeth.4236.html?foxtrotcallback=true)
```{r,eval=F}
sce_info = sc3_estimate_k(sce_info)
sce_info@sc3$k_estimation
```
And now we run SC3 using 6 clusters. Setting biology = TRUE tells SC3 that it should calculate biological properties of the clusters:
```{r,eval=F}
sce_info = sc3(sce_info, ks = 6, biology = TRUE, n_cores = 4)
```
Note: If your dataset contains more than 5000 cells, SC3 will automatically switch to the "hybrid SVM" version of the algorithm. In that case, skip the above and run the following instead:
```{r, eval = F}
sce_info = sc3(sce_info, ks = 6, biology = F, n_cores = 8)
sce_info = sc3_run_svm(sce_info)
sce_info@sc3$svm_train_inds = NULL
sce_info = sc3_calc_biology(sce_info, k=c(8,13), regime = "marker")
# to visualize the markers, use my modified fuction:
# change the plotted gene names to symbol for better readability
plot_sce = sce_info
rownames(plot_sce) = fData(plot_sce)$symbol
custom_sc3_plot_markers(plot_sce, k=6, p.val = 0.01, auroc = 0.90)
rm(plot_sce)
```
SC3 also has a couple of nice visualization functions. For example, we can plot the consensus matrix:
```{r, out.width="110%",fig.height=4}
sc3_plot_consensus(sce_info, k=6)
```
In this plot, a value of 1 means the cells are always together in the same cluster. A value of 0 means they are never in the same cluster. Values in between indicate that it is not so clear where the cell belongs.
We can also make a heatmap of gene expression. With the show_pdata parameter, we can add any column in pData sce to annotate the cells:
```{r, out.width="110%",fig.height=4}
sc3_plot_expression(sce_info, k = 6, show_pdata = c("cell_type"))
```
Because we set biology to TRUE, SC3 determined marker genes for each cluster. We can have a look at them here (NOTE: use the custom version of the `sc3_plot_markers` function if you used the hybrid SVM approach!):
```{r, out.width="110%",fig.height=6}
# change the plotted gene names to symbol for better readability
plot_sce = sce_info
rownames(plot_sce) = fData(plot_sce)$symbol
sc3_plot_markers(plot_sce, k=6, p.val = 0.01, auroc = 0.90, show_pdata = c("cell_type"))
# for hybrid SVM approach:
# custom_sc3_plot_markers(plot_sce, k=6, p.val = 0.01, auroc = 0.90)
```
In this plot, we see that SC3 correctly identified known markers for the different cell types. In addition, we see that there are 2 larger groups among the T-cells. Checking the marker expression, we find that cluster 4 (high CCL5 and IL32) corresponds to CD8+ cytotoxic T-cells, whereas the remaining T-cells likely are T helper cells, although we did not find the characteristic CD4 marker. Cluster 2 remains unlabeled. We can visualize our assignment on the t-SNE map. Setting `show_proprtions=T` adds the relative number of cells per cluster to the legend:
```{r}
assignment = data.table(clust = sce_info$sc3_6_clusters, cell_type = sce_info$cell_type)
assignment[clust == 1, cell_type:= 'T helper cell']
assignment[clust == 2, cell_type:= 'Monocyte']
assignment[clust==3,cell_type:='?']
assignment[clust==4,cell_type:='CD8+ T-cell']
assignment[clust==5,cell_type:='NK cell']
assignment[clust == 6, cell_type:= 'B-cell']
sce_info$SC3_assignment = assignment$cell_type
p = my_plot_tSNE(tsne = tsne_info,
color = pData(sce_info)[,"SC3_assignment",drop=F],
shape = pData(sce_info)[,"cell_type",drop=F],
title = "SC3 assignment",
show_proportions = T)
print(p)
save(sce_info,file = file.path(out_data_dir,"sce_info.RData"))
```
### Hierarchical clustering (hclust)
Hierarchical clustering groups items according to some measure of similarity by sequentially joining the two most similar observations into a cluster. Therefore, selecting an informative distance measure is crucial for this algorithm to work. We will consider two commonly used distance measures in the following.
#### Euclidean distance
Euclidean distances in very high dimensional space tend to get all very large and very similar to each other, making cluster identification near impossible. As a workaround, we will reduce the dimensionality of the dataset using PCA before calculating the cell-cell distances.
```{r}
pca = my_plot_PCA(counts = norm_exprs(sce_info),return_pca=T)$pca
screeplot(pca,type = 'lines')
```
From the screeplot, we see that after the 6th component, the variance stays more or less constant. We therefore select 6 components for the distance calculation:
```{r}
dist_eucl = dist.gen(pca$x[,1:6],method='euclidean')
hfit = hclust(dist_eucl,method="average")
plot(hfit, labels = F, main = "hclust on euclidean distance in PCA space")
```
In this dendrogram, we see that there seem to be 6 major clusters present, however, they are somewhat nested. A fixed height cut of the dendrogram would here merge some clusters that should not be merged while creating small sets of outlier cells. To prevent this, we can use dynamic ct of the dendrogram:
```{r, message =F}
library(dynamicTreeCut)
groups_hclust_eucl = cutreeDynamic(hfit, distM = as.matrix(dist_eucl), deepSplit = 0, minClusterSize = 5, maxCoreScatter = 0.70, minGap = 0.25)
```
To get an idea of the quality of our clustering, we can make a silhoutte plot:
```{r}
library(cluster)
si = silhouette(groups_hclust_eucl,dist_eucl)
plot(si, col = "darkgray", border=NA, main = "Silhouette plot for hclust (euclidean in PCA space)")
```
The cluster silhoutte is a measure of how similar a point is to other points in the same cluster, relative to how similar it is to points in the closest cluster it does not belong to. A value close to 1 means the point is very well clustered. Values close to 0 indicate points lying between clusters. A negative value means the point is probably misassigned.
We can also plot the silhoutte values on the tSNE map:
```{r}
sce_info$hclust_sil = si[,3]
p = my_plot_tSNE(tsne = tsne_info,
color = pData(sce_info)[,"hclust_sil",drop=F],
shape = pData(sce_info)[,"cell_type",drop=F],
title = "tSNE colored by silhouette width")
print(p+scale_color_distiller(type="div", palette = "RdBu"))
```
As expected, the points with low silhoutte values are in between the clearly visible clusters.
Now we can compare the new assignment with what we obtained from SC3:
```{r}
sce_info$hclust_eucl = as.factor(groups_hclust_eucl)
table(sce_info$SC3_assignment,sce_info$hclust_eucl)
```
We see that the assignments of the two methods are very similar. In addition to the clusters found by SC3, hclust identified a tiny cluster of monocytes (cluster 6). Let's have a look at the expression of some monocyte marker genes. To do so, we make use of the `plotExpression` function from the scater package:
```{r}
# change the plotted gene names to symbol for better readability
plot_sce = sce_info
rownames(plot_sce) = fData(plot_sce)$symbol
monocyte_markers = which(fData(sce_info)$symbol %in% c('CD14','LYZ','FCGR3A','MS4A7'))
p = plotExpression(plot_sce,features = monocyte_markers, x="hclust_eucl",
colour_by = "hclust_eucl")
print(p)
```
We see that our small population of monocytes has low expression of LYZ and CD14 but high expression of CD16 (FCGR3A) and MS4A7. We therefore conclude that this small population corresponds to the CD14+/CD16++ monocytes whereas the remaining monocytes are the "classical" CD14++/CD16- monocytes.
We can now label our assignment accordingly and visualize on tSNE map:
```{r,fig.width = 8}
sce_info$hclust_eucl = factor(sce_info$hclust_eucl, levels = levels(sce_info$hclust_eucl), labels = c("T-helper cell","CD14++/CD16- Monocyte","B-cell","CD8+ T-cell","NK cell","CD14+/CD16++ Monocyte"))
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"hclust_eucl",drop=F],
shape = pData(sce_info)[,"cell_type",drop=F],
title = "hclust (euclidean) assignment",
show_proportions = T)
print(p)
```
#### Pearson distance
Another possible distance measure is Pearson correlation, where the distance is calculated as 1-correlation. We again try to get 6 clusters:
```{r}
library(dendextend)
dist_pearson = dist.gen(t(norm_exprs(sce_info)),method = "pearson")
hfit = hclust(dist_pearson,method="average")
groups_hclust_pearson = cutree(hfit, k=6)
sce_info$hclust_pearson = as.factor(groups_hclust_pearson)
hfit2 = color_branches(hfit, k=6)
hfit2 = hfit2 %>% set("labels", rep("",dim(sce_info)[2]))
plot(hfit2, main = "hclust on Pearson correlation")
```
From the dendrogram, we can already guess that we did not get a very fine-grained clustering. But let's check on the tSNE-map anyway:
```{r,fig.width=8}
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"hclust_pearson",drop=F],
shape = pData(sce_info)[,"cell_type",drop=F],
title = "hclust (Pearson) assignment",
show_proportions = T)
print(p)
```
While we can find the major cell types, we can no longer identify subgroups within the T-cells and the monocytes. Most likely this is due to the underlying noise in the data, which makes all correlations very similar. Sometimes, using the euclidean distance of the correlation matrix improves the clustering. We could also use PCA here to reduce the number of dimensions before calculating the correlation matrix. This would hopefully increase the signal to noise ratio, but since we already succesfully applied dimensionality reduction in combination with euclidean distance, we leave it be.
In conclusion, hierarchical clustering is a very useful clustering technique that does not require any assumptions on the number of clusters (at least, not before the algorithm is run, you still have to decide where to cut the dendrogram afterwards) or the distribution the data come from. However, selecting an informative input distance is crucial. Reducing dimensionality before calculating distances often improves the signal to noise ratio, but might come at the cost of loosing some information. The major drawback of hierarchical clustering is that it is very computationally expensive and becomes infeasible for very large datasets (ten thousands of cells).
### pcaReduce
pcaReduce is an agglomerative clustering method based on k-means and PCA. Cells are initially grouped into many clusters using k-means in PCA space. Clusters are then merged, and data are projected into lower dimensional space (i.e. for each reduction in the number of clusters, one principal component is removed). For details, see the [paper](https://bmcbioinformatics.biomedcentral.com/articles/10.1186/s12859-016-0984-y).
```{r}
library(pcaReduce)
expr_mat_info = t(norm_exprs(sce_info))
assignment_info = PCAreduce(expr_mat_info, nbt = 5, q = 6, method = "M")
```
`pcaReduce` returns a list of cluster assignments. Each element of the list corresponds to one run of the algorithm (here, we ran it 5 times by setting `nbt=5`) and is a matrix of cluster assignments, starting with `q+1` clusters in the first column and ending with 2 clusters in the last. Here, we will look at the assignment with 4 clusters:
```{r,fig.width=12,fig.height=6}
table(assignment_info[[1]][,4])
plots = list()
for(i in 1:5){
df = data.frame(apply(assignment_info[[i]],c(1,2),as.factor))
p = my_plot_tSNE(tsne=tsne_info, color = df[,'cl_id.2',drop=F],
shape = pData(sce_info)[,"cell_type",drop=F],
title = paste0("pcaReduce, run ", i))
plots[[i]] = p
}
ggmultiplot(plots[[1]],plots[[2]],plots[[3]],plots[[4]],plots[[5]],cols=3)
```
Note that each time, the output is slighrly different, but the overall structure of the clusters is consistent.
### Graph-based methods
#### MCL
The MCL algorithm is short for the Markov Cluster Algorithm. It is an unsupervised cluster algorithm for graphs based on simulation of (stochastic) flow in graphs ([van Dongen et. al](https://micans.org/mcl/)).
As a first step, we will construct an adjacency matrix from a similarity matrix using the function `build_adjacency_matrix`. This function takes as input either a pre-computed similarity matrix or the raw counts from which to calculate a correlation matrix. In addition, it requires a value for the similarity cutoff. It then builds a binary matrix of 1s and 0s form this information. A 1 means the similarity was larger than the cutoff. We can set the cutoff to "auto", this way, the algorithm will look for a valley in the distribution of similarities and use this as a cutoff. The function returns a list with the following entries:
* adj: The adjacency matrix
* cor: The similarity matrix
* cutoff: The similarity cutoff
We will use the 1 - the relative euclidean distance in PCA space as our similarity measure:
```{r, message = F}
sim = 1-as.matrix(dist_eucl)/max(dist_eucl)
adj_corr = build_adjacency_matrix(mat = sim,cutoff="auto",is_similarity=T)
```
Now we run MCL with the above list as input:
```{r, message = F}
groups_MCL = MCLcell.clust(adj_corr,mcl_path = "/da/dmp/cb/prog/mcl-14-137/bin/mcl")
sce_info$MCL = as.factor(groups_MCL)
table(sce_info$MCL,sce_info$hclust_eucl)
```
We see that the result is almost the same as that found by the hierarchical clustering, also visible on the tSNE-map:
```{r, fig.width = 8}
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"MCL",drop=F],
shape = pData(sce_info)[,"hclust_eucl",drop=F],
title = "MCL (cutoff=auto) assignment",
show_proportions = T)
print(p)
```
However, MCL did not manage to find the two T-cell populations. We can try changing the cutoff for the calculation of the adjacency matrix and re-run the algorithm:
```{r,fig.height=6,fig.width = 9}
adj_corr = build_adjacency_matrix(mat = sim,cutoff=0.8,is_similarity=T)
groups_MCL = MCLcell.clust(adj_corr,mcl_path = "/da/dmp/cb/prog/mcl-14-137/bin/mcl")
sce_info$MCL2 = as.factor(groups_MCL)
table(sce_info$MCL2,sce_info$hclust_eucl)
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"MCL2",drop=F],
shape = pData(sce_info)[,"hclust_eucl",drop=F],
title = "MCL (cutoff=0.7) assignment",
show_proportions = T)
p = p + scale_color_manual(values = brewer.pal(10,"Paired"))
print(p)
```
We note that by raising the similarity cutoff, we can force MCL to make more clusters. We now find the expected populations, but we also start splitting clusters that probably should not be split.
In conclusion, MCL performs similar to hierearchical clustering. Its main advantage is that it is much faster than hclust and can therefore be used on datasets with ten thousands of cells. The main drawback is that MCL is very sensitive to the provided input. Using a similarity measure that does not appropriately separate cells or using the wrong similarity cutoff will lead to MCL making lots of clusters with just one cell inside. The automated cutoff determination should provide some guidance here, but it is not guaranteed to work in all cases.
#### Seurat
Note: You might have to restart R before trying to load Seurat, because this package alone loads 121 (!) dependencies, which might just crash R.
We can run the clustering part of seurat by using the `seurat_clustering` wrapper (note that the two following sections are not run in the example due to the `maximum number of DLLs reached` error that is encountered when loading Seurat):
```{r,eval = F}
library(Seurat)
seurat_assignments = seurat_clustering(sce_info,vars.to.regress=NULL,res=1.2)
sce_info$seurat = as.factor(seurat_assignments)
```
And compare the assignments to hclust:
```{r,fig.width=8, eval = F}
table(sce_info$seurat,sce_info$hclust_eucl)
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"seurat",drop=F],
shape = pData(sce_info)[,"hclust_eucl",drop=F],
title = "Seurat assignment",show_proportions = T)
print(p)
```
In general, I did not find seurat to be more useful than MCL and loading the whole package just for the clustering is a bit of a pain.
### Density clustering (DBSCAN)
DBSCAN is a density clustering algorithm that is based on a k-nearest neighbor search. In a nutshell, it identifies clusters as regions in space that contain many points with shared neighbors. DBSCAN works best in a lower dimensional space, so we weill again use the coordinates in PCA space as input. The `run_dbscan` function requires the following inputs:
* a distance matrix
* minPts: The minimal number of neighbors a point has to have to be considered "high density". Usually, this is set to the dimensionality of the dataset +1, so here, we set it to the number of principal components used (6) + 1.
* eps: Size of the epsilon neighborhoos. If we make a k-nearest neighbor distance plot using `kNNdistplot`, eps is the y-value at the "elbow" of that plot. For convenience, we can set eps to "auto", then the function `run_dbscan` will automatically set it.
* tol (optional): This is a parameter for the tolerance when determining eps. The higher it is, the higher the returned eps will be. We set it to 0.005 here, this way, eps is exactly at the elbow of the kNNdistplot.
```{r}
DBSCAN_groups = run_dbscan(dist_eucl,eps="auto",min_pts=7,tol=0.005)
```
Visualize the assignment:
```{r,fig.height=6,fig.width=8}
sce_info$DBSCAN = as.factor(DBSCAN_groups)
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"DBSCAN",drop=F],
shape = pData(sce_info)[,"hclust_eucl",drop=F],
title = "DBSCAN assignment",show_proportions = T)
print(p)
```
We see that DBSCAN correctly identified the clearly separated clusters, but failed for the more continuous ones. This illustrates the main disadvantage of this algorithm: It can only find clusters that have no density between them. On the bright side, it is really fast and it does not require any assumptions of the cluster shape or size.
To check the cluster quality, we can again make a silhouette plot:
```{r,fig.width=7,fig.height=6}
si = silhouette(DBSCAN_groups, dist_eucl)
plot(si, col = "darkgray", border=NA, main = "Silhouette plot for dbscan (euclidean in PCA space)")
```
Note that cluster 0 is not a real cluster but contains all outlier (unassigned) cells.
Another way of checking cluster confidence is bootstrapping, which can be done using the `clusterboot` function form the `fpc` package:
```{r}
boot = fpc::clusterboot(data = dist_eucl, clustermethod = fpc::dbscanCBI, eps = 5.53,
MinPts = 7,B = 100, distances = T, count=F, method = "dist",
bootmethod = "boot")
dt = melt(data.table(cluster = c(0:4), boot$bootresult),id.vars="cluster",val="jaccard index",var="boot number")
dt = dt[cluster!=0]
p = ggplot(dt, aes(x=as.factor(cluster),y=`jaccard index`)) + geom_boxplot() +theme_bw()
print(p + ggtitle("Jaccard similarity between cluster assignment on the full data and on 100 bootstrap samples"))
```
Here, we see that the 3 large clusters are highly stable whereas the smallest cluster is not.
### Model based clustering (Mclust)
Mclust uses an EM algorithm to fit a gaussian mixture model to the data. The underlying assumption is that the data come from a mixture of k multivariate normal distributions. As this often does not hold in very high-dimensional space, we will run mclust on the PCA transformed data. Note that this dataset is not ideal for the algorithm, as its main advantage is speed and it tends to be more robust on datasets with more cells.
The function _gmm_main_ is used to run the clustering. As input, we provide the following:
* pc_scores: The scores obtained from a prcomp analysis
* n_comp: The number of principal components to use. We will stick with 6.
* k: The number of clusters to test. We will fit models with 1 to 10 clusters.
* n_cores: The number of cores to be used in parallel computing. We set this to 1 for this small dataset.
* return_model: If TRUE, returns the full mclust model object, not just the cluster assignments. Default = FALSE.
`gmm_main` will run 10-fold cross-validation for each of the numbers of clusters we specified and in the end return the assignment using the model that achieves the highest likelihood while using the smallest number of clusters possible. Note that sometimes, the models fail to converge and the function returns `NA`.
```{r}
library(mclust)
mclust_assignment = gmm_main(pc_scores = pca$x,n_comp=6, k=1:8,n_cores=1)
```
This plot shows the log-likelihood of all 10 models computed for each of the numbers of clusters. Note the initial steep increase in likelihood. The "best" number of clusters is the smallest one that achieves maximum likelihood (i.e. the number of clusters where the likelihood stops increasing).
```{r}
sce_info$mclust = as.factor(mclust_assignment)
table(sce_info$mclust,sce_info$hclust_eucl)
```
Visualize on tSNE map:
```{r, fig.width = 8}
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"mclust",drop=F],
shape = pData(sce_info)[,"hclust_eucl",drop=F],
title = "Mclust assignment",show_proportions = T)
print(p)
```
We see that mclust found the larger clusters, but it has some trouble distinguishing the smaller ones. This is most likely because for small clusters, the estimation of the model parameters is more unreliable than for the larger clusters, and merging them with some larger cluster does not greatly affect the overall likelihood of the model.
If we want to fit models for a user-defined number of clusters, we can do so by setting `do_crossval = FALSE` and providing the numer of clusters with the best_k parameter. Also, if we want to get the full mclust model object instead of just the cluster assignments, we can set `return_model = TRUE`:
```{r, fig.width=8}
mclust_model = gmm_main(pc_scores = pca$x,n_comp=6,do_crossval = F, best_k = 6, return_model = TRUE)
sce_info$mclust_forced = as.factor(mclust_model$classification)
table(sce_info$mclust_forced,sce_info$hclust_eucl)
p = my_plot_tSNE(tsne = tsne_info, color = pData(sce_info)[,"mclust_forced",drop=F],
shape = pData(sce_info)[,"hclust_eucl",drop=F],
title = "Mclust assignment")
print(p)
```
Now we can also bootstrap to get an idea of the uncertainty associated with each of the estimated model parameters:
```{r,message=F,results="hide"}
mclust_boot = MclustBootstrap(mclust_model, nboot=500)
```
```{r}
summary(mclust_boot, what = "ci")
```
The mixing component tells us about the stability of cluster sizes. The confidence intervals for the mean and variance are measures of how stable the cluster position, shape and volume are. Note that for this type of model (VVI), all covariances are assumed to be 0. We can also plot the distributions of each parameter:
```{r,fig.width=8, fig.height = 4}
par(mfrow=c(1,6))
plot(mclust_boot, what = "pro")
```
```{r, fig.width=8,fig.height=12}
par(mfrow=c(6,6))
plot(mclust_boot, what = "mean")
par(mfrow=c(6,6))
plot(mclust_boot, what = "var")
par(mfrow=c(1,1))
```
Here, we see that overall, the clusters are fairly stable. Also note how the means become more and more unstable towards principal component 5 and 6, indicating that they are not too menaingful for the overall clustering.
The main advantage of using mclust is that it is pretty fast and even works on datasets with ~40000 cells (I originally used the function here on the Drop-seq dataset by [Macosko et. al, 2015](http://www.sciencedirect.com/science/article/pii/S0092867415005498)) as it does not require calculating distance matrices. Moreover, the cross-validation provides an unsupervised way of determining the number of clusters present in the dataset. However, the downsides are that because the EM procedure is stochastic, outputs differ slightly each time mclust is run. Robustness might be achieved by running the algorithm several times and create a consensus clustering, similar to the procedure used by SC3. Moreover, mclust relies on distributional assumptions, therefore, if the clusters are not gaussian ellipsoids, mclust will not be able to identify them correctly.
Save the SCESet that now contains all the assignments:
```{r, eval = F}
save(sce_info,file = file.path(out_data_dir,"sce_info.RData"))
```
### Clustering - Conclusion
There is no universal best solution for clustering. Generally, if your data contains clear clusters that are well-separated in space, any method will work provided the underlying assumptions are fulfilled and the input (e.g. the measure of similarity) is meaningful.
Regarding the choice of input parameters, SC3 is very neat as it does not require the user to make those decisions. Also, it is very well integrated in the scater workflow and comes with some nice additional tools, such as the automatic marker detection and several visualizations.
Some of the main points you want to consider when choosing an algorithm:
* The size of your data set: How much time and memory will each method need?
* Underlying assumptions: What cluster shapes and sizes does the method expect? Can it find clusters that are not well separated?
* Robustness: Is the method stochastic and will produce different output each time it is run? If the input changes slightly, how strongly will the clustering be affected?
When choosing a distance measure, most methods benefit from dimensionality reduction. Therefore, I generally use distance (euclidean or pearson) calculated on principal component scores. Because each PC score is a weighted average of gene expression, this is also more robust to dropouts. As a rule of thumb for the number of components to use, make a screeplot and look where the "elbow" is.
## Identifying (rare) cell subpopulations with CellSIUS
CellSIUS (*Cell* *S*ubtype *I*dentification from *U*pregulated gene *S*ets ) was developed by <NAME>. The underlying idea is to identify cluster-specific correlated gene sets that exhibit a bimodal distribution and then classify cells according to their expression of this gene set.
The parameters for this algorithm are as follows:
* sce: The SCESet with all our data
* group_id: A column name in pData() that specifies the cell assignment to main clusters. Here, we pretend we only found the 4 major groups and use the manual `cell_type` grouping.
* min_n_cells: The minimal number of cells per subcluster. Note: Main clusters that do not contain at least twice as many cells will be ignored.
* verbose: Logical. Whether to print a summary or not.
* min_fc: The minimum difference between the first and second mode of the bimodal gene distribution, on a log2 scale. The default is 2.
distribution.
* fc_between_cutoff: Numeric, defaults to 1. Minimum difference [log2] in gene expression between cells in the subcluster and all other cells. The higher, the more cluster-specific the genes. Note that this should not be set higher than min_fc.
* organism: Only relevant if verbose is `TRUE`. Specifies which genome annotation (human or mouse) to use when getting the gene descriptions.
* iter: 0 or 1. If 1, when assigning the cells to subclusters, the first mode of the gene expression distribution is ignored. This results in a more stringent classification, at the risk of missing out true cell subtypes. The default is 0.
* max_perc_cells: Numeric, between 0 and 100. Maximum percentage of cells per cluster that can be part of a subgroup. The default is 50, implying that it does not make sense to identify something as a "subgroup" if it contains more than half of the total observations.
```{r, warning=F}
sce_clean$cell_type = sce_info$cell_type
cellsius_out = cellsius_main(sce_clean, group_id = "cell_type", min_n_cells = 5,
verbose =T, min_fc = 2, organism = "human", iter=0,
max_perc_cells = 50, fc_between_cutoff = 1)
```
Because we set verbose to `TRUE`, the function printed a nicely human-readable summary. you can always re-print the summary using `cellsius_print_summary(cellsius_out)`. The same information can also be extracted from the output, let's have a look:
```{r}
cellsius_out
```
This looks quite confusing at first, so how do we get any information from here? Essentially, a data.table is a collection of key/value pairs. For example, the first row tells us that the cell with barcode `AAAGCAAGTCAAGCG` has an expression value of 0 for the gene `ENSG00000105374`. It also tells us that this cell is in the main cluster `T-cell`. There is a lot of additional information, but we will ignore this for now.
If we want to know all the subclusters the cell `AAAGCAAGTCAAGCG` is a part of, we can do it as follows:
```{r}
unique(cellsius_out[cell_idx=="AAAGCAAGTCAAGCGA"]$sub_cluster)
```
This tells us that this cell is *not* a member of subcluster 1. Subclusters are named as follows:
[Name-of-main-cluster]_[number of subcluster]_[0 or 1], where in the last position 0 means the cell is not a member, 1 means it is a member.
If we want to know which genes are in a specific subcluster (here, I take T-cell 1), we can do so using the following query:
```{r}
unique(cellsius_out[sub_cluster == "T-cell_1_1"][,c('gene_id','symbol','description')])
```
Or, we might want to know how many cells are in each of the subclusters:
```{r}
cellsius_out[,length(unique(cell_idx)),by="sub_cluster"]
```
If you are not familiar with the `data.table` syntax, here's what we're doing in the above query:
* we access a column variable (cell_idx) in the `data.table`
* we apply a function to it
* the last argument "by" specifies that we want to apply the function several times, namely for each unique value of `sub_cluster` (which is equivalent to looping over all clusters)
To visualize the result on a t-SNE map, use the `plot_rare_cells` helper function:
```{r}
plot_rare_cells(rare=cellsius_out, tsne=tsne_info)
```
If you only want to look at one main cluster (here, this does not really make sense because there is only one subcluster anyway), just subset the `rare` table:
```{r}
plot_rare_cells(rare=cellsius_out[main_cluster=="T-cell"], tsne=tsne_info)
```
Or, maybe you only want to show the first T-cell subcluster:
```{r}
plot_rare_cells(rare=cellsius_out[sub_cluster=="T-cell_1_1"], tsne=tsne_info)
```
If you want to plot the expression of the identified markers on a tSNE map, there are two ways to do so. Manually:
```{r, fig.width=8,fig.height=6}
marker_idx = which(rownames(sce_clean)%in%cellsius_out[sub_cluster=='T-cell_1_1']$gene_id)
plotlist = list()
colors = t(norm_exprs(sce_clean)[marker_idx,,drop=F])
colnames(colors) = fData(sce_clean)$symbol[marker_idx]
for(i in seq(dim(colors)[2])){
plotlist[[i]] = my_plot_tSNE(tsne = tsne_info,
color = colors[,i,drop=F],
alpha = 0.8, title = colnames(colors)[i]) + scale_color_distiller(palette = 'RdYlBu')
}
ggmultiplot(plotlist[[1]],plotlist[[2]],plotlist[[3]], plotlist[[4]],cols = 2)
```
Or, launch an interactive shiny app (currently, this is experimental):
```{r, eval = F}
library(shiny)
launch_marker_vis_app(tsne = tsne_info, sce=sce_clean, marker_idx = marker_idx)
```
Here, we see that these markers are really specific to one sub-population of the T-cells. Expression of granzyme and NKG7 indicates that we re-identified the T-killer cell population. Note: We do not see CD8 here, because this gene is expressed at levels below our fold change (i.e. mean log expression difference) cutoff.
To get a final cluster assignment, run `cellsius_final_cluster_assignment`:
```{r}
final_clusters = cellsius_final_cluster_assignment(cellsius_out, sce_clean, group_id = "cell_type", min_n_genes=3)
table(final_clusters$cluster)
p = my_plot_tSNE(tsne = tsne_info, color = final_clusters, title = "CellSIUS cluster assignment")
print(p)
```
## Differential expression analysis
The workflow contains wrapper functions for running differential expression analysis using several widely-used packages. For a comparison of methods, consider the recent study by <NAME> Robinson, which can be found [here](https://doi.org/10.1101/143289).
The main findings of the study are that methods differ in the number and characteristics of the genes they report as differentially expressed in a manner that is dependent on the respective dataset. Performance of the methods overall was found to be similar across methods, with those developed for bulk data not being significantly worse than those specifically designed for single-cell data.
If we are interested in finding a small number of high-confidence marker genes, it might be most useful to run several methods and check what their overlap is. In general, I found the methods to be fairly consistent, especially for high expressed genes. For low expressed genes, results from any analysis should be taken with a grain of salt because of the very high underlying technical variability. Special care should be taken when comparing cell types that differ in size and/or RNA content and therefore have cell-specific dropout rates, in which case most low expressed genes are only detected in the large cells.
Currently, wrappers to one non-parametric test (Wilcoxon/Mann-Whitney) and two methods based on linear models (limma, MAST) are provided.
Every wrapper function takes the same four variables as input:
* sce: the full SCESet after QC and normalization
* cl_id: The name of the grouping that should be used. Here, we use the assignment obtained from hiererchical clustering on distances in PCA space, which we called "hclust_eucl".
* cl_ref: Which cluster we want to compare against all the others. We select "B-cell". Note: If you wish to do a direct comparison between two clusters, you can do so by setting all assignments but the two you want to compare to `NA`, which for factors is very convenient using `droplevels()`.
* fc_cutoff and alpha: The cutoffs for fold changes and p-values used to determine whether a gene is significantly DE. Note that your cutoffs have no effect on the analysis, and because the results for all genes are returned, you can still change the cutoffs afterwards.
Before we can start, we need to add some of the cluster assignments we obtained in the previous section to the SCESet that contains all genes:
```{r}
sce_clean$SC3_assignment = sce_info$SC3_assignment
sce_clean$hclust_eucl = sce_info$hclust_eucl
```
### Wilcoxon test
We can run the Wilcoxon test using the `run_wilcoxon_test` wrapper function. This will take as input the above specified variables and return a `data.table` containing (adjusted) p-values and fold changes per gene.
NOTE: The `pseudocount` parameter is deprecated and will be removed!
```{r}
de_wilcox = run_wilcoxon_test(sce_clean, cl_id = "hclust_eucl", cl_ref = "B-cell",
fc_cutoff = 1, alpha = 0.05)
dim(de_wilcox)
head(de_wilcox)
```
We see that the function returned a `data.table` containing all gene IDs plus the test statistics and estimated fold changes for each of them. We can use the DE_flag entry to check how many genes were found to be significantly DE (i.e. adjusted p-value < 0.05 and absolute log2 fold change > 1).
```{r}
table(de_wilcox$DE_flag)
```
A useful way to check whether the method was biased towards calling genes in a specific expression range DE is to plot log2 fold changes v.s. the mean expression of a gene. We will add the mean_exprs column in the feature metadata to the `de_wilcox` table by using `merge` from the `data.table` package:
```{r}
mean_exprs_dt = data.table(gene_id = rownames(sce_clean),mean_exprs = fData(sce_clean)$mean_exprs)
de_wilcox = merge(de_wilcox,mean_exprs_dt, by = "gene_id")
names(de_wilcox)
```
We note that the mean_exprs column has been added to `de_wilcox`. Now we make a plot by calling `generic_scatterplot`. This function takes a `data.table` as input and makes a scatterplot of two columns, x_col and y_col, against each other. Optional column names can be provided to control color, shape and size of the points. The function returns a `ggplot` object, to which we can easily add other features, for example, a title:
```{r}
p = generic_scatterplot(de_wilcox, x_col = "mean_exprs", y_col = "log2fc",
color = "DE_flag")
print(p+ggtitle('MA plot for Wilcoxon test'))
```
We see that because fold changes are estimated as the difference in log2 mean expression rather than a ratio, very low expressed genes have fold changes around zero.
To make a volcano plot, we can again use `generic_scatterplot`:
```{r}
de_wilcox[,log10_pval:=-log10(adj_pval)]
p = generic_scatterplot(de_wilcox, x_col = "log2fc", y_col = "log10_pval",
color = "DE_flag")
print(p+ggtitle('Volcano plot for Wilcoxon test'))
```
Note: In general, the more cells you have, the more tiny changes will become significant. The `DE_flag` parameter is therfore controlled mostly by your fold change cutoff, unless you set a very stringent p-value cutoff (~10^-20). It is probably best to use the fold change / p-value combination more as a way of ranking genes than as an absolute threshold and focus on the genes that come out on top.
Now let's check whether the identified genes make sense:
```{r,message=F}
library(DT)
top_DE = de_wilcox[DE_flag==TRUE][order(log2fc,decreasing = T)]$gene_id[1:20]
gene_table = get_gene_annotations(top_DE,get_descriptions = T)
datatable(gene_table, caption = "Top 20 upregulated genes in B-cells")
```
And we are happy to see that the top upregulated genes correspond to known B-cell markers such as CD79 or MHCII subunits.
### limma
Limma was originally developed for bulk RNA-seq data, but in most cases, it also performs fairly well on single-cell data. However, especially the voom version can become unreliable in the presence of many zero counts, therefore, it is recommended to filter out low-abundant genes prior to running the analysis. In the following, we will run both limma-voom and limma-trend and compare their outputs.
The function `run_limma` is used for both methods. In addition to the standard input described above, we need to provide the following inputs:
* method: which limma method we want to use.
* count_thr, pct: Threshold for gene filtering. Genes that do not have a minimum of `count_thr` counts in at least `pct` percent of cells in at least one cluster will be ignored. For this extremely sparse data, we set this to 1.
```{r}
de_limma_voom = run_limma(sce_clean, cl_id = "hclust_eucl", cl_ref = "B-cell",
method = "voom", fc_cutoff = 1, alpha = 0.05, count_thr = 1,pct=50)
```
Looking at the voom plot, we should be a bit suspicious. The heel at the left side of the plot indicates that there are still a lot of zero counts, and our filtering may not have been very succesful. Let's have a look at the output:
```{r}
dim(de_limma_voom)
names(de_limma_voom)
```
We see that, like the `run_wilcoxon_test`, this function returned a `data.table`. note that because of the filtering, the limma table only contains 3012 gene IDs plus the limma test statistics for each of them. We can again use the DE_flag entry to check how many genes were found to be significantly DE (i.e. adjusted p-value < 0.05 and absolute log2 fold change > 1) and also compare this to the Wilcoxon test:
```{r}
table(de_limma_voom$DE_flag)
table(de_wilcox[de_limma_voom$gene_id,on="gene_id"]$DE_flag,de_limma_voom$DE_flag)
```
We see that of the genes that are within the set tested by limma, all 35 genes identified to be DE by the Wilcoxon test were also identified by limma. This is not very surprising, because again, the decision to cal a gene DE is mainly based on fold change.
Make an MA plot for limma-voom:
```{r}
de_limma_voom = merge(de_limma_voom,mean_exprs_dt, by = "gene_id")
names(de_limma_voom)
p = generic_scatterplot(de_limma_voom, x_col = "mean_exprs", y_col = "logFC",
color = "DE_flag")
print(p+ggtitle('MA plot for limma-voom'))
```
We see that there is only a slight bias towards very low expressed genes. Keep in mind, however, that we already filtered out ~70% of all the genes before running the analysis. Let's see what happens if we omit the filtering:
```{r}
voom_no_filt = run_limma(sce_clean, cl_id = "hclust_eucl", cl_ref = "B-cell",
method = "voom", fc_cutoff = 1, alpha = 0.05, count_thr = 0)
voom_no_filt = merge(voom_no_filt, mean_exprs_dt)
p = generic_scatterplot(voom_no_filt, x_col = "mean_exprs", y_col = "logFC",
color = "DE_flag")
print(p+ggtitle("MA plot for limma-voom, no filtering"))
table(voom_no_filt[DE_flag==TRUE]$gene_id%in%de_limma_voom[DE_flag==TRUE]$gene_id)
```
For this dataset, limma-voom remains stable and finds the same number of DE genes, even if we don't filter. In some cases, however, the method can fail and produce a mean v.s. log FC plot that is shifted along the y-axis, looking somewhat like this:
```{r}
example_dt = copy(voom_no_filt)
example_dt[,logFC:=logFC-1*1/(mean_exprs+1)]
example_dt[,DE_flag := adj.P.Val < 0.05 & abs(logFC)>1]
p = generic_scatterplot(example_dt, x_col = "mean_exprs", y_col = "logFC",
color = "DE_flag") + geom_hline(yintercept = 0)
print(p+ggtitle("An example of an MA plot for limma gone wrong"))
```
We can see that in this case, many low expressed genes would be falsely called DE. It is therfore always a good idea to inspect the output of any differential expression analysis, as each method has its own biases and cases in which it fails.
To run limma-trend, we use exactly the same code, but set method = "trend":
```{r}
de_limma_trend = run_limma(sce_clean, cl_id = "hclust_eucl", cl_ref = "B-cell",
method = "trend", fc_cutoff = 1, alpha = 0.05, count_thr = 1, pct=50)
de_limma_trend = merge(de_limma_trend, mean_exprs_dt)
de_limma_trend[,voom_overlap:=de_limma_trend$DE_flag == de_limma_voom$DE_flag]
p = generic_scatterplot(de_limma_trend, x_col = "mean_exprs", y_col = "logFC",
color = "DE_flag", shape = "voom_overlap")
print(p + ggtitle("MA plot for limma-trend"))
table(de_limma_trend$DE_flag,de_limma_voom$DE_flag)
table(de_wilcox[de_limma_trend$gene_id,on="gene_id"]$DE_flag,de_limma_trend$DE_flag)
# Compare p-values between Wilcoxon test and limma
ggplot(data.table(wilcox = de_wilcox[de_limma_trend$gene_id,on="gene_id"]$pval,
limmatrend = de_limma_trend$P.Val),
aes(x=-log10(wilcox),y=-log10(limmatrend)))+geom_point()+theme_bw()+
ggtitle('Comparison of p-values between limmatrend and Wilcoxon test')
```
Limma-trend finds exactly the same genes as the wilcoxon test, probably because the way fold changes are estimated is the same and we filter mainly based on fold changes. Comparing the p-values, limma-trend and the Wilcoxon test still agree very well.
### MAST
MAST is a framework designed for single-cell data that is based on a zero-inflated negative binomial model. A hurdle model is used to estimate differetial expression by jointly modeling discrete (cellular detection rates, zero v.s. non-zero values) and continuous (positive mean expression) values. For more information, see the [MAST paper](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4676162/) or the [package vignette](http://bioconductor.org/packages/release/bioc/vignettes/MAST/inst/doc/MAITAnalysis.html).
MAST ususally has run times similar to limma. However, I found that it often freezes on the barolo and mithril rstudio server, probably this has something to do with the versios of BLAS/LAPACK on these systems. You might therefore want to run MAST from command line or on the other rstudio server.
We can run MAST using the `run_MAST` wrapper that works analogous to the two methods previously described. We provide the following additional parameters:
* set_thresh: Should MAST try to find expression thresholds? We will initially set this to TRUE, and check the thresholds on the output plot. If we cannot see a clear bimodal distribution of counts, we should set this to FALSE. The thresholding also takes the optional `min_per_bin` and `n_bins` arguments, which we will leave at their defaults for now.
* norm: use normalized values? Set to TRUE.
* n_cores: number of cores to use for parallel computing.
```{r, message = F}
de_MAST = run_MAST(sce_clean,cl_id = "hclust_eucl",cl_ref = "B-cell",norm=T,
set_thresh=T,fc_cutoff = 1, alpha=0.05)
```
We clearly see that the thresholds are pretty random as for most bins, no clear bimodal distribution is visible. Therefore, we re-run MAST setting `set_thresh = FALSE`:
```{r, message = F}
de_MAST = run_MAST(sce_clean,cl_id = "hclust_eucl",cl_ref = "B-cell",norm=T,
set_thresh=F,fc_cutoff = 1, alpha=0.5)
```
Again, let's make a plot and compare to limma-trend and DESeq2:
```{r,fig.width=10}
de_MAST = merge(de_MAST, mean_exprs_dt)
p = generic_scatterplot(de_MAST, x_col = "mean_exprs", y_col = "log2FC",
color = "DE_flag")
print(p+ggtitle("MA plot for MAST"))
table(de_MAST$DE_flag)
table(de_MAST[de_limma_trend$gene_id,]$DE_flag,de_limma_trend$DE_flag)
# Compare p-values between MAST and limma
ggplot(data.table(MAST = de_MAST[de_limma_trend$gene_id,on="gene_id"]$pval,
limmatrend = de_limma_trend$P.Val),
aes(x=-log10(MAST),y=-log10(limmatrend)))+geom_point()+theme_bw()+
ggtitle('Comparison of p-values between limmatrend and MAST')
```
We see that MAST performs similar to the other methods we used.
Finally, we can check the overlap of all the methods we tested:
```{r,fig.width=10, eval = T}
merged = merge(de_MAST,
de_limma_trend[, c("gene_id","DE_flag"),with=F],
by = "gene_id",all=T)
merged = merge(merged, de_wilcox[,c("gene_id","DE_flag"),with=F],by="gene_id",all=T)
setnames(merged,which(grepl("DE_flag",names(merged))),paste0("DE_flag_",c(1:3)))
merged[,overlap:=factor(DE_flag_1==T & DE_flag_2==T & DE_flag_3==T, labels =c("Not DE or not found by all methods","Overlap of all methods"))]
p = generic_scatterplot(merged, x_col = "mean_exprs", y_col = "log2FC", color = "overlap" )
print(p+ggtitle("Overlap between all methods tested") + ylab("log2FC (MAST)"))
```
Form this, we conclude that the top DE genes are ceonserved between methods, whereas the ones with lower expression or close to the seleceted cutoffs differ between methods.
Once we identified a core set of high confidence genes, we could look for additional markers by looking for genes that are highly correlated with the identified markers or by clustering the genes according to their expression pattern across cells.
### Using SC3 to find markers
This sections shows how to tweak the `sc3_calc_biology` function to work with any arbitrary clustering.
```{r, eval = T, message = F}
library(SC3)
# add the slots the calc biology function checks
dummy = list(`0`=0)
sce_clean@sc3$consensus = dummy
sce_clean@sc3$n_cores = 4
fData(sce_clean)$sc3_gene_filter = rep(TRUE,dim(sce_clean)[1]) #do not filter out any genes
# add whatever clustering assignment you want to the sc3_0_clusters slot
sce_clean$sc3_0_clusters = as.factor(sce_info$cell_type)
sce_clean = sc3_calc_biology(sce_clean, k = 0)
```
Plot markers:
```{r, out.width="110%",fig.height=6}
# change the plotted gene names to symbol for better readability
plot_sce = sce_clean[!is.na(fData(sce_clean)$symbol),]
rownames(plot_sce) = fData(plot_sce)$symbol
custom_sc3_plot_markers(plot_sce, k=0, p.val = 0.01, auroc = 0.90, show_pdata='sc3_0_clusters')
```
### Differential expression analysis - Conclusion
We saw that the high-confidence (highly expressed and large fold changes) DE genes are the same across all methods used, which is not surprising. All methods find a large number of significant hits (this becomes even more apparent in larger datasets), therefore the main criterion for calling a gene DE is its fold change. Instead of setting fixed thresholds, it might be more useful to just rank the genes according to fold change and p-value and focus on those that come out on top.
The Wilcoxon test or limma are definitely the methods of choice in terms of speed. However, note that the Wilcoxon test will become unreliable for very small (< 10 cells) groups.
For limma, especially limma-voom can be unreliable in the presence of many zero counts. Filtering may help, but it is not guaranteed. Therefore, if you use limma, always check the MA-plot. If it is shifted along the y-axis, be more stringent in your filtering or choose a different method.
MAST, like limma, is based on a linear modelling framework, making it very flexible. In addition, it is tailored to single-cell data and very robust on sparse data. Another plus of MAST is that it is quite fast and scales quite well even to very large datasets.
## Functions
This section lists all custom functions that are part of the workflow. These are equivalent to everything that is provided in the ./code directory, therefore this section is merely for documentation purposes.
### Libraries required throughout the analysis
The function _library_calls()_ calls all the libraries that are required throughout the workflow. Additional packages are loaded whenever needed. The reason for this is that some of the newer bioconductor packages load a million dependencies, and currently, R has a limit on how many packages can be loaded at any time.
```{r}
library_calls = function(){
library(Rtsne)
library(ggplot2)
library(data.table)
library(scater)
library(scran)
library(RColorBrewer)
}
```
### Gene annotation
#### Gene annotation using ensembldb
This is the default function to annotate genes. It uses the ensembldb and EnsDb.Hsapiens.v79 packages. Ensembldb is preferred over biomaRt because it is much faster and it uses a specific annotation package, making it more reproducible. Optionally, gene descriptions in human-readable form are obtained from org.Hs.eg.db.
Input:
* gene_list = a list of ensembl gene IDs as a character vector
* get_descriptions = should descriptions be obtained from org.Hs.eg.db/org.Mm.eg.db? TRUE or FALSE. Note that this is slow for a long gene list.
* v = verbose flag. If set to true, prints all the errors that my_get() catches. Should be set to true only for debugging purposes.
* organism: one of either "mouse" or "human"
Output:
* geneName = a data.table of gene annotations. Note that this table is sorted by gene identifier.
```{r}
get_gene_annotations = function(gene_list,v=F,get_descriptions=T,organism = "human"){
library(ensembldb)
if(organism == "human"){
library(EnsDb.Hsapiens.v79)
edb = EnsDb.Hsapiens.v79
} else if(organism == "mouse"){
library(EnsDb.Mmusculus.v75)
edb = EnsDb.Mmusculus.v75
} else {stop("Currently, annotation is only available for organisms human or mouse.")}
my_get = function(x,db,v){
out = tryCatch({get(x,db)[1]},
error = function(cond){
if(v) {message(cond)}
return("")},
finally = {})
return(out)
}
gene_info = ensembldb::genes(edb,filter = list(GeneIdFilter(gene_list)))
gene_info_dt = data.table(gene_id = names(gene_info),
chr = as.character(seqnames(gene_info)),
symbol = make.unique(gene_info$symbol),
gene_biotype = gene_info$gene_biotype)
geneName = data.table(gene_id = gene_list)
geneName = merge(geneName,gene_info_dt,by="gene_id",all=T)
if(get_descriptions & organism == "human"){
library(org.Hs.eg.db)
geneName[,eg:=my_get(gene_id,db=org.Hs.egENSEMBL2EG,v),by="gene_id"]
geneName[,description:=my_get(eg,db=org.Hs.egGENENAME,v),by="eg"]
} else if(get_descriptions){
library(org.Mm.eg.db)
geneName[,eg:=my_get(gene_id,db=org.Mm.egENSEMBL2EG,v),by="gene_id"]
geneName[,description:=my_get(eg,db=org.Mm.egGENENAME,v),by="eg"]
}
return(geneName)
}
```
#### Gene annotation using biomaRt
Gene annotations can also be retrieved from biomaRt, however, ensembldb is preferred for the above mentioned reasons.
```{r}
get_gene_annotations_biomart = function(gene_list){
library(biomaRt)
# Load the organism-specific biomart
ensembl = biomaRt::useEnsembl(
biomart = 'ensembl',
dataset = paste0('hsapiens', '_gene_ensembl'),
version = 83
)
#
geneName = biomaRt::getBM(attributes = c('ensembl_gene_id','hgnc_symbol',
"entrezgene", "description","chromosome_name"),
filters = 'ensembl_gene_id',
values = gene_list,
mart = ensembl)
description = lapply(seq(length(geneName$description)),function(i){
strsplit(geneName$description[i],"[[]")[[1]][1]
})
description = (unlist(description))
geneName$description = description
colnames(geneName) = c('gene_id','symbol','eg','description','chr')
geneName = data.table(geneName)
setkey(geneName,'gene_id')
geneName = unique(geneName) #remove duplicate entrez gene identifiers
geneName[,symbol:=make.unique(symbol)]
#save(geneName,file="data/output/geneName.RData")
return(geneName)
}
```
### Quality control
#### Filtering of genes and cells
The functions below are used for manual filtering of cells and genes based on several QC metrics.
Input:
* counts: Matrix of raw counts.
* n_th: A single number specifying the cutoff for the respective filter. In the gene filter, this is the minimal number of cells with counts above `min_counts`. In the feature_counts and n_UMI filters, this is the minimal number of total counts or total UMIs, respectively, per cell.
* min_counts: In the gene filter, this specifies the minimum number of counts. The filter removes genes that do not have at least `min_counts` counts in at least `n_th` cells.
* mt_genes.amount: a vector containing the percentage of mitochondrial genes per cell. This information is stored in sce$percent_feature_controls_MT.
* t: a single number specifying the maximum percentage of reads mapped to mitochondrial genes.
```{r}
#_____________
# Gene filters
#___________
# Filtering out genes that are not expressed at a minimum of min_counts in at least n_th cells
gene_filter_by_feature_count = function(counts, n_th , min_counts = 1){
discard = rowSums(counts>=min_counts) <= n_th
message(paste('Flagged', length(which(discard)), 'genes.'))
return(discard)
}
#______________
# Cell filters
#______________
# Filtering out cells with fewer than n_th detected features
cell_filter_by_feature_count = function(counts, n_th){
discard = colSums(counts>0) <= n_th
message(paste('Flagged', length(which(discard)), 'cells.'))
return(discard)
}
# Filtering out cells with fewer than n_th total UMI counts
cell_filter_by_total_UMI = function(counts, n_th){
discard = colSums(counts) <= n_th
message(paste('Flagged', length(which(discard)), 'cells.'))
return(discard)
}
# Filtering out cells with high mitochondrial gene content
calc_mt_content = function(counts, geneName){
mt = rownames(counts[rownames(counts) %in% rownames(geneName[geneName$chromosome_name=="MT",]),])
mt_not = setdiff(rownames(counts),rownames(counts[mt,]))
counts_mt = counts[mt,]
mt_genes.amount = 100/colSums(counts)*colSums(counts[mt,])
return(mt_genes.amount)
}
cell_filter_by_mt_content = function(mt_genes.amount, t){
discard = mt_genes.amount > t
message(paste('Flagged', length(which(discard)),'cells.'))
return(discard)
}
```
#### Visualizing the manual filters
Input:
* sce, input_sce: an SCESet from which the things to plot are taken
* min_genes, min_UMI, t: the cutoffs selected for minimum number of genes per cell [log2], minimum number of UMIs per cell [log2], and maximum percentage of mitochondrial genes
```{r}
# Plotting QC based on RNA amount detected per cell
plot_RNA_QC = function(input_sce, min_genes, min_UMI){
par(mfrow=c(1,3))
hist(log2(input_sce$total_features),xlab="log2[ # detected genes per cell]", main='', cex.axis=1.5,n=100)
abline(v=min_genes,col=2)
hist(log2(input_sce$total_counts),xlab="log2 [# of UMIs per cell]", main='', cex.axis=1.5,n=100)
abline(v=min_UMI,col=2)
plot(log2(input_sce$total_features),log2(input_sce$total_counts),xlab="log2[ # detected features per cell]",ylab="log2 [total counts per cell]", cex.axis=1.5)
abline(v=min_genes,col=2)
abline(h=min_UMI,col=2)
}
# Plotting mitochondrial gene QC
plot_MT_QC = function(sce, t){
par(mfrow=c(1,1))
mt_genes.amount = sce$pct_counts_feature_controls_MT
#mt gene content per cell
plot(seq(length(mt_genes.amount)),(mt_genes.amount),pch=10,cex=1.5,col="gray",main=""
, cex.axis=2,cex.lab=1.5,xlab="cell index",ylab="Ratio of MT-genes[%]")
points(seq(length(mt_genes.amount))[mt_genes.amount<t],mt_genes.amount[mt_genes.amount<t],pch=10,cex=1.5)
abline(h=t,col="red",lty=2,cex=5)
#UMI vs no. genes colored by mt gene content
plotPhenoData(sce, aes_string(x = "log2(total_features)",
y = "log2(total_counts)",
colour = "pct_counts_feature_controls_MT"))+
xlab("Total detected features [log2]") + ylab("Total counts [log2]")+
ggtitle("Total features vs. total counts, colored by MT content")
}
```
#### Cell cycle assignment
Using the cyclone function from scran:
```{r}
annotate_cell_cycle = function(sce, organism = "human", gene.names = rownames(sce)){
if(organism == "human"){
hs.pairs = readRDS(system.file("exdata", "human_cycle_markers.rds", package="scran"))
assigned = cyclone(sce, pairs=hs.pairs, gene.names = gene.names)} else if (organism == "mouse"){
mm.pairs = readRDS(system.file("exdata", "mouse_cycle_markers.rds", package="scran"))
assigned = cyclone(sce, pairs=mm.pairs, gene.names = gene.names)
} else {stop("Organism has to be human or mouse.")}
return(assigned)
}
```
Using annotations from cyclebase:
```{r}
annotate_cell_cycle_custom = function(log2_counts, organism = "human", input_dir = file.path(code_dir, "input_files")){
# Load list of cell-cycle genes from cyclebase
load(file.path(input_dir,"cell.cycle.gene.RData"))
head(cell.cycle.gene)
#plot(sort(cell.cycle.gene$periodicity_pvalue))
cc = cell.cycle.gene[which(cell.cycle.gene$periodicity_pvalue<.05),]
# 220/361 genes are a subset of the variable gene list of our dataset
if(organism == "human"){
cc = cc[cc$Ensembl.Gene.ID %in% rownames(log2_counts),]
# selecting genes associetes with cell-cycle phase
G1.genes = cc[which(cc$peaktime>0 & cc$peaktime<47 ),]$Ensembl.Gene.ID
S.genes = cc[which(cc$peaktime>47 & cc$peaktime<70 ),]$Ensembl.Gene.ID
G2.genes = cc[which(cc$peaktime>70 & cc$peaktime<90 ),]$Ensembl.Gene.ID
M.genes = cc[which(cc$peaktime>90 & cc$peaktime<100 ),]$Ensembl.Gene.ID
G1_S.genes = cc[which(cc$peaktime>40 & cc$peaktime<50 ),]$Ensembl.Gene.ID
S_G2.genes = cc[which(cc$peaktime>60 & cc$peaktime<70 ),]$Ensembl.Gene.ID
G2_M.genes = cc[which(cc$peaktime>80 & cc$peaktime<90 ),]$Ensembl.Gene.ID
} else if(organism == "mouse"){
cc = cc[cc$Ensembl.Gene.ID.1 %in% rownames(log2_counts),]
# selecting genes associetes with cell-cycle phase
G1.genes = cc[which(cc$peaktime>0 & cc$peaktime<47 ),]$Ensembl.Gene.ID.1
S.genes = cc[which(cc$peaktime>47 & cc$peaktime<70 ),]$Ensembl.Gene.ID.1
G2.genes = cc[which(cc$peaktime>70 & cc$peaktime<90 ),]$Ensembl.Gene.ID.1
M.genes = cc[which(cc$peaktime>90 & cc$peaktime<100 ),]$Ensembl.Gene.ID.1
G1_S.genes = cc[which(cc$peaktime>40 & cc$peaktime<50 ),]$Ensembl.Gene.ID.1
S_G2.genes = cc[which(cc$peaktime>60 & cc$peaktime<70 ),]$Ensembl.Gene.ID.1
G2_M.genes = cc[which(cc$peaktime>80 & cc$peaktime<90 ),]$Ensembl.Gene.ID.1
} else { stop ("Organism has to be either human or mouse")}
# Compute the smean of genes associated with each cell-phase
G1.sum = apply(log2_counts[G1.genes,colnames(log2_counts)],2,mean)
S.sum = apply(log2_counts[S.genes,colnames(log2_counts)],2,mean)
G2.sum = apply(log2_counts[G2.genes,colnames(log2_counts)],2,mean)
M.sum = apply(log2_counts[M.genes,colnames(log2_counts)],2,mean)
G1_S.sum = apply(log2_counts[G1_S.genes,colnames(log2_counts)],2,mean)
S_G2.sum = apply(log2_counts[S_G2.genes,colnames(log2_counts)],2,mean)
G2_M.sum = apply(log2_counts[G2_M.genes,colnames(log2_counts)],2,mean)
# Create a matrix with the sum of genes associated with each cell-cycle pahse per cells
G1.S.G2.M = rbind(G1.sum[names(sort(G1.sum))],S.sum[names(sort(G1.sum))],
G2.sum[names(sort(G1.sum))] ,
M.sum[names(sort(G1.sum))],G1_S.sum[names(sort(G1.sum))],
S_G2.sum[names(sort(G1.sum))],G2_M.sum[names(sort(G1.sum))])
rownames(G1.S.G2.M) = c("G1","S","G2","M","G1_S","S_G2","G2_M")
# compute a cell cycle score (divide by totl expression)
# note that this is biased by expression differences in cc genes,
# better to use correlations as in Seurat or scran
cell.phase = do.call(cbind,
lapply(seq(dim(G1.S.G2.M)[2]),function(i){
res = G1.S.G2.M[,i]/sum(G1.S.G2.M[,i])
}))
colnames(cell.phase) = colnames(G1.S.G2.M)
cell.phase = t(cell.phase)
cell.phase = as.data.frame(cell.phase)
cell.phase = as.data.frame(t(cell.phase),stringsAsFactors = F)
return(cell.phase)
}
```
### Normalization
All available normalizations are collapsed in a single function `normalize_counts` for convenience.
Input:
* sce: SCESet. Contains all your data.
* method: Character. The method you want to use to normalize. Choices are:
+ TC = total count normalization (multiply this by 10^6 to get CPMs)
+ UQ = upperquartile
+ RLE = relative log-expression, as in DESeq2
+ TMM = trimmed mean of M-values, as in edgeR
+ scran (default) = Lun sum factors, implemented in scran package
Output:
* an SCESet with the normalized expression values in the exprs and norm_exprs slots
```{r}
normalize_counts = function(sce,method = "scran"){
#calculate size factors according to method
switch(method,
"TC" ={sce = normalizeExprs(sce, method="none",return_norm_as_exprs=T)},
"RLE" = {sce = normalizeExprs(sce, method="RLE",return_norm_as_exprs=T)},
"TMM" = {sce = normalizeExprs(sce, method="TMM",return_norm_as_exprs=T)},
"UQ" = {sce = normalizeExprs(sce, method="upperquartile",return_norm_as_exprs=T)},
"scran" = {clusters = quickCluster(sce)
sizes = seq(20,100,5)
if(min(table(clusters))>max(sizes)){
sce = computeSumFactors(sce,clusters = clusters,sizes=sizes)
} else{
message("Clustering of cells failed, using global scaling factors")
sce = computeSumFactors(sce)
if(any(sizeFactors(sce) < 0)) {
warning("Negative size factors generated. Most likely, this is due to some cells having very low total feature counts. Consider using more stringent QC cutoffs.")
}
}
sce = scater::normalize(sce, return_norm_as_exprs=T)}
)
return(sce)
}
```
### Feature selection
#### Highly variable genes (Brennecke et. al, 2013)
This method implements the approach presented by Brennecke et. al, NMeth, 2013 ([here](http://www.nature.com/nmeth/journal/v10/n11/full/nmeth.2645.html?foxtrotcallback=true)).
Input:
* x: a matrix of normalized counts, NOT on log scale. Note that therefore you will need to provide 2^norm_exprs(SCESet)-1 if your input comes from an SCESet.
* PLOT: logical. Should a plot be printed?
* qcv: Between 0 and 1. Threshold for the coefficient of variation (see below).
* q: Between 0 and 1. The q-th quantile of the mean expression of all genes having a CV > qcv is used as a threshold. Genes having mean below this threshold are not included in the analysis.
* pv: the p-value cutoff
* minBiolDisp: Between 0 and 1. The CV of the underlying biological variation. Leave at default unless you have a good reason to change it.
Output:
* info: a vector of logicals specifying whther a gene is informative or not.
```{r}
info.genes = function(x,PLOT=F,qcv=.3,pv=.05,q=.95,minBiolDisp=0.1, perc_genes = NULL){
if(!(is.null(perc_genes)|is.null(pv))){
stop("Please provide either pv or perc_genes, not both!")
}
library(statmod)
# calculate mean, variance and CV
means = rowMeans(x)
vars = (apply(x,1,var))
cv2 = vars/means^2
# exclude genes with very low mean
minMeanForFit = unname( quantile( means[ which( cv2 > qcv) ], q ) )#is the 95% of the means with a dispersion greter than 0.3
useForFit = means >= minMeanForFit
#fit model
fit = glmgam.fit( cbind( a0 = 1, a1tilde = 1/means[useForFit] ),cv2[useForFit] ) # linear fit
fit$coefficients
a0 = unname(fit$coefficients["a0"])
a1 = unname(fit$coefficients["a1tilde"]) #we assume xi = mean(technical size factors) = 0
minBiolDisp = minBiolDisp^2 #squared minimum biological variance
psia1theta = a1 # this is the term psi+a1*theta that appears in the formula for omega
# again, we assume that the technical sf = 0 and mean ratio of all size factors = 1
m = ncol(x)
cv2th = a0 + minBiolDisp + a0 * minBiolDisp #a0 adjusted for min biol variation
testDenom = ( means * psia1theta + means^2 * cv2th ) / ( 1 + cv2th/m ) #omega
pval = pchisq(vars*(m-1)/testDenom,df=m-1,lower.tail=F) #Chi^2 distribution
adj.pval = sort(p.adjust(pval,"fdr"))
if(!is.null(pv)){
info = adj.pval < pv
} else {
info = adj.pval < adj.pval[as.integer(perc_genes/100*length(adj.pval))]
}
if(PLOT){
if(min(means)<=0) ps = .1-min(means)
if(min(means)>0) ps = 0
xg = 1000^(seq( min(log(means+ps)), max(log(means+ps)), length.out=5000 ))
vfit = a1/xg + a0 #estimated technical variation
vfit_biol = psia1theta/xg + a0 + minBiolDisp # expected total variation
xlabel = "log[ Average normalized read count]"
smoothScatter(log(means+ps),log(cv2),xlab=xlabel,ylab="log[ Squared coefficient of variation (CV^2)]")
points(log(means+ps),log(cv2),col="gray")
# lines(log(xg[which(vfit>0)]+ps), log(vfit[which(vfit>0)]), col="black", lwd=3,lty=2,ylim=range(cv2) )
lines(log(xg[which(vfit_biol>0)]+ps), log(vfit_biol[which(vfit_biol>0)]), col="black", lwd=3,ylim=range(cv2) )
lines(log(xg[which(vfit_biol>0)]+ps),log(vfit_biol[which(vfit_biol>0)] * qchisq(0.975,m-1)/(m-1)),lty=2,col="black")
lines(log(xg[which(vfit_biol>0)]+ps),log(vfit_biol[which(vfit_biol>0)] * qchisq(0.025,m-1)/(m-1)),lty=2,col="black")
points(log(means[names(which(info)[TRUE])]+ps),log(cv2[names(which(info)[TRUE])]),col=2,cex=.5)
}
return(info)
}
```
#### Using depth-adjusted negative binomial model (M3Drop)
This method is implemented in M3drop versions > 2.0. It models the gene counts as a negative binomial with a depth-adjusted mean. Gene-specific dispersions are then fit to the sample variance. A detailed description of the method can be found [here](https://www.biorxiv.org/content/early/2016/10/20/065094). Based on the calculated model, informative genes can be selcted by comparing expected values for dropouts (NBDrop) or dispersions (NBDisp) to the predicted ones.
The function _run_DANB_ is used for both methods.
Input:
* counts: a matrix of RAW counts
* save_plot: logical. Should the produced plot be saved?
* method: One of either "NBDrop" or "NBDisp". The method used for feature selection.
* cutoff: The p-value cutoff for NBDrop or the percentage of genes returned by NBDisp.
* perc_genes: The percentage of genes to keep (can only be provided instead of cutoff)
Output:
* info: a vector of logicals specifying whther a gene is informative or not.
```{r}
run_DANB = function(counts,save_plot=T,method="NBDrop",cutoff=NULL, perc_genes = NULL){
if((is.null(perc_genes)&is.null(cutoff))){
stop("Please provide exactly one of either cutoff or perc_genes")
}
if(!(is.null(perc_genes)|is.null(cutoff))){
stop("Please provide either cutoff or perc_genes, not both!")
}
library(M3Drop) #note that you require version > 2.0 (not on bioconductor yet)
if(!method%in%c("NBDrop","NBDisp")){
stop("Invalid method selected. Please choose one of \"NBDrop\", \"NBDisp\"")
}
# fitting the dropout model (DANB)
fit = NBumiFitModel(counts) #this fits a DANB model
fit$mus = t(sapply(fit$vals$tjs, function (x) x * fit$vals$tis/fit$vals$total))
size_coeffs = NBumiFitDispVsMean(fit, suppress.plot = T)#get coefcients of mean-dispersion fit
smoothed_size = exp(size_coeffs[1] + size_coeffs[2] * log(fit$vals$tjs/fit$vals$nc)) #predicted dispersions per gene
size_mat = matrix(rep(smoothed_size, times = fit$vals$nc), ncol = fit$vals$nc, byrow = FALSE)
exp_ps = (1 + fit$mus/size_mat)^(-size_mat) #these are the fitted values per cell and gene
exp_tot = rowSums(exp_ps) #this is the total predicted molecules per gene
plot_dt = data.table(Dropout_rate = fit$vals$djs/fit$vals$nc,
expression = fit$vals$tjs/fit$vals$nc,
sizes = fit$sizes,
pred_sizes = smoothed_size,
predicted_dropouts=exp_tot/fit$vals$nc)
if(method=="NBDrop"){
NBumiCheckFitFS(counts,fit,suppress.plot = T) #check whether the fitted droout rates are well correlated with observed ones (i.e. number of zeroes)
pvals = NBumiFeatureSelectionCombinedDrop(fit) #ranks genes by difference from expected dropout rates
if(is.null(cutoff)){ cutoff = sort(pvals)[as.integer(perc_genes/100*length(pvals))]}
info = rownames(counts)%in%names(pvals[which(pvals<cutoff)]) #select the top features based on dropout rates
plot_dt[,info:=info]
p = ggplot(plot_dt,aes(x=log10(expression),y=Dropout_rate)) +
geom_point(aes(color=info),alpha=0.7,size=2) +
geom_line(aes(x=log10(expression),y=predicted_dropouts),color=colors()[30],size=1.2)+
theme_bw() + xlab("Expression [log10]") + ylab("Dropout Rate")+
ggtitle("Dropout rate vs. Expression")+ theme(text = element_text(size=17))+
scale_color_manual(values = colors()[c(226,32)],name="is_outlier")
print(p)
if(save_plot){
ggsave(p,file=file.path(plotdir,"NBdrop_plot.pdf"),height=6,width=8)
}
} else {
resids = NBumiFeatureSelectionHighVar(fit) #ranks genes by difference from fitted mean-dispersion power law
if(is.null(cutoff)){cutoff = perc_genes/100}
info = rownames(counts)%in%names(resids[which(resids<quantile(resids,cutoff))])
plot_dt[,info:=info]
plot_dt[,est_cv2:=(1+expression/sizes)/expression] #predicted variance according to DANB model
plot_dt[,ave_cv2:=(1+expression/pred_sizes)/expression] #predicted variance according to linear fit of dispersions
p = ggplot(plot_dt,aes(x=log10(expression),y=log10(est_cv2))) +
geom_point(aes(color=info),alpha=0.7,size=2) +
geom_line(aes(x=log10(expression),y=log10(ave_cv2)),color=colors()[30],size=1.2)+
theme_bw() + xlab("Expression [log10]") + ylab("Estimated CV^2 [log10]")+
ggtitle("Mean - Dispersion Relationship")+ theme(text = element_text(size=17))+
scale_color_manual(values = colors()[c(226,32)],name="is_outlier")
print(p)
if(save_plot){
ggsave(p,file=file.path(plotdir,"NBdisp_plot.pdf"),height=6,width=8)
}
}
return(info)
}
```
#### Select genes based on GO annotation
Input:
* go_id: A GO identifier
* organism: One of either "human" or "mouse"
Output:
* gene_ens: a list of ensembl gene identifiers mapping to this GO term.
```{r}
GO_to_gene = function(go_id, organism = "human"){
if(organism == "human"){
library(org.Hs.eg.db)
gene_eg = get(go_id,org.Hs.egGO2ALLEGS) # retrieve all entrez gene identifiers mapping to go_id
gene_ens = unlist(lapply(gene_eg, function(x) get(x,org.Hs.egENSEMBL))) #convert to ensembl
} else if(organism == "mouse"){
library(org.Mm.eg.db)
gene_eg = get(go_id,org.Mm.egGO2ALLEGS) # retrieve all entrez gene identifiers mapping to go_id
gene_ens = unlist(lapply(gene_eg, function(x) get(x,org.Mm.egENSEMBL))) #convert to ensembl
} else {stop("Organism has to be human or mouse.")}
return(gene_ens)
}
```
### Clustering
#### MCL (adapted from code provided by <NAME>)
Note: This method requires an external installation of MCL which can be obtained from [here](http://micans.org/mcl/). It consists of two steps: First, _build_adjacency_matrix_ calculates an adjacency matrix from some measure of similarity (currently, the only possibility is pearson correlation but I will probably change this in the future). Second, the adjacency matrix is converted to a graph and used as input for MCL. Note that MCL is extremely sensitive to the cutoffs that are chosenn to construct the adjacency matrix. As a rule of thumb, I look for the valley in the distribution of similarities and use this as a cutoff. If this does not work (i.e. MCL returns lot of tiny clusters), consider specifying the cutoff manually.
Input:
* mat: a matrix of normalized expression values on a log2 scale or a matrix of similarities if is_similarity = TRUE
* cutoff: Either "auto" or a number between 0 and 1. Parameter for the correlation cutoff used to contruct the adjacency matrix. If set to "auto", the function will attempt to find a valley in the distribution of similarities and use this as a cutoff. If a number is provided, it will use this as a cutoff.
* adj: List. The output of _build_adjacency_matrix_, a list containing the adjacency matrix, the similarity matrix and the chosen cutoff.
Output:
* groups.MCL: The cluster assignments. "0" means the cell was not assigned to any cluster.
```{r}
build_adjacency_matrix = function(mat,cutoff="auto", is_similarity = F){
library(Ckmeans.1d.dp)
if(!is_similarity){
message("Computing cell Pearson correlation coefficient")
corr.cells = cor(mat,method="pearson")
} else {corr.cells = mat}
adj.corr = corr.cells
if(cutoff=="auto"){
# we find the best correlation cutoff by looking for a "valley"
# in the histogram of correlations. This function attempts to set the
# cutoff automatically, but might not always succeed...
# if there are more than 500 cells, randomly sample 500 correlations
if(dim(corr.cells)[1]>500){
idx = sample(seq(dim(corr.cells)[1]),size=500)
} else {idx = seq(dim(corr.cells)[1])}
freqs = hist(corr.cells[idx,idx],breaks=dim(corr.cells[idx,idx])[1]/10)
k1d = Ckmeans.1d.dp(corr.cells,k=2)
cutoff = max(as.vector(corr.cells)[which(k1d$cluster==1)])
abline(v=cutoff,col="red")
} else if (is.numeric(cutoff)){cutoff=cutoff} else {
stop("Please provide a numeric value for corr.cutoff or set to \"auto\"")
}
message("Building the adjacency matrix")
adj.corr[adj.corr<cutoff]=0
adj.corr[adj.corr>0] = 1
return(list(adj=adj.corr,cor=corr.cells,cutoff=cutoff))
}
MCLcell.clust=function(adj_list,selfloop=T,mcl_path = "/da/dmp/cb/prog/mcl-14-137/bin/mcl"){
library(igraph)
adj = adj_list$adj
corr.cells = adj_list$cor
corr.cutoff = adj_list$cutoff
if(!selfloop) diag(adj)=0 # no self-loop for MCL
message("Building Graph")
graphs = get.data.frame( graph.adjacency(adj), what = "edges") # gene connection for graphs
graphs = data.frame(graphs,CORR=sapply(seq(dim(graphs)[1]), function(i) corr.cells[graphs$from[i],graphs$to[i]] -corr.cutoff))
write.table(graphs, file = "tmp.mcl.inp",row.names=F,col.names=F,sep = " ")
message("Running MCL")
system(paste0(mcl_path, " tmp.mcl.inp --abc -o tmp.mcl.out"))
x = scan("tmp.mcl.out", what="", sep="\n")
MCL.cells = strsplit(x, "[[:space:]]+")
MCL.cells = lapply(seq(length(MCL.cells)), function(i){
tmp = sapply(seq(length(MCL.cells[[i]])),function(j){
gsub('\"','',MCL.cells[[i]][j])
})
})
system("rm tmp.mcl.inp tmp.mcl.out")
groups.MCL = matrix(rep(-1,dim(corr.cells)[2]),ncol=1)
rownames(groups.MCL) = colnames(corr.cells)
for(i in seq(length(MCL.cells))) groups.MCL[MCL.cells[[i]],]=i
#if necessary, collapse all clusters containing only 1 cell to a big "unassigned"
groups.MCL[groups.MCL %in% names(table(groups.MCL)[which(table(groups.MCL)==1)])] = 0
return(groups.MCL)
}
```
#### DBSCAN
DBSCAN is a density based algorithm that identifies clusters as regions of high density that are separated by regions of low density. Note that it is not suited for very high-dimensional data, therefore should be used only in combination with dimensionality reduction (usually PCA).
Input:
* dist: A dist object containing cell-cell distances in low-dimensional space.
* min_pts: Integer. The number minimum points in the eps neighborhood. Generally, this should be one more than the dimensionality of the space in which distances were calculated, i.e. the number of used principal components +1.
* eps: "auto" or a number. The radius of the eps neighborhood (see dbscan documentation for details). As a rule of thumb, this should be the y value of the "elbow" on the KNNdistplot. If set to "auto", eps will be determined automatically.
* tol: The tolerance when determining eps. The default is 0.01, which in general works quite well. The lower the tolerance, the smaller eps.
```{r}
run_dbscan = function(dist,eps="auto",min_pts,tol=0.01){
library(dbscan)
#automatic determination of eps (the "elbow" in the kNNdistplot)
if(eps=="auto"){
kNNdist = sort(kNNdist(dist,min_pts))
i = seq(1,length(kNNdist),as.integer(0.001*length(kNNdist)))
slope_prev = 100
for(indx in i){
slope = kNNdist[indx]/indx
if(slope_prev>=slope-tol*slope){
slope_prev = slope
} else {
elbow = indx
break
}
}
eps = kNNdist[elbow]
print(paste("Epsilon: ",eps))
} else if(!is.numeric(eps)){
stop("Please provide a value for eps or set it to \"auto\"")} else {eps=eps}
kNNdistplot(dist,k=min_pts)
abline(h=eps,col="red")
res = dbscan(dist,eps = eps,minPts = min_pts)
return(res$cluster)
}
```
#### Mclust
Mclust is a model-based clustering approach that uses an EM algorithm to fit a gaussian mixture model to the data. Mclust works under the assumption that the different cells come from a mixture of k multivariate normal distributions. In very high-dimensional space, this assumption often does not hold, therefore, mclust should only be used on coordinates in PCA space.
The actual clustering is performed by calling the function _gmm_main_ which has the following input parameters:
* norm_exprs: A matrix of normalized expression values. If missing, you have to provide pre-computed PCA scores instead.
* pc_scores: A matrix of PCA scores. Corresponds to prcomp$x.
* n_comp: Integer. the number of PCA scores to use to calculate the model.
* do_crossval: Logical. Should cross-validation be used to find the best number of clusters? If set to FALSE, you have to provide a value for best_k yourself.
* tolerance: A number specifying how tolerant the algorithm should be when finding the best number of clusters. Larger numbers will result in fewer clusters.
* k: Range of integers. The numbers of clusters to test during cross-validation.
* model_type: Specifies which parametrization to use. See the `mclustModelNames` help page for detail. The default, "VVI", corresponds to a diagonal model (i.e. all covariances are zero) with unequal variance and volume.
* return_model: Return the mclust model object? If FALSE, only the cluster assignments are returned.
```{r}
gmm_main = function(norm_exprs=NULL,pc_scores=NULL,n_comp=10,do_crossval=T, model_type = "VVI",
best_k=NULL,tolerance = 1.96,k=1:10,n_cores = 4, return_model = F){
library(mclust)
library(parallel)
if(is.null(pc_scores)){
if(is.null(norm_exprs)){
stop("Missing expression values. Please provide either a matrix of normalized counts or pre-computed PCA scores.")
}
print("Running PCA...")
pca = pca_stuff(norm_exprs)
top_pc_scores = pca$x[,1:n_comp]
} else {
top_pc_scores = pc_scores[,1:n_comp]
}
if(do_crossval){
#fit models with k-fold crossvalidation
folds = 1:10
n_folds = length(folds)
# this randomly determines which samples should be excluded from
# model fitting during each fold of the cross-validation.
idx = sample(rep(1:n_folds, length.out = nrow(top_pc_scores)))
#Set up parallel processing
library(parallel)
cl = makeCluster(n_cores)
funs = as.character(lsf.str(envir=parent.frame())) #let clusters know about functions in workspace
clusterExport(cl,funs)
#benchmark
#time = system.time(parSapply(cl,folds,cross_val,data=testset,idx=idx,structure='VVI',components=k))
print("Determining number of clusters...")
likes = parSapply(cl,folds,cross_val,data=top_pc_scores,idx=idx,structure=model_type,components=k)
stopCluster(cl)
mean_likes = apply(likes,1,function(x) sum(x[which(is.finite(x))])/length(which(x!=0 & is.finite(x))))
sd_likes = apply(likes,1,function(x) sd(x[which(x!=0 & is.finite(x))]))
sd_likes = sd_likes[which(!is.na(sd_likes))]
mean_likes = mean_likes[which(!is.na(sd_likes))]
best_idx = which(mean_likes==max(mean_likes))
ci_likes = mean_likes[best_idx]-tolerance*sd_likes[best_idx]
best_k_idx = min(which(mean_likes>=ci_likes)) #smallest numebr of components that
#fit reasonably well
best_k = k[best_k_idx]
mean_likes[best_k_idx]
col=rep(1,n_folds)
col[best_k_idx] = 33
# Plot likelihood vs number of clusters
# This should look like a ROC curve ideally. The best model should have
# a high likelihood with the smallest no. of clusters, i.e. be the one
# where the slope decreases. If there is no clear decrease in the
# slope, this means that pretty much any model fits equally well/bad and that
# most likely the clustering produces a nonsensical result
like_dt = data.table(cluster=k,color=as.factor(col),likes)
like_dt_melt = melt(like_dt,id.vars=c("cluster","color"),val="log-Likelihood",var="fold")
p = ggplot(like_dt_melt[`log-Likelihood`!=0 & is.finite(`log-Likelihood`)],aes(x=as.factor(cluster),y=`log-Likelihood`,fill=color)) +
geom_boxplot() + labs(x = "Number of clusters",
title = paste0("No. clusters v.s. log-likelihood, ",n_folds,"-fold crossvalidation"),
subtitle = paste0(n_comp," principal components used to calcualte model")) +
theme_bw() +scale_fill_manual(values=c("white","red"),guide=F)
#ggsave(p,file=file.path(plotdir,paste0("mclust_crossval_",n_comp,".pdf")),height=5,width=7)
print(p)
print(paste0("Found ",best_k," clusters."))
} else {best_k = best_k}
if(is.null(best_k)){
stop("Please provide a value for best_k or set do_crossval = TRUE")
}
print("Assigning cells to clusters...")
#assignments of cells to clusters
model = calc_model(top_pc_scores,best_k,model_type)
cluster_assignments = model$classification
if(return_model){
return(model)
} else {
return(cluster_assignments)}
}
```
Additional functions called by _gmm_main_:
```{r}
#do pca
pca_stuff = function(log_data_hv,scale_pca=T,center_pca=T){
pca = prcomp(t(log_data_hv[,-1,with=F]),scale=scale_pca,center=center_pca)
return(pca)
}
#Fitting GMM with mclust:
##############################################################################
# function to calculate different models
# k = number of compnents
# structure = model structure / constraints. See mclustModelNames for details.
calc_model = function(data,k,structure){
return(Mclust(data,G=k,modelNames = structure,initialization=
list(subset=sample(1:nrow(data),size=as.integer(nrow(data)*4/5)))))
}
#############################################################################
#Functions to calculate log-likelihood out of what mclust returns
# Probability density function for a Gaussian mixture
# Presumes the mixture object has the structure used by mclust
dnormalmix = function(x,mixture,log=FALSE) {
lambda = mixture$parameters$pro
k = length(lambda)
# Calculate share of likelihood for all data for one component
like_component = function(x, component) {
lambda[component] * dmvnorm(
x,
mean = mixture$parameters$mean[,component],
sigma = mixture$parameters$variance$sigma[,,component]
)
}
# Create array with likelihood shares from all components over all data
likes = sapply(1:k, like_component ,x = x)
# Add up contributions from components
d = rowSums(likes)
if (log) {
d = log(d)
}
return(d)
}
# Log likelihood function for a Gaussian mixture, potentially on new data
loglike_normalmix = function(x,mixture) {
loglike = dnormalmix(x, mixture, log = TRUE)
return(sum(loglike))
}
###############################################################################
#Cross validation things
#Cross validation
#data = input data
#idx = a random sample of folds (e.g. 11432...)
#fold = the current fold
#structure = model structure for mclust (e.g. 'VVI)
#components = a vector containing the numebr of components for which to test models
cross_val = function(fold,data,idx,structure,components){
#library(mclust,lib.loc = .libPaths()[[2]]) #for the VM
library(mclust)
library(mvtnorm)
like_test = c()
for(k in components){
out = tryCatch(
{
calc_model(data[which(idx!=fold),],k,structure)
},
error=function(cond){
#try to find another model
out2 = 0
counter = 0
while(out2 == 0 && counter<=5){
out2 = tryCatch(
{
calc_model(data[which(idx!=fold),],k,structure)
},
error = return(0),
warning=return(0),
finally= {counter = counter +1}
)
}
message('There was an error: \n')
message(cond)
write.csv(cond,'gmm.log',append=TRUE)
return(out2)
},
warning=function(cond){
#try to find another model
out2 = 0
counter = 0
while(out2 == 0 && counter<=10){
out2 = tryCatch(
{
calc_model(data[which(idx!=fold),],k,structure)
},
error = return(0),
warning=return(0),
finally={counter = counter +1}
)
}
message('There was a warning: \n')
message(cond)
write.csv(cond,'gmm.log',append=TRUE)
return(out2)
},
finally={
message('\n done.')
}
)
if(class(out)=='Mclust'){
like_test = append(like_test,loglike_normalmix(data[which(idx==fold),],out))
}
else{
like_test = append(like_test,0)
}
}
return(like_test)
}
```
#### Seurat
This implements the clustering method provided in Seurat. See the [package documentation](http://satijalab.org/seurat/) for details.
Input:
* sce: SCESet containing raw and normalized data.
* vars.to.regress: Character vector (optional). Names of columns in pData(sce) that are possible confounders and whose contribution to the variation should be regressed out.
* res: resolution of the clustering. The higher, the more small clusters will be made.
* n_comp: Integer. number of principal compenents to use in clustering.
```{r}
seurat_clustering = function(sce,vars.to.regress=NULL,res=0.6,n_comp=10){
library(Seurat)
#make SEURAT object, scale and optionally regress out confounders
tmp_seurat = CreateSeuratObject(raw.data = counts(sce))
tmp_seurat@data = norm_exprs(sce) #add the normalized values
# This next step is a bit of cheating. Seurat expects us to run the complete
# workflow on the same object and checks whether data have been normalized
# by checking if object@calc.params$NormalizeData$normalization.method exists.
# Since we provided normalized values, and do not want to re-run normalization,
# we just put a dummy value in that slot.
tmp_seurat@calc.params$NormalizeData = list(normalization.method ="dummy")
if(!is.null(vars.to.regress)){
if(any(!vars.to.regress%in%names(pData(sce)))){
stop("Variables to regress out have to be column names in pData(sce)")
}
tmp_seurat = AddMetadata(object = tmp_seurat, metadata = pData(sce)[,vars.to.regress])
tmp_seurat = ScaleData(object = tmp_seurat,vars.to.regress=vars.to.regress)
} else {
tmp_seurat = ScaleData(object = tmp_seurat)
}
tmp_seurat = RunPCA(object = tmp_seurat, pc.genes = rownames(sce), do.print = FALSE)
tmp_seurat = FindClusters(object = tmp_seurat, reduction.type = "pca", dims.use = 1:n_comp,
resolution = res, print.output = 0, save.SNN = TRUE)
seurat_assignment = tmp_seurat@ident
return(seurat_assignment)
}
```
### Rare cell types
This function identifies cell subclusters that are characterized by specific expression of correlated gene sets. The whole algorithm consists of 5 steps:
1. Identify genes with a bimodal distribution of expression levels
2. Test whether these genes are specific to one main cluster
3. Group candidate genes into correlated gene sets using MCL
4. Assign cells to subgroups based on mean expression of those gene sets
5. (optional) Annotate genes and print summary
The main function `rare_cell_type_identifier` takes the following arguments:
* sce: SCESet. Your dataset.
* group_id: Character. A column name in pData(sce) that specifies how the cells should be grouped in clusters.
* min_n_cells: Integer. When identifying bimodal gene distributions, this specifies the minimum number of cells per mode. Also, clusters with a total number of cells below 2x this number will be entirely ignored.
* min_fc: Numeric, defaults to 2. Minimum difference in mean [log2] between the two modes of the gene expression distribution.
* fc_between_cutoff: Numeric, defaults to 1. Minimum difference [log2] in gene expression between cells in the subcluster and all other cells. The higher, the more cluster-specific the genes. Note that this should not be set higher than min_fc.
* verbose: Logical. Should a summary of the results be printed?
* organism: One of either "human" or "mouse". Only relevant if verbose=TRUE. Specifies which genome anotation to use when printing the results summary.
* corr_cutoff: Correlation cutoff for MCL clustering of candidate marker genes. If NULL, it will be set automatically for each cluster, which in general works much better than forcing a fixed value. Therefore, leave this at the default unless you have a good reason to change it.
* iter: 0 or 1. Relevant for the final step (assigning cells to subgroups). If set to 1, the first mode of gene expression will be discarded. Cells are then assigned based on the 2nd and 3rd mode, which results in a more stringent assignment. The default is 0 and is usually stringent enough.
* max_perc_cells: Maximum percentage of cells that can be part of a subcluster. Defaults to 50, implying that a "subgroup" cannot contain more than half of the total observations.
The output is a `data.table`. Refer to the main text for how to query it.
```{r}
rare_cell_type_identifier = function(sce,group_id,min_n_cells=10,verbose = T, min_fc = 2,
organism = "human", corr_cutoff = NULL, iter=0, max_perc_cells = 50,
fc_between_cutoff = 1){
library(Ckmeans.1d.dp)
expr_dt = data.table(gene_id = rownames(sce),norm_exprs(sce))
expr_dt_melt = melt(expr_dt,id.vars="gene_id",val="expr",var="cell_idx")
expr_dt_melt = merge(expr_dt_melt,
data.table(cell_idx=colnames(sce),main_cluster=as.character(pData(sce)[,group_id])),
by="cell_idx")
#Identify genes with significant bimodal distribution
expr_dt_melt[,c("N_cells","within_p","pos0","pos1","Dpos"):=find_bimodal_genes(expr,min_n_cells = min_n_cells, max_perc_cells = max_perc_cells),by=c('gene_id','main_cluster')]
expr_dt_melt[,sig := within_p<100 & Dpos > min_fc]
expr_dt_melt[sig==T, within_adj_p:=p.adjust(within_p),by=c('cell_idx')] #correct for multiple testing, only consider genes where test has actually been run
expr_dt_melt[,sig:=within_adj_p<0.1]
expr_dt_melt = expr_dt_melt[gene_id %in% expr_dt_melt[!is.na(sig) & sig==T]$gene_id]
# If no bimodal gene were found, exit and return NA
if(dim(expr_dt_melt)[1] == 0){
print("No genes with bimodal distribution found, returning NA.")
return(NA)
}
# Check whether these genes are specific to the subcluster
for(clust in unique(expr_dt_melt$main_cluster)){
expr_dt_melt = expr_dt_melt[,paste0(clust,"_",c("p_between","fc")):=test_cluster_specificity(
expr,main_cluster,clust, fc_between_cutoff = fc_between_cutoff),by="gene_id"]
expr_dt_melt[main_cluster==clust,keep:=(expr_dt_melt[main_cluster==clust][[paste0(clust,"_p_between")]] < 0.1)]
}
expr_dt_melt = expr_dt_melt[keep==TRUE & !is.na(sig)]
# If there are still non-specific genes, discard them (this can happen for
# very high expressed genes like mitochondrial genes)
expr_dt_melt[,n_clust_per_gene:=length(unique(main_cluster)),by='gene_id']
expr_dt_melt = expr_dt_melt[n_clust_per_gene==1]
expr_dt_melt[,n_clust_per_gene:=NULL]
# Identify correlated gene sets with MCL
expr_dt_melt = expr_dt_melt[,gene_cluster:=0]
expr_dt_melt = find_gene_sets(expr_dt_melt, corr_cutoff = corr_cutoff)
# discard gene sets that only contain one gene (those are assigned to cluster 0)
expr_dt_melt = expr_dt_melt[gene_cluster !=0 ]
if(dim(expr_dt_melt)[1] == 0){
print("No subclusters found, returning NA.")
return(NA)
}
# Extract cell subclusters
expr_dt_melt[,sub_cluster:=main_cluster]
expr_dt_melt[,mean_expr := mean(expr), by = c('main_cluster','gene_cluster','cell_idx')]
expr_dt_melt[,sub_cluster:=sub_cluster(mean_expr,sub_cluster,gene_cluster, iter=iter),by=c('main_cluster','gene_cluster')]
# Check how many cells belong to the subgroup relative to the total cluster size.
# If a sub cluster contains more than max_perc_cells cells, discard it.
clust_list = expr_dt_melt[,list(sub = length(unique(cell_idx))) ,by=c('sub_cluster','main_cluster')]
clust_list[,tot := sum(sub)/(length(sub_cluster)/2), by= 'main_cluster']
clust_list = clust_list[grep('_1$',sub_cluster)]
clust_list[,perc:=sub/tot*100]
discard_sub_clust = clust_list[perc > max_perc_cells]$sub_cluster
discard_sub_clust = append(discard_sub_clust,gsub('_1$','_0',discard_sub_clust))
expr_dt_melt = expr_dt_melt[!sub_cluster%in%discard_sub_clust]
# If verbose is TRUE, print a summary of the results
if(verbose){
# annotate genes (only if verbose)
gene_info = get_gene_annotations(unique(expr_dt_melt$gene_id),get_descriptions = T,
organism = organism)
expr_dt_melt = merge(expr_dt_melt,gene_info, by = 'gene_id')
print_summary(expr_dt_melt)
}
return(expr_dt_melt)
}
##################################################
# STEP 1: Identify genes with bimodal distribution
##################################################
find_bimodal_genes = function(expr, min_n_cells, max_perc_cells){
#skip genes with 0 expression
if(sum(expr)==0){
return(list(-1,100,-1,-1,-1))
}
# run k-means
k1d = Ckmeans.1d.dp(expr,k=2)
# check if a cluster with more than n cells exists
indx = which(k1d$size>min_n_cells)
if(length(indx)>1 ){
# do statistic only if in pos2 cells are less than max_perc_cells% of the total cells in the cluster
if(k1d$size[2] < round(length(expr)*max_perc_cells/100)){
t1=tryCatch({t.test(expr[which(k1d$cluster==2)],y=expr[which(k1d$cluster==1)])},
error = function(cond){return(0)},
finally={}
)
if(!is.numeric(t1)){
p1=t1$p.value
N0=k1d$size[1] # number of cells where the gene is downregulated
N1=k1d$size[2] # number of cells where the gene is upregulated
pos0=k1d$centers[1]
pos1=k1d$centers[2]
Dpos=pos1-pos0
return(list(N1,p1,pos0,pos1,Dpos))
} #else {print(paste("ttest failed, dpos = ",pos1-pos0))} # for testing
}
}
# if no cluster was found, return a list of dummy values
return(list(-1,100,-1,-1,-1))
}
##################################################
# STEP 2: Check whether these genes are specific to one cell subgroup
###################################################
test_cluster_specificity = function(exprs, cluster, current_cluster, fc_between_cutoff){
in_clust = which(cluster == current_cluster)
k1d = Ckmeans.1d.dp(exprs[in_clust],k=2)
in_subclust = in_clust[which(k1d$cluster==2)]
mean_in = mean(exprs[in_subclust])
mean_out = mean(exprs[-in_subclust])
mean_out_nozero = mean(exprs[-in_subclust][exprs[-in_subclust]>0])
# If there are subclusters, but all cells outside the subcluster express 0,
# set mean_out_nozero to 0
if(length(in_subclust>0) && !any(exprs[-in_subclust]>0)){mean_out_nozero=0}
fc = mean_in - mean_out
ts = tryCatch({t.test(exprs[in_subclust],exprs[-in_clust])},
error = function(cond){ return(0)})
if(!is.numeric(ts)){pv = ts$p.value} else {
#print(paste("ttest failed, fc = ",mean_in-mean_out_nozero)) #for testing only
pv=999}
if(!is.nan(mean_out_nozero) && (mean_in-mean_out_nozero < fc_between_cutoff)) pv = 999
return(list(pv,fc))
}
#####################################################
# STEP 3: MCL clustering to find correlated gene sets
#####################################################
find_gene_sets = function(expr_dt_melt, corr_cutoff = NULL, min_corr = 0.35, max_corr = 0.5,
mcl_path = "/da/dmp/cb/prog/mcl-14-137/bin/mcl"){
library(igraph)
for(clust in unique(expr_dt_melt$main_cluster)){
if(length(unique(expr_dt_melt[main_cluster == clust]$gene_id))==1) { next }
mat = dcast.data.table(expr_dt_melt[main_cluster==clust], gene_id ~ cell_idx,
value.var = 'expr')
mat = mat[rowSums(mat[,-1,with=F])!=0,]
corr.mat = cor(t(mat[,-1,with=F]))
dimnames(corr.mat) = list(mat$gene_id,mat$gene_id)
if(is.null(corr_cutoff)){
corr_cutoff = max(quantile(corr.mat[corr.mat!=1],0.95),min_corr)
corr_cutoff = min(corr_cutoff, max_corr)}
adj.corr = corr.mat
adj.corr[adj.corr<corr_cutoff] = 0
adj.corr[adj.corr>=corr_cutoff] = 1
diag(adj.corr) = 0 # no self-loop for MCL
graphs = get.data.frame( graph_from_adjacency_matrix(adj.corr), what = "edges") # gene connection for graphs
# if a graph has no edges (i.e. all genes are uncorrelated),
# assign all genes to cluster "0" and go to next iteration
if(dim(graphs)[1]==0){
expr_dt_melt = expr_dt_melt[main_cluster == clust, gene_cluster := 0]
next
}
graphs = data.frame(graphs,CORR=sapply(seq(dim(graphs)[1]), function(i) corr.mat[graphs$from[i],graphs$to[i]] -corr_cutoff))
write.table(graphs, file = "tmp.mcl.inp",row.names=F,col.names=F,sep = " ")
system(paste0(mcl_path, " tmp.mcl.inp --abc -o tmp.mcl.out"))
x = scan("tmp.mcl.out", what="", sep="\n")
y = strsplit(x, "[[:space:]]+")
y = lapply(seq(length(y)), function(i){
tmp = sapply(seq(length(y[[i]])),function(j){
gsub('\"','',y[[i]][j])
})
})
for(i in seq(length(y))){
if(length(y[[i]] > 1)){
expr_dt_melt = expr_dt_melt[main_cluster==clust & gene_id %in% y[[i]],gene_cluster:=i]
}
}
}
return(expr_dt_melt)
}
############################################
# Step 4: Assign cells to subgroups
############################################
sub_cluster = function(mean_expr,sub_cluster,gene_cluster, iter = 0){
k1d = Ckmeans.1d.dp(mean_expr,k=2)$cluster
cells_sub = (k1d==2)
if(iter == 0){return(paste0(sub_cluster,"_",gene_cluster,"_",as.numeric(cells_sub)))}
# if iter is set higher than 0, a second step of kmeans clustering.
# This will remove the lowest peak and can sometimes help to get a more
# accurate classification.
k1d = Ckmeans.1d.dp(mean_expr[cells_sub],k=2)$cluster
if (max(k1d)>1) {
cells_sub[cells_sub] = (k1d==2)
return(paste0(sub_cluster,"_",gene_cluster,"_",as.numeric(cells_sub)))
}
return(paste0(sub_cluster,"_",gene_cluster,"_",0))
}
#######################################
# Step 5: Print summary
#######################################
print_summary = function(expr_dt_melt){
cat('--------------------------------------------------------\n',
'Summary of rare cell types\n',
'--------------------------------------------------------\n\n')
for(clust in unique(expr_dt_melt$main_cluster)){
if(!any(expr_dt_melt[main_cluster==clust]$gene_cluster!=0)){
next
}
cat('Main cluster: ', clust, '\n', '---------------\n')
subclusts = unique(expr_dt_melt[main_cluster==clust & gene_cluster!=0][order(gene_cluster)]$gene_cluster)
for(subclust in subclusts){
cat('Subcluster: ', subclust, '\n',
'Number of cells: ',
length(unique(expr_dt_melt[main_cluster==clust &
sub_cluster == paste(clust,subclust,1,sep="_")]$cell_idx)),
'\n Marker genes: \n')
print(unique(expr_dt_melt[main_cluster==clust & gene_cluster == subclust][,c("gene_id","symbol","description")]))
cat('\n\n')
}
}
}
# Visualize output of rare cell type algorithm on tSNE map
# tsne = RTsne object
# rare = output of the rare cell types algorithm (a data.table)
plot_rare_cells = function(tsne,rare){
tsne_dt = data.table(tSNE1 = tsne$Y[,1], tSNE2 = tsne$Y[,2], cell_idx = rownames(tsne$Y))
tsne_dt = merge(tsne_dt, rare[,c('cell_idx','main_cluster','sub_cluster')],
by = c('cell_idx'), all = T)
tsne_dt[is.na(main_cluster),main_cluster:='Other']
tsne_dt[main_cluster == 'Other',sub_cluster:='none']
tsne_dt[grepl('_0$',sub_cluster),sub_cluster:= 'none']
setkey(tsne_dt, 'cell_idx')
tsne_dt = unique(tsne_dt)
rc_cols = brewer.pal(10,"Spectral")[rep(c(1,9,7,2,6,10,3,8),3)]
p = ggplot(tsne_dt, aes(x = tSNE1, y= tSNE2)) +
geom_point(color = "darkgray", alpha = 0.5, size = 1.5)+
theme_bw() + theme(text = element_text(size = 15))
p = p + geom_point(data = tsne_dt[sub_cluster!='none'], aes(x=tSNE1, y=tSNE2, color = sub_cluster))+
scale_color_manual(values = rc_cols) + guides(color = guide_legend(title = 'Subcluster'))
return(p)
}
```
Function to plot result of rare cell algorithm on tSNE map:
* tsne: Rtsne object. A pre-computed tSNE map.
* rare: data.table. The output of the rare cell type algorithm.
```{r}
# Visualize output of rare cell type algorithm on tSNE map
# tsne = RTsne object
# rare = output of the rare cell types algorithm (a data.table)
plot_rare_cells = function(tsne,rare){
tsne_dt = data.table(tSNE1 = tsne$Y[,1], tSNE2 = tsne$Y[,2], cell_idx = rownames(tsne$Y))
tsne_dt = merge(tsne_dt, rare[,c('cell_idx','main_cluster','sub_cluster')],
by = c('cell_idx'), all = T)
tsne_dt[is.na(main_cluster),main_cluster:='Other']
tsne_dt[main_cluster == 'Other',sub_cluster:='none']
tsne_dt[grepl('_0$',sub_cluster),sub_cluster:= 'none']
setkey(tsne_dt, 'cell_idx')
tsne_dt = unique(tsne_dt)
rc_cols = brewer.pal(10,"Spectral")[rep(c(1,9,7,2,6,10,3,8),3)]
p = ggplot(tsne_dt, aes(x = tSNE1, y= tSNE2)) +
geom_point(color = "darkgray", alpha = 0.5, size = 1.5)+
theme_bw() + theme(text = element_text(size = 15))
p = p + geom_point(data = tsne_dt[sub_cluster!='none'], aes(x=tSNE1, y=tSNE2, color = sub_cluster))+
scale_color_manual(values = rc_cols) + guides(color = guide_legend(title = 'Subcluster'))
return(p)
}
```
### Differential Expression Analysis
The functions in the following are wrappers to the respective packages. for details what each of them does, please refer to the package documenatations.
General input for all of them:
* sce = the SCESet after QC or after normalization
* cl_id : the name of the grouping (e.g. "mclust") used in the comparison. Must be
a column name of pData(sce)
* cl_ref: the entry in pData(sce)$cl_id that should be used as the reference,
i.e. against which all the rest of the cells are compared
* alpha = false discovery rate cutoff, default = 0.05
* fc_cutoff = log2 fold change cutoff, default = 0.5
#### Wilcoxon test
This function runs the Wilcoxon test to calculate p-values, adjusts them for multiple correction using Benjamini-Hochberg method, and calculates fold changes. There is one additional parameter:
* pseudocount: Deprecated and will be removed!
```{r}
run_wilcoxon_test = function(sce,cl_id,cl_ref,
alpha=0.05,fc_cutoff=0.5,pseudocount=NULL){
if(!is.null(pseudocount)){warning("The pseudocount argument is deprecated and will be removed!")}
ignore = is.na(pData(sce)[,cl_id])
sce = sce[,!ignore]
in_clust = pData(sce)[,cl_id] %in% cl_ref
pvals = apply(norm_exprs(sce),1,
function(x) wilcox.test(x=x[in_clust],y=x[!in_clust])$p.value)
fc = apply(norm_exprs(sce),1,
function(x) mean(x[in_clust])-mean(x[!in_clust]))
#log2((mean(2^x[in_clust]-1)+pseudocount)/(mean(2^x[!in_clust]-1)+pseudocount))
out = data.table(gene_id = rownames(sce), pval = pvals, log2fc = fc)
out[,adj_pval:=p.adjust(pval,method="fdr")]
out[,DE_flag:=(adj_pval<alpha & abs(log2fc)>fc_cutoff)]
return(out)
}
```
#### limma
This function implements the limma-voom and limma-trend methods. It takes three additional parameters:
* count_thr, pct: Filter criteria. Genes that do not have a minimum count of `count_thr` in `pct`% of cells in at least one cluster are excluded. This is required because limma can become unreliable in the presence of too many very low expressed genes.
* method: one of "voom" or "trend". Specifies which limma method to use. The default is "trend" since this seems to work better with zero-inflated data.
```{r}
run_limma = function(sce,cl_id,cl_ref,
alpha=0.05,fc_cutoff=0.5,count_thr=1,pct=50, method = "trend"){
if(!method %in% c("voom","trend")){
stop("Method has to be either \"voom\" or \"trend\".")
}
ignore = is.na(pData(sce)[,cl_id])
sce = sce[,!ignore]
res = as.factor(pData(sce)[,cl_id] %in% cl_ref)
design = model.matrix(~0+res)
colnames(design) = c("Rest","Cluster")
rownames(design) = colnames(sce)
# filter out genes not detected at a count of count-thr in at least
# 50% of cells in at least one cluster. Outlier cells (clusters with only one cell) are ignored.
clust_sizes = table(pData(sce)[,cl_id])
clusts = names(clust_sizes[which(clust_sizes>1)])
keep_mat = matrix(rep(NA,dim(sce)[1]*length(clusts)),ncol = length(clusts))
for(i in seq(length(clusts))){
keep_mat[,i] = rowSums(counts(sce)[,pData(sce)[,cl_id]==clusts[i]]>=count_thr)>=pct/100*length(which(pData(sce)[,cl_id]==clusts[i]))
}
keep = apply(keep_mat, 1, function(x) any(x))
#convert to DGEList and filter
dge = convertTo(sce[keep,],"edgeR")
contrast_matrix = limma::makeContrasts(Cluster-Rest, levels = design)
if(method == "voom"){
# transforming counts
voomt = limma::voom(dge,plot=T,design = design)
#do differential expression analysis on voom transformed data
fit = limma::lmFit(voomt, design)
fit2 = limma::contrasts.fit(fit,contrast_matrix)
fit2 = limma::eBayes(fit2)
} else {
logCPM = edgeR::cpm(dge, log=TRUE, prior.count=1)
fit = limma::lmFit(logCPM, design)
fit2 = limma::contrasts.fit(fit,contrast_matrix)
fit2 = limma::eBayes(fit2, trend = T)
}
diff_exp = limma::topTable(fit2,adjust="BH",number = dim(dge)[1])
out = data.table(gene_id = rownames(diff_exp),diff_exp)
out[,DE_flag:=as.factor(adj.P.Val < alpha & abs(logFC) > fc_cutoff)]
return(out)
}
```
#### MAST
This function has several additional parameters:
* n_cores: Number of cores to be used.
* n_bins: Number of bins used to estimate expression threshold.
* min_per_bin: Minimum number of genes per bin.
* norm: Logical. Use the normalized expression values?
* set_thresh: Logical. Should expression thresholds be determined? If you cannot see clear bimodal distributions on the MAST_thresholds plot, set this to false.
```{r}
run_MAST = function(sce,cl_id,cl_ref,n_cores = 8,nbins=10,min_per_bin=30,
alpha=0.05,fc_cutoff=0.5,norm=F,set_thresh=T){
library(MAST)
ignore = is.na(pData(sce)[,cl_id])
sce = sce[,!ignore]
options(mc.cores = n_cores)
if(norm){
sca = FromMatrix(norm_exprs(sce), pData(sce), fData(sce))} else {
sca = FromMatrix(log2(counts(sce)+1), pData(sce), fData(sce))
}
# adaptive thresholding
# note how the threshold moves with median expression
if(set_thresh){
message("Calculating expression thresholds...\n
Check the MAST_theresholds plot. If there are no clear bimodal\n
distributions, the thresholds are likely to be nonsense.\n
If that is the case, re-run this function setting set_thresh = F")
thres = thresholdSCRNACountMatrix(assay(sca), nbins = nbins, min_per_bin = min_per_bin)
if(!any(thres$cutpoint!=0)){message("All cut points are zero. Try using a different
value of nbins and min_per_bin or set set_thresh=FALSE")}
par(mfrow=c(nbins%%4+1,4))
plot(thres)
dev.copy2pdf(file = file.path(plotdir,"MAST_thresholds.pdf"),width=8,height=3*(nbins%%4+1))
par(mfrow=c(1,1))
assays(sca) = list(thresh=thres$counts_threshold, counts=assay(sca))
}
cond=factor(colData(sca)[,cl_id]==cl_ref)
cond=relevel(cond,"FALSE")
colData(sca)$condition=cond
# calculate the cellular detection rate as no. detected features / no. total features
# and center it
colData(sca)$cngeneson = scale(pData(sce)$total_features/dim(sce)[1],scale=F)
# fit model (note that this will take time for large datasets!!)
message("Fitting models...")
zlmCond = zlm(~condition + cngeneson, sca)
summaryCond = summary(zlmCond, doLRT='conditionTRUE')
#extract the results as a data.table
summaryDt = summaryCond$datatable
fcHurdle = merge(summaryDt[contrast=='conditionTRUE' & component=='H',.(primerid, `Pr(>Chisq)`)], #hurdle P values
summaryDt[contrast=='conditionTRUE' & component=='logFC', .(primerid, coef, ci.hi, ci.lo)], by='primerid') #logFC coefficients
fcHurdle[,fdr:=p.adjust(`Pr(>Chisq)`, 'fdr')]
names(fcHurdle)[1:3] = c("gene_id","pval","log2FC")
fcHurdle[,DE_flag:=as.factor(fdr<alpha & abs(log2FC)>fc_cutoff)]
return(fcHurdle)
}
```
### Miscellaneous Plotting
#### Generic scatterplot using ggplot2 and data.table
This function takes a data.table as input and plots two columns, x_col and y_col, against each other. Optional arguments can be provided to control color, size and shape of the plotted symbols.
Input:
* dt: data.table with all the data to be plotted
* x_col: name of the column to lot on x axis
* y_col: name of column to plot on y axis
* color: name of column to use as color values. If numeric, a continuous color scheme will be applied, if character or factor, colors will be discrete.
* shape: name of column to use for shape
* size: name of column to use for size
* alpha: transparency
* abs_size; If no values for size are provided, abs_size sets the absolute size of the points on the plot.
Output:
* p: The plot as a ggplot object
```{r}
generic_scatterplot = function(dt, x_col, y_col,
color = NULL, shape = NULL, size = NULL, alpha = 0.8, abs_size = 2){
plot_dt = dt[,c(x_col,y_col),with=F]
#by default, do not show any legends
show_col = F
show_shape = F
show_size = F
continuous = F
discrete = F
if(!is.null(color)){
plot_dt[,c(color):=dt[[color]]]
if(!is.numeric(dt[[color]])){
show_col = guide_legend(color)
discrete = T
} else{
show_col = guide_colorbar(color)
continuous = T
}
} else {
color = "dummy_color"
plot_dt[,dummy_color:=factor(1)]
}
if(!is.null(shape)){
show_shape = guide_legend(shape)
plot_dt[,c(shape):=dt[[shape]]]
} else {
shape = "dummy_shape"
plot_dt[,dummy_shape:=factor(1)]
}
if(!is.null(size)){
show_size = guide_legend(size)
plot_dt[,c(size):=dt[[size]]]
} else {
size ="dummy_size"
plot_dt[,dummy_size:= 1]
}
p = ggplot(na.omit(plot_dt), aes_string(x=paste0("`",x_col,"`"),y=paste0("`",y_col,"`")))
if(size == "dummy_size"){
p = p+geom_point(aes_string(color=paste0("`",color,"`"),
shape=paste0("`",shape,"`"),
size=paste0("`",size,"`")),
alpha=alpha,size=abs_size)
} else{
p = p+ geom_point(aes_string(color=paste0("`",color,"`"),
shape=paste0("`",shape,"`"),
size=paste0("`",size,"`")),
alpha=alpha)}
p = p + guides(color = show_col, shape = show_shape, size = show_size)+
theme_bw()+theme(text=element_text(size=15))
if(continuous){
p = p+scale_color_continuous(low = "lightgray", high = "darkblue")
}
if(discrete){
if(length(unique(na.omit(plot_dt[[color]])))==2){
p = p+scale_color_manual(values = c("lightgray","darkred"))
} else{p = p + scale_color_brewer(type = "qual",palette = 2)}
}
if(color == "dummy_color"){
p = p + scale_color_manual(values = "darkgrey")
}
if(shape!="dummy_shape"){
if(length(unique(na.omit(plot_dt[[shape]])))>9) {stop("Too many different shapes provided. Please provide a maximum of 9 shapes, otherwise, your plot will be a mess.")}
p = p + scale_shape_manual(values = c(15,16,17,18,8,0,1,2,3))
}
return(p)
}
```
#### PCA plot
Calculates a PCA and makes a plot.
Input:
* counts: A matrix of log2 transformed, raw or normalized counts. If no counts are provided, a pre-computed prcomp object has to be provided instead.
* pca: prcomp object. A result from a previous PCA calculation. If missing, a new PCA is calculated.
* scale_pca: Logical. Should the data be scaled to have unit variance? Default = TRUE.
* center_pca: Logical. Should the data be centered before calculating PCA? Default = TRUE.
* comp: Numerical vector with 2 elements. The 2 components to plot against each other.
* return_pca: Logical. Should the prcomp object be returned? If TRUE, the function returns a list with pca = the prcomp object and plot = the plot. If false, only the plot is returned as a ggplot2 object.
* use_irlba: Logical. Should the principal components be calculated using prcomp_irlba? Using irlba ignificantly increases speed for large datasets.
* color, size and shape: Each a data.frame with one column containing the respective values to plot. For colors, numeric values are plotted on a continuous scale, factors as discrete colors. Note that the rownames of the data.frame have to be the same as the rownames of pca, but can be in any order. By default, the column name is used as a label for the color legend. The easiest way of setting any of those values is to use columns in the phenoData of your SCESet, e.g. colors = pData(sce)[,"cluster",drop=F].
* alpha: Between 0 and 1. Transparency of the points.
* tite: Title of the plot.
```{r}
my_plot_PCA = function(counts=NULL,pca=NULL, alpha = 0.7, scale_pca = T, center_pca=T,comp=c(1,2),
color=NULL,size=NULL,shape=NULL,return_pca=F,title="PCA",abs_size=2, use_irlba=F){
if(is.null(counts)&is.null(pca)){
message('Please provide either a count matrix or pre-computed
principal component analysis as a prcomp object.')
} else if(is.null(pca)){
if(use_irlba){
library(irlba)
if(packageDescription("irlba")$Version <= 2.3){
stop("Please update irlba to version 2.3.2 (github). There is a bug in versions < 2.3 which results in unreliable output.")
}
pca = prcomp_irlba(t(counts),n=max(comp),center=center_pca,scale. = scale_pca)
rownames(pca$x) = colnames(counts)} else{
pca<-prcomp(t(counts), scale = scale_pca, center = center_pca)}
}
pca_1.2<-cbind(pca$x[,comp[1]],pca$x[,comp[2]])
if(!use_irlba){
sdev1<-round((pca$sdev[comp[1]]**2)/sum(pca$sdev **2)*100,2)
sdev2<-round((pca$sdev[comp[2]]**2)/sum(pca$sdev **2)*100,2)
}
pca_1.2 = data.table(pca_1.2)
names(pca_1.2) = paste0("PC",comp)
if(!is.null(color)){
pca_1.2[,color:=color[rownames(pca$x),]]
setnames(pca_1.2,"color",colnames(color))
color = colnames(color)
}
if(!is.null(size)){
pca_1.2[,size:=size[rownames(pca$x),]]
setnames(pca_1.2, "size", colnames(size))
size = colnames(size)
}
if(!is.null(shape)){
pca_1.2[,shape:=shape[rownames(pca$x),]]
setnames(pca_1.2, "shape", colnames(shape))
shape = colnames(shape)
}
p = generic_scatterplot(pca_1.2, x_col = paste0("PC",comp[1]), y_col = paste0("PC",comp[2]), color = color,
size = size, shape = shape, abs_size = abs_size, alpha = alpha)
if(use_irlba){p = p+ggtitle(title)} else {
p = p + xlab(paste("PC ",comp[1], " [",sdev1, "%]",sep="")) +
ylab(paste("PC ", comp[2], " [",sdev2, "%]",sep="")) + ggtitle(title)
}
if(return_pca){
return(list(plot = p, pca = pca))
} else{
return(p)
}
}
```
#### Visualize PC loadings
Input:
* pca: a prcomp object
* comp: which principal component to plot
```{r}
plot_pca_loadings = function(pca, comp = 1){
loading_dt = data.table(pca$rotation[,comp])
names(loading_dt) = "loading"
loading_dt[,gene_id:=rownames(pca$rotation)]
loading_dt = loading_dt[order(loading,decreasing=T)]
n = length(loading_dt$loading)
loading_dt = loading_dt[append(c(1:15),seq(n-15,n,1)),]
loading_dt$gene_id = factor(loading_dt$gene_id, levels = loading_dt$gene_id)
p = ggplot(loading_dt, aes(x=loading, y=gene_id))+
geom_point()+theme_bw()
return(p)
}
```
#### tSNE plot
Pretty much the same as the PCA plot function, but makes a tSNE map instead.
Input:
* counts: A matrix of log2 transformed, raw or normalized counts or a distance matrix. If a distance is used, is_distance has to be set to TRUE. If no values are provided, a pre-computed Rtsne object has to be provided instead.
* tsne: Rtsne object. A result from a previous tSNE calculation. If missing, a new tSNE is calculated.
* return_tsne: Logical. Should the Rtsne object be returned? If TRUE, the function returns a list with tsne = the Rtsne object and plot = the plot. If false, only the plot is returned as a ggplot2 object.
* is_distance: Logical. Is the input for Rtsne a distance matrix?
* scale_pca: Logical. Should the data be scaled to have unit variance? Default = FALSE.
* n_comp: Number of principal components used by tSNE.
* color, size and shape: Each a data.frame with one column containing the respective values to plot. For colors, numeric values are plotted on a continuous scale, factors as discrete colors. Note that the rownames of the data.frame have to be the same as the rownames of pca, but can be in any order. By default, the column name is used as a label for the color legend. The easiest way of setting any of those values is to use columns in the phenoData of your SCESet, e.g. colors = pData(sce)[,"cluster",drop=F].
* alpha: Between 0 and 1. Transparency of the plotted points.
* tite: Title of the plot.
* show_proportions: Logical. if the plot is colored by a dsicrete variable, should the proprtions of points per color be shown in the legend?
```{r}
my_plot_tSNE = function(counts=NULL,tsne=NULL,alpha = 0.7, color=NULL,abs_size = 2,
size=NULL,shape=NULL,return_tsne=F,is_distance=F,show_proportions=F,
n_comp = 50, scale_pca=F, use_irlba = F, title="tSNE"){
if(is.null(counts)&is.null(tsne)){
message('Please provide either a count matrix or pre-computed
tSNE map as an Rtsne object.')
} else if(is.null(tsne)){
if(use_irlba){
library(irlba)
if(packageDescription("irlba")$Version <= 2.3){
stop("Please update irlba to version 2.3.2 (github). There is a bug in versions < 2.3 which results in unreliable output.")
}
pca = prcomp_irlba(t(counts),n=n_comp,center=T,scale. = scale_pca)
rownames(pca$x) = colnames(counts)
tsne = Rtsne(pca$x,pca = F, initial_dims = n_comp, is_distance = F)
rownames(tsne$Y) = colnames(counts)
} else{
tsne<-Rtsne(t(counts),initial_dims=n_comp,pca=T,
is_distance=is_distance,pca_scale=scale_pca)
rownames(tsne$Y) = colnames(counts)
}
}
tsne_1.2 = data.table(tsne$Y)
names(tsne_1.2) = c("tSNE1","tSNE2")
if(!is.null(color)){
if(show_proportions){
if(is.numeric(color[[colnames(color)]])){stop("Proportions can only be calculated for discrete variables. Please provide your color scale as character or factor.")}
color[[colnames(color)]] = paste0(color[[colnames(color)]]," [",
round(calc_percentage(color[[colnames(color)]]),2),"%]")
}
tsne_1.2[,color:= color[rownames(tsne$Y),]]
setnames(tsne_1.2,"color",colnames(color))
color = colnames(color)
}
if(!is.null(size)){
tsne_1.2[,size:=size[rownames(tsne$Y),]]
setnames(tsne_1.2, "size", colnames(size))
size = colnames(size)
}
if(!is.null(shape)){
tsne_1.2[,shape:=shape[rownames(tsne$Y),]]
setnames(tsne_1.2, "shape", colnames(shape))
shape = colnames(shape)
}
p = generic_scatterplot(tsne_1.2, x_col = "tSNE1", y_col = "tSNE2", color = color,
size = size, shape = shape, abs_size = abs_size, alpha = alpha)
p = p+ggtitle(title)
if(return_tsne){
return(list(plot = p, tsne = tsne))
} else{
return(p)
}
}
```
#### Make a pairs plot
This function takes a matrix as input, plots each column against all other columns, makes a histogram for each column and calculates the correlations between all columns. Please don't try to plot more than 10 columns this way...
```{r}
make_pairs_plot = function(input_mat,main=""){
## puts histograms on the diagonal
panel.hist <- function(x, ...)
{
usr <- par("usr"); on.exit(par(usr))
par(usr = c(usr[1:2], 0, 1.5) )
h <- hist(x, plot = FALSE)
breaks <- h$breaks; nB <- length(breaks)
y <- h$counts; y <- y/max(y)
rect(breaks[-nB], 0, breaks[-1], y,
col = "lightgray", ...)
}
## put (absolute) correlations on the upper panels,
## with size proportional to the correlations.
panel.cor <- function(x, y, digits = 2,
prefix = "", cex.cor, ...)
{
usr <- par("usr"); on.exit(par(usr))
par(usr = c(0, 1, 0, 1))
r <- abs(cor(x, y,use="na.or.complete"))
txt <- format(c(r, 0.123456789), digits = digits)[1]
txt <- paste0(prefix, txt)
if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)
text(0.5, 0.5, txt, cex = cex.cor * r)
}
pairs(input_mat,upper.panel=panel.cor,diag.panel=panel.hist,main=main)
}
```
#### Plotting multiple ggplots on one page
The function is taken from the r-cookbook website and can be found [here](http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/)
```{r}
ggmultiplot = function(..., plotlist=NULL, file, cols=1, layout=NULL) {
library(grid)
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# If layout is NULL, then use 'cols' to determine layout
if (is.null(layout)) {
# Make the panel
# ncol: Number of columns of plots
# nrow: Number of rows needed, calculated from # of cols
layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
ncol = cols, nrow = ceiling(numPlots/cols))
}
if (numPlots==1) {
print(plots[[1]])
} else {
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
# Make each plot, in the correct location
for (i in 1:numPlots) {
# Get the i,j matrix positions of the regions that contain this subplot
matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))
}
}
}
```
## Session Info
```{r}
sessionInfo()
```
<file_sep>/README.md
# README #
### What is this repository for? ###
This repository contains a workflow for the analysis fo single-cell RNASeq data using R/bioconductor.
The main steps included are:
* Quality control
* Data normalization
* Feature selection
* Clustering
* Differential expression analysis
* Detection of rare cell subtypes with CellSIUS
* Visualization
[](https://zenodo.org/badge/latestdoi/189391647)
### How do I get set up? ###
Check the vignette (vignettes/workflow_vignette.html) for a detailed description. All code can be run directly form the R-Markdown document (vignettes/workflow_vignette.Rmd).
IMPORTANT: This workflow was built and tested using Bioconductor 3.5. Because some of the packages it uses (especially scater) changed between Bioconductor 3.5 and 3.6, currently, the only supported version is R3.4.1 with Bioconductor 3.5.
### Need help? ###
Please contact <NAME> [<EMAIL>](mailto:<EMAIL>) or <NAME> [<EMAIL>](mailto:<EMAIL>)
<file_sep>/example_data/example_setup.R
######################################################
# Setupfile for running SCDE on the PBMC example data
######################################################
library(scater) #needed to load the SCESets
#loading data
load("/da/dmp/cb/wegmare1/scRNASeq/data/example/output/sce_clean.RData")
load("/da/dmp/cb/wegmare1/scRNASeq/data/example/output/sce_info.RData")
# the count matrix
# Note that raw counts are required as input
counts = counts(sce_clean)
# the cell assignments as a named factor
# here, we collapse all the non-B-cells into a single group "Others",
# because scde cannot work with very small groups
groups = sce_info$hclust_eucl
levels(groups)[groups!="B-cell"] = "Others"
names(groups) = colnames(sce_info)
# directory to save output to
out_data_dir = "/da/dmp/cb/wegmare1/scRNASeq/data/example/output/"
# cores to use
ncores=8
# define list of groups to compare. Entries of this list are the
# identifier of the group you want to compare the rest against
diff_pair_list = list(
Bcell_vs_Rest = "B-cell"
)<file_sep>/code/marker_vis_app/app.R
library(data.table)
library(ggplot2)
# for testing purposes
# source("/da/dmp/cb/wegmare1/scRNASeq/workflow_devel/scRNASeq_workflow/code/scRNASeq_pipeline_functions.R")
# plot_dt = data.table(tSNE1 = c(1,2,3,4), tSNE2=c(1,2,3,4), col1 = c(1,1,1.5,2), col2 = c(1,1,1.5,2),factor = factor(c(1,1,2,2)))
ui <- fluidPage(
titlePanel("Marker gene expression"),
sidebarLayout(
sidebarPanel(
selectInput("color", label = "Choose marker:",
choices = as.list(names(plot_dt)[-c(1,2)]),
selected = names(plot_dt)[3]),
sliderInput("size", label = "Point size:",
min = 1, max = 10, value = 3),
sliderInput("alpha", label = "Transparency:",
min = 0.1, max = 1, value = 0.8),
selectInput("pal", label = "Color palette:",
choices = list('default', 'red-blue', 'heat'),
selected = 'default')
),
mainPanel(
h3(textOutput("selected_col")),
plotOutput("plot"))
)
)
# Define server logic ----
server <- function(input, output) {
output$selected_col <- renderText({
paste("tSNE map, colored by", input$color)
})
output$plot = renderPlot({
switch(input$pal,
'default' = generic_scatterplot(plot_dt,
x_col = "tSNE1",
y_col="tSNE2",
color = input$color,
abs_size = input$size,
alpha = input$alpha),
'red-blue' = generic_scatterplot(plot_dt,
x_col = "tSNE1",
y_col="tSNE2",
color = input$color,
abs_size = input$size,
alpha = input$alpha) + scale_color_distiller(palette='RdBu'),
'heat' = generic_scatterplot(plot_dt,
x_col = "tSNE1",
y_col="tSNE2",
color = input$color,
abs_size = input$size,
alpha = input$alpha) + scale_color_distiller(palette='RdYlBu')
)
})
}
# Run the app ----
shinyApp(ui = ui, server = server)<file_sep>/code/scrnaseq_workflow_Feature_Selection.R
#####################################################
#
# scRNASeq pipeline functions
#
# PART IV: Feature selection
# _______________________
#
# This script contains wrapper functions to different feature selection methods.
#
# Authors:
# <NAME> (<EMAIL>)
# <NAME> (<EMAIL>)
####################################################
#-----------------------------------------------
# LICENSE
#-----------------------------------------------
#Copyright 2018 Novartis Institutes for BioMedical Research 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 "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.
# limitations under the License.
###########################################
# Feature selection
###########################################
# Based on GO terms
#_____________________________
# go_id = a GO identifier, e.g. "GO:0007049"
# returns a list of ensembl gene identifiers annotated with this GO ID or one of its child terms
GO_to_gene = function(go_id, organism = "human"){
if(organism == "human"){
library(org.Hs.eg.db)
gene_eg = get(go_id,org.Hs.egGO2ALLEGS) # retrieve all entrez gene identifiers mapping to go_id
gene_ens = unlist(lapply(gene_eg, function(x) get(x,org.Hs.egENSEMBL))) #convert to ensembl
} else if(organism == "mouse"){
library(org.Mm.eg.db)
gene_eg = get(go_id,org.Mm.egGO2ALLEGS) # retrieve all entrez gene identifiers mapping to go_id
gene_ens = unlist(lapply(gene_eg, function(x) get(x,org.Mm.egENSEMBL))) #convert to ensembl
} else {stop("Organism has to be human or mouse.")}
return(gene_ens)
}
# Based on highly variable genes (Brennecke 2013)
#_______________________________
info.genes = function(x,PLOT=F,qcv=.3,pv=.05,q=.95,minBiolDisp=0.1, perc_genes = NULL){
if(!(is.null(perc_genes)|is.null(pv))){
stop("Please provide either pv or perc_genes, not both!")
}
library(statmod)
# calculate mean, variance and CV
means = rowMeans(x)
vars = (apply(x,1,var))
cv2 = vars/means^2
# exclude genes with very low mean
minMeanForFit = unname( quantile( means[ which( cv2 > qcv) ], q ) )#is the 95% of the means with a dispersion greter than 0.3
useForFit = means >= minMeanForFit
#fit model
fit = glmgam.fit( cbind( a0 = 1, a1tilde = 1/means[useForFit] ),cv2[useForFit] ) # linear fit
fit$coefficients
a0 = unname(fit$coefficients["a0"])
a1 = unname(fit$coefficients["a1tilde"]) #we assume xi = mean(technical size factors) = 0
minBiolDisp = minBiolDisp^2 #squared minimum biological variance
psia1theta = a1 # this is the term psi+a1*theta that appears in the formula for omega
# again, we assume that the technical sf = 0 and mean ratio of all size factors = 1
m = ncol(x)
cv2th = a0 + minBiolDisp + a0 * minBiolDisp #a0 adjusted for min biol variation
testDenom = ( means * psia1theta + means^2 * cv2th ) / ( 1 + cv2th/m ) #omega
pval = pchisq(vars*(m-1)/testDenom,df=m-1,lower.tail=F) #Chi^2 distribution
adj.pval = sort(p.adjust(pval,"fdr"))
if(!is.null(pv)){
info = adj.pval < pv
} else {
info = adj.pval < adj.pval[as.integer(perc_genes/100*length(adj.pval))]
}
if(PLOT){
if(min(means)<=0) ps = .1-min(means)
if(min(means)>0) ps = 0
xg = 10^(seq( min(log(means+ps)), max(log(means+ps)), length.out=5000 ))
vfit = a1/xg + a0 #estimated technical variation
vfit_biol = psia1theta/xg + a0 + minBiolDisp # expected total variation
xlabel = "log[ Average normalized read count]"
smoothScatter(log(means+ps),log(cv2),xlab=xlabel,ylab="log[ Squared coefficient of variation (CV^2)]")
points(log(means+ps),log(cv2),col="gray")
# lines(log(xg[which(vfit>0)]+ps), log(vfit[which(vfit>0)]), col="black", lwd=3,lty=2,ylim=range(cv2) )
lines(log(xg[which(vfit_biol>0)]+ps), log(vfit_biol[which(vfit_biol>0)]), col="black", lwd=3,ylim=range(cv2) )
lines(log(xg[which(vfit_biol>0)]+ps),log(vfit_biol[which(vfit_biol>0)] * qchisq(0.975,m-1)/(m-1)),lty=2,col="black")
lines(log(xg[which(vfit_biol>0)]+ps),log(vfit_biol[which(vfit_biol>0)] * qchisq(0.025,m-1)/(m-1)),lty=2,col="black")
points(log(means[names(which(info)[TRUE])]+ps),log(cv2[names(which(info)[TRUE])]),col=2,cex=.5)
}
return(info)
}
# M3Drop, using the two DANB based methods
#_______________________________________________
run_DANB = function(counts,save_plot=T,method="NBDrop",cutoff=NULL, perc_genes = NULL){
if((is.null(perc_genes)&is.null(cutoff))){
stop("Please provide exactly one of either cutoff or perc_genes")
}
if(!(is.null(perc_genes)|is.null(cutoff))){
stop("Please provide either cutoff or perc_genes, not both!")
}
library(M3Drop) #note that you require version > 2.0 (not on bioconductor yet)
if(!method%in%c("NBDrop","NBDisp")){
stop("Invalid method selected. Please choose one of \"NBDrop\", \"NBDisp\"")
}
# fitting the dropout model (DANB)
fit = NBumiFitModel(counts) #this fits a DANB model
fit$mus = t(sapply(fit$vals$tjs, function (x) x * fit$vals$tis/fit$vals$total))
size_coeffs = NBumiFitDispVsMean(fit, suppress.plot = T)#get coefcients of mean-dispersion fit
smoothed_size = exp(size_coeffs[1] + size_coeffs[2] * log(fit$vals$tjs/fit$vals$nc)) #predicted dispersions per gene
size_mat = matrix(rep(smoothed_size, times = fit$vals$nc), ncol = fit$vals$nc, byrow = FALSE)
exp_ps = (1 + fit$mus/size_mat)^(-size_mat) #these are the fitted values per cell and gene
exp_tot = rowSums(exp_ps) #this is the total predicted molecules per gene
plot_dt = data.table(Dropout_rate = fit$vals$djs/fit$vals$nc,
expression = fit$vals$tjs/fit$vals$nc,
sizes = fit$sizes,
pred_sizes = smoothed_size,
predicted_dropouts=exp_tot/fit$vals$nc)
if(method=="NBDrop"){
NBumiCheckFitFS(counts,fit,suppress.plot = T) #check whether the fitted droout rates are well correlated with observed ones (i.e. number of zeroes)
pvals = NBumiFeatureSelectionCombinedDrop(fit) #ranks genes by difference from expected dropout rates
if(is.null(cutoff)){ cutoff = sort(pvals)[as.integer(perc_genes/100*length(pvals))]}
info = rownames(counts)%in%names(pvals[which(pvals<cutoff)]) #select the top features based on dropout rates
plot_dt[,info:=info]
p = ggplot(plot_dt,aes(x=log10(expression),y=Dropout_rate)) +
geom_point(aes(color=info),alpha=0.7,size=2) +
geom_line(aes(x=log10(expression),y=predicted_dropouts),color=colors()[30],size=1.2)+
theme_bw() + xlab("Expression [log10]") + ylab("Dropout Rate")+
ggtitle("Dropout rate vs. Expression")+ theme(text = element_text(size=17))+
scale_color_manual(values = colors()[c(226,32)],name="is_outlier")
print(p)
if(save_plot){
ggsave(p,file=file.path(plotdir,"NBdrop_plot.pdf"),height=6,width=8)
}
} else {
resids = NBumiFeatureSelectionHighVar(fit) #ranks genes by difference from fitted mean-dispersion power law
if(is.null(cutoff)){cutoff = perc_genes/100}
info = rownames(counts)%in%names(resids[which(resids<quantile(resids,cutoff))])
plot_dt[,info:=info]
plot_dt[,est_cv2:=(1+expression/sizes)/expression] #predicted variance according to DANB model
plot_dt[,ave_cv2:=(1+expression/pred_sizes)/expression] #predicted variance according to linear fit of dispersions
p = ggplot(plot_dt,aes(x=log10(expression),y=log10(est_cv2))) +
geom_point(aes(color=info),alpha=0.7,size=2) +
geom_line(aes(x=log10(expression),y=log10(ave_cv2)),color=colors()[30],size=1.2)+
theme_bw() + xlab("Expression [log10]") + ylab("Estimated CV^2 [log10]")+
ggtitle("Mean - Dispersion Relationship")+ theme(text = element_text(size=17))+
scale_color_manual(values = colors()[c(226,32)],name="is_outlier")
print(p)
if(save_plot){
ggsave(p,file=file.path(plotdir,"NBdisp_plot.pdf"),height=6,width=8)
}
}
return(info)
}
<file_sep>/code/scrnaseq_workflow_Plotting.R
#####################################################
#
# scRNASeq pipeline functions
#
# Plotting and dimensionality reduction
# _______________________
#
# This script contains helper functions to make PCA and tSNE plots, some other miscellaneous ggplot-wrappers and modified versions of some SC3 and scater plotting functions.
#
# Authors:
# <NAME> (<EMAIL>)
# <NAME> (<EMAIL>)
####################################################
##############################
# General dimensionality reduction and plotting
#############################
#plot PCA. Need to submit either the counts or a pre-calculated PCA
my_plot_PCA = function(counts=NULL,pca=NULL, alpha = 0.7, scale_pca = T, center_pca=T,comp=c(1,2),
color=NULL,size=NULL,shape=NULL,return_pca=F,title="PCA",abs_size=2, use_irlba=F){
if(is.null(counts)&is.null(pca)){
message('Please provide either a count matrix or pre-computed
principal component analysis as a prcomp object.')
} else if(is.null(pca)){
if(use_irlba){
library(irlba)
if(packageDescription("irlba")$Version <= 2.3){
stop("Please update irlba to version 2.3.2 (github). There is a bug in versions < 2.3 which results in unreliable output.")
}
pca = prcomp_irlba(t(counts),n=max(comp),center=center_pca,scale. = scale_pca)
rownames(pca$x) = colnames(counts)} else{
pca<-prcomp(t(counts), scale = scale_pca, center = center_pca)}
}
pca_1.2<-cbind(pca$x[,comp[1]],pca$x[,comp[2]])
if(!use_irlba){
sdev1<-round((pca$sdev[comp[1]]**2)/sum(pca$sdev **2)*100,2)
sdev2<-round((pca$sdev[comp[2]]**2)/sum(pca$sdev **2)*100,2)
}
pca_1.2 = data.table(pca_1.2)
names(pca_1.2) = paste0("PC",comp)
if(!is.null(color)){
pca_1.2[,color:=color[rownames(pca$x),]]
setnames(pca_1.2,"color",colnames(color))
color = colnames(color)
}
if(!is.null(size)){
pca_1.2[,size:=size[rownames(pca$x),]]
setnames(pca_1.2, "size", colnames(size))
size = colnames(size)
}
if(!is.null(shape)){
pca_1.2[,shape:=shape[rownames(pca$x),]]
setnames(pca_1.2, "shape", colnames(shape))
shape = colnames(shape)
}
p = generic_scatterplot(pca_1.2, x_col = paste0("PC",comp[1]), y_col = paste0("PC",comp[2]), color = color,
size = size, shape = shape, abs_size = abs_size, alpha = alpha)
if(use_irlba){p = p+ggtitle(title)} else {
p = p + xlab(paste("PC ",comp[1], " [",sdev1, "%]",sep="")) +
ylab(paste("PC ", comp[2], " [",sdev2, "%]",sep="")) + ggtitle(title)
}
if(return_pca){
return(list(plot = p, pca = pca))
} else{
return(p)
}
}
# Visualize the top PC loadings
plot_pca_loadings = function(pca, comp = 1){
loading_dt = data.table(pca$rotation[,comp])
names(loading_dt) = "loading"
loading_dt[,gene_id:=rownames(pca$rotation)]
loading_dt = loading_dt[order(loading,decreasing=T)]
n = length(loading_dt$loading)
loading_dt = loading_dt[append(c(1:15),seq(n-15,n,1)),]
loading_dt$gene_id = factor(loading_dt$gene_id, levels = loading_dt$gene_id)
p = ggplot(loading_dt, aes(x=loading, y=gene_id))+
geom_point()+theme_bw()
return(p)
}
#plot tSNE. Need to submit either the counts or a pre-calculated Rtsne object
# note thet for discrete color labels, the colors argument must be a factor
my_plot_tSNE = function(counts=NULL,tsne=NULL,alpha = 0.7, color=NULL,abs_size = 2,
size=NULL,shape=NULL,return_tsne=F,is_distance=F,show_proportions=F,
n_comp = 50, scale_pca=F, use_irlba = F, title="tSNE"){
if(is.null(counts)&is.null(tsne)){
message('Please provide either a count matrix or pre-computed
tSNE map as an Rtsne object.')
} else if(is.null(tsne)){
if(use_irlba){
library(irlba)
if(packageDescription("irlba")$Version <= 2.3){
stop("Please update irlba to version 2.3.2 (github). There is a bug in versions < 2.3 which results in unreliable output.")
}
pca = prcomp_irlba(t(counts),n=n_comp,center=T,scale. = scale_pca)
rownames(pca$x) = colnames(counts)
tsne = Rtsne(pca$x,pca = F, initial_dims = n_comp, is_distance = F)
rownames(tsne$Y) = colnames(counts)
} else{
tsne<-Rtsne(t(counts),initial_dims=n_comp,pca=T,
is_distance=is_distance,pca_scale=scale_pca)
rownames(tsne$Y) = colnames(counts)
}
}
tsne_1.2 = data.table(tsne$Y)
names(tsne_1.2) = c("tSNE1","tSNE2")
if(!is.null(color)){
if(show_proportions){
if(is.numeric(color[[colnames(color)]])){stop("Proportions can only be calculated for discrete variables. Please provide your color scale as character or factor.")}
color[[colnames(color)]] = paste0(color[[colnames(color)]]," [",
round(calc_percentage(color[[colnames(color)]]),2),"%]")
}
tsne_1.2[,color:= color[rownames(tsne$Y),]]
setnames(tsne_1.2,"color",colnames(color))
color = colnames(color)
}
if(!is.null(size)){
tsne_1.2[,size:=size[rownames(tsne$Y),]]
setnames(tsne_1.2, "size", colnames(size))
size = colnames(size)
}
if(!is.null(shape)){
tsne_1.2[,shape:=shape[rownames(tsne$Y),]]
setnames(tsne_1.2, "shape", colnames(shape))
shape = colnames(shape)
}
p = generic_scatterplot(tsne_1.2, x_col = "tSNE1", y_col = "tSNE2", color = color,
size = size, shape = shape, abs_size = abs_size, alpha = alpha)
p = p+ggtitle(title)
if(return_tsne){
return(list(plot = p, tsne = tsne))
} else{
return(p)
}
}
# Convenience function to calculate percentages of a vector of discrete variables
calc_percentage = function(x){
perc = table(x)/sum(table(x))*100
idx = sapply(x, function(x) which(names(perc)==x))
return(as.numeric(perc[idx]))
}
# Putting multiple ggplots on one image
# The function is from here: http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/
ggmultiplot = function(..., plotlist=NULL, file, cols=1, layout=NULL) {
library(grid)
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# If layout is NULL, then use 'cols' to determine layout
if (is.null(layout)) {
# Make the panel
# ncol: Number of columns of plots
# nrow: Number of rows needed, calculated from # of cols
layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
ncol = cols, nrow = ceiling(numPlots/cols))
}
if (numPlots==1) {
print(plots[[1]])
} else {
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
# Make each plot, in the correct location
for (i in 1:numPlots) {
# Get the i,j matrix positions of the regions that contain this subplot
matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))
}
}
}
#_________________________________________________
# Make a pairs plot (e.g. to compare size factors)
# Input:
# - input_mat = a matrix of columns that you want to plot against each other
#
make_pairs_plot = function(input_mat,main=""){
## puts histograms on the diagonal
panel.hist <- function(x, ...)
{
usr <- par("usr"); on.exit(par(usr))
par(usr = c(usr[1:2], 0, 1.5) )
h <- hist(x, plot = FALSE)
breaks <- h$breaks; nB <- length(breaks)
y <- h$counts; y <- y/max(y)
rect(breaks[-nB], 0, breaks[-1], y,
col = "lightgray", ...)
}
## put (absolute) correlations on the upper panels,
## with size proportional to the correlations.
panel.cor <- function(x, y, digits = 2,
prefix = "", cex.cor, ...)
{
usr <- par("usr"); on.exit(par(usr))
par(usr = c(0, 1, 0, 1))
r <- abs(cor(x, y,use="na.or.complete"))
txt <- format(c(r, 0.123456789), digits = digits)[1]
txt <- paste0(prefix, txt)
if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)
text(0.5, 0.5, txt, cex = cex.cor * r)
}
pairs(input_mat,upper.panel=panel.cor,diag.panel=panel.hist,main=main)
}
# Generic scatterplot using data.table and ggplot2
#__________________________________
# Convenience function to plot 2 columns of a data.table against each other
# dt = data table
# x_col = name of the column to lot on x axis
# y_col = name of column to plot on y axis
# color = name of column to use as color values. If numeric, a continuous color scheme will be applied, if character or factor, colors will be discrete.
# shape = name of column to use for shape
# size = name of column to use for size
# alpha = transparency
generic_scatterplot = function(dt, x_col, y_col,
color = NULL, shape = NULL, size = NULL, alpha = 0.8, abs_size = 2){
plot_dt = dt[,c(x_col,y_col),with=F]
#by default, do not show any legends
show_col = F
show_shape = F
show_size = F
continuous = F
discrete = F
if(!is.null(color)){
plot_dt[,c(color):=dt[[color]]]
if(!is.numeric(dt[[color]])){
show_col = guide_legend(color)
discrete = T
} else{
show_col = guide_colorbar(color)
continuous = T
}
} else {
color = "dummy_color"
plot_dt[,dummy_color:=factor(1)]
}
if(!is.null(shape)){
show_shape = guide_legend(shape)
plot_dt[,c(shape):=dt[[shape]]]
} else {
shape = "dummy_shape"
plot_dt[,dummy_shape:=factor(1)]
}
if(!is.null(size)){
show_size = guide_legend(size)
plot_dt[,c(size):=dt[[size]]]
} else {
size ="dummy_size"
plot_dt[,dummy_size:= 1]
}
p = ggplot(na.omit(plot_dt), aes_string(x=paste0("`",x_col,"`"),y=paste0("`",y_col,"`")))
if(size == "dummy_size"){
p = p+geom_point(aes_string(color=paste0("`",color,"`"),
shape=paste0("`",shape,"`"),
size=paste0("`",size,"`")),
alpha=alpha,size=abs_size)
} else{
p = p+ geom_point(aes_string(color=paste0("`",color,"`"),
shape=paste0("`",shape,"`"),
size=paste0("`",size,"`")),
alpha=alpha)}
p = p + guides(color = show_col, shape = show_shape, size = show_size)+
theme_bw()+theme(text=element_text(size=15))
if(continuous){
p = p+scale_color_continuous(low = "lightgray", high = "darkblue")
}
if(discrete){
if(length(unique(na.omit(plot_dt[[color]])))==2){
p = p+scale_color_manual(values = c("lightgray","darkred"))
} else{p = p + scale_color_brewer(type = "qual",palette = 2)}
}
if(color == "dummy_color"){
p = p + scale_color_manual(values = "darkgrey")
}
if(shape!="dummy_shape"){
if(length(unique(na.omit(plot_dt[[shape]])))>9) {stop("Too many different shapes provided. Please provide a maximum of 9 shapes, otherwise, your plot will be a mess.")}
p = p + scale_shape_manual(values = c(15,16,17,18,8,0,1,2,3))
}
return(p)
}
# The following functions are modified from scater / SC3
# Custom plotHighest expression
# This function is a modified version of the plotHighestExpression function from scater
custom_plotHighestExprs = function (object, col_by_variable = "total_features", n = 50,
drop_features = NULL, exprs_values = "counts", feature_names_to_plot = NULL
)
{
if (!(col_by_variable %in% colnames(pData(object)))) {
warning("col_by_variable not found in pData(object).\\n Please make sure pData(object)[, variable] exists. Colours will not be plotted.")
plot_cols <- FALSE
}
else plot_cols <- TRUE
x <- pData(object)[, col_by_variable]
typeof_x <- scater:::.getTypeOfVariable(object, col_by_variable)
if (!(is.null(drop_features) | length(drop_features) == 0)) {
if (is.character(drop_features))
drop_features <- which(rownames(object) %in% drop_features)
if (is.logical(drop_features))
object <- object[!drop_features, ]
else object <- object[-drop_features, ]
}
if (!is.null(fData(object)$is_feature_control))
object <- calculateQCMetrics(object, feature_controls = fData(object)$is_feature_control)
else object <- calculateQCMetrics(object)
exprs_values <- match.arg(exprs_values, c("exprs", "tpm",
"cpm", "fpkm", "counts"))
exprs_mat <- get_exprs(object, exprs_values)
if (is.null(exprs_mat) && !is.null(counts(object))) {
exprs_mat <- counts(object)
message("Using counts as expression values.")
exprs_values <- "counts"
}
else if (is.null(exprs_mat)) {
exprs_mat <- exprs(object)
message("Using exprs(object) values as expression values.")
exprs_values <- "exprs"
}
if (exprs_values == "exprs")
exprs_mat <- 2^exprs_mat - object@logExprsOffset
fdata <- fData(object)
# if (paste0("total_feature_", exprs_values) %in% colnames(fdata))
# oo <- order(fdata[[paste0("total_feature_", exprs_values)]],
# decreasing = TRUE)
# else {
# if ("total_feature_counts" %in% colnames(fdata)) {
# oo <- order(fdata[["total_feature_counts"]], decreasing = TRUE)
# exprs_values <- "counts"
# message("Using counts to order total expression of features.")
# }
# else {
# exprs_values <- "exprs"
# oo <- order(fdata[["total_feature_exprs"]], decreasing = TRUE)
# message("Using 'exprs' to order total expression of features.")
# }
# }
oo <- order(fdata[["total_feature_counts"]],decreasing=T)
fdata$mean = log2(fdata[["total_feature_counts"]]/dim(object)[2])
if (is.null(feature_names_to_plot) || is.null(fData(object)[[feature_names_to_plot]]))
fdata$feature <- factor(featureNames(object), levels = featureNames(object)[rev(oo)])
else fdata$feature <- factor(fData(object)[[feature_names_to_plot]],
levels = fData(object)[[feature_names_to_plot]][rev(oo)])
fdata$Feature <- fdata$feature
if (is.null(fdata$is_feature_control))
fdata$is_feature_control <- rep(FALSE, nrow(fdata))
total_exprs <- sum(exprs_mat)
total_feature_exprs <- fdata[[paste0("total_feature_", exprs_values)]]
top50_pctage <- 100 * sum(total_feature_exprs[oo[1:n]])/total_exprs
df_pct_exprs_by_cell <-log2(t(exprs_mat[oo[1:n], ]+1))
df_pct_exprs_by_cell_long <- reshape2::melt(df_pct_exprs_by_cell)
df_pct_exprs_by_cell_long$Feature <- fdata[as.character(df_pct_exprs_by_cell_long$Var2),
"feature"]
df_pct_exprs_by_cell_long$Var2 <- factor(df_pct_exprs_by_cell_long$Var2,
levels = rownames(object)[rev(oo[1:n])])
df_pct_exprs_by_cell_long$Feature <- factor(df_pct_exprs_by_cell_long$Feature,
levels = fdata$feature[rev(oo[1:n])])
if (typeof_x == "discrete")
df_pct_exprs_by_cell_long$colour_by <- factor(x)
else df_pct_exprs_by_cell_long$colour_by <- x
plot_most_expressed <- ggplot(df_pct_exprs_by_cell_long,
aes_string(y = "Feature", x = "value", colour = "colour_by")) +
geom_point(alpha = 0.6, shape = 124) + ggtitle(paste0("Top ",
n, " account for ", format(top50_pctage, digits = 3),
"% of total")) + ylab("Feature") + xlab("log2(counts+1)") +
theme_bw(8) + theme(legend.position = c(1,
0), legend.justification = c(1, 0), axis.text.x = element_text(colour = "gray35"),
axis.text.y = element_text(colour = "gray35"), axis.title.x = element_text(colour = "gray35"),
axis.title.y = element_text(colour = "gray35"), title = element_text(colour = "gray35"))
if (typeof_x == "discrete") {
plot_most_expressed <- scater:::.resolve_plot_colours(plot_most_expressed,
df_pct_exprs_by_cell_long$colour_by, col_by_variable)
}
else {
plot_most_expressed <- plot_most_expressed + scale_colour_gradient(name = col_by_variable,
low = "lightgoldenrod", high = "firebrick4", space = "Lab")
}
plot_most_expressed + geom_point(aes_string(x = "mean",
y = "Feature", fill = "is_feature_control"),
data = fdata[oo[1:n], ], colour = "gray30", shape = 21) +
scale_fill_manual(values = c("aliceblue", "wheat")) +
guides(fill = guide_legend(title = "Feature control?"))
}
# Function to launch the marker_vis shiny app (pre-alpha version and very buggy...)
launch_marker_vis_app = function(tsne,sce,marker_idx){
plot_dt = data.table(tSNE1=tsne$Y[,1],tSNE2=tsne$Y[,2],
t(norm_exprs(sce)[marker_idx,,drop=F]))
names(plot_dt)[-c(1,2)] = fData(sce)$symbol[marker_idx]
assign("plot_dt",plot_dt,.GlobalEnv)
runApp(file.path(code_dir,'marker_vis_app'))
}
## Custom version of the sc3_plot_markers function, taken from the SC3 package
custom_sc3_plot_markers = function (object, k, auroc = 0.85, p.val = 0.01, show_pdata = NULL, order_dend = F)
{
if (is.null(object@sc3$consensus)) {
warning(paste0("Please run sc3_consensus() first!"))
return(object)
}
if(order_dend){
hc <- object@sc3$consensus[[as.character(k)]]$hc
}
dataset <- get_processed_dataset(object)
if (!is.null(object@sc3$svm_train_inds)) {
dataset <- dataset[, object@sc3$svm_train_inds]
}
add_ann_col <- FALSE
ann <- NULL
if (!is.null(show_pdata)) {
ann <- SC3:::make_col_ann_for_heatmaps(object, show_pdata)
if (!is.null(ann)) {
add_ann_col <- TRUE
rownames(ann) <- colnames(dataset)
}
}
markers <- SC3:::organise_marker_genes(object, k, p.val, auroc)
markers <- SC3:::markers_for_heatmap(markers)
row.ann <- data.frame(Cluster = factor(markers[, 1], levels = unique(markers[,
1])))
if(order_dend){
order = hc$order
} else { order = order(object[[paste('sc3',k,'clusters',sep='_')]])}
groups = object[[paste('sc3',k,'clusters',sep='_')]][order]
gaps = sapply(unique(groups), function(y) max(which(groups==y)))
rownames(row.ann) <- rownames(markers)
do.call(pheatmap::pheatmap, c(list(dataset[rownames(markers), order,
drop = FALSE], show_colnames = FALSE, cluster_rows = FALSE,
cluster_cols = FALSE, gaps_col = gaps,
annotation_row = row.ann,
annotation_names_row = FALSE, gaps_row = which(diff(markers[,
1]) != 0), cellheight = 10), list(annotation_col = ann)[add_ann_col]))
}
|
9c4f90c130dba8c3425055795236d3471716534e
|
[
"RMarkdown",
"Markdown",
"R"
] | 14 |
RMarkdown
|
yangchuhua/scRNAseq_workflow_benchmark
|
1137a0c57fa0f2705a308acd15c555c9ae1d88d8
|
f79201ebd4c4720bdd82b95c32f4026c77cc87e4
|
refs/heads/master
|
<repo_name>runeanielsen/nixos-dotfiles<file_sep>/README.md
# NIX-OS
Currently just playing around in a VM.
<file_sep>/configuration.nix
# Edit this configuration file to define what should be installed on
# your system. Help is available in the configuration.nix(5) man page
# and in the NixOS manual (accessible by running ‘nixos-help’).
{ config, pkgs, options, ... }:
{
imports =
[ # Include the results of the hardware scan.
./hardware-configuration.nix
(import "${builtins.fetchTarball https://github.com/rycee/home-manager/archive/master.tar.gz}/nixos")
];
services.xserver = {
enable = true;
layout = "us";
desktopManager = {
xterm.enable = true;
};
windowManager.xmonad = {
enable = true;
};
};
home-manager.users.notation = { pkgs, ... }: {
programs.git = {
enable = true;
userName = "<NAME>";
userEmail = "<EMAIL>";
};
};
# Use the GRUB 2 boot loader.
boot.loader.grub.enable = true;
boot.loader.grub.version = 2;
# Define on which hard drive you want to install Grub.
boot.loader.grub.device = "/dev/sda"; # or "nodev" for efi only
networking.hostName = "freeprogrammer"; # Define your hostname.
# networking.wireless.enable = true; # Enables wireless support via wpa_supplicant.
# The global useDHCP flag is deprecated, therefore explicitly set to false here.
# Per-interface useDHCP will be mandatory in the future, so this generated config
# replicates the default behaviour.
networking.useDHCP = false;
networking.interfaces.enp0s3.useDHCP = true;
# Select internationalisation properties.
i18n.defaultLocale = "en_US.UTF-8";
console = {
font = "Lat2-Terminus16";
keyMap = "us";
};
# Set your time zone.
time.timeZone = "Europe/Copenhagen";
# Add custom packages
# nixpkgs.overlays = import ./packages;
nixpkgs.config.allowUnfree = true;
# List packages installed in system profile. To search, run:
# $ nix search wget
environment.systemPackages = with pkgs; [
# Standard
xclip
firefox
wget
vim
coreutils
git
unzip
sshfs
gnumake
];
# Some programs need SUID wrappers, can be configured further or are
# started in user sessions.
programs.mtr.enable = true;
programs.gnupg.agent = {
enable = true;
enableSSHSupport = true;
};
# List services that you want to enable:
# Enable the OpenSSH daemon.
services.openssh.enable = true;
# Enable sound.
sound.enable = true;
hardware.pulseaudio.enable = true;
# Enable touchpad support.
services.xserver.libinput.enable = true;
# Define a user account. Don't forget to set a password with ‘<PASSWORD>’.
users.users.notation = {
isNormalUser = true;
extraGroups = [ "wheel" "video" "networkmanager" ]; # Enable ‘sudo’ for the user.
};
# This value determines the NixOS release from which the default
# settings for stateful data, like file locations and database versions
# on your system were taken. It‘s perfectly fine and recommended to leave
# this value at the release version of the first install of this system.
# Before changing this value read the documentation for this option
# (e.g. man configuration.nix or on https://nixos.org/nixos/options.html).
system.stateVersion = "20.03"; # Did you read the comment?
}
|
53321a5dd7bff62e13ec22c2d9830ec51fd49738
|
[
"Markdown",
"Nix"
] | 2 |
Markdown
|
runeanielsen/nixos-dotfiles
|
a6e3b430608859aca9fb5b2acaf52203afa4572f
|
3bbc9392bd5b0387225cfa65f208acfae1d59626
|
refs/heads/master
|
<file_sep># WeaTodo
A practice weather lookup and to do list app
<a href="url"><img src="https://github.com/Kab777/WeaTodo/blob/master/device-2016-03-02-214403.png" align="left" height="500" width="300" ></a>
<a href="url"><img src="https://github.com/Kab777/WeaTodo/blob/master/device-2016-03-02-214456.png" align="left" height="500" width="300" ></a>
<file_sep>package com.example.junyu.hmw2;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class Weather extends AppCompatActivity {
private ArrayList<String> to_do_list;
private ArrayAdapter<String> adapter;
// String base = "http://api.openweathermap.org/data/2.5/weather?q=";
// String cyname = "Waterloo,Ca";
// String tail = "&units=metric&appid=44db6a862fba0b067b1930da0d769e98";
//String url = "http://api.openweathermap.org/data/2.5/weather?q=Waterloo,Ca&units=metric&appid=44db6a862fba0b067b1930da0d769e98";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
}
public void GetWeather(View view) {
String base = "http://api.openweathermap.org/data/2.5/weather?q=";
String cyname = "Waterloo,Ca";
String tail = "&units=metric&appid=44db6a862fba0b067b1930da0d769e98";
final TextView cname = (TextView)findViewById(R.id.cityname);
final TextView Temper = (TextView)findViewById(R.id.Tem);
final TextView Status = (TextView)findViewById(R.id.Status);
EditText input = (EditText) findViewById(R.id.Input);
String url = base + cyname + tail;
String uin = input.getText().toString();
Log.v("beizi", uin);
if(uin != null && !uin.isEmpty()){
url = base + uin + tail;
}else{
url = base + cyname + tail;
}
Log.v("beizi", url);
Ion.with(this)
.load(url)
.asString()
.setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
try{
JSONObject data = new JSONObject(result);
JSONObject main = data.getJSONObject("main");
JSONArray sts = data.getJSONArray("weather");
String my_status = sts.getJSONObject(0).getString("main");
String name=data.getString("name");
String s = main.getString("temp");
String celcus = " \u2103";
s = s + celcus;
cname.setText(name);
Temper.setText(s);
Status.setText(my_status);
Log.v("beizi", name);
Log.v("beizi", result);
Log.v("beizi",s);
Log.v("beizi", my_status);
}catch (JSONException ie){
ie.printStackTrace();
}
}
});
}
}
<file_sep>package com.example.junyu.hmw2;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class Adding_List extends AppCompatActivity {
private ArrayList<String> to_do_list;
private ArrayAdapter<String> adapter;
final static private String filename = "lists.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding__list);
to_do_list = new ArrayList<String>();
ListView my_item = (ListView)findViewById(R.id.my_list_item);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,to_do_list);
my_item.setAdapter(adapter);
readFile();
my_item.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
ListView future_list = (ListView) findViewById(R.id.my_list_item);
String pos = future_list.getItemAtPosition(position).toString();
//removeFromFile(to_do_list.get(position));
to_do_list.remove(position);
adapter.notifyDataSetChanged();
return true;
}
});
}
public void Add_Item(View view) {
EditText new_item = (EditText) findViewById(R.id.input_list);
String new_iem = new_item.getText().toString();
if (new_iem == null) {
return;
} else {
to_do_list.add(new_iem);
}
new_item.setText("");
adapter.notifyDataSetChanged();
}
@Override
protected void onPause() {
super.onPause();
try{
// rewrite the file based on current to_do_list
PrintStream output = new PrintStream(openFileOutput(filename, MODE_PRIVATE));
for(String s:to_do_list){
output.println(s);
}
output.close();
}catch (Exception e){
Log.wtf("update file failed", e);
}
}
@Override
protected void onResume() {
super.onResume();
readFile();
}
public void goback(View view) {
Intent intent = new Intent();
finish();
}
// clear todolist, then read all items from file, and update adapter
private void readFile(){
to_do_list.clear();
try{
Scanner scan = new Scanner(openFileInput(filename));
while (scan.hasNextLine()){
String line = scan.nextLine();
to_do_list.add(line);
}
scan.close();
adapter.notifyDataSetChanged();
}catch (Exception e){
Log.wtf("raed file failed", e);
}
}
}
|
5f93455357878f4b2fb9c442f06210b184640319
|
[
"Java",
"Markdown"
] | 3 |
Java
|
Kab777/WeaTodo
|
8753af97369edf2ba86d41cfab65d4f4e6cbf5b0
|
0620de66b38d0553b224f64dbc01df2dac8e1f8f
|
refs/heads/master
|
<repo_name>skrumblenetwork/skm-token-bridge-ui<file_sep>/README.md
# skm-token-bridge-ui
|
574e0ba9102a1e2975879da6125433250e72ef73
|
[
"Markdown"
] | 1 |
Markdown
|
skrumblenetwork/skm-token-bridge-ui
|
bb40072214a5785048f899ab638ac42e0ea43166
|
2ac8a1b31f574cf1b982f6d887bd1ba72e2071ba
|
refs/heads/main
|
<file_sep>from django.urls import path
from blog.views import my_test_view, my_first_page, main_feed, get_post
urlpatterns = [
path('test/', my_test_view),
path('page/', my_first_page),
path('list/', main_feed),
path('post/<int:post_id>/', get_post)
]
<file_sep>from django.shortcuts import render
from django.http.response import HttpResponse
from blog.models import Post
# Create your views here.
def my_test_view(request):
return HttpResponse('Some text')
def my_first_page(request):
return render(request, 'index.html', {
'my_param': 'My text',
'my_param2': 'TEXT'
})
def main_feed(request):
max_posts_on_page = 10
page = int(request.GET.get('page', 1))
start_item = (page-1) * max_posts_on_page
end_item = start_item + max_posts_on_page
posts = Post.objects.all()[start_item:end_item]
return render(request, 'feed.html', {
'posts_list': posts,
})
def get_post(request, post_id):
post = Post.objects.get(id=post_id)
return render(request, 'page.html', {
'post': post
})
<file_sep>from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Category(models.Model):
class Meta:
db_table = 'categories'
verbose_name = 'Category'
verbose_name_plural = 'Categories'
title = models.CharField(verbose_name='Title', max_length=200, blank=False, null=False)
def __str__(self):
return self.title
class Post(models.Model):
class Meta:
db_table = 'posts'
verbose_name = 'Post'
verbose_name_plural = 'Posts'
user = models.ForeignKey(User, verbose_name='Owner', on_delete=models.CASCADE)
title = models.CharField(verbose_name='Title', max_length=200, blank=False, null=False)
content = models.TextField(verbose_name='Content', blank=False, null=False)
time_created = models.DateTimeField(verbose_name='Created time', auto_now_add=True)
category = models.ForeignKey(Category, verbose_name='Category', on_delete=models.CASCADE, blank=True, null=True)
photo = models.ImageField(upload_to='images', null=True, blank=True)
|
aea31cdc6eb8f046958be9a47a87483a5f88befd
|
[
"Python"
] | 3 |
Python
|
6048566/pasv-blog
|
c4ec952be3d53721d3056671719ab20d68b51c5a
|
a1be45c6e81baee264c6a3472d152f0f5c38803d
|
refs/heads/master
|
<file_sep>package com.omnidexter.test.damage;
import org.junit.Test;
import com.omnidex.ability.Ability;
import com.omnidex.damage.StatusDamage;
import com.omnidex.pokemon.ActivePokemon;
import com.omnidex.pokemon.Species;
import static org.junit.Assert.*;
public class StatusDamageTest {
/**
* Test of applyStatusDamage method, of class StatusDamage.
*/
@Test
public void testApplyStatusDamage_RegPoison() {
System.out.println("applyStatusDamage reg poison");
ActivePokemon poke = new ActivePokemon(Species.QUAGSIRE);
poke.setHpEv(252);
poke.setRegPoison();
StatusDamage.applyStatusDamage(poke);
assertEquals(345, poke.getCurrHp());
}
/**
* Test of applyStatusDamage method, of class StatusDamage.
*/
@Test
public void testApplyStatusDamage_ToxPoison() {
System.out.println("applyStatusDamage toxic Poison for 2 turns");
ActivePokemon poke = new ActivePokemon(Species.QUAGSIRE);
poke.setHpEv(252);
poke.setToxPoison();
assertEquals(394, poke.getCurrHp());
StatusDamage.applyStatusDamage(poke);
assertEquals(370, poke.getCurrHp());
StatusDamage.applyStatusDamage(poke);
assertEquals(321, poke.getCurrHp());
}
/**
* Test of applyStatusDamage method, of class StatusDamage.
*/
@Test
public void testApplyStatusDamage_ToxPoison_Poison_Heal() {
System.out.println("applyStatusDamage toxic Poison turn 2");
ActivePokemon poke = new ActivePokemon(Species.BRELOOM);
poke.setAbility(Ability.POISON_HEAL);
poke.setHpEv(252);
poke.setToxPoison();
StatusDamage.applyStatusDamage(poke);
assertEquals(324, poke.getCurrHp());
}
/**
* Test of applyStatusDamage method, of class StatusDamage.
*/
@Test
public void testApplyStatusDamage_RegPoison_Poison_Heal() {
System.out.println("applyStatusDamage toxic Poison turn 2");
ActivePokemon poke = new ActivePokemon(Species.BRELOOM);
poke.setAbility(Ability.POISON_HEAL);
poke.setHpEv(252);
poke.setRegPoison();
StatusDamage.applyStatusDamage(poke);
assertEquals(324, poke.getCurrHp());
}
/**
* Test of applyStatusDamage method, of class StatusDamage.
*/
@Test
public void testApplyStatusDamage_Burn_Poison_Heal() {
System.out.println("applyStatusDamage burn w/ poison heal");
ActivePokemon poke = new ActivePokemon(Species.BRELOOM);
poke.setAbility(Ability.POISON_HEAL);
poke.setHpEv(252);
poke.setBurnt();
StatusDamage.applyStatusDamage(poke);
assertEquals(284, poke.getCurrHp());
}
/**
* Test of applyStatusDamage method, of class StatusDamage.
*/
@Test
public void testApplyStatusDamage_Burn() {
System.out.println("applyStatusDamage burn");
ActivePokemon poke = new ActivePokemon(Species.BRELOOM);
poke.setAbility(Ability.EFFECT_SPORE);
poke.setHpEv(252);
poke.setBurnt();
StatusDamage.applyStatusDamage(poke);
assertEquals(284, poke.getCurrHp());
}
/**
* Test of applyStatusDamage method, of class StatusDamage.
*/
@Test
public void testApplyStatusDamage_Burn_Heatproof() {
System.out.println("applyStatusDamage burn heatproof");
ActivePokemon poke = new ActivePokemon(Species.BRONZONG);
poke.setAbility(Ability.HEATPROOF);
poke.setHpEv(252);
poke.setBurnt();
StatusDamage.applyStatusDamage(poke);
assertEquals(317, poke.getCurrHp());
}
/**
* Test of applyStatusDamage method, of class StatusDamage.
*/
@Test
public void testApplyStatusDamage_Burn_MagicGuard() {
System.out.println("applyStatusDamage magicguard");
ActivePokemon poke = new ActivePokemon(Species.BRONZONG);
poke.setAbility(Ability.MAGIC_GUARD);
poke.setHpEv(252);
poke.setBurnt();
StatusDamage.applyStatusDamage(poke);
assertEquals(338, poke.getCurrHp());
}
/**
* Test of applyStatusHealing method, of class StatusDamage.
*/
@Test
public void testApplyStatusHealing_reg_poison() {
System.out.println("applyStatusHealing Rain Dry Skin");
ActivePokemon poke = new ActivePokemon(Species.BRELOOM);
poke.setHpEv(252);
poke.setAbility(Ability.POISON_HEAL);
poke.setCurrHp(100);
poke.setRegPoison();
StatusDamage.applyStatusHealing(poke);
assertEquals("should be 140", 140, poke.getCurrHp());
}
/**
* Test of applyStatusHealing method, of class StatusDamage.
*/
@Test
public void testApplyStatusHealing_tox_poison() {
System.out.println("applyStatusHealing Rain Dry Skin");
ActivePokemon poke = new ActivePokemon(Species.BRELOOM);
poke.setHpEv(252);
poke.setAbility(Ability.POISON_HEAL);
poke.setCurrHp(100);
poke.setToxPoison();
StatusDamage.applyStatusHealing(poke);
assertEquals("should be 140", 140, poke.getCurrHp());
}
@Test
public void testApplyLeechSeed() {
System.out.println("applying leech seed");
ActivePokemon healer = new ActivePokemon(Species.ABOMASNOW);
healer.setHpEv(252);
healer.setCurrHp(342);
ActivePokemon seeded = new ActivePokemon(Species.ABSOL);
seeded.setHpEv(252);
seeded.activateSeeds();
assertEquals(healer.getCurrHp(), 342);
assertEquals(seeded.getCurrHp(), 334);
assertEquals(seeded.getMaxHp(), 334);
StatusDamage.applyLeechSeed(seeded, healer);
assertEquals(seeded.getCurrHp(), 293);
assertEquals(healer.getCurrHp(), 383);
}
}
<file_sep>package com.omnidexter.main;
/**
* @author OmniDex
*/
public class TestTeamBuilder {
// public static Team getStarterTestTeam() {
// Team team = new DeepTeam();
// Pokemon t1P1 = new DeepPokemon();
// t1P1.setSpecies(Species.CHARMANDER);
// t1P1.setAbility(Ability.BLAZE);
// t1P1.setLevel(5);
// t1P1.setAtkEv(252);
// t1P1.setSpeEv(252);
// t1P1.setMove(Move.SCRATCH, 0);
// t1P1.setMove(Move.EMBER, 1);
// t1P1.setMove(Move.SCRATCH, 2);
// t1P1.setMove(Move.SCRATCH, 3);
// team.addTeamMate(t1P1);
//
// Pokemon t1P2 = new DeepPokemon();
// t1P2.setSpecies(Species.BULBASAUR);
// t1P2.setAbility(Ability.OVERGROW);
// t1P2.setLevel(5);
// t1P2.setAtkEv(252);
// t1P2.setSpeEv(252);
// t1P2.setMove(Move.TACKLE, 0);
// t1P2.setMove(Move.VINE_WHIP, 1);
// t1P2.setMove(Move.TACKLE, 2);
// t1P2.setMove(Move.TACKLE, 3);
// team.addTeamMate(t1P2);
//
// Pokemon t1P3 = new DeepPokemon();
// t1P3.setSpecies(Species.SQUIRTLE);
// t1P3.setAbility(Ability.TORRENT);
// t1P3.setLevel(5);
// t1P3.setAtkEv(252);
// t1P3.setSpeEv(252);
// t1P3.setMove(Move.TACKLE, 0);
// t1P3.setMove(Move.BUBBLE, 1);
// t1P3.setMove(Move.TACKLE, 2);
// t1P3.setMove(Move.TACKLE, 3);
// team.addTeamMate(t1P3);
//
// return team;
// }
// public static Team getStarterTestTeam2() {
// Team team = new DeepTeam();
// Pokemon t1P1 = new DeepPokemon();
// t1P1.setSpecies(Species.CHARMANDER);
// t1P1.setAbility(Ability.BLAZE);
// t1P1.setLevel(5);
// t1P1.setAtkEv(252);
// t1P1.setSpeEv(252);
// t1P1.setMove(Move.SCRATCH, 0);
// t1P1.setMove(Move.EMBER, 1);
// t1P1.setMove(Move.SCRATCH, 2);
// t1P1.setMove(Move.SCRATCH, 3);
//
//
// Pokemon t1P2 = new DeepPokemon();
// t1P2.setSpecies(Species.BULBASAUR);
// t1P2.setAbility(Ability.OVERGROW);
// t1P2.setLevel(5);
// t1P2.setAtkEv(252);
// t1P2.setSpeEv(252);
// t1P2.setMove(Move.TACKLE, 0);
// t1P2.setMove(Move.VINE_WHIP, 1);
// t1P2.setMove(Move.TACKLE, 2);
// t1P2.setMove(Move.TACKLE, 3);
// team.addTeamMate(t1P2);
//
// Pokemon t1P3 = new DeepPokemon();
// t1P3.setSpecies(Species.SQUIRTLE);
// t1P3.setAbility(Ability.TORRENT);
// t1P3.setLevel(5);
// t1P3.setAtkEv(252);
// t1P3.setSpeEv(252);
// t1P3.setMove(Move.TACKLE, 0);
// t1P3.setMove(Move.BUBBLE, 1);
// t1P3.setMove(Move.TACKLE, 2);
// t1P3.setMove(Move.TACKLE, 3);
// team.addTeamMate(t1P3);
// team.addTeamMate(t1P1);
// return team;
// }
//
//
// public static Team getTestSquritle() {
// Team team = new DeepTeam();
// Pokemon t1P1 = new DeepPokemon();
// t1P1.setSpecies(Species.SQUIRTLE);
// t1P1.setAbility(Ability.TORRENT);
// t1P1.setLevel(5);
// t1P1.setHpEv(252);
// t1P1.setDefEv(252);
// t1P1.setMove(Move.TACKLE, 0);
// t1P1.setMove(Move.U_TURN, 1);
// t1P1.setMove(Move.ABSORB, 2);
// t1P1.setMove(Move.AERIAL_ACE, 3);
// team.addTeamMate(t1P1);
// return team;
// }
//
// public static Team getTestTeamOne() {
// Team team = new DeepTeam();
//
// Pokemon t1P1 = new DeepPokemon();
//
// t1P1.setSpecies(Species.AGGRON);
// t1P1.setAbility(Ability.STURDY);
// t1P1.setAtkEv(252);
// t1P1.setSpeEv(252);
// t1P1.setMove(Move.AQUA_TAIL, 3);
// t1P1.setMove(Move.EARTHQUAKE, 1);
// t1P1.setMove(Move.STONE_EDGE, 2);
// t1P1.setMove(Move.ICE_PUNCH, 0);
// team.addTeamMate(t1P1);
//
// Pokemon t1P2 = new DeepPokemon();
// t1P2.setSpecies(Species.SPIRITOMB);
// t1P2.setAbility(Ability.PRESSURE);
// t1P2.setHpEv(252);
// t1P2.setSpDefEv(252);
//
// t1P2.setMove(Move.SUCKER_PUNCH, 0);
// t1P2.setMove(Move.SHADOW_BALL, 1);
// t1P2.setMove(Move.WILL_O_WISP, 2);
// t1P2.setMove(Move.PAIN_SPLIT, 3);
// team.addTeamMate(t1P2);
//
// Pokemon t1P3 = new DeepPokemon();
// t1P3.setSpecies(Species.GYARADOS);
// t1P3.setAbility(Ability.INTIMIDATE);
// t1P3.setHpEv(252);
// t1P3.setAtkEv(252);
// t1P3.setSpeEv(4);
//
// t1P3.setMove(Move.WATERFALL, 0);
// t1P3.setMove(Move.ICE_FANG, 1);
// t1P3.setMove(Move.SUBSTITUTE, 2);
// t1P3.setMove(Move.DRAGON_DANCE, 3);
// team.addTeamMate(t1P3);
// return team;
// }
//
// public static Team getTestTeamTwo() {
// Team t2 = new DeepTeam();
// Pokemon t2P1 = new DeepPokemon();
// t2P1.setSpecies(Species.MAGMAR);
// t2P1.setAbility(Ability.FLAME_BODY);
// t2P1.setAtkEv(252);
// t2P1.setSpeEv(252);
// t2P1.setMove(Move.FIRE_BLAST, 0);
// t2P1.setMove(Move.FOCUS_BLAST, 1);
// t2P1.setMove(Move.THUNDERBOLT, 2);
// t2P1.setMove(Move.SOLARBEAM, 3);
// t2.addTeamMate(t2P1);
// Pokemon t2P2 = new DeepPokemon();
// t2P2.setSpecies(Species.HAUNTER);
// t2P2.setAbility(Ability.LEVITATE);
// t2P2.setAtkEv(252);
// t2P2.setSpeEv(252);
//
// t2P2.setMove(Move.SUCKER_PUNCH, 0);
// t2P2.setMove(Move.SHADOW_BALL, 1);
// t2P2.setMove(Move.WILL_O_WISP, 2);
// t2P2.setMove(Move.PAIN_SPLIT, 3);
// t2.addTeamMate(t2P2);
//
// Pokemon t2P3 = new DeepPokemon();
// t2P3.setSpecies(Species.BRONZONG);
// t2P3.setAbility(Ability.HEATPROOF);
//
// t2P3.setHpEv(252);
// t2P3.setSpDefEv(252);
//
// t2P3.setMove(Move.GYRO_BALL, 0);
// t2P3.setMove(Move.EARTHQUAKE, 1);
// t2P3.setMove(Move.HYPNOSIS, 2);
// t2P3.setMove(Move.THUNDER_WAVE, 3);
// t2.addTeamMate(t2P3);
// return t2;
// }
}
<file_sep>package com.omnidex.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* This is a base dao class for handling constructor and all basic SQL methods
*/
public class DAO {
/**
* @param query
* a String representing the SQL query
* @return the ResultSet of the query
*/
protected static ResultSet queryDB(String query) {
ResultSet rs = null;
Connection conn = OmniDex.getConnection();
try {
PreparedStatement pst = conn.prepareStatement(query);
rs = pst.executeQuery();
} catch (SQLException e) {
System.out.println("query : " + query + " failed!");
e.printStackTrace();
}
return rs;
}
/**
* This method inserts new records into db.
*
* @param insert
* a String representing insert statement
*/
protected static void insertDB(String insert) {
Connection conn = OmniDex.getConnection();
if (conn != null) {
try {
PreparedStatement pst = conn.prepareStatement(insert);
pst.execute();
} catch (SQLException e) {
System.out.println("insert : " + insert + " failed!");
e.printStackTrace();
}
} else {
System.out.println("Connection is null!");
}
}
/**
* This method updates a record in the db.
*
* @param update
* a String representation of the update statement
*/
protected static void updateDB(String update) {
Connection conn = OmniDex.getConnection();
if (conn != null) {
try {
PreparedStatement pst = conn.prepareStatement(update);
pst.executeUpdate();
} catch (SQLException e) {
System.out.println("update : " + update + " failed!");
e.printStackTrace();
}
} else {
System.out.println("Connection is null!");
}
}
public static void setValues(Object... values) {
for (Object o : values) {
System.out.println(o);
}
}
/**
* This method updates a record in the db.
*
* @param delete
* a String representation of the update statement
*/
protected static void deleteRecord(String delete) {
Connection conn = OmniDex.getConnection();
if (conn != null) {
try {
PreparedStatement pst = conn.prepareStatement(delete);
pst.execute();
} catch (SQLException e) {
System.out.println("delete : " + delete + " failed!");
e.printStackTrace();
}
} else {
System.out.println("Connection is null!");
}
}
}
<file_sep>package com.omnidex.type;
/**
* The Pokemon Types
* @author jakers
*/
public enum Type {
NO_TYPE(0, "(none)"), BUG(1,"Bug"), DARK(2, "Dark"), DRAGON(3, "Dragon"),
ELECTRIC(4, "Electric"), FIGHTING(5, "Fighting"), FIRE(6, "Fire"),
FLYING(7, "Flying"), GHOST(8, "Ghost"), GRASS(9, "Grass"),
GROUND(10, "Ground"), ICE(11, "Ice"), NORMAL(12, "Normal"), POISON(13, "Poison"),
PSYCHIC(14, "Psychic"), ROCK(15, "Rock"), STEEL(16, "Steel"), WATER(17, "Water");
private int index;
private String name;
Type(int index, String name) {
this.index = index;
this.name = name;
}
public int getIndex() {
return index;
}
public String toString() {
return name;
}
}
<file_sep>package com.omnidex.damage;
import com.omnidex.ability.Ability;
import com.omnidex.pokemon.ActivePokemon;
import com.omnidex.type.Type;
import com.omnidex.weather.Weather;
public class WeatherDamage {
/**
* Applies the damage if any from the Current Weather
* @param field the weather on the field
* @param poke the DeepPokemon whose turn it is to be affected by weather
* damage.
*
* If Sand:
* 1/16 Max Hp if Current DeepPokemon isn't Rock/Ground/Steel Type or
* current DeepPokemon's ability is Sand Veil, Sand Rush, Sand Force,
* overcoat or magic guard
*
* If Hail:
* 1/16 Max Hp if Current DeepPokemon isn't Ice Type or current ability isn't
* ice Body, snow Cloak, overcoat or magic guard
*
* If Sun & ability == Solar Power or Dry Skin
* 1/8 Max Hp for Solar Power and Dry Skin
*
*/
public static void applyDamagingWeather(Weather field, ActivePokemon poke) {
Ability ability = poke.getAbility();
if (!poke.hasAbility(Ability.OVERCOAT)
&& !poke.hasAbility(Ability.MAGIC_GUARD)) {
if (field.isSand()) {
if (!(poke.isType(Type.GROUND) || poke.isType(Type.STEEL)
|| poke.isType(Type.ROCK) || poke.isDiving()
|| poke.isDigging() || ability.equals(Ability.SAND_VEIL)
|| poke.getAbility().equals(Ability.SAND_FORCE) || ability
.equals(Ability.SAND_RUSH))) {
PokemonMath.applyFractionalDamage(poke, PokemonMath.ONE_SIXTEENTH);
}
} else if (field.isHail()) {
if (!(poke.isType(Type.ICE)
|| ability.equals(Ability.SNOW_CLOAK) || ability
.equals(Ability.ICE_BODY))
|| poke.isDigging()
|| poke.isDiving()) {
PokemonMath.applyFractionalDamage(poke, PokemonMath.ONE_SIXTEENTH);
}
} else if (field.isSun()) {
if (poke.hasAbility(Ability.SOLAR_POWER)
|| poke.hasAbility(Ability.DRY_SKIN)) {
PokemonMath.applyFractionalDamage(poke, PokemonMath.ONE_EIGHTH);
}
}
}
}
/**
* Applies healing if any from the Current Weather
* @param weather the weather on the field
* @param poke the DeepPokemon whose turn it is to be affected by weather
* healing
*
* If Rain:
* Rain Dish, Hydration, Dry Skin 1/16 of Max Hp
* If Hail:
* Ice Body 1/16 of Max Hp
*/
public static void applyHealingWeather(Weather weather, ActivePokemon poke) {
if (weather.isRain()) {
if (poke.hasAbility(Ability.RAIN_DISH)) {
PokemonMath.applyFractionalHealing(poke, PokemonMath.ONE_SIXTEENTH);
} else if (poke.hasAbility(Ability.DRY_SKIN)) {
PokemonMath.applyFractionalHealing(poke, PokemonMath.ONE_EIGHTH);
} else if (poke.hasAbility(Ability.HYDRATION)) {
poke.cureStatus();
}
} else if (weather.isHail()) {
if (poke.hasAbility(Ability.ICE_BODY)) {
PokemonMath.applyFractionalHealing(poke, PokemonMath.ONE_SIXTEENTH);
}
}
}
}
<file_sep>package com.omnidex.pokemon;
public enum Gender {
MALE("Male"), FEMALE("Female"), NEUTRAL("Genderless");
private String name;
Gender(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
<file_sep>package com.omnidexter.test.damage;
import org.junit.Test;
import com.omnidex.ability.Ability;
import com.omnidex.battlefield.team.DeepTeam;
import com.omnidex.battlefield.team.Team;
import com.omnidex.damage.EntryHazardDamage;
import com.omnidex.pokemon.Pokemon;
import com.omnidex.pokemon.InactivePokemon;
import com.omnidex.pokemon.Species;
import static org.junit.Assert.*;
public class EntryHazardDamageTest {
private Pokemon accelgor;
public EntryHazardDamageTest(){
accelgor = new InactivePokemon(Species.ACCELGOR);
accelgor.setHpEv(252);
}
@Test
public void one_layer_of_spikes() {
Team team = new DeepTeam();
team.addTeamMate(accelgor);
team.addSpikes();
EntryHazardDamage.applySpikeDamage(team);
assertEquals(319, team.getActivePokemon().getCurrHp());
}
@Test
public void two_layers_of_spikes(){
Team team = new DeepTeam();
team.addTeamMate(accelgor);
team.addSpikes();
team.addSpikes();
EntryHazardDamage.applySpikeDamage(team);
assertEquals(304, team.getActivePokemon().getCurrHp());
}
@Test
public void three_layers_of_spikes(){
Team team = new DeepTeam();
team.addTeamMate(accelgor);
team.addSpikes();
team.addSpikes();
team.addSpikes();
EntryHazardDamage.applySpikeDamage(team);
assertEquals(273, team.getActivePokemon().getCurrHp());
}
@Test
public void one_layer_of_toxic_spikes(){
Team team = new DeepTeam();
team.addTeamMate(accelgor);
team.addToxicSpikes();
EntryHazardDamage.applyToxicSpikes(team);
assertTrue(team.getActivePokemon().isRegPoison());
assertFalse(team.getActivePokemon().isToxPoison());
}
@Test
public void two_layers_of_toxic_spikes() {
Team team = new DeepTeam();
team.addTeamMate(accelgor);
team.addToxicSpikes();
team.addToxicSpikes();
EntryHazardDamage.applyToxicSpikes(team);
assertTrue(team.getActivePokemon().isToxPoison());
assertFalse(team.getActivePokemon().isRegPoison());
}
@Test
public void toxic_layers_with_poisonType() {
Pokemon arbok = new InactivePokemon(Species.ARBOK);
Team team = new DeepTeam();
team.addTeamMate(arbok);
team.addToxicSpikes();
team.addToxicSpikes();
assertTrue(team.hasToxicSpikes());
EntryHazardDamage.applyToxicSpikes(team);
assertFalse(team.hasToxicSpikes());
assertEquals(0, team.getToxicSpikesCount());
}
@Test
public void toxic_layers_with_lev_poisonType() {
Pokemon gengar = new InactivePokemon(Species.GENGAR);
gengar.setAbility(Ability.LEVITATE);
Team team = new DeepTeam();
team.addTeamMate(gengar);
team.addToxicSpikes();
team.addToxicSpikes();
assertTrue(team.hasToxicSpikes());
EntryHazardDamage.applyToxicSpikes(team);
assertTrue(team.hasToxicSpikes());
assertEquals(2, team.getToxicSpikesCount());
}
@Test
public void toxic_layers_with_flying_poisonType() {
Pokemon crobat = new InactivePokemon(Species.CROBAT);
crobat.setAbility(Ability.INNER_FOCUS);
Team team = new DeepTeam();
team.addTeamMate(crobat);
team.addToxicSpikes();
team.addToxicSpikes();
assertTrue(team.hasToxicSpikes());
EntryHazardDamage.applyToxicSpikes(team);
assertTrue(team.hasToxicSpikes());
assertEquals(2, team.getToxicSpikesCount());
}
@Test
public void toxic_layers_with_flyingType() {
Pokemon pidgeot = new InactivePokemon(Species.PIDGEOT);
pidgeot.setAbility(Ability.KEEN_EYE);
Team team = new DeepTeam();
team.addTeamMate(pidgeot);
team.addToxicSpikes();
team.addToxicSpikes();
assertTrue(team.hasToxicSpikes());
EntryHazardDamage.applyToxicSpikes(team);
assertTrue(team.hasToxicSpikes());
assertEquals(2, team.getToxicSpikesCount());
}
@Test
public void four_times_weak_to_stealthRocks() {
Pokemon charizard = new InactivePokemon(Species.CHARIZARD);
charizard.setHpEv(252);
Team team = new DeepTeam();
team.addTeamMate(charizard);
team.addStealthRocks();
EntryHazardDamage.applyStealthRocks(team);
assertEquals(180,team.getActivePokemon().getCurrHp());
}
}<file_sep>package com.omnidex.db;
import com.omnidex.move.Move;
public class MoveDAO extends DAO {
private static String INSERT_MOVE = "INSERT INTO move VALUES(?,?,?,?,?,?,?,?)";
private static String UPDATE_MOVE = "UPDATE move SET type=?, base_power=?,move_category=?,priority=?,pp=?,target=?,accuracy=? WHERE move=?";
public static void insertMove(Move move) {
System.out.println(move);
String insert = "INSERT INTO move VALUES ('"
+ move
+"', '" + move.getType()
+ "', '" + move.getBasePower()
+ "', '" + move.getCategory() + "')";
insertDB(insert);
}
public static void updateMove(Move move) {
String update = "UPDATE move SET type='"+move.getType()
+"', base_power='"+move.getBasePower()+"', move_category='"+move.getCategory()
+"', priority='"+move.getPriority()+"', pp='" + move.getPP()+"', target='"+move.getTarget()+
"' WHERE move='"+move.getName()+"'";
updateDB(update);
}
}
<file_sep>package PokemonShowdownRC;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import com.omnidex.battlefield.team.DeepTeam;
import com.omnidex.battlefield.team.Team;
import com.omnidex.db.MovesetDAO;
import com.omnidex.game.Game;
import com.omnidex.move.Move;
import com.omnidex.pokemon.InactivePokemon;
import com.omnidex.pokemon.Pokemon;
import com.omnidex.pokemon.Species;
import com.omnidexter.ai.BattleAI;
import com.omnidexter.battlefield.SingleBattleField;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class BattleRC {
public static final int RANDOM_BATTLE = 0;
public static final int OU = 5;
public static final int UBERS = 8;
public static final int UU = 9;
public static final int RU = 10;
public static final int NU = 11;
public static final int LC = 12;
public static final int UU_CHALLENGE = 8;
private WebDriver driver;
private WebElement element;
private WebDriverWait wait;
private Team omnidexter;
private Team opponent;
private Game game;
public BattleRC(WebDriver driver) {
this.driver = driver;
wait = new WebDriverWait(this.driver,
WebDriverWait.DEFAULT_SLEEP_TIMEOUT);
omnidexter = new DeepTeam();
opponent = new DeepTeam();
loadGame();
}
public void lookForABattle(Team omnidexter) {
element = wait.until(ExpectedConditions.visibilityOf(driver
.findElement(By.className("mainbutton"))));
System.out.println("Searching for random battle");
element.click();
loadGame();
}
public void loadGame() {
loadTeam();
//loadOppTeam();
String oppName = driver.findElement(By.className("rightbar"))
.findElement(By.className("trainer")).getText();
game = new Game(new SingleBattleField(), omnidexter, opponent, oppName);
game.printBattleField();
}
public void sendGoodGameMessage() {
WebElement textarea = driver.findElement(By.className("textbox"));
textarea.sendKeys("gg" + Keys.ENTER);
}
private void loadPokemonMoves(Pokemon poke, boolean isActive, int index) {
if (isActive) {
wait.until(ExpectedConditions.elementToBeClickable(By
.className("movemenu")));
element = driver.findElement(By.className("movemenu"));
List<WebElement> attackBtn = element.findElements(By
.tagName("button"));
String s = driver
.findElement(By.cssSelector("div.statbar.rstatbar"))
.findElements(By.tagName("small")).get(1).getText();
s = s.substring(1);
poke.setLevel(Integer.valueOf(s));
for (int i = 0; i < attackBtn.size(); i++) {
String movename = attackBtn.get(i).getText();
StringTokenizer token = new StringTokenizer(movename, "\n");
Move move = Move.findMoveByName(token.nextToken());
poke.setMove(move, i);
}
} else {
Actions mouseover = new Actions(driver);
List<WebElement> switchOptions = driver.findElement(
By.className("switchmenu")).findElements(
By.tagName("button"));
mouseover.moveToElement(switchOptions.get(index)).build().perform();
}
}
private void loadTeam() {
List<String> teamList = getOwnParty();
boolean isActive = true;
for (int i = 0; i < teamList.size(); i++) {
Pokemon poke = new InactivePokemon(Species.findSpeciesByName(teamList
.get(i)));
loadPokemonMoves(poke, isActive, i);
isActive = false;
omnidexter.addTeamMate(poke);
}
}
public String getOpponentsActivePokemon() {
List<WebElement> oppActive = driver.findElements(By.tagName("img"));
return stripImageUrl(oppActive.get(1).getAttribute("src"));
}
public List<String> getOwnParty() {
List<WebElement> switchOptions = driver.findElement(
By.className("switchmenu")).findElements(By.tagName("button"));
List<String> party = new ArrayList<String>();
for (int i = 0; i < switchOptions.size(); i++) {
party.add(switchOptions.get(i).getText());
}
return party;
}
public void deliberate() {
clickAttack(BattleAI.getBestMove(game, 1));
}
public void clickAttack(int moveslot) {
wait.until(ExpectedConditions.elementToBeClickable(By
.className("movemenu")));
element = driver.findElement(By.className("movemenu"));
List<WebElement> attackBtn = element.findElements(By.tagName("button"));
if (moveslot < attackBtn.size()) {
System.out.println(attackBtn.get(moveslot).getText());
attackBtn.get(moveslot).click();
} else {
// handles lock on situations ie outrage
attackBtn.get(0).click();
}
}
public static void loadOppTeam(String tier, WebDriver driver, WebDriverWait wait) {
wait.until(ExpectedConditions.elementToBeClickable((By.className("innerbattle"))));
List<WebElement> imgs= driver.findElement(By.className("innerbattle")).findElements(By.tagName("img"));
for (int i = 0; i < imgs.size(); i ++) {
System.out.println(imgs.get(i).getAttribute("src"));
String form = stripImageUrl(imgs.get(i).getAttribute("src"));
Pokemon poke = MovesetDAO.guessMoveset(form,tier);
System.out.println(poke);
System.out.println("===============================");
}
}
/**
* Retrieves pokemon name from image recourse
*
* @param url
* image path to pokemon
* @return
*/
private static String stripImageUrl(String url) {
/* strips file path */
int position = url.lastIndexOf('/');
url = url.substring(position + 1);
/* strips file ext */
position = url.indexOf('.');
url = url.substring(0, position);
/* strips gender from url */
if (url.contains("-f") || url.contains("-m")) {
url = url.substring(0, url.indexOf('-'));
}
// unown
if (url.contains("unown")) {
url = "unown";
}
return url;
}
}
<file_sep>package com.omnidex.game;
import java.util.ArrayList;
import java.util.List;
import com.omnidex.battlefield.team.DeepTeam;
import com.omnidex.battlefield.team.Team;
import com.omnidex.damage.MainDamageFormula;
import com.omnidex.damage.PokemonMath;
import com.omnidex.damage.StatusDamage;
import com.omnidex.damage.WeatherDamage;
import com.omnidex.item.ItemActivation;
import com.omnidex.pokemon.Pokemon;
import com.omnidexter.ai.AiWriter;
import com.omnidexter.ai.BattleAI;
import com.omnidexter.ai.Fitness;
import com.omnidexter.ai.FitnessScore;
import com.omnidexter.battlefield.BattleField;
import com.omnidexter.battlefield.SingleBattleField;
public class Game {
public static final int OMNIDEXTER = 0;
public static final int OPPONENT = 1;
private Team omnidexter;
private String opponentName;
private Team opponent;
private BattleField bf;
public Game(BattleField bf, Team omnidexter, Team opponent,
String oppentName) {
this.bf = bf;
this.omnidexter = omnidexter;
omnidexter.setTeamId(OMNIDEXTER);
this.opponent = opponent;
opponent.setTeamId(OPPONENT);
this.opponentName = oppentName;
}
public Game(Game game) {
omnidexter = game.getOmnidexter();
opponent = game.getOpponent();
bf = game.getBf();
}
public boolean isGameOver() {
double fitness = FitnessScore.calcFitness(omnidexter, opponent);
return fitness == Fitness.PLAYER_ONE_WINS
|| fitness == Fitness.PLAYER_TWO_WINS;
}
public void printBattleField() {
System.out.println(opponentName);
for (int i = 0; i < opponent.getParty().size() + 1; i++) {
System.out.print("* ");
}
System.out.println("\n" + opponent.getActivePokemon() + "Lv:"
+ opponent.getActivePokemon().getLevel());
printHpBar(opponent.getActivePokemon());
System.out.print("\t\t\t");
for (int i = 0; i < omnidexter.getParty().size() + 1; i++) {
System.out.print("* ");
}
System.out.println();
System.out.println("\t\t\t" + omnidexter.getActivePokemon() + " Lv:"
+ omnidexter.getActivePokemon().getLevel());
System.out.print("\t\t\t");
System.out.println(omnidexter.getActivePokemon().getCurrHp() + "/"
+ omnidexter.getActivePokemon().getMaxHp());
printMoves(omnidexter.getActivePokemon());
System.out.println("---------------------------");
printSwitchOption(Game.OMNIDEXTER);
}
private void printHpBar(Pokemon poke) {
double hpbar = (poke.getCurrHp() / (double) poke.getMaxHp()) * 100;
hpbar = Math.floor(hpbar);
System.out.println(hpbar + "%");
}
private void printMoves(Pokemon poke) {
for (int i = 0; i < 4; i++) {
System.out.println(i + ") " + poke.getMove(i).getMove().getName());
}
}
public List<Integer> getAllPossibleMoves() {
List<Integer> allPossibleMoves = new ArrayList<Integer>();
// Populate attacking options by integer values first
// int = team 1 second int = team 2
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
allPossibleMoves.add(i);
allPossibleMoves.add(j);
}
}
int omnidextersize = omnidexter.getParty().size();
int opponentsize = opponent.getParty().size();
if (omnidextersize > 0) {
for (int i = -1; i > -omnidextersize; i--) {
for (int j = 0; j < 4; j++) {
allPossibleMoves.add(i);
allPossibleMoves.add(j);
}
}
}
if (opponentsize > 0) {
for (int i = -1; i > -opponentsize; i--) {
for (int j = 0; j < 4; j++) {
allPossibleMoves.add(j);
allPossibleMoves.add(i);
}
}
}
if (omnidextersize > 0 && opponentsize > 0) {
for (int i = -1; i > -omnidextersize; i--) {
for (int j = -1; j > -opponentsize; j--) {
allPossibleMoves.add(i);
allPossibleMoves.add(j);
}
}
}
return allPossibleMoves;
}
public void printSwitchOption(int player) {
List<Pokemon> party = new ArrayList<Pokemon>();
if (player == OMNIDEXTER) {
party = omnidexter.getParty();
} else {
party = opponent.getParty();
}
if (party.isEmpty()) {
System.out.println("No avaliable switches");
} else {
for (int i = 1; i <= party.size(); i++) {
System.out.println(-i + ")" + party.get(i - 1) + " "
+ party.get(i - 1).getCurrHp() + "/"
+ party.get(i - 1).getMaxHp());
}
}
}
public void applyTurn(int player1Choice, int player2Choice) {
omnidexter.setChoice(player1Choice);
opponent.setChoice(player2Choice);
Team[] speedOrder = PokemonMath.getFasterPoke(omnidexter, opponent);
Team first = speedOrder[0];
Team second = speedOrder[1];
if (first.getChoice() < 0) {
first.switchActivePokemon(first.getActivePokemon().getMove(
first.getChoice()));
}
if (second.getChoice() < 0) {
second.switchActivePokemon(second.getActivePokemon().getMove(
second.getChoice()));
}
if (first.getChoice() >= 0) {
attack(first.getTeamId(), first.getChoice());
}
if (second.getChoice() >= 0 && !second.getActivePokemon().hasFainted()) {
attack(second.getTeamId(), second.getChoice());
}
}
// @Override
public void applieAfterTurnAffects() {
Team[] temp = PokemonMath.getFasterPoke(omnidexter, opponent);
Team fasterTeam = temp[0];
Team slowerTeam = temp[1];
omnidexter.decrementRelfect();
opponent.decrementRelfect();
omnidexter.decrementLightScreen();
opponent.decrementLightScreen();
omnidexter.decrementMist();
opponent.decrementMist();
omnidexter.decrementSafeguard();
opponent.decrementSafeguard();
omnidexter.decrementTailWind();
opponent.decrementTailWind();
omnidexter.decrementLuckyChant();
opponent.decrementLuckyChant();
omnidexter.decrementWishCount();
opponent.decrementWishCount();
WeatherDamage.applyDamagingWeather(bf, fasterTeam.getActivePokemon());
WeatherDamage.applyDamagingWeather(bf, slowerTeam.getActivePokemon());
WeatherDamage.applyHealingWeather(bf, fasterTeam.getActivePokemon());
WeatherDamage.applyHealingWeather(bf, slowerTeam.getActivePokemon());
// Check if Gravity wears off
bf.decrementGravity();
// applies damage/healing from status
StatusDamage.applyIngrainHealing(fasterTeam.getActivePokemon());
StatusDamage.applyIngrainHealing(slowerTeam.getActivePokemon());
StatusDamage.applyAquaRingHealing(fasterTeam.getActivePokemon());
StatusDamage.applyAquaRingHealing(slowerTeam.getActivePokemon());
// TODO Check for Speed Boost/Shed Skin activation
ItemActivation.applyHealingItems(fasterTeam.getActivePokemon());
ItemActivation.applyHealingItems(slowerTeam.getActivePokemon());
StatusDamage.applyLeechSeed(slowerTeam.getActivePokemon(),
fasterTeam.getActivePokemon());
StatusDamage.applyLeechSeed(fasterTeam.getActivePokemon(),
slowerTeam.getActivePokemon());
// Check for Status Damage/Nightmare
// Checks for fainting inside healing method.
if (!fasterTeam.getActivePokemon().hasFainted()
&& !fasterTeam.getActivePokemon().isOk()) {
StatusDamage.applyStatusDamage(fasterTeam.getActivePokemon());
StatusDamage.applyStatusHealing(fasterTeam.getActivePokemon());
}
if (!slowerTeam.getActivePokemon().hasFainted()
&& !slowerTeam.getActivePokemon().isOk()) {
StatusDamage.applyStatusDamage(slowerTeam.getActivePokemon());
StatusDamage.applyStatusHealing(slowerTeam.getActivePokemon());
}
ItemActivation.burnOrbActivation(fasterTeam.getActivePokemon());
ItemActivation.toxicOrbActivation(fasterTeam.getActivePokemon());
ItemActivation.burnOrbActivation(slowerTeam.getActivePokemon());
ItemActivation.toxicOrbActivation(slowerTeam.getActivePokemon());
StatusDamage.applyCurseDamage(fasterTeam.getActivePokemon());
StatusDamage.applyCurseDamage(slowerTeam.getActivePokemon());
StatusDamage.applyPartialTrappingDamage(fasterTeam.getActivePokemon(),
slowerTeam.getActivePokemon());
StatusDamage.applyPartialTrappingDamage(slowerTeam.getActivePokemon(),
fasterTeam.getActivePokemon());
StatusDamage.applyBadDreams(slowerTeam.getActivePokemon(),
fasterTeam.getActivePokemon());
StatusDamage.applyBadDreams(fasterTeam.getActivePokemon(),
slowerTeam.getActivePokemon());
// TODO Check for end of outrage, petal dance, uproar, thrash
// TODO Check for end of disable
// TODO Check for Encore ending
// TODO Check for Taunt
// TODO Check for Magnet Rise
fasterTeam.getActivePokemon();
slowerTeam.getActivePokemon();
// TODO Check Heal Block
// TODO Check Embargo
// TODO Check Yawn
// TODO Sticky Barb
// TODO Doom Desire, Future Sight
// TODO Perish Song
// Trick Room
bf.decrementTrickRoom();
bf.decrementMagicRoom();
bf.decrementWonderRoom();
switchIfFainted(fasterTeam);
switchIfFainted(slowerTeam);
// TODO Slow Start
}
public void switchIfFainted(Team first) {
if (first.getActivePokemon().hasFainted()
&& first.getParty().size() > 0) {
int choice;
if (first.getTeamId() == OMNIDEXTER) {
choice = BattleAI.getNextPoke(this, OMNIDEXTER,
BattleAI.MAX_DEPTH);
} else if (AiWriter.isSearchMode) {
choice = BattleAI.getNextPoke(this, OPPONENT,
BattleAI.MAX_DEPTH);
} else {
printSwitchOption(OPPONENT);
System.out.println("Please choice a new pokemon");
choice = -1;
}
AiWriter.setSearchMode(true);
first.switchActivePokemon(first.getActivePokemon().getMove(choice));
}
}
public void attack(int player, int moveSlot) {
int damage[];
Team attack;
Team defend;
if (player == OMNIDEXTER) {
attack = omnidexter;
defend = opponent;
} else {
attack = opponent;
defend = omnidexter;
}
damage = MainDamageFormula.damage(attack, defend, bf, attack
.getActivePokemon().getMove(moveSlot).getMove());
defend.getActivePokemon().setCurrHp(
defend.getActivePokemon().getCurrHp() - damage[1]);
AiWriter.writeAttack(attack.getActivePokemon(), moveSlot, damage[1],
player);
}
public Team getOmnidexter() {
return new DeepTeam(omnidexter);
}
public void setOmnidexter(Team omnidexter) {
this.omnidexter = omnidexter;
}
public Team getOpponent() {
return new DeepTeam(opponent);
}
public void setOpponent(Team opponent) {
this.opponent = opponent;
}
public BattleField getBf() {
return new SingleBattleField(bf);
}
public void setBf(BattleField bf) {
this.bf = bf;
}
}
<file_sep>package com.omnidex.pokemon;
public interface Stageable {
int getStage();
void boostStage(int boost);
void decreaseStage(int decrease);
void boostToMaxStage();
void decreaseToMinStage();
void resetToInitialStage();
double getStageModifier();
}
<file_sep>package com.omnidex.pokemon;
import com.omnidex.type.Type;
/**
* Stats are HP, ATK, DEF, SPATK, SPDEF, SPE, ACCURACY, EVASION Methods here
* perform calculations and set and retrieve stats.
*
* @author jakers
*/
public interface Stats {
// constants for elements of arrays
static final int CURR_HP = 1;
static final int MAX_HP = 0;
static final int ATK = 1;
static final int DEF = 2;
static final int SPATK = 3;
static final int SPDEF = 4;
static final int SPE = 5;
static final int ACCURARY = 0;
static final int EVASION = 1;
/**
* Assigns the Pokemon the specified Nature
*
* @param nature
* a Nature enum for the Pokemon to have next
*/
void setNature(Nature nature);
/**
* @return a Nature enum representing the Pokemon's nature.
*/
Nature getNature();
/**
* @return an int[] of all the base stats for the pokemon in the following
* order. hp, atk, def, spAtk, spDef, spe
*/
int[] getBaseStats();
/**
* @param baseStats
* an int array of a Pokemon's base states in the order: hp, atk,
* def, spAtk, spDef, spe
*/
void setBaseStats(int[] baseStats);
/**
* Sets a Pokemon's evs to the specified values in evs[].
*
* @param evs
* an int[] of all the evs a Pokemon has earned. The order of the
* evs are: hp, atk, def, spAtk, spDef, spe
*/
void setEvs(int[] evs);
/**
* @return an int[] of the Pokemons current ivs. The order of the ivs are:
* hp, atk, def, spAtk, spDef, spe
*/
int[] getIvs();
/**
* Sets the Pokemon's ivs to those specified in ivs[].
*
* @param ivs
* an int[] of ivs for the Pokemon. The order of the ivs is: hp,
* atk, def, spAtk, spDef, spe
*/
void setIvs(int[] ivs);
/**
* @return an int representing the pokemon's unmodified attack stat.
*/
int getAtk();
/**
* @return an int representing the pokemon's unmodified defense stat.
*/
int getDef();
/**
* @return an int representing the pokemon's unmodified special attack stat.
*/
int getSpAtk();
/**
* @return an int representing the pokemon's unmodified special defense
* stat.
*/
int getSpDef();
/**
* @return an int representing the pokemon's unmodified speed stat.
*/
int getSpe();
// TODO javadocs
void setHpBase(int hpBase);
void setAtkBase(int atkBase);
void setDefBase(int defBase);
void setSpAtkBase(int spAtkBase);
void setSpDefBase(int spDefBase);
void setSpeBase(int speBase);
// TODO javadocs
int getHpBase();
int getAtkBase();
int getDefBase();
int getSpAtkBase();
int getSpDefBase();
int getSpeBase();
// TOOD javadocs
void setLevel(int level);
int getLevel();
int getHpIv();
int getAtkIv();
int getDefIv();
int getSpAtkIv();
int getSpDefIv();
int getSpeIv();
int[] getEvs();
int getHpEv();
int getAtkEv();
int getDefEv();
int getSpAtkEv();
int getSpDefEv();
int getSpeEv();
void setHpIv(int hpIv);
void setAtkIv(int atkIv);
void setDefIv(int defIv);
void setSpAtkIv(int spAtkIv);
void setSpDefIv(int spDefIv);
void setSpeIv(int speIv);
void setHpEv(int hpEv);
void setAtkEv(int atkEv);
void setDefEv(int defEv);
void setSpAtkEv(int spAtkEv);
void setSpDefEv(int spDefEv);
void setSpeEv(int speEv);
/**
* @return an int representing the current hit points.
*/
int getCurrHp();
/**
* @return an int representing the base power of the hidden power.
*/
int getHiddenPowerBasePower();
/**
* @return a Type representing the type of the hidden power's type.
*/
Type getHiddenPowerType();
/**
* @return an int representing the maximum hit points available when at full
* health.
*/
int getMaxHp();
/**
* Sets the current Hit Points.
*
* @param an
* int representing the new value of the current Hit Points
*/
void setCurrHp(int currHp);
// TODO javadocs
/**
* Sets all the stats at the same time.
*
* @param stats
* an array of ints representing the stats in the following order
* int[0] = hp int[3] = spAtk int[1] = atk int[4] = spDef int[2]
* = def int[5] = spe
*/
void setStats(int[] stats);
/**
* Sets atk,def,spatk,spdef,spe,accuracy, evasion and stages for the
* respective stats equals to those values from the newStats.
*
* @param newStat
* a Stats object that that the current stats will be set to
*/
void setStats(Stats newStat);
/**
* Sets all the stats at once.
*
* @param hp
* an int representing the new maximum hit point stat Ensures:
* that the current hit points equals the maximum hit points
* @param atk
* an int representing the new attack stat
* @param def
* an int representing the new defense stat
* @param spAtk
* an int representing the new special attack stat
* @param spDef
* an int representing the new special defense stat
* @param spe
* an int representing the new speed stat
*/
void setStats(int hp, int atk, int def, int spAtk, int spDef, int spe);
String getStatAt(int position);
}
<file_sep>package com.omnidex.pokemon;
public class CriticalHitStages extends Stage {
private static final double STAGE_ONE = 0.0625;
private static final double STAGE_TWO = 0.125;
private static final double STAGE_THREE = 0.25;
private static final double STAGE_FOUR = 0.333;
private static final double STAGE_FIVE = 0.5;
public CriticalHitStages() {
super(1, 5, 1);
}
@Override
public double getStageModifier() {
double stageModifier = STAGE_ONE;
switch (stage) {
case 2:
stageModifier = STAGE_TWO;
break;
case 3:
stageModifier = STAGE_THREE;
break;
case 4:
stageModifier = STAGE_FOUR;
break;
case 5:
stageModifier = STAGE_FIVE;
default:
stageModifier = STAGE_ONE;
}
return stageModifier;
}
}
<file_sep>package com.omnidex.item;
/**
* An enum of all the items in Pokemon
* @author jakers
*/
public enum Item {
/* A items */
ABSORB_BULB("Absorb Bulb"),
ADAMANT_ORB("Adamant Orb"),
AGUAV_BERRY("Aguav Berry"),
AIR_BALLOON("Air Balloon"),
AMULET_COIN("Amulet Coin"),
ANTIDOTE("Antidote"),
APICOT_BERRY("Apicot Berry"),
ARMOR_FOSSIL("Armor Fossil"),
ASPEAR_BERRY("Aspear Berry"),
AWAKENING("Awakening"),
/* B items */
BABIRI_BERRY("Babiri Berry"),
BELUE_BERRY("Belue Berry"),
BERRY_JUICE("Berry Juice"),
BIG_ROOT("Big Root"),
BIG_MUSHROOM("Big Mushroom"),
BIG_PEARL("Big Pearl"),
BINDING_BAND("Binding Band"),
BLACK_BELT("Black Belt"),
BLACK_FLUTE("Black Flute"),
BLACK_SLUDGE("Black Sludge"),
BLACKGLASSES("Blackglasses"),
BLUE_FLUTE("Blue Flute"),
BLUE_SCARF("Blue Scarf"),
BLUE_SHARD("Blue Shard"),
BLUK_BERRY("Bluk Berry"),
BRIGHTPOWDER("Brightpowder"),
BUG_GEM("Bug Gem"),
BURN_DRIVE("Burn Drive"),
BURN_HEAL("Burn Heal"),
/* C items */
CALCIUM("Calcium"),
CARBOS("Carbos"),
CASTELIACONE("Casteliacone"),
CELL_BATTERY("Cell Battery"),
CHARCOAL("Charcoal"),
CHARTI_BERRY("Charti Berry"),
CHERI_BERRY("Cheri Berry"),
CHESTO_BERRY("Chesto Berry"),
CHILAN_BERRY("Chilan Berry"),
CHILL_DRIVE("Chill Drive"),
CHOICE_BAND("Choice Band"),
CHOICE_SCARF("Choice Scarf"),
CHOICE_SPECS("Choice Specs"),
CHOPLE_BERRY("Chople Berry"),
CLAW_FOSSIL("Claw Fossil"),
CLEANSE_TAG("Cleanse Tag"),
COBA_BERRY("Coba Berry"),
COLBUR_BERRY("Colbur Berry"),
CORNN_BERRY("Cornn Berry"),
COVER_FOSSIL("Cover Fossil"),
CUSTAP_BERRY("Custap Berry"),
/* D items */
DAMP_MULCH("Damp Mulch"),
DAMP_ROCK("Damp Rock"),
DARK_GEM("Dark Gem"),
DAWN_STONE("Dawn Stone"),
DEEPSEASCALE("DeepSeaScale"),
DEEPSEATOOTH("DeepSeaTooth"),
DESTINY_KNOT("Destiny Knot"),
DIRE_HIT("Dire Hit"),
DOME_FOSSIL("Dome Fossil"),
DOUSE_DRIVE("Douse Driver"),
DRACO_PLATE("Draco Plate"),
DRAGON_FANG("Dragon Fang"),
DRAGON_GEM("Dragon Gem"),
DREAD_PLATE("Dread Plate"),
DRAGON_SCALE("Dragon Scale"),
DUBIOUS_DISC("Dubious Disc"),
DURNIN_BERRY("Durnin Berry"),
DUSK_STONE("Dusk Stone"),
/* E items */
EARTH_PLATE("Earth Plate"),
EJECT_BUTTON("Eject Button"),
ELECTIRIZER("Electirizer"),
ELECTRIC_GEM("Electric Gem"),
ELIXIR("Elixir"),
ENERGYPOWDER("EnergyPowder"),
ENERGY_ROOT("Energy Root"),
ENIGMA_BERRY("Enigma Berry"),
ESCAPE_ROPE("Escape Rope"),
ETHER("Ether"),
EVERSTONE("Everstone"),
EVIOLITE("Eviolite"),
EXP_SHARE("Exp. Share"),
EXPERT_BELT("Expert Belt"),
/* F items */
FIGHTING_GEM("Fighting Gem"),
FIGY_BERRY("Figy Berry"),
FIRE_GEM("Fire Gem"),
FIRE_STONE("Fire Stone"),
FIST_PLATE("Fist Plate"),
FLAME_ORB("Flame Orb"),
FLAME_PLATE("Flame Plate"),
FLOAT_STONE("Float Stone"),
FLUFFY_TAIL("Fluffy Tail"),
FLYING_GEM("Flying Gem"),
FOCUS_BAND("Focus Band"),
FOCUS_SASH("Focus Sash"),
FRESH_WATER("Fresh Water"),
FULL_HEAL("Full Heal"),
FULL_INCENSE("Full Incense"),
FULL_RESTORE("Full Restore"),
/* G items */
GANLON_BERRY("Ganlon Berry"),
GHOST_GEM("Ghost Gem"),
GOOEY_MULCH("Gooey Mulch"),
GRASS_GEM("Grass Gem"),
GREEN_SCARF("Green Scarf"),
GREEN_SHARD("Green Shard"),
GREPA_BERRY("Grepa Berry"),
GRIP_CLAW("Grip Claw"),
GRISEOUS_ORB("Griseous Orb"),
GROUND_GEM("Ground Gem"),
GROWTH_MULCH("Growth Mulch"),
GUARD_SPEC("Guard Spec."),
/* H items */
HABAN_BERRY("Haban Berry"),
HARD_STONE("Hard Stone"),
HEAL_POWDER("Heal Powder"),
HEAT_ROCK("Heat Rock"),
HEART_SCALE("Heart Scale"),
HELIX_FOSSIL("Helix Fossil"),
HP_UP("Hp Up"),
HONDEW_BERRY("Hondew Berry"),
HONEY("Honey"),
/* I items */
IAPAPA_BERRY("Iapapa Berry"),
ICE_GEM("Ice Gem"),
ICE_HEAL("Ice Heal"),
ICICLE_PLATE("Icicle Plate"),
ICY_ROCK("Icy Rock"),
INSECT_PLATE("Insect Plate"),
IRON("Iron"),
IRON_BALL("Iron Ball"),
IRON_PLATE("Iron Plate"),
/* J items */
JABOCA_BERRY("Jaboca Berry"),
/* K items */
KASIB_BERRY("Kasib Berry"),
KEBIA_BERRY("Kebia Berry"),
KELPSY_BERRY("Kelpsy Berry"),
KINGS_ROCK("King's Rock"),
/* L items */
LAGGING_TAIL("Lagging Tail"),
LANSAT_BERRY("Lansat Berry"),
LAVA_COOKIE("Lava Cookie"),
LAX_INCENSE("Lax Incense"),
LEAF_STONE("Leaf Stone"),
LEFTOVERS("Leftovers"),
LEMONADE("Lemonade"),
LEPPA_BERRY("Leppa Berry"),
LIFE_ORB("Life Orb"),
LIECHI_BERRY("Liechi Berry"),
LIGHT_BALL("Light Ball"),
LIGHT_CLAY("Light Clay"),
LUCK_INCENSE("Luck Incense"),
LUCKY_EGG("Lucky Egg"),
LUCKY_PUNCH("Lucky Punch"),
LUM_BERRY("Lum Berry"),
LUSTROUS_ORB("Lustrous Orb"),
/* M items */
MACHO_BRACE("Macho Brace"),
MAGMARIZER("Magmarizer"),
MAGNET("Magnet"),
MAGO_BERRY("Mago Berry"),
MAGOST_BERRY("Magost Berry"),
MAX_ELIXIR("Max Elixir"),
MAX_ETHER("Max Ether"),
MAX_REPEL("Max Repel"),
MAX_REVIVE("Max Revive"),
MEADOW_PLATE("Meadow Plate"),
MENTAL_HERB("Mental Herb"),
METAL_COAT("Metal Coat"),
METAL_POWDER("Metal Powder"),
METRONOME("Metronome"),
MICLE_BERRY("Micle Berry"),
MIND_PLATE("Mind Plate"),
MIRACLE_SEED("Miracle Seed"),
MOON_STONE("Moon Stone"),
MOOMOO_MILK("MooMoo Milk"),
MUSCLE_BAND("Muscle Band"),
MYSTIC_WATER("Mystic Water"),
/* N items */
NANAB_BERRY("Nanab Berry"),
NEVERMELTICE("Nevermeltice"),
NO_ITEM("Nothing"),
NOMEL_BERRY("Nomel Berry"),
NORMAL_GEM("Normal Gem"),
NUGGET("Nugget"),
/* O items */
OCCA_BERRY("Occa Berry"),
ODD_INCENSE("Odd Incense"),
ODD_KEYSTONE("Odd Keystone"),
OLD_AMBER("Old Amber"),
OLD_GATEAU("Old Gateau"),
ORAN_BERRY("Oran Berry"),
OVAL_STONE("Oval Stone"),
/* P items */
PAMTRE_BERRY("Pamtre Berry"),
PARLYZ_HEAL("Parlyz Heal"),
PASSHO_BERRY("Passho Berry"),
PAYAPA_BERRY("Payapa Berry"),
PEARL("Pearl"),
PECHA_BERRY("Pecha Berry"),
PETAYA_BERRY("Petaya Berry"),
PINAP_BERRY("Pinap Berry"),
PINK_SCARF("Pink Scarf"),
PLUME_FOSSIL("Plume Fossil"),
POISON_BARB("Poison Barb"),
POISON_GEM("Poison Gem"),
POKE_DOLL("Poke Doll"),
POMEG_BERRY("Pomeg Berry"),
POWER_ANKLET("Power Anklet"),
POWER_BAND("Powder Band"),
POWER_BELT("Power Belt"),
POWER_BRACER("Power Bracer"),
POWER_HERB("Power Herb"),
POWER_LENS("Power Lens"),
POWER_WEIGHT("Power Weight"),
PP_MAX("Pp Max"),
PP_UP("Pp Up"),
PERSIM_BERRY("Persim Berry"),
PROTECTOR("Protector"),
PROTEIN("Protein"),
PSYCHIC_GEM("Psychic Gem"),
PURE_INCENSE("Pure Incense"),
/* Q items */
QUALOT_BERRY("Qualot Berry"),
QUICK_CLAW("Quick Claw"),
QUICK_POWDER("Quick Powder"),
/* R items */
RABUTA_BERRY("Rabuta Berry"),
RARE_BONE("Rare Bone"),
RARE_CANDY("Rare Candy"),
RAWST_BERRY("Rawst Berry"),
RAZOR_CLAW("Razor Claw"),
RAZOR_FANG("Razor Fang"),
RAZZ_BERRY("Razz Berry"),
REAPER_CLOTH("Reaper Cloth"),
RED_CARD("Red Card"),
RED_FLUTE("Red Flute"),
RED_SCARF("Red Scarf"),
RED_SHARD("Red Shard"),
REPEL("Repel"),
REVIVE("Revive"),
REVIVAL_HERB("Revival Herb"),
RINDO_BERRY("Rindo Berry"),
RING_TARGET("Ring Target"),
ROCK_GEM("Rock Gem"),
ROCK_INCENSE("Rock Incense"),
ROCKY_HELMET("Rocky Helmet"),
ROOT_FOSSIL("Root Fossil"),
ROSE_INCENSE("Rose Incense"),
ROWAP_BERRY("Rowap Berry"),
/* S items */
SACRED_ASH("Sacred Ash"),
SALAC_BERRY("Salac Berry"),
SCOPE_LENS("Scope Lens"),
SEA_INCENSE("Sea Incense"),
SHARP_BEAK("Sharp Beak"),
SHED_SHELL("Shed Shell"),
SHELL_BELL("Shell Bell"),
SHINY_STONE("Shiny Stone"),
SHOAL_SALT("Shoal Salt"),
SHOAL_SHELL("Shoal Shell"),
SHOCK_DRIVE("Shock Drive"),
SHUCA_BERRY("Shuca Berry"),
SILK_SCARF("Silk Scarf"),
SILVERPOWDER("Silverpowder"),
SITRUS_BERRY("Sitrus Berry"),
SKULL_FOSSIL("Skull Fossil"),
SKY_PLATE("Sky Plate"),
SMOKE_BALL("Smoke Ball"),
SMOOTH_ROCK("Smooth Rock"),
SODA_POP("Soda Pop"),
SOFT_SAND("Soft Sand"),
SOOTHE_BELL("Soothe Bell"),
SOUL_DEW("Soul Dew"),
SUN_STONE("Sun Stone"),
SUPER_REPEL("Super Repel"),
SPELL_TAG("Spell Tag"),
SPELON_BERRY("Spelon Berry"),
SPLASH_PLATE("Splash Plate"),
SPOOKY_PLATE("Spooky Plate"),
STABLE_MULCH("Stable Mulch"),
STARDUST("Stardust"),
STARF_BERRY("Starf Berry"),
STAR_PIECE("Star Piece"),
STEEL_GEM("Steel Gem"),
STICK("Stick"),
STICKY_BARB("Sticky Barb"),
STONE_PLATE("Stone Plate"),
/* T items */
TAMATO_BERRY("Tamato Berry"),
TANGA_BERRY("Tanga Berry"),
THICK_CLUB("Thick Club"),
THUNDERSTONE("Thunderstone"),
TINYMUSHROOM("Tinymushroom"),
TOXIC_ORB("Toxic Orb"),
TOXIC_PLATE("Toxic Plate"),
TWISTEDSPOON("Twistedspoon"),
/* U items */
UP_GRADE("Up-Grade"),
/* V items */
/* W items */
WACAN_BERRY("Wacan Berry"),
WATER_GEM("Water Gem"),
WATER_STONE("Water Stone"),
WATMEL_BERRY("Watmel Berry"),
WAVE_INCENSE("Wave Incense"),
WEPEAR_BERRY("Wepear Berry"),
WHITE_FLUTE("White Flute"),
WHITE_HERB("White Herb"),
WIDE_LENS("Wide Lens"),
WISE_GLASSES("Wise Glasses"),
WIKI_BERRY("Wiki Berry"),
/* X items */
X_ACCURAY("X Acc."),
X_ATTACK("X Atk."),
X_DEFEND("X Def."),
X_SPDEF("X SpDef."),
X_SPECIAL("X Special"),
X_SPEED("X Speed"),
/* Y items */
YACHE_BERRY("Yache Berry"),
YELLOW_FLUTE("Yellow Flute"),
YELLOW_SCARF("Yellow Scarf"),
YELLOW_SHARD("Yellow Shard"),
/* Z items */
ZAP_PLATE("Zap Plate"),
ZINC("Zinc"),
ZOOM_LENS("Zoom Lens");
public static Item findItemByName(String name) {
Item item = null;
for (Item i : Item.values()) {
if (i.toString().toLowerCase().equals(name.toLowerCase())) {
item = i;
break;
}
}
return item;
}
public String toString() {
return name;
}
private String name;
Item(String name) {
this.name = name;
}
}
<file_sep>OmniDexter
==========
Pokemon Battler AI<file_sep>package com.omnidex.pokemon;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.omnidex.ability.Ability;
import com.omnidex.item.Item;
import com.omnidex.move.Move;
import com.omnidex.move.MoveWithPP;
import com.omnidex.pokemon.Species;
import com.omnidex.type.Type;
/**
* A DeepPokemon object that holds all the stats of a DeepPokemon species.
*
* @convention an Undeclared DeepPokemon is initially set as MissingNo. This
* class utilizes function from the PokemonDatabase class and is
* connected with OmniDex.mdb file.
* @author jakers
*/
public class InactivePokemon implements Pokemon, Status, Stats {
private static final int NUM_OF_STATS = 6;
private static final int HP = 0;
private static final int SP_ATK = 3;
private static final int SP_DEF = 4;
protected Stats stats;
protected Species forme;
protected String nickName;
protected int gen;
protected Nature nature;
protected String gender;
protected boolean isShiny;
protected Status status;
protected Ability ability;
protected Item item;
protected double weight;
protected MoveWithPP move1;
protected MoveWithPP move2;
protected MoveWithPP move3;
protected MoveWithPP move4;
protected MoveWithPP switch1;
protected MoveWithPP switch2;
protected MoveWithPP switch3;
protected MoveWithPP switch4;
protected MoveWithPP switch5;
protected int friendship;
public InactivePokemon() {
forme = Species.MISSINGNO;
nickName = forme.toString();
item = Item.NO_ITEM;
ability = Ability.NO_ABILITY;
nature = Nature.HARDY;
int[] iv = { MAX_IV_VALUE, MAX_IV_VALUE, MAX_IV_VALUE, MAX_IV_VALUE,
MAX_IV_VALUE, MAX_IV_VALUE };
int[] ev = { 0, 0, 0, 0, 0, 0, 0 };
stats = new PokeStats(nature, forme.getAllBases(), iv, ev);
status = new PokeStatus();
MoveWithPP m = new MoveWithPP(Move.NONE);
move1 = m;
move2 = m;
move3 = m;
move4 = m;
isShiny = false;
}
public InactivePokemon(ResultSet rs) {
try {
rs.next();
forme = Species.findSpeciesByName(rs.getString("form"));
item = Item.findItemByName(rs.getString("item"));
ability = Ability.findAbilityByName(rs.getString("ability"));
nature = Nature.findNatureByName((rs.getString("nature")));
int[] iv = { MAX_IV_VALUE, MAX_IV_VALUE, MAX_IV_VALUE,
MAX_IV_VALUE, MAX_IV_VALUE, MAX_IV_VALUE };
int[] evs = new int[6];
evs[0] = rs.getInt("hp_iv");
evs[1] = rs.getInt("atk_iv");
evs[2] = rs.getInt("def_iv");
evs[3] = rs.getInt("spatk_iv");
evs[4] = rs.getInt("spdef_iv");
evs[5] = rs.getInt("spe_iv");
stats = new PokeStats(nature, forme.getAllBases(), iv, evs);
status = new PokeStatus();
move1 = new MoveWithPP(Move.findMoveByName(rs.getString("move_1")));
move2 = new MoveWithPP(Move.findMoveByName(rs.getString("move_2")));
move3 = new MoveWithPP(Move.findMoveByName(rs.getString("move_3")));
move4 = new MoveWithPP(Move.findMoveByName(rs.getString("move_4")));
} catch (SQLException e) {
System.out.println("Failed to load in a pokemon by usage stats");
e.printStackTrace();
}
isShiny = false;
}
@Override
public void setAbility(Ability ability) {
this.ability = ability;
}
@Override
public Ability getAbility() {
return ability;
}
@Override
public void setFrozen() {
status.setFrozen();
}
@Override
public void setFainted() {
status.setFainted();
}
@Override
public void setBurnt() {
status.setBurnt();
}
@Override
public void setItem(Item item) {
this.item = item;
}
@Override
public Item getItem() {
return this.item;
}
public InactivePokemon(Species pokemon) {
int[] iv = { 31, 31, 31, 31, 31, 31 };
int[] ev = { 0, 0, 0, 0, 0, 0 };
ability = Ability.NO_ABILITY;
nature = Nature.HARDY;
forme = pokemon;
nickName = forme.toString();
item = Item.NO_ITEM;
stats = new PokeStats(MAX_LEVEL, nature, forme.getAllBases(), iv, ev);
status = new PokeStatus();
isShiny = false;
}
public InactivePokemon(Species forme, int level, Nature nature, int[] ivs,
int[] evs, MoveWithPP[] moveSet) {
move1 = moveSet[MOVE_ONE];
move2 = moveSet[MOVE_TWO];
move3 = moveSet[MOVE_THREE];
move4 = moveSet[MOVE_FOUR];
this.forme = forme;
stats = new PokeStats(level, nature, this.forme.getAllBases(), ivs, evs);
this.nature = nature;
ability = Ability.NO_ABILITY;
isShiny = false;
}
@Override
public void setMove(Move move, int slot) {
if (slot == MOVE_ONE) {
move1 = new MoveWithPP(move);
} else if (slot == MOVE_TWO) {
move2 = new MoveWithPP(move);
} else if (slot == MOVE_THREE) {
move3 = new MoveWithPP(move);
} else if (slot == MOVE_FOUR) {
move4 = new MoveWithPP(move);
} else if (slot == SWITCH_ONE) {
switch1 = new MoveWithPP(move);
} else if (slot == SWITCH_TWO) {
switch2 = new MoveWithPP(move);
} else if (slot == SWITCH_THREE) {
switch3 = new MoveWithPP(move);
} else if (slot == SWITCH_FOUR) {
switch4 = new MoveWithPP(move);
} else if (slot == SWITCH_FIVE) {
switch5 = new MoveWithPP(move);
}
}
@Override
public int[] getEvs() {
return stats.getEvs();
}
@Override
public int[] getIvs() {
return stats.getIvs();
}
@Override
public int[] getBaseStats() {
return stats.getBaseStats();
}
public InactivePokemon(Pokemon p) {
stats = new PokeStats(p.getStats());
forme = p.getSpecies();
nickName = p.getNickName();
ability = p.getAbility();
stats.setEvs(p.getEvs());
stats.setIvs(p.getIvs());
status = new PokeStatus(p.getStatus());
stats.setBaseStats(p.getBaseStats());
gender = p.getGender();
stats.setLevel(p.getLevel());
nature = stats.getNature();
item = p.getItem();
move1 = p.getMove(MOVE_ONE);
move2 = p.getMove(MOVE_TWO);
move3 = p.getMove(MOVE_THREE);
move4 = p.getMove(MOVE_FOUR);
isShiny = p.isShiny();
}
@Override
public void setNature(Nature nature) {
stats.setNature(nature);
}
public void setIvs(int hpIv, int atkIv, int defIv, int spAtkIv,
int spDefIv, int spdIv) {
stats.setHpIv(hpIv);
stats.setAtkIv(atkIv);
stats.setDefIv(defIv);
stats.setSpAtkIv(spAtkIv);
stats.setSpDefIv(spDefIv);
stats.setSpeIv(spdIv);
}
public int getGen() {
return gen;
}
public MoveWithPP getMove1() {
return move1;
}
public MoveWithPP getMove2() {
return move2;
}
public MoveWithPP getMove3() {
return move3;
}
public MoveWithPP getMove4() {
return move4;
}
@Override
public MoveWithPP getMove(int slot) {
MoveWithPP result = null;
if (slot == MOVE_ONE) {
result = move1;
} else if (slot == MOVE_TWO) {
result = move2;
} else if (slot == MOVE_THREE) {
result = move3;
} else if (slot == MOVE_FOUR) {
result = move4;
} else if (slot == SWITCH_ONE) {
result = switch1;
} else if (slot == SWITCH_TWO) {
result = switch2;
} else if (slot == SWITCH_THREE) {
result = switch3;
} else if (slot == SWITCH_FOUR) {
result = switch4;
} else if (slot == SWITCH_FIVE) {
result = switch5;
}
return result;
}
@Override
public void setIvs(int newIvs[]) {
stats.setHpIv(newIvs[HP]);
stats.setAtkIv(newIvs[ATK]);
stats.setDefIv(newIvs[DEF]);
stats.setSpAtkIv(newIvs[SP_ATK]);
stats.setSpDefIv(newIvs[SP_DEF]);
stats.setSpeIv(newIvs[SPE]);
}
public void setEvs(int hpEv, int atkEv, int defEv, int spAtkEv,
int spDefEv, int spdEv) {
stats.setHpEv(hpEv);
stats.setAtkEv(atkEv);
stats.setDefEv(defEv);
stats.setSpAtkEv(spAtkEv);
stats.setSpDefEv(spDefEv);
stats.setSpeEv(spdEv);
}
@Override
public void setEvs(int newEvs[]) {
stats.setEvs(newEvs);
}
@Override
public void setHpEv(int hpEv) {
stats.setHpEv(hpEv);
}
@Override
public void setAtkEv(int atkEv) {
stats.setAtkEv(atkEv);
}
@Override
public void setDefEv(int defEv) {
stats.setDefEv(defEv);
}
@Override
public void setSpDefEv(int spDefEv) {
stats.setSpDefEv(spDefEv);
}
@Override
public void setSpeEv(int speEv) {
stats.setSpeEv(speEv);
}
@Override
public void setHpIv(int hpIv) {
stats.setHpIv(hpIv);
}
@Override
public void setLevel(int level) {
stats.setLevel(level);
}
@Override
public int getLevel() {
return stats.getLevel();
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String getGender() {
return gender;
}
@Override
public void setSpecies(Species forme) {
this.forme = forme;
int[] baseStats = { forme.getHpBase(), forme.getAtkBase(),
forme.getDefBase(), forme.getspAtkBase(), forme.getspDefBase(),
forme.getspeBase() };
stats.setBaseStats(baseStats);
}
@Override
public boolean hasFainted() {
return status.hasFainted();
}
@Override
public void setNickName(String newNickName) {
nickName = newNickName;
}
@Override
public String getNickName() {
return nickName;
}
@Override
public int getHpIv() {
return stats.getHpIv();
}
@Override
public int getAtkIv() {
return stats.getAtkIv();
}
@Override
public int getDefIv() {
return stats.getDefIv();
}
@Override
public int getSpAtkIv() {
return stats.getSpAtkIv();
}
@Override
public int getSpDefIv() {
return stats.getSpDefIv();
}
@Override
public int getSpeIv() {
return stats.getSpeIv();
}
@Override
public int getHpEv() {
return stats.getHpEv();
}
@Override
public int getAtkEv() {
return stats.getAtkEv();
}
@Override
public int getDefEv() {
return stats.getDefEv();
}
@Override
public int getSpAtkEv() {
return stats.getSpAtkEv();
}
@Override
public int getSpDefEv() {
return stats.getSpDefEv();
}
@Override
public int getSpeEv() {
return stats.getSpeEv();
}
public int getHPBase() {
return stats.getHpBase();
}
@Override
public int getAtkBase() {
return stats.getAtkBase();
}
@Override
public int getDefBase() {
return stats.getDefBase();
}
@Override
public int getSpAtkBase() {
return stats.getSpAtkBase();
}
@Override
public int getSpDefBase() {
return stats.getSpDefBase();
}
@Override
public int getSpeBase() {
return stats.getSpeBase();
}
@Override
public int getMaxHp() {
return stats.getMaxHp();
}
@Override
public void setShiny(boolean isShiny) {
if (isShiny == true) {
this.isShiny = true;
} else {
this.isShiny = false;
}
}
public boolean getShiny() {
return isShiny;
}
public int[] getCalcStats() {
int[] result = new int[NUM_OF_STATS];
result[HP] = stats.getCurrHp();
result[ATK] = stats.getAtk();
result[DEF] = stats.getDef();
result[SP_ATK] = stats.getSpAtk();
result[SP_DEF] = stats.getSpDef();
result[SPE] = stats.getSpe();
return result;
}
@Override
public int getCurrHp() {
return stats.getCurrHp();
}
@Override
public Stats getStats() {
return stats;
}
@Override
public void setCurrHp(int newHp) {
if (newHp <= 0) {
stats.setCurrHp(0);
status.setFainted();
} else {
stats.setCurrHp(newHp);
}
}
@Override
public void incrementToxCount() {
status.incrementToxCount();
}
@Override
public int getSleepDuration() {
return status.getSleepDuration();
}
@Override
public void decrementSleep() {
status.decrementSleep();
}
@Override
public int getInitialSleepDuration() {
return status.getInitialSleepDuration();
}
@Override
public double getAtkMod() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public double getSpeMod() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void cureStatus() {
status.cureStatus();
}
@Override
public boolean isBurnt() {
return status.isBurnt();
}
@Override
public boolean isAsleep() {
return status.isAsleep();
}
@Override
public boolean isParalyzed() {
return status.isParalyzed();
}
@Override
public boolean isOk() {
return status.isOk();
}
@Override
public boolean isRegPoison() {
return status.isRegPoison();
}
@Override
public boolean isToxPoison() {
return status.isToxPoison();
}
@Override
public boolean isFrozen() {
return status.isFrozen();
}
@Override
public void setSleep(int duration) {
status.setSleep(duration);
}
@Override
public boolean doesThaw() {
return status.doesThaw();
}
@Override
public void setToxPoison() {
status.setToxPoison();
}
@Override
public int getToxCount() {
return status.getToxCount();
}
@Override
public void setRegPoison() {
status.setRegPoison();
}
@Override
public void setParalysis() {
status.setParalysis();
}
@Override
public boolean doesFullyParalyze() {
return status.doesFullyParalyze();
}
@Override
public void setBaseStats(int[] baseStats) {
stats.setBaseStats(baseStats);
}
@Override
public void setHpBase(int hpBase) {
stats.setHpBase(hpBase);
}
@Override
public void setAtkBase(int atkBase) {
stats.setAtkBase(atkBase);
}
@Override
public void setDefBase(int defBase) {
stats.setDefBase(defBase);
}
@Override
public void setSpAtkBase(int spAtkBase) {
stats.setSpAtkBase(spAtkBase);
}
@Override
public void setSpDefBase(int spDefBase) {
stats.setSpDefBase(spDefBase);
}
@Override
public void setSpeBase(int speBase) {
stats.setSpeBase(speBase);
}
@Override
public int getHpBase() {
return stats.getHpBase();
}
@Override
public void setAtkIv(int atkIv) {
stats.setAtkIv(atkIv);
}
@Override
public void setDefIv(int defIv) {
stats.setDefIv(defIv);
}
@Override
public void setSpAtkIv(int spAtkIv) {
stats.setSpAtkIv(spAtkIv);
}
@Override
public void setSpDefIv(int spDefIv) {
stats.setSpDefIv(spDefIv);
}
@Override
public void setSpeIv(int speIv) {
stats.setSpeIv(speIv);
}
@Override
public int getHiddenPowerBasePower() {
return stats.getHiddenPowerBasePower();
}
@Override
public Type getHiddenPowerType() {
return stats.getHiddenPowerType();
}
@Override
public void setStats(int[] stats) {
this.stats.setStats(stats);
}
@Override
public void setStats(Stats newStat) {
stats.setStats(newStat);
}
@Override
public void setStats(int hp, int atk, int def, int spAtk, int spDef, int spe) {
stats.setStats(hp, atk, def, spAtk, spDef, spe);
}
@Override
public Nature getNature() {
return nature;
}
@Override
public void setSpAtkEv(int spAtkEv) {
stats.setSpAtkEv(spAtkEv);
}
@Override
public int getAtk() {
return stats.getAtk();
}
@Override
public int getDef() {
return stats.getDef();
}
@Override
public int getSpAtk() {
return stats.getSpAtk();
}
@Override
public int getSpDef() {
return stats.getSpDef();
}
@Override
public int getSpe() {
return stats.getSpe();
}
@Override
public boolean isShiny() {
return isShiny;
}
@Override
public Species getSpecies() {
return forme;
}
@Override
public Type getFirstType() {
return forme.getFirstType();
}
@Override
public Type getSecondType() {
return forme.getSecondType();
}
@Override
public Status getStatus() {
return status;
}
@Override
public boolean isType(Type type) {
return type.equals(getFirstType()) || type.equals(getSecondType());
}
@Override
public String toString() {
String s = forme + " @ " + item + "\n" + ability + "\n"
+ stats.getHpEv() + "\n" + stats.getAtkEv() + "/"
+ stats.getDefEv() + "/" + stats.getSpAtkEv() + "/"
+ stats.getSpDefEv() + "/" + stats.getSpeEv() + "\n"
+ stats.getNature() + "\n-" + move1 + "\n-" + move2 + "\n-"
+ move3 + "\n-" + move4;
return s;
}
@Override
public String getStatAt(int position) {
return stats.getStatAt(position);
}
@Override
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public double getWeight() {
return weight;
}
@Override
public void setFriendship(int friendship) {
this.friendship = friendship;
}
@Override
public int getFriendship() {
return friendship;
}
@Override
public boolean hasAbility(Ability ability) {
return this.ability.equals(ability);
}
@Override
public boolean isGender(Gender gender) {
return this.gender.equals(gender);
}
@Override
public boolean hasItem(Item item) {
return this.item.equals(item);
}
@Override
public boolean isSpecies(Species species) {
return this.forme.equals(species);
}
}<file_sep>package com.omnidex.test.battlefield;
import org.junit.Test;
import com.omnidexter.battlefield.BattleField;
import com.omnidexter.battlefield.SingleBattleField;
import static org.junit.Assert.*;
public class Battlefieldtest {
private BattleField bf;
public Battlefieldtest() {
bf = new SingleBattleField();
}
@Test
public void printBattleField() {
bf.printBattleField();
}
@Test
public void set_Gravity() {
assertFalse(bf.hasGravity());
bf.setGravity(BattleField.DUR_5);
assertTrue(bf.hasGravity());
assertEquals(BattleField.DUR_5, bf.getGravityCount());
}
@Test
public void decrement_Gravity() {
assertFalse(bf.hasGravity());
bf.setGravity(BattleField.DUR_5);
assertTrue(bf.hasGravity());
assertEquals(BattleField.DUR_5, bf.getGravityCount());
bf.decrementGravity();
assertTrue(bf.hasGravity());
assertEquals(4, bf.getGravityCount());
}
@Test
public void copy_constructor_test() {
bf.setRain(5);
BattleField newBf = new SingleBattleField(bf);
assertTrue(bf.isRain());
assertTrue(newBf.isRain());
assertEquals(BattleField.DUR_5, bf.getDuration());
assertEquals(BattleField.DUR_5, newBf.getDuration());
}
}
<file_sep>package com.omnidex.pokemon;
import com.omnidex.ability.Ability;
import com.omnidex.item.Item;
import com.omnidex.move.Move;
import com.omnidex.move.MoveWithPP;
import com.omnidex.type.Type;
/**
* @author jakers
*/
public interface Pokemon extends Status, Stats{
static final int MAX_IV_VALUE = 31;
static final int MAX_LEVEL = 100;
static final int MOVE_ONE = 0;
static final int MOVE_TWO = 1;
static final int MOVE_THREE = 2;
static final int MOVE_FOUR = 3;
static final int SWITCH_ONE = -1;
static final int SWITCH_TWO = -2;
static final int SWITCH_THREE = -3;
static final int SWITCH_FOUR = -4;
static final int SWITCH_FIVE = -5;
/**
* @return a Type enum representing the Pokemon's
* first type.
*/
Type getFirstType();
/**
* @return a Type enum representing the Pokemon's
* second type.
*/
Type getSecondType();
/**
* @return a Stat object representing the Pokemon's
* current stats.
*/
Stats getStats();
/**
* @return a Status object representing the Pokemon's
* current status.
*/
Status getStatus();
/**
* @param type a Type enum to check the type of against the
* Pokemon's type(s)
* @return true if type matches either of the possible two types
* the Pokemon has.
*/
boolean isType(Type type);
Ability getAbility();
String getGender();
boolean hasAbility(Ability ability);
void setAbility(Ability abillity);
void setNickName(String nickname);
String getNickName();
Species getSpecies();
boolean isGender(Gender gender);
void setItem(Item item);
Item getItem();
MoveWithPP getMove(int moveSlot);
void setMove(Move name, int moveSlot);
boolean isShiny();
void setShiny(boolean state);
void setSpecies(Species forme);
void setFriendship(int friendship);
int getFriendship();
boolean hasItem(Item item);
boolean isSpecies(Species species);
void setWeight(double weight);
double getWeight();
}
<file_sep>package com.omnidex.ability;
import com.omnidex.pokemon.Pokemon;
import com.omnidex.type.Type;
import com.omnidex.weather.Weather;
/**
* Enum of all Pokemon abilities.
*
* @author jakers
*/
public enum Ability {
NO_ABILITY("(none)"),
UNKNOWN_ABILITY("(unknown)"),
/* A abilities */
ADAPTABILITY("Adaptability"),
AFTERMATH("Aftermath"),
AIR_LOCK("Air Lock"),
ANALYTIC("Analytic"),
ANGER_POINT("Anger Point"),
ANTICIPATION("Anticipation"),
ARENA_TRAP("Arena Trap"),
/* B abilities */
BAD_DREAMS("Bad Dreams"),
BATTLE_ARMOR("Battle Armor"),
BIG_PECKS("Big Pecks"),
BLAZE("Blaze"),
/* C abilities */
CHLOROPHYLL("Chlorophyll"),
CLEAR_BODY("Clear Body"),
CLOUD_NINE("Cloud Nine"),
COLOR_CHANGE("Color Change"),
COMPOUND_EYES("Compound Eyes"),
CONTRARY("Contrary"),
CURSED_BODY("Cursed Body"),
CUTE_CHARM("Cute Charm"),
/* C abilities */
DAMP("Damp"),
DEAFEATIST("Deafeatist"),
DEFIANT("Defiant"),
DOWNLOAD("Download"),
DRIZZLE("Drizzle"),
DROUGHT("Drought"),
DRY_SKIN("Dry Skin"),
/* E abilities */
EARLY_BIRD("Early Bird"),
EFFECT_SPORE("Effect Spore"),
/* F abilities */
FILTER("Filter"),
FLAME_BODY("Flame Body"),
FLARE_BOOST("Flare Boost"),
FLASH_FIRE("Flash Fire"),
FLOWER_GIFT("Flower Gift"),
FORECAST("Forecast"),
FOREWARN("Forewarn"),
FRIEND_GUARD("Friend Guard"),
FRISK("Frisk"),
/* G abilities */
GLUTTONY("Gluttony"),
GUTS("Guts"),
/* H abilities */
HARVEST("Harvest"),
HEALER("Healer"),
HEATPROOF("Heatproof"),
HEAVY_METAL("Heavy Metal"),
HONEY_GATHER("Honey Gather"),
HUGE_POWER("Huge Power"),
HUSTLE("Hustle"),
HYDRATION("Hydration"),
HYPER_CUTTER("Hyper Cutter"),
/* I abilities */
ICE_BODY("Ice Body"),
ILLUMINATE("Illuminate"),
ILLUSION("Illusion"),
IMMUNITY("Immunity"),
IMPOSTER("Imposter"),
INFILTRATOR("Infiltrator"),
INNER_FOCUS("Inner Focus"),
INSOMNIA("Insomnia"),
INTIMIDATE("Intimidate"),
IRON_BARBS("Iron Barbs"),
IRON_FIST("Iron Fist"),
/* J abilities */
JUSTIFIED("Justified"),
/* K abilities */
KEEN_EYE("Keen Eye"),
KLUTZ("Klutz"),
/* L abilities */
LEAF_GUARD("Leaf Guard"),
LEVITATE("Levitate"),
LIGHT_METAL("Light Metal"),
LIGHTNINGROD("LightningRod"),
LIMBER("Limber"),
LIQUID_OOZE("Liquid Ooze"),
/* M abilities */
MAGIC_BOUNCE("Magic Bounce"),
MAGIC_GUARD("Magic Guard"),
MAGMA_ARMOR("Magma Armor"),
MAGNET_PULL("Magnet Pull"),
MARVEL_SCALE("Marvel Scale"),
MINUS("Minus"),
MOLD_BREAKER("Mold Breaker"),
MOODY("Moody"),
MOTOR_DRIVE("Motor Drive"),
MOXIE("Moxie"),
MULTISCALE("Multiscale"),
MULTITYPE("Multitype"),
MUMMY("Mummy"),
/* N abilities */
NATURAL_CURE("Natural Cure"),
NO_GUARD("No Guard"),
NORMALIZE("Normalize"),
/* O abilities */
OBLIVIOUS("Oblivious"),
OVERCOAT("Overcoat"),
OVERGROW("Overgrow"),
OWN_TEMPO("Own Tempo"),
/* P abilities */
PICK_UP("Pick Up"),
PICKPOCKET("Pickpocket"),
PLUS("Plus"),
POISON_HEAL("Poison Heal"),
POISON_POINT("Poison Point"),
POISON_TOUCH("Poison Touch"),
PRANKSTER("Prankster"),
PRESSURE("Pressure"),
PURE_POWER("Pure Power"),
/* Q abilities */
QUCIK_FEET("Qucik Feet"),
/* R abilities */
RAIN_DISH("Rain Dish"),
RATTLED("Rattled"),
RECKLESS("Reckless"),
REGENERATOR("Regenerator"),
RIVALRY("Rivalry"),
ROCK_HEAD("Rock Head"),
ROUGH_SKIN("Rough Skin"),
RUN_AWAY("Run Away"),
/* S abilities */
SAND_FORCE("Sand Force"),
SAND_RUSH("Sand Rush"),
SAND_STREAM("Sand Stream"),
SAND_VEIL("Sand Veil"),
SAP_SIPPER("Sap Sipper"),
SERENE_GRACE("Serene Grace"),
SHADOW_TAG("Shadow Tag"),
SHED_SKIN("Shed Skin"),
SHEER_FORCE("Sheer Force"),
SHELL_ARMOR("Shell Armor"),
SHIELD_DUST("Shield Dust"),
SIMPLE("Simple"),
SKILL_LINK("Skill Link"),
SLOW_START("Slow Start"),
SNIPER("Sniper"),
SNOW_CLOAK("Snow Cloak"),
SNOW_WARNING("Snow Warning"),
SOLAR_POWER("Solar Power"),
SOLID_ROCK("Solid Rock"),
SOUNDPROOF("Soundproof"),
SPEED_BOOST("Speed Boost"),
STALL("Stall"),
STATIC("Static"),
STEADFAST("Steadfast"),
STENCH("Stench"),
STICKY_HOLD("Sticky Hold"),
STORM_DRAIN("Storm Drain"),
STURDY("Sturdy"),
SUCTION_CUPS("Suction Cups"),
SUPER_LUCK("Super Luck"),
SWARM("Swarm"),
SWIFT_SWIM("Swift Swim"),
SYNCHRONIZE("Synchronize"),
/* T abilities */
TANGLED_FEET("Tangled Feet"),
TECHNICIAN("Technician"),
TELEPATHY("Telepathy"),
TERAVOLT("Teravolt"),
THICK_FAT("Thick Fat"),
TINTED_LENS("Tinted Lens"),
TORRENT("Torrent"),
TOXIC_BOOST("Toxic Boost"),
TRACE("Trace"),
TRUANT("Truant"),
TURBOBLAZE("Turboblaze"),
/* U abilities */
UNAWARE("Unaware"),
UNBURDEN("Unburden"),
UNNERVE("Unnerve"),
/* V abilities */
VICTORY_STAR("Victory Star"),
VITAL_SPIRT("Vital Spirt"),
VOLT_ABSORB("Volt Absorb"),
/* W abilities */
WATER_ABSORB("Water_Absorb"),
WATER_VEIL("Water Veil"),
WEAK_ARMOR("Weak Armor"),
WHITE_SMOKE("White Smoke"),
WONDER_GUARD("Wonder Guard"),
WONDER_SKIN("Wonder Skin"),
/* X abilities */
/* Y abilities */
/* Z abilities */
ZEN_MODE("Zen Mode");
private String name;
Ability(String name) {
this.name = name;
}
public static Ability findAbilityByName(String name) {
Ability ability = null;
for (Ability ab : Ability.values()) {
if (ab.toString().toLowerCase().equals(name.toLowerCase())) {
ability = ab;
break;
}
}
return ability;
}
public boolean preventsSwitching(Pokemon switching) {
switch (this) {
case SHADOW_TAG:
return switching.getAbility() != SHADOW_TAG;
case MAGNET_PULL:
return switching.isType(Type.STEEL);
case ARENA_TRAP:
// TODO implement arena trap ability
return false;
default:
return false;
}
}
public boolean preventsWeather() {
switch (this) {
case CLOUD_NINE:
case AIR_LOCK:
return true;
default:
return false;
}
}
public boolean preventsBurn(Weather weather) {
switch (this) {
case WATER_VEIL:
return true;
case LEAF_GUARD:
return weather.isSun();
default:
return false;
}
}
public boolean accuracyCheckRequired(Pokemon target) {
switch (this) {
case NO_GUARD:
return false;
default:
return target.getAbility() == NO_GUARD;
}
}
public boolean preventsPoision(Pokemon target) {
return this == IMMUNITY;
}
public boolean preventsParalysis(Pokemon target) {
return this == LIMBER;
}
public boolean preventsSleep() {
switch(this) {
case INSOMNIA:
case VITAL_SPIRT:
return true;
default:
return false;
}
}
public boolean preventsFreezing(Pokemon target) {
return this == FLAME_BODY;
}
public boolean preventsConfusion() {
return this == OWN_TEMPO;
}
public boolean reflectsStatus(Pokemon self) {
switch(this) {
case SYNCHRONIZE:
return !self.isOk();
default:
return false;
}
}
public boolean ignoresBurnDebuff() {
return this == GUTS;
}
public boolean ignoreParaSpeedDebuff() {
return this == QUCIK_FEET;
}
public boolean healsWhenPoisoned() {
return this == POISON_HEAL;
}
// TODO can cure own status
public boolean preventsSoundMoves() {
return this == SOUNDPROOF;
}
public boolean regenerates() {
return this == REGENERATOR;
}
public boolean clearsStatusAfterSwitch() {
return this == NATURAL_CURE;
}
// TODO immune to ground
// TODO early wake up
// TODO reduces fire damage
// TODO prevents phazing
public boolean causesBadDreams() {
return this == BAD_DREAMS;
}
public boolean preventsRecoil() {
switch(this) {
case ROCK_HEAD:
case MAGIC_GUARD:
return true;
default:
return false;
}
}
public boolean preventsSecondaryDamage() {
return this == MAGIC_GUARD;
}
public boolean hurtsLeecher() {
return this == LIQUID_OOZE;
}
public boolean weakensSEHits() {
switch(this) {
case FILTER:
case SOLID_ROCK:
return true;
default:
return false;
}
}
public boolean strengthensNVEHits() {
return this == TINTED_LENS;
}
public boolean burnsExtraPP() {
return this == PRESSURE;
}
public boolean ignoresDamagePreventingAbilities() {
switch(this) {
case MOLD_BREAKER:
case TERAVOLT:
case FLARE_BOOST:
return true;
default:
return false;
}
}
public boolean buffsCritDamage() {
return this == SNIPER;
}
// TODO buffs defense
// TODO buffs spatk
// TODO buffs spdef
// TODO boost speed
// TODO boost speed if flinched
public boolean buffsSTAB() {
return this == ADAPTABILITY;
}
public boolean isLoafing(boolean loaf) {
return this == TRUANT && loaf;
}
public void switchActivatedAbility(Pokemon switchIn, Pokemon opponent, Weather weather) {
switch (switchIn.getAbility()) {
case DRIZZLE:
weather.setRain(Weather.PERMANENT);
break;
case DROUGHT:
weather.setSun(Weather.PERMANENT);
break;
case SAND_STREAM:
weather.setSand(Weather.PERMANENT);
break;
case SNOW_WARNING:
weather.setHail(Weather.PERMANENT);
break;
case INTIMIDATE:
// TODO implement intimidate ability
break;
case DOWNLOAD:
// TODO implement download
break;
case TRACE:
//TODO test for aliasing of abilities
switchIn.setAbility(opponent.getAbility());
break;
case FORECAST:
// TODO implement forecast
break;
case FLOWER_GIFT:
// TODO implement flower gift
break;
default:
break;
}
}
public boolean preventsFlinching() {
return this == INNER_FOCUS;
}
public String toString() {
return name;
}
}
<file_sep>package com.omnidex.battlefield.team;
import java.util.ArrayList;
import java.util.List;
import com.omnidex.damage.EntryHazardDamage;
import com.omnidex.game.Game;
import com.omnidex.move.Move;
import com.omnidex.move.MoveWithPP;
import com.omnidex.pokemon.ActivePokemon;
import com.omnidex.pokemon.InactivePokemon;
import com.omnidex.pokemon.Pokemon;
import com.omnidexter.ai.AiWriter;
public class DeepTeam extends FieldScreen implements Team {
private int teamId;
private int choice;
private ActivePokemon activePokemon;
private List<Pokemon> party;
private boolean hasStealthRocks;
private int wishCount;
private int wishHealAmount;
private int mistCount;
private int luckyChantCount;
private int safeguardCount;
private int spikesCount;
private int toxicSpikesCount;
private int tailwindCount;
private boolean hasWaterSport;
private boolean hasMudSport;
private static final int MAX_NUM_SPIKE_LAYERS = 3;
private static final int MAX_NUM_T_SPIKE_LAYERS = 2;
private int teamSize = 0;
public DeepTeam() {
super();
party = new ArrayList<Pokemon>();
hasStealthRocks = false;
tailwindCount = 0;
luckyChantCount = 0;
safeguardCount = 0;
mistCount = 0;
spikesCount = 0;
toxicSpikesCount = 0;
teamId = Game.OPPONENT;
choice = 0;
}
public DeepTeam(Team team) {
super(team);
party = new ArrayList<Pokemon>();
activePokemon = team.getActivePokemon();
List<Pokemon> temp = team.getParty();
for (int i = 0; i < temp.size(); i++) {
party.add(temp.get(i));
}
hasStealthRocks = team.hasStealthRocks();
spikesCount = team.getSpikesCount();
toxicSpikesCount = team.getToxicSpikesCount();
teamSize = team.teamSize();
choice = team.getChoice();
teamId = team.getTeamId();
}
@Override
public void addTeamMate(Pokemon p) {
if (activePokemon == null) {
activePokemon = new ActivePokemon(p);
} else {
party.add(new InactivePokemon(p));
}
teamSize++;
}
@Override
public int size() {
if (activePokemon == null) {
return 0;
} else {
return 1 + party.size();
}
}
@Override
public ActivePokemon getActivePokemon() {
return activePokemon;
}
@Override
public void switchActivePokemon(MoveWithPP switchOption) {
Move switchTo = switchOption.getMove();
AiWriter.writeSwitch(activePokemon, teamId);
activePokemon.setSleep(activePokemon.getInitialSleepDuration());
switch (switchTo) {
case SWITCH_1:
activePokemon = new ActivePokemon(party.get(0));
break;
case SWITCH_2:
activePokemon = new ActivePokemon(party.get(1));
break;
case SWITCH_3:
activePokemon = new ActivePokemon(party.get(2));
break;
case SWITCH_4:
activePokemon = new ActivePokemon(party.get(3));
break;
case SWITCH_5:
activePokemon = new ActivePokemon(party.get(4));
break;
case SWITCH_6:
activePokemon = new ActivePokemon(party.get(5));
break;
default:
break;
}
EntryHazardDamage.applyToxicSpikes(this);
EntryHazardDamage.applySpikeDamage(this);
EntryHazardDamage.applyStealthRocks(this);
}
@Override
public List<Pokemon> getParty() {
return party;
}
@Override
public boolean hasStealthRocks() {
return hasStealthRocks;
}
@Override
public boolean hasSpikes() {
return spikesCount > 0;
}
@Override
public boolean hasToxicSpikes() {
return toxicSpikesCount > 0;
}
@Override
public void addSpikes() {
if (spikesCount < MAX_NUM_SPIKE_LAYERS) {
spikesCount++;
}
}
@Override
public void addToxicSpikes() {
if (toxicSpikesCount < MAX_NUM_T_SPIKE_LAYERS) {
toxicSpikesCount++;
}
}
@Override
public int getSpikesCount() {
return spikesCount;
}
@Override
public int getToxicSpikesCount() {
return toxicSpikesCount;
}
@Override
public void removeStealthRocks() {
hasStealthRocks = false;
}
@Override
public void removeSpikes() {
spikesCount = 0;
}
@Override
public void removeToxicSpikes() {
toxicSpikesCount = 0;
}
@Override
public void addStealthRocks() {
hasStealthRocks = true;
}
@Override
public boolean hasMist() {
return mistCount > 0;
}
@Override
public int getMistCount() {
return mistCount;
}
@Override
public boolean hasSafeguard() {
return safeguardCount > 0;
}
@Override
public int getSafeguardCount() {
return safeguardCount;
}
@Override
public boolean hasLuckyChant() {
return luckyChantCount > 0;
}
@Override
public int getLuckyChantCount() {
return luckyChantCount;
}
@Override
public void addMist(int duration) {
mistCount = duration;
}
@Override
public void decrementMist() {
if (mistCount > 0) {
mistCount--;
}
}
@Override
public void addLuckyChant(int duration) {
luckyChantCount = duration;
}
@Override
public void decrementLuckyChant() {
if (luckyChantCount > 0) {
luckyChantCount--;
}
}
@Override
public void addSafeguard(int duration) {
safeguardCount = duration;
}
@Override
public void decrementSafeguard() {
if (safeguardCount > 0) {
safeguardCount--;
}
}
@Override
public boolean hasWish() {
return wishCount > 0;
}
@Override
public void addWish(int duration, int wishHealAmount) {
wishCount = duration;
this.wishHealAmount = wishHealAmount;
}
@Override
public void decrementWishCount() {
if (wishCount > 0) {
wishCount--;
if (wishCount == 0) {
activePokemon.setCurrHp(activePokemon.getCurrHp()
+ wishHealAmount);
wishHealAmount = 0;
}
}
}
@Override
public int teamSize() {
return teamSize;
}
@Override
public void addTailWind() {
tailwindCount = 3;
}
@Override
public int getTailWindCount() {
return tailwindCount;
}
@Override
public void decrementTailWind() {
if (tailwindCount > 0) {
tailwindCount--;
}
}
@Override
public boolean hasTailWind() {
return tailwindCount > 0;
}
@Override
public void setChoice(int choice) {
this.choice = choice;
}
@Override
public int getChoice() {
return choice;
}
@Override
public int getTeamId() {
return teamId;
}
@Override
public void setTeamId(int teamId) {
this.teamId = teamId;
}
@Override
public boolean hasMudSport() {
return hasMudSport;
}
@Override
public void setMudSport(boolean state) {
hasMudSport = state;
}
@Override
public boolean hasWaterSport() {
return hasWaterSport;
}
@Override
public void setWaterSport(boolean state) {
hasWaterSport = state;
}
@Override
public boolean canSwitch(MoveWithPP switchOption, Team opponent) {
if (opponent.getActivePokemon().getAbility()
.preventsSwitching(activePokemon)) {
return false;
}
Move switchTo = switchOption.getMove();
Pokemon pokeToSwitchIn = null;
switch (switchTo) {
case SWITCH_1:
pokeToSwitchIn = party.get(0);
break;
case SWITCH_2:
pokeToSwitchIn = party.get(1);
break;
case SWITCH_3:
pokeToSwitchIn = party.get(2);
break;
case SWITCH_4:
pokeToSwitchIn = party.get(3);
break;
case SWITCH_5:
pokeToSwitchIn = party.get(4);
break;
case SWITCH_6:
pokeToSwitchIn = party.get(5);
break;
default:
break;
}
if (!pokeToSwitchIn.hasFainted()) {
return true;
} else {
return false;
}
}
}
<file_sep>package com.omnidex.pokemon;
import java.util.Random;
import com.omnidex.item.Item;
import com.omnidex.move.Move;
import com.omnidex.type.Type;
public class ActivePokemon extends InactivePokemon {
private static final int INITIAL_PERISH_COUNT = 3;
private static final int INITIAL_EMBARGO_COUNT = 5;
private static final int INITIAL_ENCORE_COUNT = 3;
private static final int INITIAL_HEAL_BLOCK_COUNT = 5;
private static final int MAX_PARTIAL_TRAPPING_COUNT = 5;
private static final int INITIAL_ELECTIC_MAGNETIC_LEVIATION_COUNT = 5;
private Stageable criticalHit;
private Stageable evasion;
private Stageable accuracy;
private Stageable attackStage;
private Stageable defenseStage;
private Stageable spAtkStage;
private Stageable spDefStage;
private Stageable speedStage;
private boolean isAttracted;
private boolean isProtected;
private boolean isIngrained;
private boolean hasAquaRing;
private boolean isConfused;
private boolean hasBeenHitByYawn;
private boolean isBehindSub;
private boolean isSeeded;
private boolean isCursed;
private boolean isHidden;
private boolean isFlying;
private boolean isDigging;
private boolean isDiving;
private boolean isUsingShadowForce;
private int perishCount;
private int embargoCount;
private int encoreCount;
private boolean hasFlinched;
private int healBlockCount;
private boolean isIgnoringFightingAndNormalImmunity;
private boolean isIgnoringPsychicImmunity;
private boolean hasNightmare;
private int magmaStormCount;
private int sandTombCount;
private int whirlpoolCount;
private int wrapCount;
private int bindCount;
private int clampCount;
private int fireSpinCount;
private boolean isTelekineticlyLevitated;
private boolean hasGravity;
private boolean isTormented;
private Move lastMove;
private boolean isTrapped;
private boolean isBracing;
private boolean hasBoostedRolloutAndIceBall;
private boolean hasFocusEnergy;
private int electricMagniticLeviationCount;
private boolean isMinimized;
private int rechargeCount;
private int chargingMoveCount;
private boolean hasTakenAim;
private boolean hasFlashFireBoost;
public ActivePokemon(Species species) {
super(species);
isAttracted = false;
isProtected = false;
isIngrained = false;
hasAquaRing = false;
isConfused = false;
hasBeenHitByYawn = false;
isBehindSub = false;
isSeeded = false;
isCursed = false;
isHidden = false;
isFlying = false;
isDigging = false;
isDiving = false;
isUsingShadowForce = false;
perishCount = 0;
embargoCount = 0;
encoreCount = 0;
hasFlinched = false;
healBlockCount = 0;
lastMove = Move.NONE;
criticalHit = new CriticalHitStages();
evasion = new HitStages();
accuracy = new HitStages();
attackStage = new StatStages();
defenseStage = new StatStages();
spAtkStage = new StatStages();
spDefStage = new StatStages();
speedStage = new StatStages();
}
public ActivePokemon(Pokemon poke) {
super(poke);
isAttracted = false;
isProtected = false;
isIngrained = false;
hasAquaRing = false;
isConfused = false;
hasBeenHitByYawn = false;
isBehindSub = false;
isSeeded = false;
isCursed = false;
isHidden = false;
isFlying = false;
isDigging = false;
isDiving = false;
isUsingShadowForce = false;
perishCount = 0;
embargoCount = 0;
encoreCount = 0;
hasFlinched = false;
healBlockCount = 0;
lastMove = Move.NONE;
criticalHit = new CriticalHitStages();
evasion = new HitStages();
accuracy = new HitStages();
attackStage = new StatStages();
defenseStage = new StatStages();
spAtkStage = new StatStages();
spDefStage = new StatStages();
speedStage = new StatStages();
}
public ActivePokemon() {
isAttracted = false;
isProtected = false;
isIngrained = false;
hasAquaRing = false;
isConfused = false;
hasBeenHitByYawn = false;
isBehindSub = false;
isSeeded = false;
isCursed = false;
isHidden = false;
isFlying = false;
isDigging = false;
isDiving = false;
isUsingShadowForce = false;
perishCount = 0;
embargoCount = 0;
encoreCount = 0;
hasFlinched = false;
healBlockCount = 0;
lastMove = Move.NONE;
criticalHit = new CriticalHitStages();
evasion = new Stage(-6, 6, 0);
attackStage = new StatStages();
defenseStage = new Stage(-6, 6, 0);
spAtkStage = new Stage(-6, 6, 0);
spDefStage = new Stage(-6, 6, 0);
speedStage = new Stage(-6, 6, 0);
}
public void activateAttract() {
isAttracted = true;
}
public boolean isAttracted() {
return isAttracted;
}
public void activateProtect() {
isProtected = true;
}
public boolean isProtected() {
return isProtected;
}
public void breakProtection() {
isProtected = false;
}
public void activateIngrain() {
isIngrained = true;
}
public boolean isIngrained() {
return isIngrained;
}
public void activateAquaRing() {
hasAquaRing = true;
}
public boolean hasAquaRing() {
return hasAquaRing;
}
public void activateConfused() {
if (getAbility().preventsConfusion()) {
isConfused = false;
} else {
isConfused = true;
}
}
public boolean isConfused() {
return isConfused;
}
public void activateYawn() {
boolean affectedByYawn = getAbility().preventsSleep() || isBehindSub
|| !isOk();
if (affectedByYawn) {
hasBeenHitByYawn = false;
} else {
hasBeenHitByYawn = true;
}
}
public boolean isBehindSub() {
return isBehindSub;
}
public boolean hasBeenHitByYawn() {
return hasBeenHitByYawn;
}
public void activateSubstitute() {
isBehindSub = true;
}
public void activateSeeds() {
if (isType(Type.GRASS) || isBehindSub) {
isSeeded = false;
} else {
isSeeded = true;
}
}
public boolean isSeeded() {
return isSeeded;
}
public void activateCurse() {
if (isType(Type.GHOST)) {
isCursed = true;
} else {
isCursed = false;
}
}
public boolean isCursed() {
return isCursed;
}
public void activateHiding() {
isHidden = true;
}
public boolean isHiding() {
return isHidden;
}
public void activateFly() {
activateHiding();
isFlying = true;
}
public boolean isFlying() {
return isFlying;
}
public void activateDig() {
activateHiding();
isDigging = true;
}
public boolean isDigging() {
return isDigging;
}
public void activateDive() {
activateHiding();
isDiving = true;
}
public boolean isDiving() {
return isDiving;
}
public void activateShadowForce() {
activateHiding();
isUsingShadowForce = true;
}
public boolean isUsingShadowForce() {
return isUsingShadowForce;
}
public void activatePerishSong() {
if (getAbility().preventsSoundMoves() || willPerish()) {
perishCount = 0;
} else {
perishCount = INITIAL_PERISH_COUNT;
}
}
public int getPerishCount() {
return perishCount;
}
public boolean willPerish() {
return perishCount > 0;
}
public void decrementPerishSong() {
if (willPerish()) {
perishCount--;
if (perishCount == 0) {
setFainted();
}
}
}
public void activateEmbargo() {
if (embargoCount == 0) {
embargoCount = INITIAL_EMBARGO_COUNT;
}
}
public boolean isEmbargoed() {
return embargoCount > 0;
}
public int getEmbargoCount() {
return embargoCount;
}
public void decrementEmbargo() {
if (embargoCount > 0) {
embargoCount--;
}
}
public void activateEncore() {
if (encoreCount == 0) {
encoreCount = INITIAL_ENCORE_COUNT;
}
}
public boolean hasEncore() {
return encoreCount > 0;
}
public int getEncoreCount() {
return encoreCount;
}
public void activateFlinch() {
if (getAbility().preventsFlinching()) {
hasFlinched = false;
} else {
hasFlinched = true;
}
}
public boolean hasFlinched() {
return hasFlinched;
}
public void activateHealBlock() {
if (healBlockCount == 0) {
healBlockCount = INITIAL_HEAL_BLOCK_COUNT;
}
}
public boolean canNotHeal() {
return healBlockCount > 0;
}
public int getHealBlockCount() {
return healBlockCount;
}
public void decrementHealBlock() {
if (healBlockCount > 0) {
healBlockCount--;
}
}
// public void activateIdentification() {
// hasBeenIdentified = true;
// }
public void activateIgnoreNormalAndFightingImmunity() {
if (isType(Type.GHOST)) {
isIgnoringFightingAndNormalImmunity = true;
} else {
isIgnoringFightingAndNormalImmunity = false;
}
}
public boolean NormalAndFightingImmunityIgnored() {
return isIgnoringFightingAndNormalImmunity;
}
public void activateIgnorePsychicImmunity() {
if (isType(Type.DARK)) {
isIgnoringPsychicImmunity = true;
} else {
isIgnoringPsychicImmunity = false;
}
}
public boolean PsychicImmunityIgnored() {
return isIgnoringPsychicImmunity;
}
public void activateNightmare() {
if (isAsleep()) {
hasNightmare = true;
} else {
hasNightmare = false;
}
}
public boolean hasNightmare() {
return hasNightmare;
}
public void activateMagmaStorm() {
magmaStormCount = determinePartialTrapCount();
}
public boolean isPartiallyTrapped() {
return hasMagmaStorm() || hasSandTomb() || hasWhirlpool()
|| isWrapped() || isBound() || isClamped() || hasFireSpin();
}
public int getMagmaStromCount() {
return magmaStormCount;
}
public boolean hasMagmaStorm() {
return magmaStormCount > 0;
}
public void decrementMagmaStorm() {
if (magmaStormCount > 0) {
magmaStormCount--;
}
}
public void activateSandTomb() {
sandTombCount = determinePartialTrapCount();
}
public int getSandTombCount() {
return sandTombCount;
}
public boolean hasSandTomb() {
return sandTombCount > 0;
}
private int determinePartialTrapCount() {
int count = 0;
if (getItem().equals(Item.GRIP_CLAW)) {
count = MAX_PARTIAL_TRAPPING_COUNT;
} else {
count = new Random().nextInt(4) + 2;
}
return count;
}
public void decrementSandTomb() {
if (sandTombCount > 0) {
sandTombCount--;
}
}
public void activateWhirlpool() {
whirlpoolCount = determinePartialTrapCount();
}
public boolean hasWhirlpool() {
return whirlpoolCount > 0;
}
public int getWhirlpoolCount() {
return whirlpoolCount;
}
public void decrementWhirlpool() {
if (whirlpoolCount > 0) {
whirlpoolCount--;
}
}
public void activateWrap() {
wrapCount = determinePartialTrapCount();
}
public boolean isWrapped() {
return wrapCount > 0;
}
public int getWrapCount() {
return wrapCount;
}
public void decrementWrap() {
if (wrapCount > 0) {
wrapCount--;
}
}
public void activateBind() {
bindCount = determinePartialTrapCount();
}
public boolean isBound() {
return bindCount > 0;
}
public int getBindCount() {
return bindCount;
}
public void decrementBind() {
if (bindCount > 0) {
bindCount--;
}
}
public void activateClamp() {
clampCount = determinePartialTrapCount();
}
public boolean isClamped() {
return clampCount > 0;
}
public int getClampCount() {
return clampCount;
}
public void decrementClamp() {
if (clampCount > 0) {
clampCount--;
}
}
public void activateFireSpin() {
fireSpinCount = determinePartialTrapCount();
}
public boolean hasFireSpin() {
return fireSpinCount > 0;
}
public int getFireSpinCount() {
return fireSpinCount;
}
public void decrementFireSpin() {
if (fireSpinCount > 0) {
fireSpinCount--;
}
}
public void activateTelekineticLevitation() {
if (isIngrained() || getItem().equals(Item.IRON_BALL) || hasGravity) {
isTelekineticlyLevitated = false;
} else {
isTelekineticlyLevitated = true;
}
}
public boolean isTelekineticlyLevitated() {
return isTelekineticlyLevitated && !hasGravity && !isIngrained()
&& !getItem().equals(Item.IRON_BALL);
}
public void activateGravity() {
hasGravity = true;
}
public void activateTorment() {
isTormented = true;
}
public boolean isTormented() {
return isTormented;
}
public void setLastMove(Move move) {
lastMove = move;
}
public Move getLastMove() {
return lastMove;
}
public boolean canUseMove(Move move) {
if (isTormented()) {
return !lastMove.equals(move);
} else if (chargingMoveCount > 0) {
return false;
} else {
return true;
}
}
public boolean canSwith() {
return !isTrapped || getItem().equals(Item.SHED_SHELL);
}
public void activateTrapped() {
if (getItem().equals(Item.SHED_SHELL)) {
isTrapped = false;
} else {
isTrapped = true;
}
}
public void activateBracing() {
isBracing = true;
}
public boolean isBracing() {
return isBracing;
}
public void activateBoostRolloutAndIceBall() {
hasBoostedRolloutAndIceBall = true;
}
public boolean hasBoostedRolloutAndIceBall() {
return hasBoostedRolloutAndIceBall;
}
public void activateFocusEnergy() {
hasFocusEnergy = true;
criticalHit.boostStage(2);
}
public boolean hasFocusEnergy() {
return hasFocusEnergy;
}
public int getCriticalHitStage() {
return criticalHit.getStage();
}
public double getCriticalHitModifier() {
return criticalHit.getStageModifier();
}
public void activateElectricMagniticLevitation() {
if (getItem().equals(Item.IRON_BALL)) {
electricMagniticLeviationCount = 0;
} else {
electricMagniticLeviationCount = INITIAL_ELECTIC_MAGNETIC_LEVIATION_COUNT;
}
}
public boolean hasElectricMagnitcLevitation() {
if (getItem().equals(Item.IRON_BALL)) {
electricMagniticLeviationCount = 0;
}
return electricMagniticLeviationCount > 0;
}
public void decrementElectricMagniticLeviation() {
if (electricMagniticLeviationCount > 0) {
electricMagniticLeviationCount--;
}
}
public int getElectricMagnitcLevitationCount() {
return electricMagniticLeviationCount;
}
public void activateMinimize() {
isMinimized = true;
evasion.boostStage(2);
}
public boolean isMinimized() {
return isMinimized;
}
public int getEvasionStage() {
return evasion.getStage();
}
public void boostEvasionStage(int boost) {
evasion.boostStage(boost);
}
public void decreaseEvasionStage(int decrease) {
evasion.decreaseStage(decrease);
}
public int getAccuracyStage() {
return accuracy.getStage();
}
public void boostAccuracyStage(int boost) {
accuracy.boostStage(boost);
}
public void decreaseAccuracyStage(int decrease) {
accuracy.decreaseStage(decrease);
}
public void activateRecharge() {
rechargeCount = 2;
}
public boolean hasToRecharge() {
return rechargeCount > 0;
}
public void decrementRecharge() {
if (rechargeCount > 0) {
rechargeCount--;
}
}
public void endTurnCleanup() {
decrementRecharge();
decrementCharge();
clearTakenAim();
}
private void clearTakenAim() {
if (!lastMove.isStatus()) {
hasTakenAim = false;
}
}
private void decrementCharge() {
if (chargingMoveCount > 0) {
chargingMoveCount--;
}
}
public void activateChargingMove() {
chargingMoveCount = 1;
}
public boolean hasToChargeMove() {
return chargingMoveCount > 0;
}
public void activateSkullBashBoost() {
chargingMoveCount = 1;
defenseStage.boostStage(1);
}
public void activateTakingAim() {
hasTakenAim = true;
}
public boolean hasTakenAim() {
return hasTakenAim;
}
public void activateFlashFireBoost() {
hasFlashFireBoost = true;
}
public boolean hasFlashFireBoost() {
return hasFlashFireBoost;
}
public void boostAttackStage(int boost) {
attackStage.boostStage(boost);
}
public void decreaseAttackStage(int decrease) {
attackStage.decreaseStage(decrease);
}
public void boostDefenseStage(int boost) {
defenseStage.boostStage(boost);
}
public void decreaseDefenseStage(int decrease) {
defenseStage.decreaseStage(decrease);
}
public void boostSpAtkStage(int boost) {
spAtkStage.boostStage(boost);
}
public void decreaseSpAtkStage(int decrease) {
spAtkStage.decreaseStage(decrease);
}
public void boostSpDefStage(int boost) {
spDefStage.boostStage(boost);
}
public void decreaseSpDefStage(int decrease) {
spDefStage.decreaseStage(decrease);
}
public void boostSpeStage(int boost) {
speedStage.boostStage(boost);
}
public void decreaseSpeStage(int decrease) {
speedStage.decreaseStage(decrease);
}
public int getCurrAtk() {
return (int) (attackStage.getStageModifier() * stats.getAtk());
}
public int getCurrDef() {
return (int) (defenseStage.getStageModifier() * stats.getDef());
}
public int getCurrSpAtk() {
return (int) (spAtkStage.getStageModifier() * stats.getSpAtk());
}
public int getCurrSpDef() {
return (int) (spDefStage.getStageModifier() * stats.getSpDef());
}
public int getCurrSpe() {
return (int) (speedStage.getStageModifier() * stats.getSpe());
}
public int getAtkStage() {
return attackStage.getStage();
}
public int getDefStage() {
return defenseStage.getStage();
}
public int getSpAtkStage() {
return spAtkStage.getStage();
}
public int getSpDefStage() {
return spDefStage.getStage();
}
public int getSpeStage() {
return speedStage.getStage();
}
}
<file_sep>package com.omnidexter.ai;
import java.util.List;
import com.omnidex.battlefield.team.Team;
import com.omnidex.pokemon.Pokemon;
public class FitnessScore {
private final static double DRAW = 3.0;
private final static double PLAYER_ONE_WINS = 1.0;
private final static double PLAYER_TWO_WINS = -1.0;
/**
* @param t1 a DeepTeam object that represents team 1
* @param t2 a DeepTeam object that represents team 2
* @return a double representing the fitness of a situation.
* the closer the value returned is to 1.0 the more fit the situation is
* for player 1. the closer to -1.0 the more fit the situation is for
* player 2
* if 1.0 is returned that means player 1 wins. If -1.0 is returned then
* player 2
* wins
* if match is a draw (both players all Pokemon's hp = zero) then returns
* 3.0
*
* (%Hp of team 1/t1 size) - (%Hp of team2)/(t2 size)
*/
public static double calcFitness(Team t1, Team t2) {
double result = 0.0;
double team1Score = 0.0;
team1Score = t1.getActivePokemon().getCurrHp()
/ (double) t1.getActivePokemon().getMaxHp();
List<Pokemon> team1Party = t1.getParty();
for (int i = 0; i < team1Party.size(); i++) {
double temp = team1Party.get(i).getCurrHp()
/ (double) team1Party.get(i).getMaxHp();
team1Score += temp;
}
team1Score /= t1.teamSize();
double team2Score = 0.0;
team2Score = t2.getActivePokemon().getCurrHp()
/ (double) t2.getActivePokemon().getMaxHp();
List<Pokemon> team2Party = t2.getParty();
for (int i = 0; i < team2Party.size(); i++) {
double temp = team2Party.get(i).getCurrHp()
/ (double) team2Party.get(i).getMaxHp();
team2Score += temp;
}
team2Score /= t2.teamSize();
if (team1Score == 0.0 && team2Score == 0.0) {
result = DRAW;
} else if (team1Score == 0.0) {
result = PLAYER_ONE_WINS;
} else if (team2Score == 0.0) {
result = PLAYER_TWO_WINS;
} else {
result = team1Score - team2Score;
}
return result;
}
}
<file_sep>package com.omnidex.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class OmniDex {
private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/omnidex";
private static final String USER_NAME = "root";
private static final String PASSWORD = "<PASSWORD>";
private static Connection conn;
private static OmniDex instance;
public static Connection getConnection() {
if (instance == null) {
instance = new OmniDex();
}
return conn;
}
private OmniDex() {
try {
Class.forName(DRIVER_CLASS);
conn = DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
} catch (ClassNotFoundException e) {
System.out.println("Failed to locate " + DRIVER_CLASS + " driver!");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Failed to establish connection to "+DB_URL);
e.printStackTrace();
}
}
}
|
f061512dff06ecd3490fb0ad62ba293ce786c878
|
[
"Java",
"Markdown"
] | 23 |
Java
|
jakers/OmniDexter
|
24e4a53b57e23d5a6633000bfbbb804b06f4957d
|
b2029b969317a05012987c8d99e45e9d24e497ea
|
refs/heads/master
|
<file_sep>## My Portfolio Projects Landing Page
### Created using GitHub pages
#### Check it out! https://dannyrooks.github.io
<file_sep>### Guitar Collection
##### Single page JavaScript applictaion where a user can catalog a collection of guitars by guitar name, brand, and year.
##### Styled using CSS and Bootstrap.
<file_sep>## Portfolio
---
### Recent Projects
[The Fishing Report](/fishing_report_page.md)
<img src="images/Screen Shot 2021-03-17 at 5.39.13 PM.png?raw=true"/>
<!-- <img src="images/Animated GIF-downsized.gif ?raw=true"/> -->
---
[Guitar Collection](/guitar_collection_page.md)
<img src="images/Screen Shot 2021-03-17 at 5.41.54 PM.png?raw=true"/>
---
[Fly Patterns](/fly_patterns_page.md)
<img src="images/Screen Shot 2021-03-17 at 5.43.54 PM.png?raw=true"/>
---
### Category Name 2
- [Project 1 Title](http://example.com/)
- [Project 2 Title](http://example.com/)
- [Project 3 Title](http://example.com/)
- [Project 4 Title](http://example.com/)
- [Project 5 Title](http://example.com/)
---
<file_sep>### Fly Patterns
#### Single-page React/Redux application which allows users to save materials needed for tying flies.
#### Single-page application allowing users (fishermen) to keep track of materials needed for tying flies.
#### Utilized Javascript with ES6 syntax and Redux Thunk to connect React frontend to Rails and SQLite backend.
#### Styled with React-Bootstrap and CSS.
<file_sep>## Fishing Report
### Gives users the ability to sign-up and sign-in to their accounts using GitHub
### Users can create or post new locations adding details about that specific location.
### Users can also add comments with timestamps to locations created by other users.
### A user is only able to edit or delete comments they created.
|
1fcc4f8863bba4cfb0e491c69a72834969361f64
|
[
"Markdown"
] | 5 |
Markdown
|
dannyrooks/dannyrooks.github.io
|
3f63c2dfbbef05cc180e988cdbac9508a51faeb2
|
5566cc3a94afb4159eea807f02ce6de0c3c89803
|
refs/heads/master
|
<file_sep>Hot Topics:
0. LinkedList
a. Fast and Slow Counters(Cycles)
b. Removing Duplicates
c. Addition
1. Stack
a. Reverse Linked List
2. Heap
a. Kth Largest Element in a Stream
b. Top K Frequent Elements
c. Find K pairs with smallest sums
-See Lambda
-See using Lambda Aggregates in a Blockchain
3. Priority Q
4. HashMap
a. Two Sum
b. Group Anagrams
c. Array Intersection
d. Unique Email(hash Address- MD5 Public Addresses)
i. 1 way, collisionless
- hash by combination of all their information,
- hash by id, first name, lastname, in rotated order as input etc
- cryptography in an Ethereum Blockchain
- research system design scalability issues in decentralized applications on Blockchain Architecture, tradeoffs of freedom
- research potential points of failure(total system failure) in a Blockchain, Blockchain glitches
- 51% attack prevention
e. First Unique Character in String
f. Subarray Sum equals K
5. Graph
a. BFS
- Binary Tree Level Order Traversal
b. DFS
- Binary Tree Zigzag Level Order Traversal
- Num Islands
- Max Area of Island
- Word Ladder
- Number of Connected Components in an undirected Graph
c. Shortest Path
6. Tree
a. BT
- Maximum Depth of A Binary Tree
- Minimum Depth of A Binary Tree
- Merge Two Binary Trees
- Convert Sorted Array to Binary Search Tree
i. Reverse Binary Search
- Path Sum
b. BST (Balanced)
- Validate Binary Search Tree
- Construct Binary Search Tree from Preorder and Inorder traversal
7. Dynamic/Functional Programming
a. Paint Fence
b. Longest Increasing Subsequence
c. Macimum Subarray
d. Unique Paths(Perms)
e. Heist
f. Buy Sell Stock
g. Word Break
h. Coin Change(backpack)
8. Binary Search Hybrids
a. Search Insert Position
b. Find Minimum in Rotated Sorted Array
c. Search in Rotated Sorted Array
d. Capacity to Ship Packages by D-Day
9. Recursion
9. Recursion
i. Pow(x,n)
ii. K-th Symbol in Grammer
iii. Split a BST
10. Sliding Window
a. Strings
i. Longest Substring Without Repeating chars
b. Greedy Algorithms-"take it or leave it"
i. Profit Max
c. Minimum Size Subarray Sum
11. Greedy and Backtracking
a. Permutations
b. Subsets
c. Combination Sum
d. Generate Parenthesis
12. Miscellaneous
a. Move Zeroes
b. Meeting Rooms
c. Is Subsequence
d. Next Permutation
e. String to Integer(atoi)
f. ZigZag Conversion
Key Concepts:
-recursion
-dijistra's path algorithm
-cache/memoization
Javascript Specific:
- use of inner function, closer,
- callbacks and higher order functions
- async/await or promise chains
Extranneous Concepts:
- Bloom Filter
Important Datastructures for Blockchain Architecture:
- Hashmap, Map
- Linked List
- Trees, Graphs
- Bloom Filters
> check is is in Set
To Do:
- System Design Decentralized Instagram using the Blockchain architecture<file_sep>// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(A, S) {
// write your code in JavaScript (Node.js 8.9.4
let result = 0;
if(A.length<1){
return result; //base case
}
//dymamic
let runningSum = 0;
for(let i=0; i<A.length; i++){
let el = A[i];
runningSum+=el;
// if(el>S){
// continue;
// }
// else if(el===S){
// result++;
// }
// else {
// remaining=S-el;
//get left and right of S
result+= solution(A.slice(0,i), S);
result+= solution(A.slice(i+1), S);
//}
}
if(Math.floor(runningSum/A.length)===S){
result++;
}
return result;
//solutionHelper(A,S,0, A.length-1);
}
// function solutionHelper(A,S, start, end){
// if(start<=end){
// return 0;
// }
// //take it or leave
// let result = 0;
// }<file_sep># AlgoEtro
Sharkweek. Low Risk, High Yield. One Nation, Underwood.
"Some Vice Presidents are Door Mats,
others are MataDors, -no which do you think I intend to be?" Frank Underwood, House of Versace
Inversion: Leet #435
Adaptive Solutions | Forging a Better Tomorrow
//Here is a song I wrote about React.js and the Flux Paradigm
//Based on the song "Black Beatles" By <NAME>
I sent props but you said you didn't receive them(<NAME> It)
But you said didn't receive them
<file_sep>/**
* Question
Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
For example, given s = “abcba” and k = 2, the longest substring with k distinct characters is “bcb”.
*/
//longest substring with k distinc chars
//sliding window, non specific distinctions
//at MOST k distinct, we want most repetitive string as this optimiation
//maximize the length/window of the distinc with repeats(eg better compression/lossy)
/**
*
* @param {} str input string
* @param {*} k the ceiling for number of distinc within an maximized window
*/
const longestSubstring = function(str, k) {
let l=0;
let r=str.length-1;
let i = 0;
let charMap = new Map(); //map frequencies/presence/memoize
let result = '';//longest result substring with less than or equal to K distinct (if set), without distinction specifications
while(i<r) {
//sliding widnow frame;
const el = string.charAt(i);
if(charMap.has(el)){
// el is in Map
charMap.set(el, charMap.get(el) + 1); //increment
} else {
//newly set
charMap.set(el, 1);
}
//instead of having another loop, simultaneously check number of unqieu(charMap.keys().length > k, to reverse pointers)
while(charMap.size>k && l < r) {
let left = str.charAt(l);
let count = charMap.get(left);
if(count === 1) charMap.delete(left); //prioritize lowest frequency within the window
else charMap.set(left, count-1); //disclude from window
l++;
}
//counter l is for indexing which window to include, counter i is for traversing indicator
let substr = str.substring(l, i+1); //substring of window from l-i
result = substr.length > result.length ? substr : result; //Math.max regex
i++;
}
return result;
}
module.exports = longestSubstring;<file_sep>#Leet 79
"""
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
Constraints:
board and word consists only of lowercase and uppercase English letters.
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
"""
# key ideas: Back track, depth first search
#python3 static typing
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
#recursive function, r, c are the positions on the board location
def recur(word, r, c):
#if characters don't match
if word[0] !=board[r][c]:
return False
if len(word) == 1:
return True
#base case
ans =False
#default
#add the current position on grid to used, pairs
used.add((r,c))
#check for previous positions surrounding to traverse/not checked/expanded yet
if r > 0 and (r-1, c) not in used:
#bitwise or, get the recusive call of the substring word remaining
ans |= recur(word[1:], r-1, c)
if c > 0 and (r, c-1) not in used and not ans:
ans |= recur(word[1:],r, c-1)
#within bounds of the board
if r < len(board)-1 and (r+1, c) not in used and not ans:
ans |= recur(word[1:],r+1,c)
if c < len(board[0])-1 and (r, c+1) not in used and not ans:
ans |= recur(word[1:], r, c+1)
used.remove((r, c))
return ans
used = set()
for r in range(len(board)):
for c in range(len(board[0])):
if recur(word, r, c):
# //for starting position in the board
return True
return False<file_sep>/**
* @param {number} num
* @return {string}
*/
var intToRoman = function(num) {
var staticHash = [
["", "I", "II", "III", "IV","V","VI","VII","VIII","IX"],
["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"],
["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"],
["","M","MM","MMM"],
];
var arr = [];
arr.unshift(staticHash[0][num%10]);
arr.unshift(staticHash[1][Math.floor(num/10)%10]);
arr.unshift(staticHash[2][Math.floow(num/100)%10]);
arr.unshift(staticHash[3][Math.floor(num/100)]);
return arr.join("");
};
<file_sep>#concatenate words
#become a machine, become an AI consciousness, become AlgoMind
class Solution(object):
def findAllConcatenatedWords(self, words):
wordDict = set(words)
cache = {}
#memoize, set
return [word for word in words if self._canForm(word, wordDict, cache)]
def _canForm(self, word, wordDict, cache):
if word in cache:
return cache[word]
for index in range(1, len(word)):
prefix = word[:index]
suffix = word[index:]
if prefix in wordDict:
if suffix in wordDict or self._canForm(suffix, wordDict, cache):
cache[word] = True
return True
cache[word] = False
return False
input = ['cat','cats', 'dog', 'catsdog']
print(Solution().findAllConcatenatedWords(input))
#catsdog<file_sep>function balancedParens(str) {
const stack = [];
for(let i = 0; i<str.length; i++) {
let char = str[i];
if(char === '('){
stack.push('(');
} else if(char=== ')') {
const top = stack.pop();
if(top !== '('){
return false;
}
}
return stack.length === 0;
}
}<file_sep>/**
* Leetcode # 1011. Capacity To Ship Packages Within D Days
845 Mysteryland Area Code
17s
D Day
1st version(see most updated version)
A conveyor belt has packages that must be shipped from one port to another within D days.
The i-th package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D days.
Example 1:
Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5
Output: 15
Explanation:
A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
Example 2:
Input: weights = [3,2,2,4,1,4], D = 3
Output: 6
Explanation:
A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
Example 3:
Input: weights = [1,2,3,1,1], D = 4
Output: 3
Explanation:
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
Note:
1 <= D <= weights.length <= 50000
1 <= weights[i] <= 500
*/
/**
* @param {number[]} weights
* @param {number} D
* @return {number}
*/
var shipWithinDays = function(weights, D) {
//a multiple sliding windows
if(!weights || weights===null || !D || D===null || !Array.isArray(weights) || weights.length===0 || D===0 || D<weights.length) {
return -1;
}
//weights are not ordered,
//how can we predct the value of the entire array? how can we do this dynamically?
//we must do an array splice minimization,
if(D===1){
return weights.reduce((a,b) => {
return a+b;
}, 0);
}
let c;
if(weights.length===1){
return weights[0];
}
//idea: get the average of the sum(O(n))/ time ,
//instead get a running averaege, programmatically
c=weights[0];
// for(let i = 1; i < weights.length; i++) {
//sliding a window frame within timeframe D
// }
//programmatically alter the array until it has a length of D
//but since arrays are immutable in nature,
//keep an index tracker..., Splice it up to D
//number of spliced segments
let chunks = 1; //number of splits for days so far
for(i=1; i<weights.length && chunks<D; i++) {
}
//other idea: have a merge sort, but for optimizing the window, not by rearragning elements, we have one merge one step ahead of the other chunk, eg chunk is a merge of 2 elements, the second is single spliced chunks,
return c; //at godspeed....
};<file_sep>/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isSymmetric = function(root) {
//use 2 queues
if(!root) return true;
let leftQ = [];
let rightQ = [];
let leftResult = [];
let rightResult = [];
//mirror image on the root
leftQ.push(root);
rightQ.push(root); //symmetry
while(leftQ.length && rightQ.length) {
let currentLeft = leftQ.pop();
leftResult.push(currentLeft.val);
let leftLen = leftQ.length;
let currentRight = rightQ.pop();
rightResult.push(currentRight.val);
let rightLen = rightQ.length;
if(currentLeft.val!==currentRight.val){
return false;
}
if(leftLen!==rightLen){
return false; //impossible to be symmetric
}
let leftTemp = [];
let rightTemp = [];
//for the current level
for(let i = 0; i < leftLen; i++) {
//level
let left= leftQ.pop();
let right = rightQ.pop();
if(left.val !== right.val){
return false;
}
leftTemp.push(left.val);
rightTemp.push(right.val);
}
leftResult.push(leftTemp);
rightResult.push(rightTemp);
if(currentLeft.left!==null) {
if(currentRight.left!==null) {
leftQ.push(currentLeft.left);
rightQ.push(currentRight.left);
}
else {
return false;
}
} else {
if(currentRight.left!==null) {
return false; //left is null but right isn't non symmetrical
}
}
if(currentLeft.right!==null) {
if(currentRight.right!==null) {
leftQ.push(currentLeft.right);
rightQ.push(currentRight.right);
}
else {
return false;
}
} else {
if(currentRight.right!==null) {
return false;
}
}
}
return true;
};<file_sep>def MakingChange(coinVal, change):
alist = [0]*(change+1)
for i in range(1, change+1):
temp = change; j = 0
while j <= len(coinVal)-1 and i >= coinVal[j]:
temp = min(alist[i-coinVal[j]], temp)
j += 1
alist[i] = temp + 1
return alist.pop()
def coinRow(coinrow):
alist = [0]*(len(coinrow)+1)
alist[1] = coinrow[0]
for i in range(2, len(coinrow)+1):
alist[i] = max(coinrow[i-1]+alist[i-2], alist[i-1])
return alist.pop()
print(coinRow([5,1,2,10,6,2]))
def maxBag(weight, value, totalWeight):
if len(weight) <= 0 or len(value) <= 0 or totalWeight <= 0 or len(weight) != len(value):
return
num = len(weight)
tempMat = []
for i in range(num+1):
tempMat.append([0]*(totalWeight+1))
for i in range(1, num+1):
for j in range(1, totalWeight+1):
if j - weight[i-1] >= 0:
tempMat[i][j] = max(tempMat[i-1][j], value[i-1] + tempMat[i-1][j-weight[i-1]])
#continue.....<file_sep>//leet 435
const eraseOverlapIntervals = (intervals) => {
//given an array of intervals
if(intervals.length <=1) {
return 0;
}
intervals = intervals.sort(function(x, y){
return x.start - y.start;
});
//rearrane the intervals from starting point order
var count = 0;
var cursor=1; //current position on the interval
while(cursor < intervals.length){
//while we are within the intervals array at position cursor is the current inner array interval
var removeIndex;
//check if the previous start index is the same as the current start index, or if the current sstart index is less thant the last end index, then it is invalid
if(intervals[cursor].start === intervals[cursor-1].start || intervals[cursor].start< intervals[cursor-1].end){
//as a result we must remove this said index from the intervals array at position cursor
removeIndex=intervals[cursor].end > intervals[cursor-1].end ? cursor : (cursor-1);
//if the current end index of the interval is wider than the previous interval end, we remove the current interval at cursor,
//if the current end index is less than or equal to the previous end and has a narrower spread, then we remove the previous wider interval to minimize spread
intervals.splice(removeIndex,1);
//remove the index interval that overlaps
count++;
continue; //break out of current iteration and do not enter next if statement
}
//if the current interval's end is smaller than the previous end, it is an overlapping interval and will not be continuous
//however, if it already passed the condition above the interval is already removed and we don't need to double check that it is in fact overlapping
if(intervals[cursor].end <= intervals[cursor-1].end){
//the remove index of the interval is current if the current start is wider than the previous, else it is the previous
removeIndex = intervals[cursor].start > intervals[cursor-1].start ? (cursor-1) : cursor;
count++;
continue;
}
cursor++;
}
return count;
};
//faster solution
var eraseOverlapIntervals = function(intervals) {
if (!intervals.length) {
return 0;
}
intervals.sort((a, b) => a[1] - b[1]);
let nonOverLappingCounter = 1;
let end = intervals[0][1];
for (let i = 1, len = intervals.length; i < len; i++) {
if (end <= intervals[i][0]) {
nonOverLappingCounter++;
end = intervals[i][1];
}
}
return intervals.length - nonOverLappingCounter;
};<file_sep>Array for Stacks:
- use push and Pop
Array for Queues:
- shift and unshift for enqueue and dequeue<file_sep>//directed graph, find if path exists between two nodes
function pathExists(graph, start, end) {
if(!graph.contains(start) || !graph.contains(end)) {
return false;
}
if(start===end) return true;
const queue = [];
const visited = new Set();
queue.push(start);
///length = 0 = false
while(queue.length) {
const currentNode = queue.shift();
if (currentNode === end) return true;
visited.add(currentNode);
const edges = graph.findEdges(currentNode)
const keys = Object.keys(edges);
for(let i = 0; i < keys.length; i++) {
const edge = edges[keys[i]];
if(!visited.has(edge)) {
queue.push(edge);
visited.add(edge)
}
}
}
return false;
}
module.exports = pathExists;<file_sep>const CONVERSION = {
1000: 'M',
900: 'CM',
500: 'D',
400: 'CD',
100: 'C',
90: 'XC',
50: 'L',
40: 'XL',
10: 'X',
9: 'IX',
5: 'V',
4: 'IV',
1: 'I',
}
var intToRoman = function(val) {
let result = ''
while(val > 0) {
let foo=Object.keys((CONVERESION).reverse().find(digit => val >=parseInt(digit));
result += CONVERSION[foo]
val -= foo
}
return result
};<file_sep>function Queue(){
this.storage = [];
this.index = 0;
}
Queue.prototype.enqueue = function(value){
this.storage[this.index++] = value;
return;
};
Queue.prototype.dequeue = function(){
if(this.storage === undefined || this.index===0){
return;
}
return this.storage.shift();
};
module.exports = Queue;<file_sep>// https://www.hackerrank.com/challenges/ctci-merge-sort/problem
'use strict';
//saucin, saucin
//watch out, oh watch out,
//and they say congratulationss..........
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString='';
let currentLine=0;
process.stdin.on('data', inputStdin => {
inputString+=inputStdin;
});
//process input string once stream of input is over
process.stdin.on('end', ()=> {
inputString=inputString.replace(/\s*$/, '')
.split('\n')
.map(str => str.replace(/\s*S/,''));
console.log(inputString, "this is the input string");
main();
});
function readLine() {
return inputString[currentLine++];
}
//start rockin the sleeve I can't ball with no Joes
function countInversions(arr){
}
function main() {
const ws=fs.createWriteStream(process.env.OUTPUT_PATH);
const t = parseInt(readLine(), 10);
for(let tItr=0; tItr<t; tItr++){
const n = parseInt(readLine(), 10);
const arr = readLine().split(' ').map(arrTemp => parseInt(arrTemp,10));
const result = countInversions(arr);
ws.write(result + '\n');
//double OT like i'm KD, coding OG
}
//when i started ballin i was yunnnnggggg
ws.end();
}<file_sep>#dp O[profits.length][capacity+1s] time O(N*C) space
def solve_knapsack(profits,weights, capacity):
dp=[[-1 for x in range(capacity+1)] for y in range(len(profits))]
return knapsack_recursive(dp, profits, weights, capacity, 0)
def knapsack_recursive(dp, profits, weights, capacity, currentIndex):
#base check
if capacity <= 0 or currentIndex >= len(profits):
return 0
#memoize
if dp[currentIndex][capacity] != -1:
return dp[currentIndex][capacity]
profit1=0 #takeit
if weights[currentIndex] <=capacity:
profit1 = profits[currentIndex]+ knapsack_recursive(
dp, profits, weights, capacity-weights[currentIndex], currentIndex+1)
#leaveit
profit2=knapsack_recursive(
dp, profits, weights, capacity, currentIndex+1)
dp[currentIndex][capacity] = max(profit1,profit2)
return dp[currentIndex][capacity]
def main():
print(solve_knapsack([1,6,10,16],[1,2,3,5],7))
print(solve_knapsack([1,6,10,16],[1,2,3,5],6))
main()<file_sep># Jack is hopping backwards and forwards in an array of size n. He starts in cell 0 and can hop f cells forwards or b cells backwards. He is allowed to jump up to max_jumps times. How many ways can he reach the last cell and finish the game?
from test_runner import run_test
#"Those who can't do, teach. Those who can't teach, teach gym" #changpagne2024
#shamwoohoo
def num_ways_helper(arr, current_index, jumps_left, f, b, cache):
n = len(arr)
#bruhhhhhhh python is so much more lit than java
#my opinions are my own don't come for me
if current_index == n - 1:
return 1
if current_index < 0 or current_index >= n:
return 0
if jumps_left == 0:
return 0
key = (current_index, jumps_left)
if key in cache:
output = cache[key]
print("From cache on line 20s: cache: key={}".format(str(key), jumps_left))
return cache[key]
back_solution = back_solution + forward_solution
cache[key] = back_solution
return solution
def num_ways(arr, f, b, max_jumps):
return num_ways_helper(arr, 0, max_jumps, f, b, {})
run_test(num_ways)
#What did C8 say to 0101 at Coachella? Drop the base.
#herro rorld
<file_sep>/**
* Given two strings text1 and text2, return the length of their longest common subsequence.
A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.
If there is no common subsequence, return 0.
Example 1:
Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.
Example 2:
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.
Example 3:
Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.
Constraints:
1 <= text1.length <= 1000
1 <= text2.length <= 1000
The input strings consist of lowercase English characters only.
*/
/**
* @param {string} text1
* @param {string} text2
* @return {number}
*/
var longestCommonSubsequence = function(text1, text2) {
let result = 0;
if(!text1 || !text2 || text1.length === 0 || text2.length === 0){
return result;
}
let substr="";
//memo
let memo = new Array(text1.length).fill(new Array(text2.length).fill(0));
//must be 2d array
for(let i=0; i<text1.length; i++){
for(let j=0; j<text2.length; j++){
//perhaps instead of using double for loop we can use a single get the array element, use ...memo[i].map(el => {})... but still On2
if(text1.charAt(i) === text2.charAt(j)){
if(i===0 || j===0){
memo[i][j] = 1;
}
else{
memo[i][j] = memo[i-1][j-1]+1;
}
if(memo[i][j]>result) {
result = memo[i][j]; //or Math.max
substr = text1.slice(i-result+1, i+1);
}
}
}
}
return result;
};<file_sep>// unidirected graph
//Node
//each node in graph contains label and list of edges(neighbors)
const Node = function(){
constructor: function(value){
this.value = value;
this.edges = [];
},
addNeighbor: function(node){
this.edges.push(node);
}
}
module.exports = graph;<file_sep>"""
Merge K Linked List Using A PQ(essentiall linear min heap)
"""
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
amount = len(lists)
interval = 1
while interval < amount:
for i in range(0, amount- interval, interval*2):
lists[i] = self.merge2Lists(lists[i], lists[i+interval])
#merging the two lists in place with a widening interval
interval *=2
return lists[0] if amount > 0 else lists
def merge2Lists(self, l1, l2):
head = point = ListNode(0)
while l1 and l2:
if l1.val <= l2.val:
point.next = l1
l1 = l1.next
else:
point.next = l2
l2 = l1 #chaining to link merge on current spaced interval
#divide and conquer(but since it is already divided, it is just the conquer)
l1 = point.next.next
point = point.next
if not l1:
point.next = l2
else:
point.next = l1
return head.next<file_sep>
//using stacks and queues in algorithsm
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
//shorted possible length
function solution(S, K) {
// write your code in JavaScript (Node.js 8.9.4)
//K consecutive remove to optimize compression
const N = S.length;
const result = ""; //reassign to the min between recursive case and th
//sliding window and dynamic programming method
//recursively
const arrayMap = [];
//maintain order and the frequency, array of mappings
//double hashMap
for(let i = 0; i<N ; i++){
let el = S.charAt(i);
//map value
let map = new Map();
let freq=1;
let j = i;
while( S.charAt(j) === el && j < N ){
//explore rest frequency
freq++;
j++;
}
i=j; //do not cut or mutate original string
map[el] = freq;
arrayMap.push(map);
for(let g = 0; g < k; g++ ){
//iterate through consectives non
}
}
//dynamic program
//we are going to store the Uppercase value as the key on the map th
return result.length;
//return shortest possible
}<file_sep>/**
* There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.
Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.
Example 1:
Input:
[[1,1,0],
[1,1,0],
[0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
The 2nd student himself is in a friend circle. So return 2.
Example 2:
Input:
[[1,1,0],
[1,1,1],
[0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
Note:
N is in range [1,200].
M[i][i] = 1 for all students.
If M[i][j] = 1, then M[j][i] = 1.
Done with 93.19% runtime percentile for Javascript, 60ms,
36.8 MB 100% memory
Leet 547
*/
/**
* @param {number[][]} M
* @return {number}
*/
var findCircleNum = function(M) {
var visited = []; //mapped as 1D array for directive, else indirective
var stack = []; //dfs
var resultCircles = 0;
for(let i = 0; i < M.length; i++) {
// visited[i].push([]); //matrix created dynamically, so not to mutate the matrix
if(!visited[i]) {
resultCircles++;
stack.push(i);
while(stack.length) {
const current = stack.pop();//remove current
visited[current] = true;
for(let j = 0; j < M[current].length; j++) {
if(!visited[j] && M[current][j]) {
stack.push(j);
}
}
}
}
}
return resultCircles;
};<file_sep>/**
* Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
*/
var MinStack = function(){
};
//prototypal inheritance, add to prototype chain the methods
MinStack.prototype.push = function(x){
}
MinStack.prototype.pop = function(){
}
MinStack.prototype.top = function(){
}
MinStack.prototype.getMind = function() {
}
module.exports = MinStack;<file_sep>// array of strings input
//get all permuations of each strign
function getPermuations(...arr) {
const output = new Set();
function generatePermuations(str, acc) {
if(!str.length) return output.add(acc);
for(let i = 0; i< str.length; i++ ){
const char = str[i];
acc += char;
//reduce
generatePermuations(str.slice(0, i) + str.slice(i+1), acc);
acc = acc.slice(0, acc.length-1);
}
}
for(const str of arr){
generatePermuations(str); //only for each loop
}
return [...output];
}
//second version
function getPerms(...arr) {
const output = new Set();
//unique perms,
//instead of double counting, we can take advantage of the symmetrical recurisve calls regardless of palindrome
function helper(str, acc) {
if(str === ''){
output.add(acc);
return;
}
for(let i = 0; i< str.length; i++){
const char = str[i];
str = str.slice(0, i).concat(str.slice(i+1));
helper(str, acc+char);
str = str.slice(0, i) + char + str.slice(i);
}
}
for( let word of arr) {
helper(word, '');
}
//take advantage use of closure to prevent generating symmetrical permutations from different recursive calls
return [...output];
}
console.log(getPerms('sac','acs', 'hi', 'redundant'));
// module.exports = getPermuations;<file_sep>DFS:
- permuations, paths
- cycles
BFS:
- shortest path
- check levels
- use a Queue
A Tree: an acyclic connected graph with N nodes, N-1 edges, any two vertices have only 1 path
Tree DFS - use a stack
1. Post order: left, right, root
2. Inorder: left, root, right
3. Preorder: root, left, right
Tree BFS:
1. Level Order traversal
- use a queue
<file_sep>/**
* Leet #146
* Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
* get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
* put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
* The cache is initialized with a positive capacity.
* Follow up:
* Could you do both operations in O(1) time complexity?
*
* Example:
* LRUCache cache = new LRUCache( 2 /* capacity */
// cache.put(1, 1);
// cache.put(2, 2);
// cache.get(1); // returns 1
// cache.put(3, 3); // evicts key 2
// cache.get(2); // returns -1 (not found)
// cache.put(4, 4); // evicts key 1
// cache.get(1); // returns -1 (not found)
// cache.get(3); // returns 3
// cache.get(4); // returns 4
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
//using ES5 with var
var capacity = capacity;
var cache = {}; //hash mapping,
//use a heap like structure to store the least recently used for removable
var leastUsed = []; //leastused key, like stack
//every get required an update to re-heap
//on the cache we map the key, to an array [value, frequency]
var reheap = function(key) {
if(leastUsed.length===0) {
//only 1 element
leastUsed.push({key: 1});
}
else {
if(leastUsed===key) {
//re update frquency
}
}
}
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
//using prototype chain
if(cache(key)){
cache[key].frequency++;
//call a private re-heap
LRUCache.reheap(key);
return cache[key].value;
}
else {
return -1;
}
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
};
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/<file_sep>Applications of Linked Lists:
- stack
- queue<file_sep>/**
*
* Say you have an array prices for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
*/
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
// array of prices
//unlimited number of trades/transactions in the duration
//cannot have mulitple same day transactions
//tactic : you either buy the lowers marginal difference, or you sell the highest margin of your current stock portfolio,
//essentially, calculate the max profits between your portfolio, if it doesn't exist, you should still buy,
// if it does exist, only filter through any net positives, and
//can you predict history prices/history to presume volatility
// if the array is only like a week, backtrack greedy dynamic program using recursion functional program
//sliding window dynamic programming
//range of profit optimizations
//never buy on last day of the trade
//if it is a decreasing interval, you never at all, return 0
//if it's just a single increasing interval,
//only buy on day 1, sell on the last day
// it is inefficient to check the interval being sorted, therefore we assume that every two consecutive transactions is just one very small interval between buying/selling sorts
let profit = 0;
//two pointers, slide the window between local min and max, buy on local min, sell on local max
//never buy the last one,
//this is all the same as 1 stock in a time series data
// recursively shrink the array until it's length is 1 or 0
//have a running closure for the result, backpack scoped,
let localMinima = Infinity; //always set the bar as polar opposite
let currentProfit = 0;
for(let i=0; i < prices.length; i++) {
let localProfit = prices[i] - localMinima;
if (localProfit < currentProfit) {
profit += currentProfit; //dynamic
currentProfit = 0;
localMinima = Infinity;
}
if (prices[i] < localMinima) localMinima = prices[i]; //found a lower min value to buy
if (localProfit > currentProfit) {
currentProfit = localProfit;
} //localprofit, we do not need to track the indexes of buy and sell
}
if (currentProfit>0){
profit += currentProfit;
}
return profit;
};<file_sep>const Node = function(value){
this.value = value;
this.next = null;
};
//predefined a singly linked list
// use a Queue for breadth first search
const Queue = function(){
this.storage = [];
this.index = 0;
}
Queue.prototype.enqueue = function(value){
this.storage[this.index++] = value;
return;
};
Queue.prototype.dequeue = function(){
if(this.storage === undefined || this.index === 0){
return;
}
this.storage.shift();
//the prototype chain acquires this. context of the original functional class with Object as the root
}
//use a HashMap, Map, or {} hashmap to track parents and reconstruct path
/**
*
* @param {*} a to Node
* @param {*} b from Node
* @return Linked List Path of the Nodes
*/
const shortestPath = (a, b) => {
if(!a || a === null || !b || b === null) {
return;
}
else if(a === b) {
return null; //the path is none
}
const toVisit = new Queue();
toVisit.enqueue(a); //the start of the optimized path
const parents = {};
parents[a] = null;
while(!toVisit.storage.length === 0){
const currentNode = toVisit.dequeue;
if(currentNode.children===null){
}
if(currentNode = b){
}
}
};
<file_sep>//2D regular(not optimized DP)
function regDP(nums) {
let sum = 0;
for(let num of nums){
sum +=num;
}
if((sum & 1) == 1){
return false;
}
hSum = sum/2;
//store cache, fil in smaller repeated subproblems
const DP = new Array(nums.length+1);
for(let i =0; i< DP.length; i++){
DP[i] = (new Array(hSum+1)).fill(false);
}
for(let i =0; i<(nums.length+1); i++){
DP[0][i] = false;
}
for(let i = 0; i< hSum+1; i++){
DP[0][i]= false;
}
DP[0][0] = true;
for(let i =1; i< nums.length+1; i++){
for(let s = 1; s<(hSum+1); s++){
const currentNum = nums[i-1];
if(currentNum > s){
DP[i][s] = DP[i-1][s];
} else {
const takeIt = DP[i-1][s-currentNum];
const leaveIt = DP[i-1][s];
DP[i][s] = takeIt || leaveIt;
}
}
}
return DP[nums.length][hSum]
}
//Optimized DP
function optDP(nums) {
let sum = 0;
for (let num of nums){
sum += num;
}
if((sum & 1) == 1){
return false;
}
hSum = 2;
const DP = (new Array(hSum+1)).fill(false);
DP[0] = true;
for(let i = 0; i< nums.length; i++){
for(let s = hSum; s>0; s--){
if(nums[i] > s){
//do nothing
} else {
const takeIt = DP[s-nums[i]]
const leaveIt = DP[s]
DP[s] = takeIt || leaveIt;
}
}
}
return DP[hSum]
}<file_sep>Dijkstra:
- shortest path
- shortest weighted path
-Shortest Optimal Path
-Weighted Edges/Values
-City Mappings
Approach:
- using a priority queue
White Board Application:
-Autocomplete
<file_sep>/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
//main function
//use of divide and conquer/PQ
const mergeKLists = (lists){
if(lists.length ===0){
return null;
}
while(lists.length>1){
//length of lists is dynamically shrinking as an interval is expanding
let a = lists.shift(); //remove the first 2 elements
let b = lists.shift();
const h = mergeLists(a,b);
lists.push(h);
}
//list length is 1, interval merged, single element linkedList in the array
return lists[0];
};
const mergeLists= (a, b) => {
const result = new ListNode(0);//store result
let temp = result; //current node
while(a !==null && b !== null){
if(a.val < b.val){
temp.next = a;
a=a.next;
} else {
temp.next = b;
b = b.next;
}
temp = temp.next;
}
if(a !==null){ temp.next = a; }
if(b!==null){ temp.next = b; }
return result.next; //the next end of the head node is returned
}
<file_sep>//using
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(S, X, Y) {
// write your code in JavaScript (Node.js 8.9.4)
//X and Y are arrays both of length N-1
//string S legnth N. k=index, S[k] is the tag element
//draw circle centered at origin 0,0 that does not embed two points with the same tag S[i] !== S[j] at X(i)Y(i). X(j)Y(j) on the plane
const result = 0; //max number of points with distinct tags
//expand circle=dynamic programthe radius <=radius
//use pythagorean theorum a2 + b2= <= r^2
//keep track of unique tags, map dictionary
//singple check with short circuiting
//string is array of chars
const N;
if(Array.isArray(S) && Array.isAray(X) && Array.isArray(Y) && S.length === Y.length && Y.length === X.length){
const N = S.length;
}
else{
return 0;
}
const tupleMap = new Map(); //key will be the tag, value is an array of array that stores coordinate pairs,
//order does not matter here,
for(let i = 0; i < N ; i++){
//we could use tuples if this were in python
let point = [X[i],Y[i]];
let tag = S[i];
}
//radius is distance from origin, we want unique tag points as
//we do not want to optimize radius, but to optimize tags within unique
//from the map
//to do in place, we check string for duplicates using indexOf(char), get that index, compare their points, and choose smaller of the two, substring cut out the tag of the larger point on circle, update radius, check for uniqueness again.
return result;
}<file_sep>#python3 syntax changes from Solution(object) or self class
def solve_knapsack(profits, weights, capacity):
return knapsack_recursive(profits, weights, capacity, 0)
def knapsack_recursive(profits, weights, capacity, currentIndex):
#base case check
if capacity <= 0 or currentIndex >= len(profits):
return 0
#recursive case, if element at current index exceeds capacity, then leave
profit1 = 0
if weights[currentIndex] <= capacity:
profit1 = profits[currentIndex] + knapsack_recursive(
profits, weights, capacity-weights[currentIndex], currentIndex+1)
#recursive call after exclude element at current index
profit2 = knapsack_recursive(profits, weights, capacity,currentIndex+1)
return max(profit1, profit2)
def main():
print(solve_knapsack([1,6,10,16], [1,2,3,5], 7))
print(solve_knapsack([1,6,10,16],[1,2,3,5],6))
main()
<file_sep>//undirect path
class Graph {
constuctor() {
this.neighbors = {};
}
addEdge(u, v) {
// u and v are nodes
if(this.neighbors[u] === undefined){
this.neighbors[u] = [];
}
this.neighbors[u].push(v);
if(this.neightbors[v] === undefined){
this.neightbors[v] = [];
}
this.neightbors[v].push(u);
}
}
function bfs(graph, sourceNode) {
const queue = [{ vertex: sourceNode, count: 0 }];
const visited = { sourceNode: true };
let tail = 0;
while(tail < queue.length) {
const u = queue[tail++].vertex;
const count = u.count;
graph.neighbors[u].forEach((v) => {
if(!visited[v]) {
visited[v] = true;
queue.push({ vertex: v, count: count+1 });
}
});
}
}
function shortestPath(graph, sourceNode, targetNode) {
if(sourceNode === targetNode) {
return 0;
}
const queue = [sourceNode];
const visited = { sourceNode: true}; //map memoization
const predecessor = {};
let tail = 0;
while(tail < queue.length) {
const u = queue[tail++];
const neighbors = graph.neighbors[u];
for (let i = 0; i < neighbors.length; ++i) {
const v = neightbors[i];
if (visited[v]) {
continue;
}
visited[v] = true;
if (v === targetNode) {
const path = [v];
while (u !== sourceNode) {
path.push(u);
u = predecessor[u];
}
path.push(u);
path.reverse();
return;
}
predecessor[v] = u;
queue.push(v);
}
}
}<file_sep>// Item class
public static class Item {
int weight;
int value;
public Item(int weight, int value) {
this.weight = weight;
this.value = value;
}
}
// Recursively check every combination of items by traversing list of items
// and either including or excluding each item
public static int naiveKnapsack(Item[] items, int W) {
return naiveKnapsack(items, W, 0);
}
// Overloaded recursive function for naiveKnapsack
private static int naiveKnapsack(Item[] items, int W, int i) {
// Return when we reach the end of the list
if (i == items.length) return 0;
// If item is heavier than remaining weight, skip item
if (W - items[i].weight < 0) return naiveKnapsack(items, W, i+1);
// Try both including and excluding the current item
return Math.max(naiveKnapsack(items, W - items[i].weight, i+1) + items[i].value,
naiveKnapsack(items, W, i+1));
}
// Recursive solution that uses a cache to improve performance
public static int topDownKnapsack(Item[] items, int W) {
// Map: i -> W -> value
// Use a map instead of array because the data could be very sparse
Map<Integer, Map<Integer, Integer>> cache = new HashMap<Integer, Map<Integer, Integer>>();
return topDownKnapsack(items, W, 0, cache);
}
// Overloaded recursive function for topDownKnapsack
private static int topDownKnapsack(Item[] items, int W, int i, Map<Integer, Map<Integer, Integer>> cache) {
// Return when we reach the end of the list
if (i == items.length) return 0;
// Check the cache and return value if we get a hit
if (!cache.containsKey(i)) cache.put(i, new HashMap<Integer, Integer>());
Integer cached = cache.get(i).get(W);
if (cached != null) return cached;
// If item is heavier than remaining weight, skip item
if (W - items[i].weight < 0) return topDownKnapsack(items, W, i+1, cache);
// Try both including and excluding the current item
int toReturn = Math.max(topDownKnapsack(items, W - items[i].weight, i+1, cache) + items[i].value,
topDownKnapsack(items, W, i+1, cache));
cache.get(i).put(W, toReturn);
return toReturn;
}
// Iterative dynamic programming solution
public static int bottomUpKnapsack(Item[] items, int W) {
// cache[i][j] = max value for the first i items with a max weight of j
int[][] cache = new int[items.length + 1][W + 1];
for (int i = 1; i <= items.length; i++) {
for (int j = 0; j <= W; j++) {
// If including item[i-1] would exceed max weight j, don't
// include the item. Otherwise take the max value of including
// or excluding the item
if (items[i-1].weight > j) cache[i][j] = cache[i-1][j];
else cache[i][j] = Math.max(cache[i-1][j], cache[i-1][j-items[i-1].weight] + items[i-1].value);
}
}
return cache[items.length][W];
}<file_sep>// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
//location ID is A[K]
if(!A) {
return;
}
let locationSet = new Set(A);
let windowresult = A; //window array
let start = 0;
let end =A.length-1;
let leftIndex = 0; //like binary search overlap
let rightIndex = A.length-1;
//priority Queue, shortest path dijkstras, also optimize reduction in duplicates, and go to most locations(max and min opimie)
while(leftIndex<rightIndex){
// for(let i=start; i<=end; i++){
let potentialLeft = A.slice(leftIndex, rightIndex-1);
let potentialSetLeft = new Set(potentialLeft);
if(potentialSetLeft == locationSet){
windowresult = potentialLeft;
rightIndex--;
end = rightIndex;
}
else{
rightIndex--;
}
let potentialRight = A.slice(leftIndex+1, rightIndex);
let potentialSetRight = new Set(potentialRight);
if(potentialSetRight == locationSet){
windowresult = A.slice(leftIndex+1, rightIndex);
//account right index already possible alter
//splitting
leftIndex++
start = leftIndex;
}
else{
leftIndex++; //still move to proceed
}
//dynamic iterator
//check the leave it on opposing ends if to keep direction
//compare the set of the window with or without, take it or leave it, math.max length keep window
//only want the window set
//minimuize
//}
}
return windowresult.length;
<file_sep>//O(numItems*capacity) time complexity
const solveKnapsack = (profits, weights, capacity) => {
const dp = [];
const knapsackRecursive=(profits, weights, capacity, currentIndex) => {
if(capacity <= 0 || currentIndex >= profits.length) return 0;
dp[currentIndex] = dp[currentIndex] || [];
if(typeof dp[currentIndex][capacity] !=='undefined') {
return dp[currentIndex][capacity];
}
let profit1=0;
if(weights[currentIndex] <= capacity){
//take it
profit1 = profits[currentIndex] + knapsackRecursive(profits, weights, capacity - weights[currentIndex], currentIndex+1);
}
const profit2= knapsackRecursive(profits, weights, capacity, currentIndex+1);//leave it
dp[currentIndex][capacity] = Math.max(profit1, profit2);
return dp[currentIndex][capacity];
}
return knapsackRecursive(profits, weights, capacity,0);
};
const profits = [1,6,10,16];
const weights [1,2,3,5];
console.log(`Total knapsack profit: ---> ${solveKnapsack(profits, weights, 7)}`);
console.log(`Total knapsack profit: ---> ${solveKnapsack(profits, weights, 6)}`);
<file_sep>//dp[i][c]=max(dp[i-1][c],profit[i]+dp[i-1][c-weight[i]])
const solveKnapsack =(profits, weights, capacity) => {
const n = profits.length;
if(capacity<=0 || n==0 || weights.length!=n) return 0;
const dp= Array(profits.length)
.fill(0)
.map(() => Array(capacity+1).fill(0));
for(let i=0; i<n; i++) dp[i][0] = 0;
for(let c = 0; c<=capacity; c++){
if(weights[0] <=c) dp[0][c]= profits[0];
}
for(let i =1; i<n; i++){
for(let c =1; c<=capacity; c++){
let profit1=0, profit2=0;
if(weights[i] <= c) profit1=profits[i] + dp[i-1][c-weights[i]];
//take it
//leave it
profit2=dp[i-1][c];
//take max
dp[i][c]=Math.max(profit1,profit2);
}
}
return dp[n-1][capacity];
};
const profits = [1, 6, 10, 16];
var weights = [1, 2, 3, 5];
console.log(`Total knapsack profit: ---> ${solveKnapsack(profits, weights, 7)}`);
console.log(`Total knapsack profit: ---> ${solveKnapsack(profits, weights, 6)}`);<file_sep>/**
* Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
Note: The length of each dimension in the given grid does not exceed 50.
/**
* @param {number[][]} grid
* @return {number}
*/
var maxAreaOfIsland = function(grid) {
//DFS, use a queue
let result = 0;
//mutate grid to zeros to not repeat
for(let i=0; i<grid.length; i++){
//iter rows
for(let j=0; j<grid[0].length; j++) {
//iter cols
// let el = grid[i][j];
let area51 = processIsland(grid, i, j);
result = Math.max(area51,result);
}
}
return result;
};
//if count > 4 vertical or horizontally, DFC then we can return true
var processIsland = function(grid, i, j) {
let area51 = 0;
if(!grid || grid.length===0 || i<0 || j<0 || i>=grid.length || j>=grid[0].length){
return 0; //0 is also false
}
else{
let el = grid[i][j];
if(el===1){
area51++;
grid[i][j]=0;
area51+=processIsland(grid, i+1,j);
area51+=processIsland(grid, i-1,j);
area51+=processIsland(grid, i,j+1);
area51+=processIsland(grid, i, j-1); //not diagonals, i-1 j-1,
}
}
return area51;
}<file_sep>#counting the number of inversions that need to achieve a sorted array
#is esentially counting the number of swaps in a merge sort
#method 2: inefficient brute for case On^2
def getInvCount(arr,n):
inv_count = 0;
for i in range(n):
for j in range(i+1,n):
if (arr[i]>arr[j]):
inv_count+=1;
return inv_count
#driver code
arr=[1,20,6,4,5]
#i love python omgggggggggg this is litttttyyyyyy afffff
#lmao why did I learn java in highschool when python is litttttt
#slivinggggggg
n= len(arr)
print("Line 20s of countingInversions.py and the number of inversions are", getInvCount(arr,n))
#method 2 enhance the merge sort
def mergeSort(arr,n):
temp_arr = [0]*n
return _mergeSort(arr, temp_arr, 0, n-1)
#helper function
def _mergeSort(arr, temp_arr, left, right):
inv_count=0
#TODO see closures in Python, recursive contexts
if left < right:
mid=(left + right)//2
#this // is floor division in python
inv_count+=_mergeSort(arr, temp_arr, left, mid)
inv_count+=_mergeSort(arr, temp_arr, mid+1, right)
inv_count+=merge(arr,temp_arr, left, mid, right)
return inv_count
#to merge the arrays and add the number of swaps
def merge(arr, temp_arr, left, mid, right):
i = left
j = mid + 1
k = left
inv_count = 0
while i <= mid and j <= right:
if arr[i] <= arr[j]:
temp_arr[k] = arr[i]
k += 1
i += 1
else:
#inversion
temp_arr[k] = arr[j]
inv_count += (mid-i + 1)
k += 1
j += 1
# copy remaining elements of left subarray into temp array
while i <= mid:
temp_arr[k] = arr[i]
k += 1
i += 1
#copy the remaining elements of the right subarray
while j <= right:
temp_arr[k] = arr[j]
k += 1
j += 1
#now copy the sorted subarray into the original array
for loop_var in range(left, right + 1):
arr[loop_var] = temp_arr[loop_var]
return inv_count
#Driver code
arr = [1, 20, 6, 4, 5]
n = len(arr)
result = mergeSort(arr,n)
print("Inversions, saucin are ", result)
<file_sep>"""
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.
EX. 1
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
EX. 2
Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
EX. 3
Input: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
1st approach: breadth first search
-2D array, calculate distance
-if still 1 in the distance is not calculated, return -1
"""
class Solution(object):
def orangesRotting(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if len(grid) == 0 or len(grid[0]) == 0:
return 0
dist = []
for _ in range(len(grid)):
dist.append(len(grid[0]) * [sys.maxsize])
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 2:
self.bfs(i, j, grid, dist)
res = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
if dist[i][j] == sys.maxsize:
return -1
else:
res = max(res, dist[i][j])
return res
def bfs(self, x, y, grid, dist):
seen = set()
q = [(x, y, 0)]
while len(q) > 0:
i, j, steps = q.pop(0)
if i < 0 or i+1 > len(grid) or j < 0 or j+1 > len(grid[0]):
continue
if(i == x and j == y) or grid[i][j] == 1:
key = (i, j)
if key in seen:
continue
seen.add(key)
dist[i][j] = min(dist[i][j], steps)
q.append((i-1, j, steps+1))
q.append((i+1, j, steps+1))
q.append((i, j-1, steps+1))
q.append((i, j+1, steps+1))
<file_sep>/** Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.
Example:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
Note:
You may assume that nums' length ≥ k-1 and k ≥ 1.
*/
class KthLargest{
PriorityQueue<Integer> pq1;
int max;
public KthLargest(int k, int[] nums){
pq1 = new PriorityQueue();
max = k;
for(int i: nums){
pq1.add(i);
}
}
public int add(int val){
pq1.add(val);
while(pq1.size()>max){
pq1.poll();
}
return pq1.peek();
}
}<file_sep>
class Solution(object):
def findThreeLargestNumbers(self, array):
result = [None, None, None]
for num in array:
self._updateLargest(result, num)
return result
def _updateLargest(self, threeLargest, num):
if threeLargest[2] is None or num > threeLargest[2]:
self._shiftAndUpdate(threeLargest, num, 2)
elif threeLargest[1] is None or num > threeLargest[1]:
self._shiftAndUpdate(threeLargest, num ,1)
elif threeLargest[0] is None or num > threeLargest[0]:
self._shiftAndUpdate(threeLargest, num, 0)
def _shiftAndUpdate(self, array, num, index):
# [0, 1, 2]
for i in range(index+1):
#indexes are inclusive for range in py
if i == index:
array[i] = num
else:
array[i] = array[i+1]
print(Solution().findThreeLargestNumbers([51,5,17,-222,-1,0,21,217,166,2] ))
#51, 217, 166<file_sep># The kth largest number
#from an unsorted array
class Solution(object):
def findKthLargest(self, arr, k):
left = 0
right = len(arr) - 1
while left <= right:
pivotIndex = self._partition(arr, left, right)
if pivotIndex == len(arr) - k:
return arr[pivotIndex]
elif pivotIndex > len(arr) - k:
right = pivotIndex - 1
else:
left = pivotIndex + 1
return -1
def _partition(self, arr, low, high):
pivot = arr[high]
index = low
for j in range(low, high):
if arr[j] <= pivot:
arr[index], arr[j] = arr[j], arr[index]
index += 1
arr[index], arr[high] = arr[high], arr[index]
return index
print(Solution().findKthLargest([5,7,2,3,4,1,6], 3 ))
#5<file_sep>class Trie {
constructor() {
this.root = new Node();
}
insert(word) {
const node = this.traverse(word, true);
node.setTerminal();
}
search(word) {
const node = this.traverse(word);
if(!node) return false;
return node.isTerminal;
}
startsWith(prefix) {
const node = this.traverse(prefix);
return !node ? false : true;
}
traverse(str, append = false) {
let node = this.root;
for(const letter of str) {
if(!node.hasLetter(letter)) {
if(!append) return null;
node.addLetter(letter);
}
node = node.getLetter(letter);
}
return node;
}
}
class Node {
constructor(letter = null) {
this.letter = letter;
this.children = new Map();
this.terminal = false;
}
addLetter(letter) {
const node = new Node(letter);
this.children.set(letter, node);
}
getLetter(letter) {
if(!this.hasLetter(letter)) return null;
return this.children.get(letter);
}
hasLetter(letter) {
return this.children.has(letter);
}
get isTerminal() {
return this.terminal;
}
setTerminal() {
this.terminal = true;
}
}<file_sep>/**
* Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
*/
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
var result = nums[0];
var localmax = nums[0];
for(let i=1; i<nums.length; i++) {
let el = nums[i];
//we do not care about indexes here or tracking of the sliding window frame...
localmax = Math.max(el, el+localmax);
result = Math.max(localmax, result);
}
return result;
};<file_sep>/**
* You have K sorted Lists, each of varying lenghts of L
* You want to optimize the runtime by merging the Lists in the optimal order
* It takes K+L ms for each merge
*
*
* Example: List P: 100 elements
* List Q: 250 elements
* List R: 1000 elements
*
* Option 1: Merge P and Q=(350ms), then with R=(1350ms) total = 1700ms
*
* Option 2: Merge P and R=(1100ms), then with Q=(1350ms) total = 2450ms
*
* Option 3: Merge R and Q=(1250ms), then RQ with P(1350ms) total=2600ms
*
* Write a function, given Array A of length N, each element at A represents
* the length of a list
* find shortest path in ms to merge all N lists into 1
*
* EX 2: A[0].length=100
* A[1].length=250
* A[2].length=1000
* returns 1700 (ms)
* 0<=N<=10000
* @param array A
*/
function solution(A) {
//mergesort hybrid, multiple mergesort
//merging 1 sorted list of K elements, with a 2nd sorted list of L elements, differing lengths,
//O(K+L)
//time takes to merge more than 2 lists into 1,
//binary tree graphs, balancing the lengths of the sorted lest will lead to logarithmic patterned runtime by the height of the tree(O average length)
//if time required to merge more than 2 into 1 dependes on order in which merges are performs,
//to optimize mergesorts inherit nlogn, with sorting the lists, we must start out sorting the shorter lists together before combining with the larger(so we take advantage of the fact that O logN asymptotic takes advantage of the longest list length , and that this only happens towards the end(nature of merge sort, reverse divide and conquert))
if(!A || A.length<2) {
return 0;
}
//get a balnaced tree height runtime, but having balanced lengths
//we will mergesort(or quicksort), the list of lists in A by itself based on length,
Array.sort(A);
//use reduce
return A.reduce((acc,value) => {
return acc+value; //the optmial order for a balanced logarithmic tree
}, initialValue=0);
//from there we simple mergesort from the beginning until the end(base case length of A is 1)
//conquer largest
}
module.exports = mergeOptimization;<file_sep>/**
* Leet #206
* Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/** easy, 93.5%
* @param {ListNode} head
* @return {ListNode}
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
//do this in place
if(!head || head===null) {
return head;
}
else if(head.next===null) {
return head;
}
var previousNode= null; //to make the head the new tail
var currentNode = head;
//O(n)
var temp = currentNode.next; //temp, goal is that new temp is head assigned last of the re-linking
while(currentNode!==null) {
//as we move unidirectinally until the end of the chain
//we swap the currentNodes next pointer with the previous whilst storing next pointer in temp
temp = currentNode.next; // store temp;
currentNode.next = previousNode; //reassign it to the previous
previousNode = currentNode; //to assign tail linking
currentNode = temp; //the same thing as moving to currentNode.next
}
//now the currentNode is head
head = previousNode;
return head;
};<file_sep>def run_test(solution):
print("Testing for an array of size 11 with +5 jumps forward, -2 jumps backward, up to 9 moves")
print("Output: " + str(solution([0 for _ in range(11)], 5, 2, 9)))
print("Expected: 7")
print("~~~~~~~~~~~~~~~~~")
print("Testing for an array of size 11 with +5 jumps forward, -2 jumps backward, up to 8 moves")
print("Output: " + str(solution([0 for _ in range(11)], 5, 2, 8)))
print("Expected: 1")<file_sep># Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None: return []
q = [[root]]
for level in q:
record = []
for node in level:
if node.left: record.append(node.left)
if node.right: record.append(node.right)
if record: q.append(record)
return [[x.val for x in level] for level in q]<file_sep>//leet # 416 Partition Equal Subset Sum
// Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
// Note:
// Each of the array element will not exceed 100.
// The array size will not exceed 200.
// Example 1:
// Input: [1, 5, 11, 5]
// Output: true
// Explanation: The array can be partitioned as [1, 5, 5] and [11].
// Example 2:
// Input: [1, 2, 3, 5]
// Output: false
// Explanation: The array cannot be partitioned into equal sum subsets.
// solution 1 72 ms 35.2 MB
/**
* @param {number[]} nums
* @return {boolean}
*/
const canPartition = (nums )=> {
let sum = 0;
for(let i =0; i< nums.length; i++){
sum += nums[i];
}
if(sum % 2 !== 0) return false; //cannot divide ints evenly
sum/=2; //inversion
let dp = new Array(sum+1).fill(false);
dp[0] = true; //first element is true since this is dummy position
for(let i = 0; i<nums.length; i++){
let num = nums[i];
for(let j = sum; j>=num; j--){
dp[j] = dp[j] || dp[j-num];//if already true, short circuit to TRUE || FALSE = TRUE
}
}
return dp[sum];
};
//solution 2 uses reduce 88ms 35.4MB
//calling reduce adds layer of function complexity and a slight lag time, the tradeoff for modularity and not having to re-create
const canPartition = (nums) => {
const sum = nums.reduce((sum, currNum) => sum+=currNum, 0); //sum
if(!sum%2) return false; //must be even
const target = sum/2; //target halve the sum
const cache = new Array(target+1).fill(false);
cache[0] = true;
for(let i =0; i<nums.length; i++){
let num = nums[i];
for(let k=target; k>=num; k--){
cache[k] = cache[k] || cache[k-num];
}
}
return cache[target];
};
// third, 80ms , 35.6MB very similar
/**
* @param {number[]} nums
* @return {boolean}
*/
const canPartition = (nums) => {
let sum = 0;
for(let i =0; i<nums.length; i++){
sum+=num;
}
if(sum%2!=0) return false;
let half=sum/2;
let dp=new Array(half+1).fill(false);
dp[0]=true; //dummy placeholder
for(let i=0; i<nums.length;i++){
let num = nums[i];
for(let k=0; k>=num; k--){
dp[k]= dp[k] || dp[k-num];
}
}
return dp[half];
};
//option #3 2D array, 80 ms, 35.6MB
/**
* @param {number[]} nums
* @return {boolean}
*/
const canPartition = (nums) => {
let sum = nums.reduce((acc, v) => acc + v, 0)/2; //divide 2
if(sum!==parseInt(sum)) return false;//odd
//a dp table of dimensions nums.length+1 x sum(nums)
const dp=[];
for(let i =0; i<nums.length; i++){
dp[i] = [];
for(let j =0; j<sum+1; j++){
dp[i][j] = false;
}
} //filling the d2 array elements to false
for(let i=0; i<dp.length; i++){
dp[i][0]= true;
}
for(let j=0; j<dp.length;j++){
dp[0][j]=false;
}
dp[0][0]=true;
for(let i=1; i<=nums.length;i++){
for(let j=1; j<=sum; j++){
if(dp[i-1][j] === true){
dp[i][j]=true;
}
else if(dp[i-1][j-nums[i]] === true){
dp[i][j]= true;
}
else{
dp[i][j]=false;
}
}
}
return dp[nums.length][sum];
};
//essential explanation
//Build a "reachable numbers" in memo
//check if we can get that number with the numbers added so far
//if we can reach the target number, else we add it to the table of reachable numbers
//also 80ms, 35.6MB
const canPartition = (nums) => {
const sum = nums.reduce((acc,num) => acc+num, 0);
const target = sum/2;
if(sum & 1) return false;
if(nums[nums.length-1] > target) return false;
const memo = new Array(target+1).fill(false);
memo[0] = true;
for(let i =0; i<nums.length;i++){
let num=nums[i];
if(memo[target-num]) return true;
for(let j=target; j>=num; j--){
memo[t] = memo[t-num];
}
}
return false;
}<file_sep>/**
*
* @param {A conveyor belt has packages that must be shipped from one port to another within D days.
The i-th package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D days.
Example 1:
Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5
Output: 15
Explanation:
A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
Example 2:
Input: weights = [3,2,2,4,1,4], D = 3
Output: 6
Explanation:
A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
Example 3:
Input: weights = [1,2,3,1,1], D = 4
Output: 3
Explanation:
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1} weights
* @param {*} D
*/
/**
* @param {number[]} weights
* @param {number} D
* @return {number}
*/
var shipWithinDays = function(weights, D) {
//input check
if(!weights || !D || D<0) return -1;
//see my diagram in my blog...
//sliding windows spliced....
//array splice method recursive base case solve..
//revese of stock price buy sell or knapsack or stairs...
//essentially, this is like a reverse average, so we want to split the intervals approximately evenly by their sum..
//the brute force way is to get the sum, get the average weight capacity,
//best way is to graph on x and y axis, x axis is time Day t=0..D with D Days as the block constraint, and y axis is the sum of the set of graphed weights that can be pushed to the prior day, taken for the current day, or saved for the next day within the constraint of D Days,
//D days is a block constraint, while the y axis for Capacity on a given day can vary
//send back the capacity
var c; //c is the discrete minimum between the average Capacity per the day over D days, so the next discrete level up (all positive ints)
//on a given day, take from weights[i] up until (including) weights[i+k]... and track a global max,
//to optimize the spread we want want the Capacity c to be > largest element of the array(depending on the range of positives), and with the least additions based on the spread range of D days, to do this we can grab the average
var wacc = Math.floor(weights.reduce((a,b) => a+b, 0)/D);
//we want to take the working average of the total Absolute Capacity of the boxed elements across D days, a,d we must surpass it by a little discrete amount or meet it exactly on a given day t=i....D Days.
//a weighted average
//the issue with avg is outliers, eg 1 extreme weight, in which case that would be usually the capacity and taken as 1 item on the trip, distributing the rest, so we could compare median to mean...
//we do not need to necessary know the median,
c = wacc; //initialize it to wacc...because you will see...
var localCapacity = weights[0]; //start out
//try to avoid iterative through the weights array multiple times, track that index stored and the capacity Math.max
let index = 1;
for(let t=0; t<D && index<weights.length; t++){
//bi conditional, based on D days but constrained by array of weights as well
let el = weights[index]; //element enxt on the queue
//p = D-t days left to complete everything...
//we must factor in the days left as part of a weighted avg
//must factor remaining days as well as the average across because discrete logic.
if(localCapacity+el<wacc) {
//take it, and we stay on the current day, therefore
localCapacity+=el; //accumulation of the account...
index++; //rise of the indexed fund on weights
t--; //stay on the current day, offset t++
}
else {
//leave it on the iteration day t of D days, and empty localCapacity
//do another check first, if unassigned, since wacc is a non discrete number, but our result must be discreet, do not leave room for coicidence...
//we must check again based on not the wacc, but now based on what we have saved to c in the store
//we might have to move back an index-- this time while moving forward a day t++
// take out && c===wacc because that is probable on coincidence
if(localCapacity+el>=c && t===0){
//this is a maximization at the same time it is a minimization, we want to output the minimum weight per day to meet D days requirements, but we also must keep track of the maximum of the days to fulfill the shipping requirements in our trade war with China.
//if it is greater than, we can leave it for the next day, because it is still created than wacc, which means the next discrete number day has enough days left...
localCapacity += el;
index++; //go back a day for next capacity, leave it
c = Math.max(localCapacity, c);
}
else {
c = Math.max(localCapacity, c);
index--;
localCapacity = el; //next element for the next day with incrementing t,
}
//day will increment and continue;t++ into the next day
}
}
//do one check to compare localCapacity
// c= Math.max(c, localCapacity);
//we can do a take it or leave it, with recursive backtracking, but this is less efficient...
//what are we optimizing? what are the constraints?
//getting the minimum capacity by spreading it evenly through D days, with unequal, uncertain amounts
//graph it out! :D
return c;
};<file_sep>/**
* Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:
Input: [4,5,6,7,0,1,2]
Output: 0
*/
/**
* @param {number[]} nums
* @return {number}
*/
var findMin = function(nums) {
//approach 1: iterate array until the element previous is greater than the current element, return current element;
//O(n)
if(!nums || nums===null || nums.length===0){ return nums; }
else if(nums.length===1){ return nums[0]; }
for(let i = 1; i< nums.length; i++){
let el = nums[i]; //until last, but we will start at index 1
if(el<nums[i-1]){
return el; //we found the pivot, and therefore the min
}
}
//if we have traversed the entire array and have not found a pivot(about the min),
//then it had no pivot
return nums[0];
};
const findMin2 = () => {
//do this with binary search about the pivots, to make the search O(LogN)
}
module.exports = findMIn;
<file_sep>/**
* You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.
What is the maximum number of envelopes can you Russian doll? (put one inside other)
Note:
Rotation is not allowed.
Example:
Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
*/
/**
* @param {number[][]} envelopes
* @return {number}
*/
var maxEnvelopes = function(envelopes) {
if(!envelopes || envelopes.length===0 || enevelopes[0].length===0){
return;
}
let result = 0;
let memo = new Array(envelopes[0].length).fill(new Array(envelopes.length).fill(0));
//graph memo, optimzal subproblems that are overlapping
//let's simply just keep tabs of the min, max h and w, and then map the taken dimensions, starting with w and making sure it is within height h specificity
//do not mutate the envelopes array
let minH=0;
let maxH=0;
let minW=0;
let maxW=0;
//traverse
for(let i=0; i<envelopes[0].length; i++){
//columns on the outer
for(let j=0; j<envelopes.length; j++){
//rows down inner
let dimensions = envelopes[i][j];
//(w, h)
let w = dimensions[0];
let h = dimensions[1];
//since unsorted, we have an option to sort by increasing w, then compare heights only... merge sort would take Onlogn+On = Onlogn amotized.
//we just have to compare to the previously stored on on the table
//if
}
}
return result;
};
//you should have made this problem # 543 that would have been a lot funnier. <file_sep>// Angels of War
/**
* Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
*/
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findKthLargest = function(nums, k) {
//kth largest, dynamic programming, sliding window
//brute: we can sort and get the 3rd largest from the end, sort in O(nlogn) with merge sort, quicksort, or radix sort
//instead, we can have a running tracker of top three largest, starting with the first k elements of the array
if(!nums || nums.length < k || k<0 || nums.length === 0) {
return;
}
let kArr = [];
//this could be a heap, we will sort from largest to smallest
for(let i=0; i<nums.length; i++) {
let el = nums[i];
if(kArr.length===0){
kArr.push(el);
}
else if(kArr.length < k){
// kArr.push(el);
//add it to the relative elements
let isValid = false;
for(let j=0; j<kArr.length && !isValid; j++) {
let elk = kArr[j];
if(elk>el) {
//we can continue
continue;
}
else if(elk<=el ) {
//we must shift this element down, possibly cut out if k length
//we have found the place to shift, after the shift we can escape for loop by making valid
let temp = elk;
kArr[j] = el;
for(let p=j+1; p<kArr.length; p++) {
let current = kArr[p];
kArr[p] = temp;
temp = current; //outer scope,
}
isValid = true; //exit for loop outer
}
}
}
else {
//shift the other elements, arrange them
}
}
//or kArr.pop();
return kArr[k-1];
};<file_sep>""" Solution 1
O NlogK time , O(k) space
from Queue import PriorityQueue
class Solution(object):
def mergeKLists(self, lists):
# :type lists: List[ListNode]
# :rtype: ListNode
head = point = ListNode(0)
q = PriorityQueue()
for l in lists:
if l:
q.put((l.val,1))
while not q.empty():
val, node = q.get()
point.next = ListNode(val)
pont = point.next
node = node.next
if node:
q.put((node.val, node))
return head.next
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if not lists: return
n = len(lists)
if n == 1: return lists[0]
mid = n//2
left = self.mergeKLists(lists[:mid])
# print(left)
right = self.mergeKLists(lists[mid:])
return self.merge(left, right)
def merge(self, left, right):
dummy = ListNode(0)
cur = dummy
while left and right:
if left.val <=right.val:
cur.next = left
left = left.next
else:
cur.next = right
right = right.next
cur=cur.next
if left:
cur.next = left
if right:
cur.next = right
return dummy.next
""" Solution 2
Merge with Divide and Conquer
O nlogk time, O(1) space
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
amount = len(lists)
interval = 1
while interval < amount:
for i in range(0, amount - interval, interval * 2):
lists[i] = self.merge2Lists(lists[i], lists[i + interval])
interval *= 2
return lists[0] if amount > 0 else lists
def merge2Lists(self, l1, l2):
head = point = ListNode(0)
while l1 and l2:
if l1.val <= l2.val:
point.next = l1 #order the node relative position
l1 = l1.next
else:
point.next = l2
l2 = l1
l1 = point.next.next
point = point.next
if not l1:
point.next=l2
else:
point.next=l1
return head.next<file_sep>/*
Given a 2d grid map of 1s (land) and 0s (water), count the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands
horizontally or vertically. You may assume all four edges of the grid are all
surrounded by water.
EXAMPLE 1:
Input:
[
[0, 1, 1, 1, 0],
[1, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 0, 0]
]
Output: 1
Input:
[
[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 1]
]
Output: 3
Assume that the grid will be an array of arrays of numbers either 0 or 1, and
that the grid will have at least one element.
*/
const numIslands = grid => {
const m = grid.length;
const n = grid[0].length;
let result = 0;
//use of closure
const processIsland = (i, j) => {
grid[i][j] = 0; //mutate grid
if(i > 0 && grid[i-1][j] === 1) {
processIsland(i-1,j);
}
if(i < m-1 && grid[i+1][j] === 1) {
processIsland(i + 1, j);
}
if(j > 0 && grid[i][j-1] === 1) {
processIsland(i, j-1);
}
if(j < n-1 && grid[i][j+1]) {
processIsland(i, j+1);
}
};
for(let i=0; i<m; i++) {
for(let j=0; j<n; j++) {
if(grid[i][j]) {
result++;
processIsland(i, j);
}
}
}
return result;
}
module.exports = {numIslands};<file_sep>/**
* 863. All Nodes Distance K in Binary Tree
*
* We are given a binary tree (with root node root), a target node, and an integer value K.
Return a list of the values of all nodes that have a distance K from the target node. The answer can be returned in any order.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2
Output: [7,4,1]
Explanation:
The nodes that are a distance 2 from the target node (with value 5)
have values 7, 4, and 1.
Note that the inputs "root" and "target" are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.
Note:
The given tree is non-empty.
Each node in the tree has unique values 0 <= node.val <= 500.
The target node is a node in the tree.
0 <= K <= 1000.
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} target
* @param {number} K
* @return {number[]}
* this got 72ms, 20%
*/
var distanceK = function(root, target, K) {
if(!root){
return null;
}
var result=[];
let distance, minRoute;
const minPath = (node, target, total, route) => {
route = JSON.parse(JSON.stringify(route));
route[node.val] = true;
if(node.val === target.val){
distance = total;
minRoute = route;
return;
}
if (node.left) minPath(node.left, target, total+1, route); //if left child exists, dfs
if (node.right) minPath(node.right, target, total+1, route);
}
minPath(root, target, 0, {});
const dfs = (node, dist) => {
if (!node) return;
if (dist === K) result.push(node.val);
if (node.left) {
(minRoute[node.left.val]) ? dfs(node.left, dist - 1) : dfs(node.left, dist + 1);
}
if (node.right) {
(minRoute[node.right.val]) ? dfs(node.right, dist - 1) : dfs(node.right, dist + 1);
}
}
dfs(root, distance);
return result;
//the root is the relative position of the tree..
//return a base case helper of positive K, negativeK
//we want all nodes at target +- K distance in nodes, up and down
//we do not care about the entire height of the tree, only up to target-K and K after target
};<file_sep>/** 20. Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true */
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
let stack = [];
const mapping = {')' : '(',
'}' : '{',
']': '['};
//map the closing to the openings
for(let i = 0; i<s.length; i++) {
if (s[i] in mapping) {
const curr = stack.pop();
//found correponding opening
if (mapping[s[i]] !== curr) {
return false;
}
} else {
stack.push(s[i]);
}
}
return !stack.length;
};
module.exports= Leet20;
<file_sep>// if numbers of a set sum to a number
//Dynamic Programming
//take it or leave it(optimization, maximization/minimization)
public boolean canPartition(int [] nums) {
int sum = 0;
for( int num : nums){
sum+=num;
}
if((sum & 1) == 1){
return false;
}
sum /=2;
int n = nums.length;
boolean[] dp = new boolean[sum+1];
Arrays.fill(dp, false);
dp[0] = true;
for (int num : nums) {
for(int i = sum; i> 0 ;i--){
if (i >= num) {
dp[i] = dp[i] || dp[i-num];
}
}
}
return dp[sum];
}<file_sep>class Node:
def __init__(self, children, isWord):
self.children = children
self.isWord = isWord
class Solution:
def __init__(self):
self.trie=None
def build(self, words):
self.trie = Node({}, False)
for word in words:
current = self.trie
for char in word:
if not char in current.children:
current.children[char] = Node({}, False)
current = current.children[char]
current.isWord = True
def autocomplete(self, prefix):
current = self.trie
for char in prefix:
if not char in current.children:
return []
current = current.children[char]
return self._findWordsFromNode(current, prefix)
def _findWordsFromNode(self, node, prefix):
words = []
if node.isWord:
words += [prefix]
for char in node.children:
words += self._findWordsFromNode(node.children[char], prefix + char)
return words
s = Solution()
s.build(['dog', 'dark', 'cat', 'door', 'dodge'])
print(s.autocomplete('do'))
# ['dog', door, dodge]<file_sep>/**
* There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a
* bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.
* Return the city with the smallest number of cities that are reachable through some
* path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number. */
<file_sep>#permutations of the string s
def numDecodings(self, s: str) -> int:
memo = {'':1}
#memo is outside the context, decode is a closure function in python
def decode(s):
#if s is a key in the memo
if s in memo:
return memo[s]
if s[0]=='0':
return 0
#base case for substring recursive call
if len(s) == 1:
return 1
#base case
memo[s] = decode(s[1:])
#memoize the string with it's substring, taking only the current char
#much like Fibonacci
if int(s[0:2]) <=26:
#if ascii is lexicographic
memo[s] += decode(s[2:])
#append to the cache
return memo[s]
return decode(s)
#returning the inner funcition, but rather than sending the function definition, return invocation <file_sep>Get some FAANGS
<file_sep>/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
* 76% time percentile, 52 ms, 35 mb
*/
var levelOrder = function(root) {
if(!root){
return [];
}
var result = [];
var queue = [];
queue.push(root);
// let levels = 0;
while(queue.length) {
let level = queue.length;
let temp = [];
for(let i = 0; i < level; i++) {
let currentNode = queue.shift();
temp.push(currentNode.val);
//unlink and then add the neighbors from the queue
if(currentNode.left !==null) {
queue.push(currentNode.left);
}
if(currentNode.right !== null) {
queue.push(currentNode.right);
}
//next level...avicii
}
result.push(temp);//add current array on the current level for breadth first searching
}
return result;
};<file_sep>/**
* You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Example 1:
Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
Note:
You may assume that you have an infinite number of each kind of coin.
*/
/**
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function(coins, amount) {
if(!amount || amount === 0) return 0;
//create caching local memory
let result = 0;
for(let i=coins.length-1; i>=0; i--) {
let el = coins[i];
if(el<=amount) {
let multiple = Math.floor(amount/el); //truncated int
result+=multiple;
amount/=(el)*multiple;
}
}
if(amount!==0) {
return -1;
}
return result;
}<file_sep>// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(T, R) {
// write your code in JavaScript (Node.js 8.9.4)
//T is the test cases arrays
//R is the results cases arrays strings
//same length and corresponding test case, but we must group them
if(!T || !R || !Array.isArray(T) || !Array.isArray(R) || T.length<1 || R.length<1){
return;
}
let result = 0;
let total = 0;
let alpha = ['a','b','c','d','e','f','g'];
//add rest later
let testIndex = 0; //number of the test
let isGrouping = false;
//use map and reduce
for(let i=0; i<T.length; i++) {
let test = T[i];
// let split1 = test.split(/(\d+)/)
// let testgroup=split1[0];
// let groupnum = split1[1];
// let groupname = test.split()
let res = R[i];
//must be OK status
//check grouping
// if(split1.length>1){
// isGrouping=true;
// }
// else{
// isGrouping=false;
// }
if(res==="OK"){
// if(isGrouping){
// continue; //must pass all until entire
// }
total++;
}
else{
continue; //no need to add score
}
}
result = Math.ceil(total/R.length*100);
return result;
}<file_sep>//Brute force recursion asymptotic O(2^n)
const solveKnapsack = (profits, weights, capacity) => {
//having a closure inner function scope
const knapsackRecursive=(profits, weights, capacity, currentIndex)=>{
if(capacity <= 0 || currentIndex >=profits.length) return 0;
let profit1=0;
if(weights[currentIndex] <=capacity){
profit1=profits[currentIndex] + knapsackRecursive(profits, weights, capacity-weights[currentIndex], currentIndex+1);
}
const profit2= knapsackRecursive(profits, weights, capacity, currentIndex+1);
return Math.max(profit1, profit2);
}
return knapsackRecursive(profits, weights, capacity, 0);
};
const profits =[1,6,10,16];
const weights = [1,2,3,5];
console.log(`Total knapsack profit:--> ${solveKnapsack(profits, weights, 7)}`);
console.log(`Total knapsack profit: --> ${solveKnapsack(profits, weights, 6)}`);<file_sep>/**
* @param {number[][]} matrix
* @return {number[][]}
*/
var updateMatrix = function(matrix) {
//if it is a zero itself, the closest zero is itself, so just fill in 0
//only care if it is a 1,
if(!matrix) {
return;
}
//0 is mapped to false, 1 is mapped to true, we are looking for the inverse
// var result = []; do this in place
// let dist = 0;
let rows = matrix.length;
let cols = matrix[0].length;
let queue = [];
for(let i = 0; i < rows/2; i++){
//i is the y(rows) traverasal -y
// result.push([]);
//we can iterate though 1/4 of the entire array and do symmetrical comparisons to fill in the result matrix
for(let j = 0; j < cols/2; j++) {
let q2 = []; //we are only working through the 2nd quadrant... //first element is value, second is the coordinates
q2.push(matrix[i][j]);
q2.push([i, j]);
let q1 = []; //quadrant 1 symmetrical
q1.push(matrix[i][cols-j-1]);
q1.push([i, cols-j-1]);
let q3 = [];
q3.push(matrix[rows-i-1][j]);
q3.push([rows-i-1, j]);
let q4 = [];
q4.push(matrix[rows-i-1][cols-j-1]);
q4.push([rows-i-1, cols-j-1]);
//element value, position coordinates
//is there a way to have all these elements simultaneously using map reduce to check and get the recursive closest distance
//store each quadrant on a HashMap, with the keys being their quadrants, and have them overlap in the iterator through expanding
// let quadrantsMap = { "q1": [...q1], "q2": [...q2], "q3": [...q3], "q4": [...q4] }; //key value is string quarter of the quadrant(eg, q1 q2, q4, q3) and map the value 0 which is mapped to false, or the radial distance to put on their result position matrix for the closest 0
//if it has not yet encountered a 1 upon symmetrical radial expansion...
if(q1[0]!==0) {
queue.push(q1);
}
if(q2[0]!==0) {
queue.push(q2);
}
if(q3[0]!==0) {
queue.push(q3);
}
if(q4[0]!==0) {
queue.push(q4);
}
// quadrantsMap["q1"] = q1;
// quadrantsMap["q2"] = q2; //if el is 0, then it is mapped to false, matrix is unaltered
// quadrantsMap["q3"] = q3;
// quadrantsMap["q4"] = q4;
// //now we have queues
// let qkeys = Object.keys(quadrantsMap);
// for(let i = 0; i < qkeys.length; i++) {
// let p = quadrantsMap.keys[i];
// if(p!==0){
// queue.push(p);
// }
// }
//now we store the mapping
// result[i][j] = quadrantsMap.q2[0]; //if not in the queue, map original 0
// result[i][cols-j-1] = quadrantsMap.q1[0];
// result[rows-i-1][j] = quadrantsMap.q3[0];
// result[rows-i-1][cols-i-1] = quadrantsMap.q4[0];
while(queue.length) {
let current = queue.pop();
let currentItem = current[0]; //actual value
let currentPosition = current[1]; //array position
let currentI = currentPosition[0];
let currentJ = currentPosition[1];
let currentExpanse = 1;
while((currentI+currentExpanse<rows && matrix[currentI+currentExpanse][currentJ]!== 0) || (currentJ+currentExpanse<cols && matrix[currentI][currentJ+currentExpanse]!== 0) || (currentI-currentExpanse>=0 && matrix[currentI-currentExpanse][currentJ]!== 0) || (currentJ-currentExpanse>=0 && matrix[current][currentJ-currentExpanse]!==0 )) {
currentExpanse++;
}
matrix[currentI][currentJ] = currentExpanse;
}
}
return matrix;
//use symmetry radial level expanse on each 1 element to optimize BFS
};<file_sep>//decoding from AMZ1 encoding
//input: the compressed string
/**
*
* @param {*} str in compressed form
* @return (*) result string that is decoded
*/
const decoding = function(str) {
if(str.length===0) return '';
//in case count is >10
let currentCount = 0;
let result = '';
for(let i=0; i<str.length; i++){
const el = str.charAt(i);
currentCount *=10;
currentCount +=num; //tens place, ones,
//check if it is a count number
if(isNumber(el)){
let num = Number(char); //cast to Number typeof
} else {
for(let j=0; j<currentCount; j++){
result+=el; //do this for the count
}
currentCount = 0;
}
}
//decoded result
return result;
}
module.exports = decoding;<file_sep>/**
* Number of Closed Islands
* Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.
Return the number of closed islands.
Example 1:
Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
Output: 2
Explanation:
Islands in gray are closed because they are completely surrounded by water (group of 1s).
Example 2:
Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
Output: 1
Example 3:
Input: grid = [[1,1,1,1,1,1,1],
[1,0,0,0,0,0,1],
[1,0,1,1,1,0,1],
[1,0,1,0,1,0,1],
[1,0,1,1,1,0,1],
[1,0,0,0,0,0,1],
[1,1,1,1,1,1,1]]
Output: 2
Constraints:
1 <= grid.length, grid[0].length <= 100
0 <= grid[i][j] <=1
*/
/**
* @param {number[][]} grid
* @return {number}
*/
var closedIsland = function(grid) {
// let numIslands = 0;
// const findIsland = (i, j) => {
// if(grid[i][j]){
// return true;
// }
// if(grid[i][j] === 0){
// grid[i][j] = 2; //visitation statue
// if(i<1 || i>= grid.length-1 || j<1 || j>=grid[0].length - 1) {
// return false;
// }
// }
// }
// return numIslands;
//Solution 1: Using Standard Numislands //DFS use a stack
let result = 0;
let m = grid.length;
let n = grid[0].length;
const processIsland = (i, j, isIsland) => {
if(j<0 || j>=n || i<0 || i>=m || grid[i][j]!== 1 || grid[i][j]!==0){
return isIsland; //if the enclosing island is not by water = 1
}
else {
grid[i][j]='';
// let isIsland = true;
//do mutate this...
if(i>=0 && grid[i-1][j]) {
//if surrounded by 1
//must be true and true
isIsland = isIsland && processIsland(i-1, j); //process island until it is complete, we cannot shortcircuit without a series of checks
}
if(i<=m-1 && grid[i+1][j]) {
//m-2 index to be less than so it is an enclosed idland
//the bounds of the grid surrounding canbe 1s
isIsland = isIsland && processprocessIsland(i+1,j);
}
if(j>=0 && grid[i][j-1]) {
isIsland = isIsland && processIsland(i, j-1);
}
if(j<n && grid[i][j+1]) {
isIsland = isIsland && processIsland(i, j+1);
}
return isIsland;
}
}
for(let i=1;i<grid.length-1;i++) {
//we cannot have islands that are not enclosed
for(let j=1;j<grid[0].length-1;j++) {
//if we hit an element that has a zero(potential for island, we can increment the 1, then mutate the grid to not have any overlap, though mutating or not should be fne since they should not be continugous....)
if(grid[i][j]===0) {
result+=processIsland(i,j, true); //true or false will add a 1 or a 0
}
else {
continue;
}
}
}
return result;
};<file_sep>def test_case(solution, string, map, expected):
assert solution(string, map) == expected
print("Test case: sliding_window({}, {}) == {} passed".format(string, str(map), expected))
def run_test(solution):
test_case(solution, "adddddbcbba", {'a','b','c'}, 4)
test_case(solution, "abc", {'a','b','c'}, 3)
test_case(solution, "abdddddcbeba", {'a', 'b', 'c'}, 5)
test_case(solution, "abweweffawefcaaaaboiwuroqiwuroiueeeb", {'a', 'b', 'c'}, 6)
<file_sep>class MinHeap{
constructor() {
this.heap = [null];
}
//returns the 1st element of heap
peek(){
return this.heap[1];
}
len(){
return this.heap.length-1;
}
insert(num){
const heap = this.heap;
heap.push(num);
const heapLength = heap.length;
if(heapLength <=2){
return;
}
let id = heapLength -1;
let parentId=Math.floor(id/2);
while(parentId>=1 && heap[id] < heap[parentId]){
[heap[id], heap[parentId]] = [heap[parentId], heap[id]];
id = parentId;
parentId = Math.floor(id/2);
}
}
remove(){
const heap= this.heap;
if(heap.length<=1){
return;
}
if(heap.length<=2){
return heap.pop();
}
const last = heap.pop();
let i = 1;
const smallest = heap[i];
heap[i]=last;
let leftId=i*2;
let rightId = i*2+1;
while((heap[leftId] !== undefined && heap[i] > heap[leftId]) || (heap[rightId] !== undefined && heap[i]>heap[rightId])){
if(heap[rightId] !== undefined && heap[rightId] < heap[leftId]){
[heap[i], heap[rightId]] = [heap[rigithId], heap[i]];
i = rightId;
} else {
[heap[i], heap[leftId]] = [heap[leftId], heap[i]];
i = leftId;
}
leftId = i*2;
rightId=i*2+1;
}
return smallest;
}
inserts(nums){
for(const i of nums){
this.insert(i);
}
}
}
var KthLargset = function(k, nums){
this.heap = new MinHeap();
this.k = k;
if(nums.length<1){
return;
}
let i =0;
for(i; i<k;i++){
if(nums[i] !==undefined){
this.heap.insert(nums[i]);
}
}
for(i; i<nums.length; i++){
this.add(nums[i]);
}
};
//kth largest element eg k=2
KthLargest.prototype.add = function(val) {
if(this.heap.len() < this.k){
this.heap.insert(val);
return this.heap.peek();
}
if(this.heap.peek() < val){
this.heap.remove();
this.heap.insert(val);
return this.heap.peek();
}
return this.heap.peek();
};
<file_sep>//From BU Summer Notes
/*
You have a knapsack with a weight limit.
You are also presented with a list of singular items, each with a weight and a value.
Each item can be counted only once.
What is the optimal total value of a set of items that can fit in your knapsack?
You are presented with an array of singlular objects, each object has a weight and value.
Imagine that each object represents a unique item, to be counted once.
Find the maximum value you can fit into your knapsack, given the weight constraint.
e.g.
items = [
{weight: 1, value : 3},
{weight: 2, value : 4},
{weight: 3, value : 5},
];
knapsack(items, 3); // returns 7 (from items[0] and items[1])
knapsack(items, 5); // returns 9 (from items[1] and items[2])
*/
//recursively explore all options
const knapsack = ( itemsLeft, weightLimit) => {
if(itemsLeft.length === 0 || weightLimit === 0) return 0;
if(itemsLeft[0].weight > weightAvailable){
return knapsack(itemsLeft.slice(1), weightLimit)
}
//omit first item if it does not fit
else{
const left = itemsLeft.slice(1);
const takeIt = itemsLeft[0].value+ knapsack(left, weightLimit-itemsLeft[0].weight);
const leaveIt = knapsack(left, weightLimit);
return (takeIt>leaveIt) ? takeIt : leaveIt;
}
}
//second recursive solution with tracking
const knapsack = (itemsLeft, weightLimit) => {
const selected = {
value: 0,
list: []
};
if(itemsLeft.length===0 || weightLimit===0) return selected;
if(itemsLeft[0].weight > weightLimit){
return knapsack(itemsLeft.slice(1), weightLimit);
}
else{
const leaveIt = knapsack(itemsLeft.slice(1), weightLimit);
const considerTakeIt=knapsack(itemsLeft.slice(1), weightLimit-itemsLeft[0].weight);
considerTakeIt.list.push(itemsLeft[0]);
const takeIt={
value: itemsLeft[0].value+considerTakeIt.value,
list: considerTakeIt.list
};
return (takeIt.value > leaveIt.value) ? takeIt : leaveIt;
}
}
//dynamic programming with matrix
const knapsackAdvanced = ( items, weightLimit) => {
const table = [];
for(let i =0; i<items.length;i++){
table.push([]);
for(let capacity=0; capacity<=weightLimit;capacity++){
if(i === 0){
table[itemIndex].push(0);
continue;
}
table[i][capacity]=takeItOrLeaveIt(table[i-1], items[i-1],capacity);
}
}
return table[items.length][weightLimit];
};
const takeItOrLeaveIt = (statusCondition, item, capacity) => {
let takeIt=0;
let leaveIt = statusCondition[capacity];
if(item.weight<=capacity){
let remainingCapacity = capacity-item.weight;
takeIt += item.value;
takeIt += statusCondition[remainingCapacity];
}
return Math.max(take, not);
}
module.exports = { knapsack, knapsackAdvanced };<file_sep>from test_runner import run_test
def sliding_window(string, char_set):
left, right, best_score = 0, 0, float('inf')
letter_map = {}
characters_encountered = 0
while right < len(string) or characters_encountered == len(char_set):
if characters_encountered != len(char_set):
curr_right = string[right]
if curr_right in char_set:
letter_map[curr_right] = letter_map.get(curr_right, 0)+1
if letter_map[curr_right] == 1:
characters_encountered +=1
right += 1
else:
curr_left = string[left]
if curr_left in char_set:
letter_map[curr_left] -=1
if letter_map[curr_left] == 0:
characters_encountered -=1
left += 1
best_score = min(best_score, right - left +1)
return best_score if best_score !=float('inf') else -1
run_test(sliding_window)<file_sep>/**
* There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
*/
/**
* @param {number[]} stones
* @param {number} K
* @return {number}
*/
var mergeStones = function(stones, K) {
//combine sliding window shift
if(!K || !stones || !Array.isArray(stones) || stones.length===0 || K<0) {
return -1;
}
else if((stones.length+1)%K!==0 && K!==2) {
return -1;
}
else {
return acquisitions(stones, K, 0); //hoisted function
}
// var result = 0;
//sum of K consecutive additions in (stones.length+1)/K merges....
//O((N+1)/K*)
//number of merges needed to combine
//time complexity
//space complexity:
///window slide-greedy, take it or leave it, dynamic programming
// for(let i = 0 ; i < stones.length; i++) {
// let checkSum
// } //use recusion while loop
// use reduce with a take it or leave it callback function
//
//the runtime loks bad, but actually it isnt because of dynamic programming
// return stones.reduce((acc, current) => {
// //use of unshift, splice,
// var minSum= Math.sum(stones.slice(0, K));
// let indexTrack = 0;
// for(let i = K-1; i <stones.length; i++) {
// let currSum= Math.sum(stones.slice(i, i+K));
// if(currSum<minSum){
// indexTrack = i;
// minSum=currSum;
// }
// }
// stones.splice(indexTrack, indexTrack+K); //smaller subproblem array
// return minSum;
// }, 0)
// return result;
};
var acquisitions = function(stones, K, acc) {
if(stones.length ===0 ) {
return acc; //done
}
let arr = stones.slice(0, K);
let minSum = arr.reduce((a, currentvalue) => a + currentvalue, 0);
let indexTrack = 0;
for(let i = K-1; i <stones.length; i++) {
let currSum= stones.slice(i, i+K).reduce((a, b) => {
return a+b;
}, 0)
if(currSum<minSum){
indexTrack = i;
minSum=currSum;
}
}
// stones=stones.splice(indexTrack, indexTrack+K); //smaller subproblem array, immutable
return acquisitions(stones.splice(indexTrack, indexTrack+K), K, minSum + acc);
} <file_sep>To Migrate to Progressive Web App: Algomediocre Blog
<file_sep>Graph Search BFS
- Implement the Microsoft Paint “fill” button—given a bitmap and a starting position and a target color, find all the cells which are currently the color of the starting cell and change their color to the target color.
- Given a maze encoded in ASCII, find the shortest path from the start to the end and print out the path.
- Word chains
- Writing a web crawler
BFS: Queue, FIFO<file_sep>/** Leet 207, can finish
* There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should
also have finished course 1. So it is impossible.
Constraints:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.
1 <= numCourses <= 10^5
*/
/**
*
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {boolean}
*/
//method # 1: DFS
const canFinish = (numCourses, prerequisites){
const indegree = Array(numCourses).fill(0);
const track = {};
const queue = [];
for(const [course, dependentCourse] of prerequisites){
if(track[course]){
track[course].push(dependentCourse);
} else {
track[course] = [dependentCourse];
}
indegree[dependentCourse]++;
}
for(let i =0; i<indegree.length; i++){
if(indegree[i] === 0) queue.push(i);
}
let count = 0;
while(queue.length >0){
count++;
const current = queue.shift();
if(track[current]){
for(const dep of track[current]){
indegree[dep]--;
if(indegree[dep]===0) queue.push(dep);
}
}
}
return numCourses === count;
};
//method #2 detecting a cycle with two stacks ,
//one for current path, other for complete path
//iterate over nodes, use DFS to detect cycle
/**
* @param {number}
* @param {number[]}
* @return {boolean}
*/
const canFinish = (numCourses, prerequisites) => {
const graph = createGraph(numCourses, prerequisites);
const completed = new Set();//track finished
for(let i =0;i<numCourses; i++){
//if the course has not been completed, and there is a cycle(prerequisite is circular to another prior requisite)
if(!completed.has(i) && hasCycle(graph, i, completed)){
return false;
}
}
return true;
};
function hasCycle(graph, u, completed, visited=new Set()){
if(completed.has(u)){
//if the course has been completed, there is not a cycle
return false;
}
if(visited.has(u)){
//draw out diagram, if you have visited the node but you have not competed it, it has a redundant cycle
return true;
}
//if it has not been completed and has not been completed,
//mark visitation
visited.add(u);
//iterate through the pair of key pairs of requisites at the index of the graph
for(const v of graph[u]){
if(hasCycle(graph, v, completed, visited)) {
//check again once visited if pair has cycle, eg not complete, but already visited, having a cycle means that you cannot take the preq before the req
//because they are reqs of eachother
return true;
}
}
visited.delete(u);
completed.add(u);
return false;
}
function createGraph(numCourses, prerequisites){
const graph = new Array(numCourses).fill(null).map(() => []);
//graph the possibilities
for(const [u, v] of prerequisites){
graph[u].push(v); //graph the pairs to tie them in a path
}
return graph;
}<file_sep>/**
* @param {character[][]} matrix
* @param {string} word
* @return {boolean}
*/
const exist = (matrix, word) => {
let wordLength = word.length;
word = word.split(""); //convert the word string into array, since stirngs are immutable
//path is current location
const verify = (row, col, matrix, path) => {
//if we are out of the bounds of the grid, or if the current element does not have the current built up word at the path location
if(row<0 || col<0 || row>=matrix.length || col>=matrix[0].length || matrix[row][col]!=word[path]
|| path>wordLength) return false; //not in the search, base case, game over
//otherwise we increment the path location
path++;
matrix[row][col]='#'; //path is the buildup element char at index of word
//fill out if already visited for this context
//if we find the word
//that chars match and the path is complete
if(path === wordLength) return true;
//up
if(verify(row-1, col, matrix, path)) return true;
//right, recursively search the edges
if(verify(row, col+1, matrix, path)) return true;
//down
if(verify(row+1, col, matrix, path)) return true;
//left
if(verify(row,col-1,matrix,path)) return true;
//backtrack
matrix[row][col]=word[--path];
return false;
}
for(let i=0; i<matrix.length; i++){
for(let j =0; j<matrix[i].length; j++){
if(verify(i,j,matrix,0)) return true;
}
}
return false;
};<file_sep>/**
* @param arr [2,[3],[4,5], [[7]]]
* @return result [2,3,4,5,7]
*/
const flattenArray = (arr) => {
if(!arr || arr.length === 0) return arr;
let result = [];
//iteratively
for(let i=0; i<arr.length;i++){
let el = arr[i];
if(Array.isArray(el)){
flattened = flattendArray(el); //will recursively give back response
result.push(...flattened); //spread operator
}
else{
result.push(el);
}
}
//do in place
return arr;
}
// const helpArray = (element) => {
// //takes in type array and flatten level
// let isDone = false;
// let res = [];
// for(let j=0; j<element.length; j++){
// }
// return res;
// }
module.exports = flattenArray;<file_sep>/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
if(!prices || prices.length <2){
return 0; //cannot buy or no buy/sell can occure
}
let buy = true;
let sell = !buy;
let pMax=0;
//extremety cases, no voltility(constant up or down in candle interval)
//downwards, never buy or sell, upwards only buy first day and sell last
//short circuit these conditions
//we can use reduce compare the differences, if any consecutive element is not increasing or decreasing we breakout
let localMax=0;
let minBuyIndex;
let maxSellIndex; // make this an intial undefined, track indexes within mini windows of the stock prices graph
for(let i=0; i<prices.length-1; i++) {
let el=prices[i];
if(buy) {
//compare the mini profits in betwee, the next buy sell interval
//in a buy window, compare the minimum
if(!minBuyIndex){
//short circuit for undefined
minBuyIndex = i;
}
else if(el<prices[minBuyIndex]) {
//add back the buy from the last min and subtract off the current Index price
localMax+=prices[minBuyIndex];
localMax-=el;
minBuyIndex = i;
}
// buy = false;
// sell = !buy;
}
else if(sell) {
if(!maxSellIndex){
maxSellIndex = i;
localMax+=el;
}
else if(el>prices[maxSellIndex]) {
localMax+=el;
maxSellIndex = i;
}
else{
//it is less than max, we do not add it
}
pMax = Math.max(pMax, localMax);//only compare the two on a sell
//reset toggle buy sell, but also reset their indices to buy sell
minBuyIndex = undefined;
minSellIndex = undefined; //new buy sell cycle
// buy = true;
// sell = !buy;
}
buy = !buy; //toggle based on changes
sell = !buy;
}
//final check if we are at toggle for the sell is true, then we sell that last day of index i on the last day of the interval, candlestick method
if(sell){
pMax+=prices[prices.length-1];
}
return pMax;
};<file_sep>//Given a String S and a String T, find minimum window in S which will contain the characters of T of the order in T, in linear time
//return : the window
// For example, S = "ADOBECODEBANC", T = "ABC",
// Minimum window is "BANC".
//duplicate chars?
const minimumWindowSubstring = (S, T) => {
let tracker = {};
for(let i =0; i< T.length; i++){
let letter=T.charAt(i);
if(tracker[letter] === undefined)
{
tracker[letter]=0;
}
else
{
tracker[letter]++; //number of occurences
}
}
let counter=0;
let leftPoint=0;
let rightPoint=S.length-1;
//T is always less than S, use string manipulation
//if we splice out
for(let i = 0; i< S.length; i++){
}
}
console.log(minimumWindowSubstring('ADOBECODEBANC', 'ABC'))<file_sep>/**
* There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
*/
//Permutations, unique ways climb stairs, reverse dynamic/functional program
//order matters
//use recursion
/**
*
* @param {*} num number of stairs
* @return result number of ways with order into account
*/
export const staircase = function(num) {
//base case
if(num <1){
return 0;
}
else if(num === 1) return 1; //one way to move 1 step: 1
else if(num === 2) return 2; //two ways to move 2 steps: 1 or 2 skip
else {
//um >2
return 2 + staircase(num-1) + staircase(num-2);
//will return the number before the recursive call results
}
//O(N!) runtime
// for(let i=0; i<num; i++){
// //same as fibonacci for each case
// }
}
/**
*
* @param {*} num
* @param {*} options , eg the number of options to take the stairs eg skip 1 step, skip 2 steps, skip 5 stpes...etc
*/
export const genericstaircase = function(num, options) {
const dfs = Array(num+1).fill(0); //allocate array matrix graph
//though this is not dfs, we are just calling it dfs because it is reverse dfs
for(let i=1; i<=num; i++){
let arkansas = 0;
//fill in the dfs graph we created for cell exploration
for(let j=0; j<options.length; j++){
const option = options[j];
if(i-option > 0) arkansas+= dfs([i-option]); //we do not need to actually map out the paths, just add the options of positive steps we can take
}
dfs[i] += arkansas;
if(options.indexOf(i) !== -1) dfs[i] +=1;
}
//the last element is the sum path permutations total
return dfs[dfs.length-1];
}
export default staircase;<file_sep>//stock prices profic
//temporal array of prices
//one purchase and one sale only in 1 day
const profitMax = (prices) => {
if(!Array.isArray(prices)) {
return;
}
if(prices.length<2){
return;
}
let minPrice = prices[0];
let maxProfit = prices[1] - minPrice;
//trail the dragon...
for (let i = 1; i < prices.length; i++ ){
const currentPrice = prices[i];
const potential = currentPrice - minPrice;
maxProfit = Math.max(maxProfit, potential);
minPrice = Math.min(minPrice, currentStockPrice);
}
return maxProfit;
};
module.exports = profitMax;<file_sep>//
let oldSport = function(profits, weights, capacity) {
function oldSportRecursive(profits, weights, capacity, currentIndex) {
if(capacity <= 0 || currentIndex >= profits.length) return 0;
let profitTake = 0; //take it or leave it greedy algorithm
if (weights[currentIndex] <= capacity) {
profitTake = profits[currentIndex] + oldSportRecursive(profits, weights, capacity - weights[currentIndex], currentIndex +1);
}
let profitLeave = oldSportRecursive(profits, weights, capacity, currentIndex + 1);
return Math.max(profitTake, profitLeave);
}
return oldSportRecursive(profits, weights, capacity, 0); //recursive closure but return the invocation, so it's a higher order function
};
var profits = [1,6,10,16];
var weights = [1,2, 3, 5];
console.log(oldSport(profits, weights, 7));
console.log(oldSport(profits, weights, 10));<file_sep>
//ES5
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
if (!lists.length) {
//lists.length===0 is technically false boolean by coercion
return null;
}
var result = null;
var tail = null;
for (let i = 0; i < lists.length; i++) {
if (lists[i] === null) {
lists[i] = new ListNode(Number.POSITIVE_INFINITY);
}
}
build_min_heap(lists, lists.length, 0);
var rootValue = lists[0].val;
while (isFinite(rootValue)) {
if (result === null) {
result = new ListNode(rootValue);
tail = result;
}
else {
tail.next = new ListNode(rootValue);
tail = tail.next;
}
lists[0] = lists[0].next;
if (lists[0] === null) {
lists[0] = new ListNode(Number.POSITIVE_INFINITY);
}
min_heapify(lists, lists.length, 0);
rootValue = lists[0].val;
}
return result;
};
function swap_in_array(A, i, j) {
var temp = A[i];
A[i] = A[j];
A[j] = temp;
}
function min_heapify(A, arr_length, i) {
var l = 2 * i + 1,
r = 2 * i + 2,
smallest = i;
if (l < arr_length && A[l].val < A[smallest].val) {
smallest = l;
}
if (r < arr_length && A[r].val < A[smallest].val) {
smallest = r;
}
if (smallest !== i) {
swap_in_array(A, i, smallest);
min_heapify(A, arr_length, smallest);
}
}
function build_min_heap(A, arr_length, i) {
var l = 2 * i + 1,
r = 2 * i + 2;
if (l < arr_length) {
build_min_heap(A, arr_length, l);
}
if (r < arr_length) {
build_min_heap(A, arr_length, r);
}
min_heapify(A, arr_length, i);
}
//ES6//use of Min Heap for merge K sorted Linked Lists
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/// Leet
function build_min_heap(A, arr_length, i){
const l = 2*i+1, r=2*i+2;
if(l<arr_length){
build_min_heap(A, arr_length, l);
}
if(r<arr_length){
build_min_heap(A, arr_length, r);
}
min_heapify(A, arr_length, i);
}
/**
*
* @param {*} A lists Array of Linked Lists Nodes
* @param {*} arr_length K Linked Lists
* @param {*} i the index is the current Linked List head node
*/
function min_heapify(A, arr_length, i){
//i is building with the index, A is lists array of Linked Lists Nodes
//a heap is built keeping track of the smallest, while keeping track of left and right siblings like a horizontal binary tree
const l=2*i+1, r=2*i+2, smallest=i; //taking the array lists and making it become geometric into a tree structure
if(l<arr_length && A[l].val < A[smallest].val){
smallest = l;
}
if(r<arr_length && A[r].val < A[smallest].val){
smallest = r;
}
if(smallest !==i){
swap_in_array(A, i, smallest);
min_heapify(A, arr_length, smallest);
}
}
function swap_in_array(A, i, j){
let temp = A[i];
A[i] = A[j];
A[j] = temp;
}
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists=function(lists){
if(!lists.length){
return null;
}
let result = null;
let tail = null;
for(let i = 0; i< lists.length; i++){ //simply a validation check
if(lists[i] === null){
lists[i] = new ListNode(Number.POSITIVE_INFINITY);
}
}
build_min_heap(lists, lists.length, 0); //build a min heap starting around the head of the first Linked List
let rootValue = lists[0].val;
while(isFinite(rootValue)){
if(result === null){
result = new ListNode(rootValue);
tail=result; //re-sorting the linked list
}
else{
tail.next = new ListNode(rootValue);
tail = tail.next;
}
lists[0] = lists[0].next;
if(lists[0] === null){
lists[0] = new ListNode(Number.POSITIVE_INFINITY);
}
min_heapify(lists, lists.length, 0);
rootValue = lists[0].value;
}
return result;
};
<file_sep>/**
* You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**/
/**
* @param {number} n
* @return {number}
*/
var climbStairs = function(n) {
//permutations of stairs,
//n recursively is the stairs left
if(!n || n<=0){
return 0;
}
else if(n<2) {
return 1;//base recursive case
}
else if(n===2){
return 2;
}
else {
return 1+climbStairs(n-1) + climbStairs(n-2);
}
};<file_sep>//encoder
/**
* Question
Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character.
For example, the string “AAAABBBCCDAA” would be encoded as “4A3B2C1D2A”.
Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid.
*/
const encoding = function(str){
let current = str.charAt(0);
let count = 1;
//encoding result
let result = '';
for(let i=1; i<str.length; i++){
let el = string.charAt(i);
if(el === current) count++; //continue compression
else {
encoding += count + el; //from the previous store
//reset
count = 1;
current = el; //new store from current is the next aggregate previous
}
}
result += count + current;
return result;
}
module.exports = encoding;
|
ed2df307e4c8f1a19a0071c95f4b7f5add848345
|
[
"Java",
"Markdown",
"JavaScript",
"Python"
] | 92 |
Java
|
theangelsofwar/AlgoEtro
|
b30b3753e5849b3105f39e5d5eaa1188556a278c
|
5f0e798b6ef0454fac7eed0001ff900b24151e3b
|
refs/heads/main
|
<file_sep>/**
* 处理请求的 data
*/
function resolveData(data) {
var rows = [];
for(var key in data) {
var query = `${key}=${data[key]}`;
rows.push(query);
}
return rows.join('&');
}
// 封装 ajax 函数
function ajax(options = {}) {
var xhr = new XMLHttpRequest();
var qs = resolveData(options.data);
if(options.method.toUpperCase() === 'GET') {
xhr.open(options.method, options.url + '?' + qs);
xhr.send();
} else if(options.method.toUpperCase() === 'POST') {
xhr.open(options.method, options.url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(qs)
}
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var result = JSON.parse(xhr.response);
options.success(result);
}
}
}<file_sep>function resolveData(params) {
var rows = [];
for(var key in params) {
var str = `${key}=${params[key]}`;
rows.push(str);
}
return rows.join('&');
}
function ajax(options = {}) {
var xhr = new XMLHttpRequest();
var qs = resolveData(options.data);
if(options.method.toUpperCase() === 'GET') {
xhr.open(options.method, options.url + '?' + qs);
xhr.send();
} else if(options.method.toUpperCase() === 'POST') {
xhr.open(options.method, options.url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(qs);
}
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var result = JSON.parse(xhr.response);
options.success(result);
}
}
}
ajax({
method: 'get',
url: 'http://www.liulongbin.top:3006/api/getbooks',
success: function(result) {
console.log(result);
}
})
ajax({
method: 'post',
url: 'http://www.liulongbin.top:3006/api/addbook',
data: {
bookname: '大耳朵图图',
author: '某某某',
publisher: '某某出版社出版'
},
success: function(result) {
console.log(result);
}
})
|
52c35274312844ed6eaff39800762a3c0683917d
|
[
"JavaScript"
] | 2 |
JavaScript
|
2602047255/ajax
|
bdad058b1a1a7d510ea3377d3095f58e1ed316a8
|
073a7b82968b50cba00e521dc8ed23639d1f84e2
|
refs/heads/master
|
<file_sep>body {
background-color: aliceblue;
margin: 0px;
padding: 50px;
}
h1 {
color:blueviolet;
font-family: 'Acme', sans-serif;
font-size: 50px;
font-weight: 500;
margin: 0;
text-align: center;
}
h2 {
color: #AAA;
font-family: 'Acme', sans-serif;
font-size: 16px;
font-weight: 100;
letter-spacing: 2px;
margin: 0;
text-align: center;
text-transform: uppercase;
}
p {
color: #333;
font-family: 'Acme', sans-serif;
font-size: 20px;
font-weight: 100;
margin: 10px;
text-align: center;
}
.menu {
text-align: center;
margin-top: 30px;
}
.menu a {
background-color: lightsalmon;
border-radius: 5px;
color: darkblue;
font-family: 'Acme', sans-serif;
font-size: 16px;
font-weight: 300;
display: inline-block;
margin: 10px;
padding: 10px;
text-align: center;
text-decoration: none;
text-transform: uppercase;
}
#gameboard {
position: relative;
text-align: center;
top: 30px;
}
.card {
border: 2px solid darkblue;
display: inline-block;
height: 200px;
margin-top: 2px;
padding: 0 auto;
text-align: center;
width: 200px;
z-index: 10;
}
.card:hover {
background-color: darkblue;
border-color: honeydew;
}
.card img {
padding: 50px;
height: 100px;
width: 100px;
}
|
001121b896059c2dfae822b12a99f256756b47cb
|
[
"CSS"
] | 1 |
CSS
|
atujian/atujian.github.io
|
1b64e452f833d8b5cbca5280a928cd81f3326846
|
8bbd1a024ce7d32672c882e434e320699ee7d93f
|
refs/heads/master
|
<file_sep>#include<stdio.h>
#include<stdlib.h>
bool isIdentify(char[]);
int translate(char);
int main(void){
char id[10];
printf("請輸入身分證字號:");
scanf("%s",&id);
if(isIdentify(id)==true){
printf("符合身分字號\n");
}
else{
printf("不符合身分字號\n");
}
system("pause");
}
bool isIdentify(char id[]){
int id_int[10];
int sum,i;
int j=8;
for(i=0;i<10;i++){
id_int[i]=translate(id[i]);
}
sum=(id_int[0]/10)+((id_int[0]%10)*9);
for(i=1;i<9;i++){
sum+=id_int[i]*j;
j--;
}
sum+=id_int[9];
if(sum%10==0){
return true;
}
else{
return false;
}
}
int translate(char x){
switch(x){
case 'A':
return 10;
break;
case 'B':
return 11;
break;
case 'C':
return 12;
break;
case 'D':
return 13;
break;
case 'E':
return 14;
break;
case 'F':
return 15;
break;
case 'G':
return 16;
break;
case 'H':
return 17;
break;
case 'I':
return 34;
break;
case 'J':
return 18;
break;
case 'K':
return 19;
break;
case 'L':
return 20;
break;
case 'M':
return 21;
break;
case 'N':
return 22;
break;
case 'O':
return 35;
break;
case 'P':
return 23;
break;
case 'Q':
return 24;
break;
case 'R':
return 25;
break;
case 'S':
return 26;
break;
case 'T':
return 27;
break;
case 'U':
return 28;
break;
case 'V':
return 29;
break;
case 'W':
return 32;
break;
case 'X':
return 30;
break;
case 'Y':
return 31;
break;
case 'Z':
return 33;
break;
case '0':
return 0;
break;
case '1':
return 1;
break;
case '2':
return 2;
break;
case '3':
return 3;
break;
case '4':
return 4;
break;
case '5':
return 5;
break;
case '6':
return 6;
break;
case '7':
return 7;
break;
case '8':
return 8;
break;
case '9':
return 9;
break;
}
}
|
c4956a3b43df02975eb051426991713a264bdb24
|
[
"C++"
] | 1 |
C++
|
xup6tp6u4/advanced06
|
99e2c88302abbc6e08528f70b2f1b08506d41e67
|
1ff69514310bf25d94d7c2dcc26857ece20707e3
|
refs/heads/main
|
<file_sep># Welcome to R523
## What is it?
We are trying to learn and use IoT here by making smart things such as smart flower pot and etc.
## What we have done?
### Gooldoon [Spring 2020]
gooldoon is a two part system, one part is `goooldoon-node` which runs on the flower pot and the second part is `gooldoon-cli` which runs on you computer.
they communicate by means of CoAP protocol. the node side uses the esp32 and have senors.
|
e90091781466be96f8785e3ee18357843280b6c0
|
[
"Markdown"
] | 1 |
Markdown
|
R523/.github
|
bb2e2140d2bb03be52d09ee87a4b9ac1694cd4ab
|
a30fb014b775dd92d8b5e527e8a6e0dca5ba203f
|
refs/heads/master
|
<repo_name>zuimaz/o2o<file_sep>/README.md
# o2o
Campus shops
|
0a1ef4b52c8a7c7eaab83fc9fc725bd38e4f24da
|
[
"Markdown"
] | 1 |
Markdown
|
zuimaz/o2o
|
135ac18aeeff303c35d2de51bfbb5868c6abca27
|
ce8b829590eca4b6c1545d492575ad581fd2c0c4
|
refs/heads/master
|
<file_sep># Classification-on-transcription-factor-binding-and-non-binding-sites
Class Project
|
18ee8192ea12ea361f2573102f3629495e9ac8aa
|
[
"Markdown"
] | 1 |
Markdown
|
SannapaneniBharadwaj/Classification-on-transcription-factor-binding-and-non-binding-sites
|
45ae03763d6a69b59ccc5952e014d8ca3a36ffd5
|
4717fc7f3e2f1e426fda3acf8c24d87fb4b41bd1
|
refs/heads/master
|
<file_sep>Creating a New Page
===================
We will use the User Stories page as an example throughout this document. The source code for this page can be found in `~/projects/churro/src/pages/user-stories`
# Prerequisites
- Churro environment is set up. This document will assume a working development environment for churro is up and running. [See here for instructions](https://github.com/RallySoftware/churro#quick-start).
- Feature Toggle: typically new pages are implemented behind a feature toggle so that we can control the release of functionality independent of our deploy cadences.
- For more information regarding feature toggles and how to create a new one, look [here](https://github.com/RallySoftware/alm#feature-toggles)
# Let's Do This Thing
1. Pages should be created in the `src/pages` directory by creating a new directory. In our example, our directory will be called: `user-stories`
- Some Notes About Directory Structure
- Minimal example directory structure:
```
pages
- user-stories
- components
- containers
index.js
UserStoriesPage.js
```
- `components` should contain React component modules
- `containers` should contain an imported component connected to the Redux store via react-redux's `connect` or one of our internal higher-order components (such as `withSchema`)
- Note: Container modules names should end in `Container.js` (e.g. `UserStoriesPageContainer.js`)
- Note: Container modules should not contain React component definitions, React components should be defined in a separate file.
1. Minimum Requirements
- `index.js`
- Must fufill the following interface:
```javascript
/* index.js */
export default {
/**
* Given the current slug and application state from Redux, this function
* should return a boolean indicating whether or not this page should
* be the one rendered for the current slug.
*
* @param {String} slug The current route that the user has navigated to
* @param {Object} reduxState The current state of the application
*
* @returns {boolean} Whether this page should be displayed for the supplied `slug`
*/
matches(slug, reduxState) { /* ... */ },
/**
* Given the current navigationState and the Redux store, this function should return
* a Promise that resolves to a React Component.
*
* @param {NavigationState} navigationState
* @param {ReduxStore} reduxStore The Redux store, generally used here to either
* `store.dispatch` actions or read values from `store.getState()`
*
* @returns {Promise} Returns a Promise that resolves the React Component to be rendered for this page.
*/
initPage(navigationState, reduxStore) { /* ... */ },
/**
* @Legacy
* This legacy method should generally return an empty array for newly created pages.
* If you're not sure if you should return something here, you probably do not need to.
*
* For legacy pages, this may need to return an array containing one or
* more strings indicating legacy frameworks the page requires.
* For example, a page that requires ExtJS code from our Pinata repository
* would need to return an array such as: `['js!ext4rally']`
*/
getDependencies(reduxState, navigationState) { /* ... */ }
};
```
- Now let us take a look at the User Stories `index.js` for a full example:
- Note how the `matches` function below checks a feature toggle in addition to the slug to determine if this page should be rendered.
```javascript
/* src/pages/user-stories/index.js */
import dynamicallyLoad from 'utils/dynamicallyLoad';
import { isToggleEnabled } from 'reducers/UserContextReducer';
// When webpack is upgraded to >= v4.x.x, we'll replace this deprecated
// loader syntax and promise-loader package with dynamic imports, which
// are the modern equivalent for lazy-loading an ecmascript module.
//
// eslint-disable-next-line import/no-webpack-loader-syntax
const UserStoriesPage = require('promise-loader?global,userstories!./UserStoriesPage');
export default {
matches(slug, state) {
return (
slug === '/userstories' &&
isToggleEnabled(state, 'F20161_REACT_USER_STORIES_PAGE')
);
},
initPage() {
return dynamicallyLoad(UserStoriesPage);
},
getDependencies() {
return [];
},
};
```
- The Page (e.g. `UserStoriesPage.js`)
- Must fufill the following interface:
```javascript
export default {
/**
* The only required method for this module
* @returns {React Component} Should return a React component
*/
getReactComponent() { /* ... */ },
/**
* Optional.
* Can be used to set a document title for the page. If a dynamic document
* title is required, see the DocumentTitle component
* @returns {String} Should return an externalized string to use as the document title.
* See [here](http://churro-docs.tools.f4tech.com/guides/i18n.html) for more info on
* how we do internationalization.
*/
getTitle() { /* ... */ }
};
```
- Looking at User Stories as an example:
```javascript
import UserStoriesPageContainer from './containers/UserStoriesPageContainer';
import { formatMessageAsString } from 'i18n/StringFormatting';
export default {
getReactComponent() {
return UserStoriesPageContainer;
},
getTitle() {
return formatMessageAsString({ messageKey: 'UserStoriesPage/title' });
},
};
```
- The React Component
- Implied by `getReactComponent` above, is the need for an actual React component to render some content for the page.
- Here is an annotated example of the User Stories page's `Page.js`:
```javascript
import PropTypes from 'prop-types';
import React from 'react';
import * as ImmutablePropTypes from 'react-immutable-proptypes';
import { LoadingMask, PageHeader } from 'components/common/index';
import { formatMessageAsString } from 'i18n/StringFormatting';
import LayoutPage from 'components/layout/Page';
import Schema from 'utils/alm/Schema';
import { genGetClassName } from 'utils/Namespacing';
import SavedViewsSelect from 'components/saved-views/SavedViewsSelect';
import FeedbackButton from 'components/feedback-button/FeedbackButton';
import UserStoriesDataTable from './UserStoriesDataTable';
// We primarily use SASS for our styles, with some exceptions
// where React's inline styles are used.
import './Page.scss';
const displayName = 'UserStoriesPage';
// CSS class names should be generated via our `getClassName` utility
// which is based on SUIT CSS namespacing.
const getClassName = genGetClassName(displayName);
const userStoriesFeedbackId = 'userstories';
export default class Page extends React.Component {
// It is important that all components have a displayName property
// as this property is utilized for our client metrics infrastructure
static displayName = displayName;
static propTypes = {
schema: PropTypes.instanceOf(Schema),
scope: ImmutablePropTypes.map.isRequired,
};
// Internationalized strings are best defined once outside of the component's
// render method, unless they take arguments for value substition (such as a
// count for pluralization).
pageTitle = formatMessageAsString({ messageKey: 'UserStoriesPage/title' });
i18n = {
pageTitle: this.pageTitle,
feedbackSubject: formatMessageAsString({
messageKey: 'UserStoriesPage/feedback',
}),
feedbackTitle: formatMessageAsString({
messageKey: 'Shared/feedback-on-new-page',
title: this.pageTitle,
}),
};
render() {
const feedbackButtonProps = {
feedbackId: userStoriesFeedbackId,
subject: this.i18n.feedbackSubject,
title: this.i18n.feedbackTitle,
};
return (
{/* It is recommended to use LayoutPage to ensure a uniform look
* and (you guess it) layout for all of our React pages. */}
<LayoutPage className={getClassName()}>
{/* The PageHeader component is the recommended way of getting
* consistent layout of UI elements in the Header of a Page's
* content. This may include a feedback button as in this example
* as well as potentially a HelpButton or SavedViews select */}
<PageHeader title={this.i18n.pageTitle}>
<PageHeader.HeaderGroup position="left">
<SavedViewsSelect />
</PageHeader.HeaderGroup>
<PageHeader.HeaderGroup position="right">
<FeedbackButton {...feedbackButtonProps} />
</PageHeader.HeaderGroup>
</PageHeader>
{/* See below for comments on main content rendering logic */}
{this.renderView()}
</LayoutPage>
);
}
renderView() {
const {
changeViewModel,
viewModel,
schema,
scope,
isSavedView,
} = this.props;
// It is generally advisable to defer attempting to render any of the
// page's main content before the schema is available. Most of our
// UI is generated based on the Types and Attributes defined in the
// schema, so without it we generally can't show much of anything
// useful anyway, so we typically render a LoadingMask until it is
// available.
// The same can be said of the `viewModel` for pages utilizing
// saved views
if (!schema || !viewModel) {
return <LoadingMask />;
}
const userStoriesDataTableProps = {
changeDataTableModel: changeViewModel,
dataTableModel: viewModel,
isSavedView,
scope,
schema,
};
return (
<div className={getClassName({ descendantName: 'mainContent' })}>
<UserStoriesDataTable {...userStoriesDataTableProps} />
</div>
);
}
}
```
1. Registering the Page
- Import the `index.js` in the root of your page directory in `~/projects/churro/src/viewport/pageModules.js` and add it to the list of registered page modules.
- Note: Where you add your page in the list is only important if you are trying to add a new replacement for an existing page. In this case, it should be enough to make sure that your page is registered __above__ `LegacyPage`.
- Note: You may need to restart your Burro dev server after making this change.
1. If Applicable, turn on your feature toggle by logging into your environment as the "god mode" user. For TestN/UEShell this user will be `rallyadmin`. If you're developing against a local stack, then it will be `slmadmin`. Ask your nearest dev or QA for the password.
1. Navigate to your page in the application and view it in all it's glory!
<file_sep># abrockett.github.io
Web site
|
16fe5e0927851ffdf0f38fe6cd3ecbbc177f6a60
|
[
"Markdown"
] | 2 |
Markdown
|
abrockett/abrockett.github.io
|
bd9282f302cfc6930511cece3858049c98a88881
|
8b77d6e9125725371b140b4950386cce101d462e
|
refs/heads/master
|
<repo_name>jchasse/displaying-has-many-through-rails-lab-onl01-seng-ft-070620<file_sep>/app/views/appointments/show.html.erb
<h3>Patient: <%= link_to @appointment.patient_name, patient_path(@appointment.patient) %> </h3>
<h5>Age: <%= @appointment.patient.age %></h6>
<h3>Doctor: <%= link_to @appointment.doctor_name, doctor_path(@appointment.doctor) %> </h3>
<h5>Department: <%= @appointment.doctor.department %></h6>
<h3>Appt: <%= link_to @appointment.appointment_datetime.strftime("%B %d, %Y at %k:%M"), appointment_path(@appointment) %> </h3><file_sep>/app/views/patients/show.html.erb
<h3>Patient: <%= @patient.name %> </h3>
<h5>Age: <%= @patient.age %></h6>
Doctors:
<ul>
<% @patient.appointments.each do |appt| %>
<li> <%= link_to appt.doctor_name, doctor_path(appt.doctor_id) %> // <%= link_to appt.appointment_datetime.strftime("%B %d, %Y at %k:%M"), appointment_path(appt) %></li>
<%end%>
</ul><file_sep>/app/views/doctors/show.html.erb
<h3>Doctor: <%= @doctor.name %> </h3>
<h5>Department: <%= @doctor.department %></h6>
Patients:
<ul>
<% @doctor.appointments.each do |appt| %>
<li> <%= link_to appt.patient_name, patient_path(appt.patient_id) %> // <%= link_to appt.appointment_datetime.strftime("%B %d, %Y at %k:%M"), appointment_path(appt) %></li>
<%end%>
</ul>
|
d605a2559ab06a7eaf645b58cff8e3e5d612593d
|
[
"HTML+ERB"
] | 3 |
HTML+ERB
|
jchasse/displaying-has-many-through-rails-lab-onl01-seng-ft-070620
|
395401646fd36bde062af6711711e6a00674ee50
|
e6864719c25c5cd219045119a6e59220c962b624
|
refs/heads/master
|
<repo_name>lining1991/hello-vue<file_sep>/vue-shim.d.ts
// 告诉TypeScript *.vue后缀的文件可以交给vue模块来处理。
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}<file_sep>/src/router.js
import Vue from 'vue';
import Router from 'vue-router';
import Calendar from './views/calendar.vue';
import Done from './views/done.vue';
import List from './views/list.vue';
import Mine from './views/mine.vue';
import Detail from './views/detail.vue';
Vue.use(Router);
// name是有什么用呢
export default new Router({
// mode: 'history',
// base: process.env.BASE_URL,
routes: [
{
path: '/',
redirect: '/List'
},
{
path: '/list',
name: 'List',
component: List,
},
{
path: '/calendar',
name: 'Calendar',
component: Calendar,
},
{
path: '/done',
name: 'Done',
component: Done,
},
{
path: '/mine',
name: 'Mine',
component: Mine,
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
// 这个是异步的吗component: () => import(/* webpackChunkName: "about" */ './views/About.vue'),
},
{
path: '/detail',
name: 'Detail',
component: Detail
}
],
});
<file_sep>/src/views/component/learn.vue
<template>
<div>
<!-- 绑定class style -->
<!-- 绑定对象 -->
<div class="black" :class="{active: isActive}">这是一段语法</div>
<div :class="{active: isActive}">渲染出来的类名是active</div>
<div :class="{active: isActive, 'fs-bigger': fsBig}">渲染出来的类名是active fs-bigger</div>
<div :class="styleObj">渲染出来的类名是fs-bigger</div>
<!-- 对象语法常常结合对象的计算属性使用 -->
<div :class="classObject">结合计算属性使用</div>
<!-- 绑定数组 -->
<div :class="[activeClass, errorClass]">渲染出来的类名是active fs-bigger</div>
<div :class="[isActive ? 'active' : '', errorClass]">渲染出来的类名是active fs-bigger</div>
<div v-bind:class="[{ active: isActive }, errorClass]">p渲染出来的类名是active fs-bigger</div>
<!-- 用在组件上 class将被添加到该组件的根元素上面,且这个元素上已经存在的class不会被覆盖 -->
<!-- 绑定内联样式 css属性名可用驼峰或短横线分割,短横线分割的要用单引号括起来-->
<!-- 对象语法 -->
<div :style="{color: activeColor, fontSize: fontSize + 'px', 'background-color': 'red'}">新的咯</div>
<!-- 直接绑定到一个样式对象通常更好,这会让模板更清晰 -->
<div :style="styleObject">又一个新的咯</div>
<!-- 自动添加前缀:当 v-bind:style 使用需要添加浏览器引擎前缀的 CSS 属性时,如 transform,Vue.js 会自动侦测并添加相应的前缀。 -->
<!-- 多重值 从 2.3.0 起你可以为 style 绑定中的属性提供一个包含多个值的数组,常用于提供多个带前缀的值,例如:-->
<div :style="{ display: ['flex', '-webkit-box', '-ms-flexbox'] }">哈哈哈哈哈</div>
</div>
</template>
<script>
export default {
data () {
return {
isActive: true,
fsBig: true,
styleObj: {
active: false,
fsBig: true
},
activeClass: 'active',
errorClass: 'fs-bigger',
activeColor: 'yellow',
fontSize: 25,
styleObject: {
color: 'yellow',
'font-size': 25,
backgroundColor: 'blue'
},
error: true
}
},
beforeRouterUpdate (to, from, next) {
},
computed: {
classObject () {
return {
active: this.isActive && !this.error,
'text-danger': this.error
}
},
username () {
return this.$route.params.username;
}
},
methods: {
goBack () {
window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')
}
}
}
</script>
<style lang="scss">
.black {
color: #000;
}
.active {
color: #f04848;
}
.fs-bigger {
font-size: 24px;
}
</style>
<file_sep>/src/views/list.vue
<template>
<div class="main">
<top-input></top-input>
<filter-tab></filter-tab>
<list-item :list="true"></list-item>
</div>
</template>
<script>
import topInput from './component/input'
import filterTab from './component/filter-tab'
import listItem from './component/list-item'
export default {
components: {
topInput,
filterTab,
listItem
}
}
</script>
<style lang="scss" scoped>
.main {
padding: 10px 10px 0;
}
</style>
<file_sep>/src/store/state.js
import {playMode} from 'common/js/config'
const state = {
singer: {},
playing: false,
fullScree: false,
playlist: [],
sequenceList: [],
mode: playMode.sequence,
currentIndex: -1
}
export default state
// export let a = 3;
// let b = 3;
// export {b};
// let c = 4;
// export {c as d};
// export {d as default}
// import {a} from 'a.js';
// import {b as A} from 'a.js';
// import c; 注意如果什么都不加 会执行这个模块
<file_sep>/record.md
### npm的默认查找是js文件,现在用的ts文件 会报错找不到文件
配置resolve.extensions字段,然后还需要load来解析ts文件不然还是会有问题
### 还要安装vue-loader,这样webpack就能解析单文件组件了.这个组件做了那些事情呢
1. 允许其他webpack loaders在.vue文件中寻找各自的部分
2. Allows custom blocks in a .vue file that can have custom loader chains applied to them;
3. Treat static assets referenced in <style> and <template> as module dependencies and handle them with webpack loaders;
4. Simulate scoped CSS for each component;
5. State-preserving hot-reloading during development.
### 装完了vue-loader vue-template-compiler 提示You may need an additional loader to handle the result of these loaders.
所以呢还需要安装各处处理css js的loader
### 这中间踩了个大坑,已经爬出来了但还没太想明白
最开始的想法是用es6来写webpack配置文件,后来选用了一种方案就是直接把配置文件命名问webpack.config.xxx.js(eg:webpack.config.babel.js),这样webpack-dev-server会自动选用合适的loader来编译配置文件再输出给node去执行。但是运行后报错,提示只能输出Plugin/Preset files are not allowed to export objects, only functions. 所以按照网上的提示把配置给升级到了babel7,结果有提示需要7的版本,但是我的是6的版本。可是我的babel配置明明是7啊。不过我查看我的配置版本确实是6.我也不知道这是为啥,然后我就不用webpack.config.babel.js,正常写一个webpack.config.js,运行起来就没有问题。
### 报错vue-warn-cannot-find-element
new htmlWebpackPlugin({inject: ''}) 配错了 配置成head改为body
### 入口文件ts格式的引入scss又报错无法识别了
我原本以为是因为ts的问题,其实是我还没处理图片字体图标的laoder问题
### vue单文件组件中使用ts
我把这个awesome-typescript-loader换成ts-loader 并追加配置
另一种css的解决方案:[css-modules](https://juejin.im/post/59c62f8e6fb9a00a51439ad5)
https://juejin.im/post/5a7803335188257a5d2b0fed
- [] script支持ts
- [] css-modules
1. 点击箭头需要把写的信息添加到列表里边
2. 需要研究下vuex相关的列一下
### 有个很奇怪的事情,就是@babel-polyfill时,useage:entry 但是入口文件处并没有引入,也没有报错
最小化可执行方案,先把整体框架大概搞出来再完善具体细节
配置快捷路径:resolve:{ alias: {'src', Path.resolve(__dirname, './src')}};
下一步改做的是从列表页到详情页面的时候数据的传递,
需要给数据新增ID,可以用mock进行uuid
1023,
进入详情页的时候,做一个loading转场
还需要弄如果在详情页进行编辑,再回退的时候需要怎么处理
以及需要找一个日期插件
### mock出来的接口,get方式的话貌似不能带参数,不然会报错
<file_sep>/src/App.vue
<template>
<div class="page">
<div id="nav">
<router-link to="/list" class="tab">
<i class="iconfont icon-list-search"></i><br>列表
</router-link>
<router-link to="/done" class="tab">
<i class="iconfont icon-done"></i><br>已完成
</router-link>
<router-link to="/calendar" class="tab">
<i class="iconfont icon-calendar2"></i><br>日历
</router-link>
<router-link to="/mine" class="tab">
<i class="iconfont icon-me"></i><br>关于
</router-link>
</div>
<router-view/>
</div>
</template>
<script>
import axios from 'axios';
export default {
beforeMount () {
axios.get('/mock/list').then( res => {
this.$store.commit('init', {
data: res.data
});
});
}
}
</script>
<style lang="scss">
html, body {
margin: 0;
padding: 0;
background: #eee;
}
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
.page {
height: 100vh;
box-sizing: border-box;
padding-bottom: 50px;
}
#nav {
position: fixed;
bottom: 0;
width: 100%;
display: flex;
box-shadow: 0 0 5px 2px rgba(0,0,0,.1);
background: #fff;
.tab {
flex: 1;
text-align: center;
line-height: 24px;
}
a {
font-weight: bold;
color: #2c3e50;
text-decoration: none;
&.router-link-exact-active {
color: #42b983;
}
}
}
</style>
<file_sep>/src/views/detail.vue
<template>
<div class="main">
<div class="input-box">
<span class="label"><i class="iconfont icon-check"></i></span>
<input type="text" @focus="handleFocus" @input="handleInput" :placeholder="placeHolder" v-model="title">
<span class="go"> <i class="iconfont icon-delete"></i></span>
</div>
<div class="filter-tab">
<div class="left">
分类 <select name="" id="" class="select-tab"><option :value="category">{{category}}</option><option :value="category">{{category}}</option></select>
</div>
<div class="right">
日期 <select name="" id="" class="select-tab"><option :value="date">{{date}}</option></select>
</div>
</div>
<div class="bottom">
<textarea name="" id="" cols="30" rows="10" placeholder="请输入描述内容" v-model="content"></textarea>
</div>
</div>
</template>
<script>
// import topInput from './component/input'
// import filterTab from './component/filter-tab'
// import listItem from './component/list-item'
import axios from 'axios';
export default {
data () {
return {
placeHolder: '请输入描述内容',
content: '',
title: '',
category: '',
date: ''
}
},
// beforeRouteEnter (to, from, next) {
// // console.log(to, from, next);
// },
// 路由改变前,组件就已经渲染完了
// 逻辑稍稍不同
// beforeRouteUpdate (to, from, next) {
// console.log('beforeRouteUpdate', to, from, next);
// this.post = null
// getPost(to.params.id, (err, post) => {
// this.setData(err, post)
// next()
// })
// },
beforeRouteLeave () {
console.log('将要离开详情页面了');
console.log(this.content);
},
beforeDestory () {
alert('你将要离开吗');
console.log('组件将被销毁');
// 离开页面时 这个钩子并不会发生
},
created () {
this.fetchData();
},
methods: {
fetchData () {
let uid = this.$route.params.uid;
console.log('uid', uid);
axios.post('/mock/get_detail', {uid})
.then(response => {
let res = response.data;
let data = res.data;
if (res.error_code === 0) {
// let title, category, date, content;
// {title, category, date, content} = data;
// {this.title, this.category, this.date, this.content} = data;
// console.log('detail', res.data);
this.title = data.title;
this.content = data.content;
this.category = data.category;
this.date = data.date;
}
});
},
handleFocus () {
},
handleInput () {
}
}
}
</script>
<style lang="scss" scoped>
// todo需要弄一个日历的控件
@import 'src/css/input.scss';
.main {
padding: 10px 10px 0;
}
.filter-tab {
display: flex;
justify-content: space-between;
margin-bottom: 5px;
}
.select-tab {
background: #fff;
font-size: 16px;
border-radius: 2px;
outline: none;
border: none;
text-align: center;
text-align-last: center;
width: auto;
line-height: 1.4;
}
.bottom textarea {
padding: 5px;
display: block;
width: 100%;
box-sizing: border-box;
}
</style>
<file_sep>/src/views/done.vue
<template>
<div class="wrapper">
<list-item :status="true"></list-item>
</div>
</template>
<script>
import listItem from './component/list-item';
// vue组件的三种方式
// 箭头函数如果要返回一个对象需要在对象外部加圆括号 因为语句的开始也是以花括号开始的
export default {
components: {
listItem
},
data: () => ({
list: [{
status: 'done',
content: '吃饭',
date: '11月25日'
},{
status: 'done',
content: '喝水',
date: '11月26日'
}]
}),
mounted () {
// console.log(this.list);
}
// data: function () {
// return {
// list: [{
// status: 'done',
// content: '吃饭',
// date: '11月25日'
// },{
// status: 'done',
// content: '喝水',
// date: '11月26日'
// }]
// }
// }
}
</script>
<file_sep>/webpack.config.js
// import Path from 'path';
// import VueLoaderPlugin from 'vue-loader/lib/plugin';
// import autoprefixer from 'autoprefixer';
const Path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const autoprefixer = require('autoprefixer');
const htmlWebpackPlugin = require('html-webpack-plugin');
// VueLoaderPlugin负责拷贝你已经定义的其他rules,然后应用到.vue的各个相关block 比方说<script>
// const webpack
module.exports = {
mode: 'development',
devServer: {
host:'0.0.0.0',
// contentBase: Path.resolve(__dirname, './dist'),
// hot: true,
port: 8084,
after: function(app, server) {
console.log(`运行在哪个port*******`)
},
// https: true,
// disableHostCheck: true, //绕过主机检查不建议这样做,
// index: 'index.html',
// publicPath: '/assets/'
},
entry: {
app: './src/main.js'
},
output: {
filename: '[name].[hash:7].js',
path: Path.resolve(__dirname, 'dist')
},
resolve: {
extensions: ['.js', '.ts', '.tsx', '.vue', '.json'],
alias: {
'src': Path.resolve(__dirname, './src'),
'views': Path.resolve(__dirname, './views')
}
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/
// options: {
// appendTsSuffixTo: [/\.vue$/]
// }
},
{
test: /.vue$/,
loader: 'vue-loader'
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: [ autoprefixer({
remove: false,
browsers: ['last 10 versions']
}) ]
}
}
]
},
{
test: /\.scss$/,
use: [
'vue-style-loader',
'css-loader?sourceMap',
{
loader: 'postcss-loader',
options: {
plugins: [ autoprefixer({
remove: false,
browsers: ['last 10 versions']
}) ]
}
},
'sass-loader'
]
},
// 这个同webpack的source-map选项区别呢
{
enforce: 'pre',
test: /\.js$/,
loader: 'source-map-loader'
},
{
test: /\.(png|jpe?g|gif|svg)$/,
loader: 'url-loader',
query: {
limit: 10000,
name: 'assets/[name].[ext]'
}
},
{
test: /\.(ttf|woff2?|eot)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: 'assets/fonts/[name].[hash:7].[ext]'
}
}
]
},
plugins: [
new VueLoaderPlugin(),
new htmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html',
inject: 'body'
})
]
}<file_sep>/src/views/component/input.vue
<template>
<div class="input-box">
<span class="label" @click="isInput = !isInput"><i class="iconfont" :class="iconObj"></i></span>
<input type="text" @focus="handleFocus" @input="handleInput" @keyup.enter="addList" :placeholder="placeHolder" v-model="message" ref="inputBox">
<span class="go" @click="addList"> <i class="iconfont icon-arrow-r"></i></span>
</div>
</template>
<script>
// const PlaceHolder:string = '请输入'
import axios from 'axios';
export default {
data () {
return {
inputText: '',
placeHolder: '请输入待办事项...',
isInput: {
type: Boolean,
default: true
},
message: ''
}
},
computed: {
iconObj: function () {
// return this.isInput ? 'icon-plus' : 'icon-search';
return {
'icon-plus': this.isInput,
'icon-search': !this.isInput
}
}
},
methods: {
handleFocus () {
console.log('focus');
},
toggle () {
this.isInput = !this.isInput;
},
addList () {
let inputStr = this.$refs.inputBox.value;
// let s = [234, 12];
// let t = [...s, 34];
// console.log('hahah', this.$store);
if (inputStr.trim()) {
let ajaxData = {
title: inputStr,
isdone: false,
content: '',
category: 'default',
date: new Date()
};
axios.post('/mock/add', ajaxData).then(res => {
this.$store.commit('add', ajaxData);
this.$refs.inputBox.value = '';
});
} else {
// ui表示
alert('请输入代办事项');
}
// todo:添加的时间应该都是为今天可以写死,ps:这个地方需要调用接口后才这样执行
console.log('输入字符串', inputStr);
},
handleInput (e) {
console.log(e);
}
},
}
</script>
<style lang="scss" scoped>
@import 'src/css/input.scss';
</style>
<file_sep>/src/views/component/filter-tab.vue
<template>
<div class="filter-wrapper">
<span class="tab">全部</span>
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss">
.filter-wrapper {
margin-bottom: 10px;
.tab {
background: #fff;
font-size: 14px;
color: #333;
padding: 4px 6px;
border-radius: 5px;
}
}
</style>
<file_sep>/src/store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
console.log('vuexxxxxxxx');
export default new Vuex.Store({
state: {
list: [], // 首页列表数据
count: 0
},
mutations: {
add (state, payload) {
// let listObj = {
// title: payload,
// date: Random.date(),
// content: Random.cparagraph(),
// isdone: Random.boolean(),
// category: Random.category()
// }
state.list.unshift(payload);
},
done (state, payload) {
// ? 这样子的用for循环会不会更好些呢 可以break能省掉一些循环
state.list.forEach(item => {
if (item.uid === payload.uid) {
console.log('发生了done');
item.isdone = true;
}
});
},
init (state, payload) {
state.list.push(...payload.data);
},
increment (state, payload) {
state.count += payload.count;
}
},
actions: {
},
});
<file_sep>/src/views/component/list-item.vue
<template>
<div>
<!-- 绑定class style -->
<!-- 绑定对象 -->
<!-- <div class="black" :class="{active: isActive}">这是一段语法</div>
<div :class="{active: isActive}">渲染出来的类名是active</div>
<div :class="{active: isActive, 'fs-bigger': fsBig}">渲染出来的类名是active fs-bigger</div>
<div :class="styleObj">渲染出来的类名是fs-bigger</div> -->
<!-- 对象语法常常结合对象的计算属性使用 -->
<!-- <div :class="classObject">结合计算属性使用</div> -->
<!-- 绑定数组 -->
<!-- <div :class="[activeClass, errorClass]">渲染出来的类名是active fs-bigger</div>
<div :class="[isActive ? 'active' : '', errorClass]">渲染出来的类名是active fs-bigger</div>
<div v-bind:class="[{ active: isActive }, errorClass]">p渲染出来的类名是active fs-bigger</div> -->
<!-- 用在组件上 class将被添加到该组件的根元素上面,且这个元素上已经存在的class不会被覆盖 -->
<!-- 绑定内联样式 css属性名可用驼峰或短横线分割,短横线分割的要用单引号括起来-->
<!-- 对象语法 -->
<!-- <div :style="{color: activeColor, fontSize: fontSize + 'px', 'background-color': 'red'}">新的咯</div> -->
<!-- 直接绑定到一个样式对象通常更好,这会让模板更清晰 -->
<!-- <div :style="styleObject">又一个新的咯</div> -->
<!-- 自动添加前缀:当 v-bind:style 使用需要添加浏览器引擎前缀的 CSS 属性时,如 transform,Vue.js 会自动侦测并添加相应的前缀。 -->
<!-- 多重值 从 2.3.0 起你可以为 style 绑定中的属性提供一个包含多个值的数组,常用于提供多个带前缀的值,例如:-->
<!-- <div :style="{ display: ['flex', '-webkit-box', '-ms-flexbox'] }">哈哈哈哈哈</div> -->
<div class="item-wrapper">
<div class="item" v-for="item in userList" @click="goModify(item.uid)" :key="item.uid">
<i class="iconfont icon-check" @click.stop="done(item.uid)"></i>
<span class="text">{{item.title}}</span>
<span class="time">{{item.date | formatDate}}</span>
</div>
</div>
</div>
</template>
<script>
import {mapState} from 'vuex';
import axios from 'axios';
// https://vuex.vuejs.org/zh/guide/state.html
export default {
data () {
return {
// isActive: true,
// fsBig: true,
// styleObj: {
// active: false,
// fsBig: true
// },
// activeClass: 'active',
// errorClass: 'fs-bigger',
// activeColor: 'yellow',
// fontSize: 25,
// styleObject: {
// color: 'yellow',
// 'font-size': 25,
// backgroundColor: 'blue'
// },
// error: true
// list: [{
// title: '这是一条TODO记录',
// date: '今天'
// }, {
// title: '这是第二条记录',
// date: '昨天'
// }, {
// title: '这是第三天记录',
// date: '2019-2-1'
// }]
}
},
props: {
status: {
type: Boolean
}
},
computed: {
classObject () {
return {
active: this.isActive && !this.error,
'text-danger': this.error
}
},
userList () {
return this.list.filter((item) => {
return item.isdone === this.status;
})
},
...mapState([
'count',
'list'
])
},
created () {
},
mounted () {
console.log('abahah', this.list);
},
// computed: {
// count () {
// return this.$store.state.count;
// },
// list () {
// return this.$store.state.list;
// }
// }
// 换一种写法试试
// computed: {
// s () {},
// ...mapState([
// 'count',
// 'list'
// ])
// },
// computed: mapState([
// 'count',
// 'list'
// ]),
methods: {
done (uid) {
// ①这种写法 mock会报错
// axios.get('/mock/done', {
// params: {
// uid
// }
// })
// ②这种写法也报错
// axios.get(`/mock/done?uid=123`)
axios.post('/mock/done', {uid})
.then((res) => {
let data = res.data;
// vuex
if (data.error_code === 0) {
this.$store.commit('done', {uid});
}
})
.catch(error => {
console.log(error);
});
console.log('done');
},
goModify (uid) {
// 修改当前待办事项
console.log('modify', uid);
this.$router.push({name: 'Detail', params: {uid}});
}
}
}
</script>
<style lang="scss">
@import 'src/css/mixin.scss';
.black {
color: #000;
}
.active {
color: #f04848;
}
.fs-bigger {
font-size: 24px;
}
.item-wrapper {
background: #fff;
border-radius: 5px;
.item {
font-size: 12px;
color: #333;
padding: 5px;
display: flex;
align-items: center;
border-bottom: 1px solid #eee;
.iconfont {
margin-right: 5px;
font-size: 10px;
}
.text {
flex: 1;
@include ellipsis;
line-height: 20px;
height: 20px;
margin-right: 14px;
}
.time {
flex-basis: 10em;
text-align: right;
}
}
}
</style>
|
a7c5c79f412dbc9dae7f536bf78f877ea84148bc
|
[
"Markdown",
"TypeScript",
"JavaScript",
"Vue"
] | 14 |
Markdown
|
lining1991/hello-vue
|
c72ee22c3ad839ace475d2145c8d12ebcad42bf6
|
87b0314582b7e56ea4b7e996f6e31bd44baca31f
|
refs/heads/master
|
<file_sep>[package]
name = "windows-toolchain-builder"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
[dependencies]
archlinux-repo = "0.1.3"
futures = "0.3.5"
tokio = { version = "0.2.21", features = ["macros", "rt-threaded", "fs"] }
clap = "2.33.0"
indicatif = "0.15.0"
num_cpus = "1.13.0"
compress-tools = "0.6.0"
regex = "1.3.9"<file_sep>//! This module provides configuration from CLI arguments
use clap::{ArgMatches, App, Arg};
use crate::config::{IntoConfig, Config};
use std::str::FromStr;
use regex::Regex;
use std::path::PathBuf;
impl IntoConfig for ArgMatches<'static> {
fn to_config(&self) -> Config {
let cpu_count = num_cpus::get().to_string();
Config {
package: self.value_of("package").unwrap().to_string(),
repository: self.value_of("repository").unwrap().to_string(),
repository_name: self.value_of("repository-name").unwrap().to_string(),
architecture: self.value_of("architecture").unwrap().to_string(),
parallelism: u32::from_str(&self.value_of("parallelism").unwrap_or(&cpu_count).to_string()).unwrap(),
exclude: self.values_of("exclude").map(|v| v.map(|val| Regex::new(val).unwrap()).collect()).unwrap_or(Vec::new()),
include: self.values_of("include").map(|v| v.map(|val| Regex::new(val).unwrap()).collect()).unwrap_or(Vec::new()),
output_folder: PathBuf::from(self.value_of("output").unwrap())
}
}
}
fn args() -> Box<ArgMatches<'static>> {
Box::new(
App::new("windows-toolchain-builder")
.version(env!("CARGO_PKG_VERSION"))
.author("<NAME> <<EMAIL>>")
.arg(
Arg::with_name("package")
.index(1)
.help("Package name")
.required(true)
)
.arg(
Arg::with_name("repository")
.short("r")
.long("repository")
.value_name("REPOSITORY")
.help("Address to package repository")
.takes_value(true)
.default_value("http://repo.msys2.org/mingw")
)
.arg(
Arg::with_name("repository-name")
.short("n")
.long("reponame")
.value_name("REPOSITORY_NAME")
.help("Package repository name")
.takes_value(true)
.default_value("mingw64")
)
.arg(
Arg::with_name("output")
.short("o")
.long("output")
.value_name("OUTPUT")
.help("Output folder")
.takes_value(true)
.default_value("./")
)
.arg(
Arg::with_name("parallelism")
.short("p")
.value_name("PARALLELISM")
.help("Download/extract thread pool parallelism")
.takes_value(true)
)
.arg(
Arg::with_name("exclude")
.short("e")
.value_name("EXCLUDE")
.help("Exclude files or folders by regex")
.multiple(true)
.takes_value(true)
)
.arg(
Arg::with_name("include")
.short("i")
.value_name("INCLUDE")
.help("Include files or folders by regex. Only files which matches regex will be included. All files which matches include and exclude regex will *not* be included")
.multiple(true)
.takes_value(true)
)
.arg(
Arg::with_name("architecture")
.short("a")
.long("arch")
.value_name("ARCH")
.help("Package architecture")
.takes_value(true)
.default_value("x86_64")
.validator(|arch| {
if arch == "x86_64" || arch == "i686" {
return Ok(());
}
Err(String::from(format!("Unknown architecture: \"{}\"", arch)))
})
)
.get_matches()
)
}
/// Parse CLI arguments, deserialize them to configuration and return it.
/// Will panic when have illegal or insufficient arguments.
pub fn config() -> Config {
args().to_config()
}<file_sep>use regex::Regex;
use std::path::PathBuf;
pub mod clap;
/// Application configuration
#[derive(Clone, Debug)]
pub struct Config {
/// Package name which will be used as root to download all stuff
pub package: String,
/// Repository base URL (will be appended with architecture to get repo URL)
pub repository: String,
/// Repository name (required to download {}.db.tar.gz file)
pub repository_name: String,
/// Wanted architecture. Will be used with repository base URL to crete repo URL
pub architecture: String,
/// Download/extract parallel task count
pub parallelism: u32,
/// Match files/folders to exclude them from output
pub exclude: Vec<Regex>,
/// Match files/folders to include them into output. Have less priority than `exclude`. Will match
/// all packages if empty.
pub include: Vec<Regex>,
/// Output folder path. Will be created automatically with all parents, if not exist
pub output_folder: PathBuf,
}
impl Config {
pub fn repository_url(&self) -> String {
self.repository.clone() + "/" + &self.architecture
}
}
pub trait IntoConfig {
fn to_config(&self) -> Config;
}<file_sep>use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use std::sync::Arc;
use tokio::time::Duration;
use archlinux_repo::Package;
pub struct Progress {
progress: Arc<MultiProgress>
}
impl Progress {
pub fn new() -> Self {
let progress = Arc::new(MultiProgress::new());
let progress_exec = progress.clone();
std::thread::spawn(move || {
loop {
progress_exec.join().unwrap();
std::thread::sleep(Duration::from_millis(100));
}
});
Progress { progress }
}
pub fn repo(&self) -> RepoLoadProgress {
RepoLoadProgress {
progress: self.progress.clone(),
repo_load_progress: None
}
}
pub fn tree(&self) -> TreeBuildProgress {
TreeBuildProgress::new(self.progress.clone())
}
pub fn package_download(&self, name: &str) -> PackageDownloadProgress {
PackageDownloadProgress::new(self.progress.as_ref(), name)
}
pub fn package_extract(&self, name: &str) -> PackageExtractProgress {
PackageExtractProgress::new(self.progress.as_ref(), name)
}
}
pub struct PackageDownloadProgress {
progress: ProgressBar,
name: String
}
impl PackageDownloadProgress {
fn new(progress: &MultiProgress, package: &str) -> Self {
let bar = progress.add(ProgressBar::new(1));
bar.set_style(
ProgressStyle::default_spinner()
.template("{spinner:.green} Downloading {wide_msg}: [{elapsed_precise}] [{bar:80.cyan/blue}] {bytes}/{total_bytes} ({eta})")
.progress_chars("#>-")
);
bar.set_message(package);
PackageDownloadProgress { progress: bar, name: package.to_owned() }
}
pub fn chunk(&self, pos: u64, max: u64) {
self.progress.set_length(max);
self.progress.set_position(pos);
}
pub fn complete(self) {
let msg = format!("Package {} downloaded", &self.name);
self.progress.println(msg);
self.progress.finish_and_clear();
}
}
pub struct PackageExtractProgress {
progress: ProgressBar,
name: String
}
impl PackageExtractProgress {
fn new(progress: &MultiProgress, package: &str) -> Self {
let bar = progress.add(ProgressBar::new(1));
bar.set_style(
ProgressStyle::default_spinner()
.template("{spinner:.green} Extracting {wide_msg}: [{elapsed_precise}] [{bar:80.cyan/blue}] {pos}/{len} ({eta})")
.progress_chars("#>-")
);
bar.set_message(package);
PackageExtractProgress { progress: bar, name: package.to_owned() }
}
pub fn set_count(&self, count: usize) {
self.progress.set_length(count as u64);
}
pub fn file(&self, file: &str) {
self.progress.set_message(file);
self.progress.inc(1);
}
pub fn complete(self) {
let msg = format!("Package {} extracted", &self.name);
self.progress.println(msg);
self.progress.finish_and_clear();
}
}
pub struct RepoLoadProgress {
progress: Arc<MultiProgress>,
repo_load_progress: Option<ProgressBar>
}
impl RepoLoadProgress {
pub fn report(&mut self, progress: archlinux_repo::Progress) {
let multi_progress = self.progress.as_ref();
match progress {
archlinux_repo::Progress::LoadingDb => {}
archlinux_repo::Progress::LoadingFilesMetadata => {}
archlinux_repo::Progress::LoadingDbChunk(current, size) => {
let progress = self.repo_load_progress
.get_or_insert_with(|| {
let p = multi_progress.add(if let Some(max) = size {
ProgressBar::new(max)
} else {
ProgressBar::new_spinner()
});
p.set_style(
ProgressStyle::default_spinner()
.template("{spinner:.green} {wide_msg}: [{elapsed_precise}] [{bar:80.cyan/blue}] {bytes}/{total_bytes} ({eta})")
.progress_chars("#>-")
);
p.set_message("Loading repository");
p
});
progress.set_position(current);
if let Some(s) = size {
if s == current {
progress.println("Repository loaded");
progress.finish_and_clear();
self.repo_load_progress = None
}
}
}
archlinux_repo::Progress::ReadingDbFile(file) => {
let progress = self.repo_load_progress
.get_or_insert_with(|| {
let p = multi_progress.add(ProgressBar::new_spinner());
p.set_style(
ProgressStyle::default_spinner()
.template("{spinner:.green} {wide_msg}: [{bar:80.cyan/blue}]")
.progress_chars("#>-")
);
p
});
let msg = format!("Reading file {}", file);
progress.set_message(&msg);
}
archlinux_repo::Progress::ReadingDbDone => {
if let Some(progress) = self.repo_load_progress.as_ref() {
progress.println("Repository reading complete");
progress.finish_and_clear();
}
self.repo_load_progress = None
}
archlinux_repo::Progress::LoadingFilesMetadataChunk(current, size) => {
let progress = self.repo_load_progress
.get_or_insert_with(|| {
let p = multi_progress.add(if let Some(max) = size {
ProgressBar::new(max)
} else {
ProgressBar::new_spinner()
});
p.set_style(
ProgressStyle::default_spinner()
.template("{spinner:.green} {wide_msg}: [{elapsed_precise}] [{bar:80.cyan/blue}] {bytes}/{total_bytes} ({eta})")
.progress_chars("#>-")
);
p.set_message("Loading files metadata");
p
});
progress.set_length(current);
if let Some(s) = size {
if s == current {
progress.println("Files metadata loaded");
progress.finish_and_clear();
self.repo_load_progress = None
}
}
}
archlinux_repo::Progress::ReadingFilesMetadataFile(file) => {
let progress = self.repo_load_progress
.get_or_insert_with(|| {
let p = multi_progress.add(ProgressBar::new_spinner());
p.set_style(
ProgressStyle::default_spinner()
.template("{spinner:.green} {wide_msg}: [{bar:80.cyan/blue}]")
.progress_chars("#>-")
);
p
});
let msg = format!("Reading file {}", file);
progress.set_message(&msg);
}
archlinux_repo::Progress::ReadingFilesDone => {
if let Some(progress) = self.repo_load_progress.as_ref() {
progress.println("Repository files metadata reading complete");
progress.finish_and_clear();
}
self.repo_load_progress = None
}
}
}
}
pub struct TreeBuildProgress {
progress_bar: ProgressBar
}
impl TreeBuildProgress {
fn new(progress: Arc<MultiProgress>) -> Self {
let progress_bar = progress.add(ProgressBar::new_spinner());
progress_bar.set_style(
ProgressStyle::default_spinner()
.template("{spinner:.green} {wide_msg}: [{elapsed_precise}] [{bar:80.cyan/blue}]")
.progress_chars("#>-")
);
progress_bar.set_message("Building tree");
TreeBuildProgress { progress_bar }
}
pub fn index(&self, package: &Package) {
let msg = format!("Indexing {}", package.name);
self.progress_bar.set_message(&msg);
}
pub fn done(self) {
self.progress_bar.println("Tree built");
self.progress_bar.finish_and_clear();
}
}<file_sep>mod config;
mod progress;
use archlinux_repo::{RepositoryBuilder, Package, Repository};
use std::sync::RwLock;
use crate::progress::Progress;
use std::path::PathBuf;
use std::error::Error;
use tokio::fs::OpenOptions;
use futures::StreamExt;
use crate::config::Config;
use compress_tools::{list_archive_files, uncompress_archive_file};
use std::io::{Write, Cursor};
use std::fmt::{Display, Formatter};
#[derive(Clone, Debug, Eq, PartialEq)]
enum ProgramError {
PackageNotFound(String),
}
impl Display for ProgramError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ProgramError::PackageNotFound(name) => write!(f, "Package {} not found", name)
}
}
}
impl Error for ProgramError {}
struct Program {
config: Config,
progress: Progress,
output: PathBuf,
repository: Repository,
}
impl Program {
pub async fn new(config: Config) -> Result<Self, Box<dyn Error>> {
let progress = Progress::new();
let output = config.output_folder.clone();
tokio::fs::create_dir_all(&output).await?;
let repo_progress = RwLock::new(progress.repo());
let repository = RepositoryBuilder::new(&config.repository_name, &config.repository_url())
.progress_listener(Box::new(move |p| repo_progress.write().unwrap().report(p)))
.load()
.await?;
Ok(Program {
config,
output,
progress,
repository
})
}
pub async fn run(&self, package: &str) -> Result<(), Box<dyn Error>> {
let package = self.repository[package].to_owned();
let tree = self.build_package_tree(package)?;
let mut download_stream = futures::stream::iter(tree.iter().map(|package| self.process_package(package)))
.buffer_unordered(self.config.parallelism as usize);
loop {
let (result, stream) = download_stream.into_future().await;
download_stream = stream;
if result.is_none() {
break;
}
}
Ok(())
}
async fn process_package(&self, package: &Package) -> Result<(), Box<dyn Error>> {
let archive = self.download_package(&package).await?;
self.extract_package(archive, &package).await?;
Ok(())
}
async fn extract_package(&self, archive: Vec<u8>, package: &Package) -> Result<(), Box<dyn Error>> {
use tokio::io::AsyncWriteExt;
let progress = self.progress.package_extract(&package.name);
let files = list_archive_files(&archive[..])?;
progress.set_count(files.len());
for file in files.iter() {
progress.file(file);
if file.ends_with('/') || file.starts_with('.') {
continue;
}
if self.config.exclude.iter().any(|regex| regex.is_match(file)) {
continue;
}
if self.config.include.is_empty() || self.config.include.iter().any(|regex| regex.is_match(file)) {
let mut vec = Vec::<u8>::new();
let buf = Cursor::new(&mut vec);
uncompress_archive_file(&archive[..], buf, file)?;
let path = self.output.join(file);
tokio::fs::create_dir_all(path.parent().unwrap()).await?;
let mut fs_file = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&path).await?;
fs_file.write_all(&vec[..]).await?;
fs_file.flush().await?;
}
}
progress.complete();
Ok(())
}
async fn download_package(&self, package: &Package) -> Result<Vec<u8>, Box<dyn Error>> {
let progress = self.progress.package_download(&package.name);
let mut buf = Vec::new();
let mut response = self.repository.request_package(&package.name).await?;
let mut bytes_read: u64 = 0;
let length = response.content_length().unwrap();
while let Some(chunk) = response.chunk().await? {
buf.write_all(&chunk[..])?;
bytes_read += chunk.len() as u64;
progress.chunk(bytes_read, length);
}
progress.complete();
Ok(buf)
}
fn build_package_tree(&self, package: Package) -> Result<Vec<Package>, ProgramError> {
let progress = self.progress.tree();
let mut tree = Vec::<Package>::new();
tree.push(package);
loop {
let mut modified = false;
let mut patch = Vec::<Package>::new();
for item in tree.iter() {
progress.index(item);
if let Some(deps) = item.depends.as_ref() {
for dependency in deps {
let package = self.repository.get_package_by_name(&dependency.name)
.ok_or_else(|| ProgramError::PackageNotFound(dependency.name.clone()))?;
if !tree.contains(package) && !patch.contains(package) {
patch.push(package.to_owned());
modified = true;
}
}
}
}
tree.append(&mut patch);
if !modified {
break
}
}
progress.done();
Ok(tree)
}
}
#[tokio::main(core_threads = 8, max_threads = 16)]
async fn main() {
let config = config::clap::config();
let program = Program::new(config.clone()).await.unwrap();
program.run(&config.package).await.unwrap();
}
|
9a1e10725deb1f34be92ec1efdaf2c5b37369491
|
[
"Rust",
"TOML"
] | 5 |
Rust
|
alesharik/windows-toolchain-builder
|
a0c9b6b8a9d45c9cf05d4f56d79648993000b072
|
9df1be95805eef0b1cf448d5852623f98d815c3a
|
refs/heads/master
|
<repo_name>VirendraDeveloper/Dooooit<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/fragments/MapaFragment.java
package cl.activaresearch.android_app.Dooit.fragments;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.activities.FilterActivity;
import cl.activaresearch.android_app.Dooit.activities.HomeActivity;
import cl.activaresearch.android_app.Dooit.models.CategoryBean;
import cl.activaresearch.android_app.Dooit.models.TaskBean;
import cl.activaresearch.android_app.Dooit.recievers.LocationTrack;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiCallback;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiClient;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiHelper;
import cl.activaresearch.android_app.Dooit.utils.Constants;
import cl.activaresearch.android_app.Dooit.utils.FilePathManager;
import cl.activaresearch.android_app.Dooit.utils.SharedPreferenceUtility;
import static android.app.Activity.RESULT_OK;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 18 Jun,2018
*/
public class MapaFragment extends Fragment implements OnMapReadyCallback, View.OnClickListener {
private final int FILTER_CODE = 1022;
private Activity mContext;
private MapView mMapView;
private GoogleMap googleMap;
private ImageView ivFilter, ivGps;
private Location myLocation;
private int distance;
private String category;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mapa, container, false);
initUI(view);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(mContext);
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(this);
mMapView.onSaveInstanceState(savedInstanceState);
ivFilter.setOnClickListener(this);
ivGps.setOnClickListener(this);
getCategory();
return view;
}
private void getCategory() {
String cat = "[";
for (CategoryBean categoryBean : FilterActivity.categories) {
if (categoryBean.isSelect()) {
cat = cat + categoryBean.getId() + ",";
}
}
if (!cat.equalsIgnoreCase("[")) {
cat = cat.substring(0, cat.length() - 1);
}
cat = cat + "]";
category = cat;
distance = FilterActivity.distance;
}
private void initUI(View view) {
mMapView = (MapView) view.findViewById(R.id.mapView);
ivFilter = (ImageView) view.findViewById(R.id.iv_filter);
ivGps = (ImageView) view.findViewById(R.id.iv_gps);
}
@Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
myLocation = new LocationTrack(getActivity()).getLocation();
// latitude and longitude
if (myLocation != null) {
LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
// create marker
MarkerOptions marker = new MarkerOptions().position(latLng).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_dooit_marker));
// adding marker
googleMap.addMarker(marker);
zoomLocation(latLng);
}
}
private void zoomLocation(LatLng latLng) {
CameraPosition cameraPosition = new CameraPosition.Builder().target(
latLng).zoom(11).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
String token = SharedPreferenceUtility.getInstance(mContext).getString(Constants.TOKEN);
Location location = new LocationTrack(getActivity()).getLocation();
if (location != null) {
((HomeActivity) mContext).showProgress();
ApiHelper.getInstance().getAllTask(token, location.getLatitude() + "", location.getLongitude() + "", distance + "", category, new ApiCallback.TasksListener() {
@Override
public void onSuccess(List<TaskBean> taskBeans) {
for (TaskBean taskBean : taskBeans) {
if (googleMap != null) {
new LoadMarker().execute(taskBean);
addTaskMarker(taskBean);
}
}
((HomeActivity) mContext).dismissProgress();
}
@Override
public void onFailure(String error) {
((HomeActivity) mContext).dismissProgress();
// ((HomeActivity) mContext).showToast(error);
}
});
}
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_filter:
Intent intent = new Intent(mContext, FilterActivity.class);
startActivityForResult(intent, FILTER_CODE);
mContext.overridePendingTransition(R.anim.right_to_left, R.anim.left_to_right);
break;
case R.id.iv_gps:
Location location = new LocationTrack(getActivity()).getLocation();
// latitude and longitude
if (location != null) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
zoomLocation(latLng);
}
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FILTER_CODE) {
if (resultCode == RESULT_OK) {
distance = data.getIntExtra(Constants.DISTANCE, 0);
category = data.getStringExtra(Constants.CATEGORIES);
Log.d("", "");
}
}
}
private void addTaskMarker(TaskBean taskBean) {
LatLng latLng = new LatLng(Double.parseDouble(taskBean.getLat()), Double.parseDouble(taskBean.getLon()));
// create marker
MarkerOptions marker = new MarkerOptions().position(latLng).title(taskBean.getNombre()).snippet(taskBean.getCategoria());
// Changing marker icon
marker.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_dooit_marker));
// adding marker
googleMap.addMarker(marker);
}
private class LoadMarker extends AsyncTask<TaskBean, Void, TaskBean> {
@Override
protected TaskBean doInBackground(TaskBean... params) {
// Get bitmap from server
TaskBean taskBean;
Bitmap overlay;
try {
taskBean = params[0];
URL url = new URL(ApiClient.BASE_URL + taskBean.getIcono());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
overlay = BitmapFactory.decodeStream(input);
taskBean.setBitmap(overlay);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return taskBean;
}
@SuppressLint("ResourceType")
protected void onPostExecute(TaskBean taskBean) {
LatLng latLng = new LatLng(Double.parseDouble(taskBean.getLat()), Double.parseDouble(taskBean.getLon()));
// If received bitmap successfully, draw it on our drawable
if (taskBean.getBitmap() != null) {
View custom_layout = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker, null);
ImageView ivMarkerBg = (ImageView) custom_layout.findViewById(R.id.iv_marker_bg);
ImageView iv_category_logo = (ImageView) custom_layout.findViewById(R.id.iv_marker);
ivMarkerBg.setColorFilter(Color.parseColor(taskBean.getColor()));
//frameLayout.setBackgroundTintList(getResources().getColorStateList(Color.parseColor(taskBean.getColor())));
Bitmap pinbit = Bitmap.createScaledBitmap(taskBean.getBitmap(), 40, 60, false);
iv_category_logo.setImageBitmap(pinbit);
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(FilePathManager.getMarkerBitmapFromView(custom_layout));
// Add the new marker to the map
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("")
.snippet("")
.icon(bitmapDescriptor));
} else {
// Add the new marker to the map
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_marker)));
}
}
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/models/UserBean.java
package cl.activaresearch.android_app.Dooit.models;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 21 Jun,2018
*/
public class UserBean {
/**
* cod_shopper : 206593538
* fecha_inicio : 2018-06-20T13:10:20.000Z
* fecha_fin : null
* ip : null
* latitud : null
* longitud : null
* finaliza : null
* password : <PASSWORD>
* nombres : Hello
* apellidos : Okay
* email : <EMAIL>
* sexo : Female
* fecha_nac : 2018-06-21
* tel_fijo : null
* tel_movil : null
* pais : null
* region : 3
* comuna : 3201
* ciudad : null
* direccion : indore
* foto_perfil : https://firebasestorage.googleapis.com/v0/b/dooit-207809.appspot.com/o/images%2F1529547990_dooit.jpg?alt=media&token=<PASSWORD>
* cuenta_nom_titular : null
* cuenta_rut_titular : null
* cuenta_numero : null
* cuenta_banco : null
* cuenta_tipo : null
* nivel : null
* tipo_registro : login
* token : <KEY>DwHuDgDppp9L9UR4Kp3VsTHnnqIefvdH6QxAU77wPZsFbI2YjIzwMj<KEY>Doc<KEY>
* completed_profile : 0
* completed_additional : 0
* started_additional : 0
* regionAsString : Atacama
* cityAsString : Chañaral
*/
private String cod_shopper;
private String fecha_inicio;
private Object fecha_fin;
private Object ip;
private Object latitud;
private Object longitud;
private Object finaliza;
private String password;
private String nombres;
private String apellidos;
private String email;
private String sexo;
private String fecha_nac;
private Object tel_fijo;
private Object tel_movil;
private Object pais;
private int region;
private int comuna;
private Object ciudad;
private String direccion;
private String foto_perfil;
private Object cuenta_nom_titular;
private Object cuenta_rut_titular;
private Object cuenta_numero;
private Object cuenta_banco;
private Object cuenta_tipo;
private Object nivel;
private String tipo_registro;
private String token;
private int completed_profile;
private int completed_additional;
private int started_additional;
private String regionAsString;
private String cityAsString;
public String getCod_shopper() {
return cod_shopper;
}
public void setCod_shopper(String cod_shopper) {
this.cod_shopper = cod_shopper;
}
public String getFecha_inicio() {
return fecha_inicio;
}
public void setFecha_inicio(String fecha_inicio) {
this.fecha_inicio = fecha_inicio;
}
public Object getFecha_fin() {
return fecha_fin;
}
public void setFecha_fin(Object fecha_fin) {
this.fecha_fin = fecha_fin;
}
public Object getIp() {
return ip;
}
public void setIp(Object ip) {
this.ip = ip;
}
public Object getLatitud() {
return latitud;
}
public void setLatitud(Object latitud) {
this.latitud = latitud;
}
public Object getLongitud() {
return longitud;
}
public void setLongitud(Object longitud) {
this.longitud = longitud;
}
public Object getFinaliza() {
return finaliza;
}
public void setFinaliza(Object finaliza) {
this.finaliza = finaliza;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNombres() {
return nombres;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getFecha_nac() {
return fecha_nac;
}
public void setFecha_nac(String fecha_nac) {
this.fecha_nac = fecha_nac;
}
public Object getTel_fijo() {
return tel_fijo;
}
public void setTel_fijo(Object tel_fijo) {
this.tel_fijo = tel_fijo;
}
public Object getTel_movil() {
return tel_movil;
}
public void setTel_movil(Object tel_movil) {
this.tel_movil = tel_movil;
}
public Object getPais() {
return pais;
}
public void setPais(Object pais) {
this.pais = pais;
}
public int getRegion() {
return region;
}
public void setRegion(int region) {
this.region = region;
}
public int getComuna() {
return comuna;
}
public void setComuna(int comuna) {
this.comuna = comuna;
}
public Object getCiudad() {
return ciudad;
}
public void setCiudad(Object ciudad) {
this.ciudad = ciudad;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getFoto_perfil() {
return foto_perfil;
}
public void setFoto_perfil(String foto_perfil) {
this.foto_perfil = foto_perfil;
}
public Object getCuenta_nom_titular() {
return cuenta_nom_titular;
}
public void setCuenta_nom_titular(Object cuenta_nom_titular) {
this.cuenta_nom_titular = cuenta_nom_titular;
}
public Object getCuenta_rut_titular() {
return cuenta_rut_titular;
}
public void setCuenta_rut_titular(Object cuenta_rut_titular) {
this.cuenta_rut_titular = cuenta_rut_titular;
}
public Object getCuenta_numero() {
return cuenta_numero;
}
public void setCuenta_numero(Object cuenta_numero) {
this.cuenta_numero = cuenta_numero;
}
public Object getCuenta_banco() {
return cuenta_banco;
}
public void setCuenta_banco(Object cuenta_banco) {
this.cuenta_banco = cuenta_banco;
}
public Object getCuenta_tipo() {
return cuenta_tipo;
}
public void setCuenta_tipo(Object cuenta_tipo) {
this.cuenta_tipo = cuenta_tipo;
}
public Object getNivel() {
return nivel;
}
public void setNivel(Object nivel) {
this.nivel = nivel;
}
public String getTipo_registro() {
return tipo_registro;
}
public void setTipo_registro(String tipo_registro) {
this.tipo_registro = tipo_registro;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public int getCompleted_profile() {
return completed_profile;
}
public void setCompleted_profile(int completed_profile) {
this.completed_profile = completed_profile;
}
public int getCompleted_additional() {
return completed_additional;
}
public void setCompleted_additional(int completed_additional) {
this.completed_additional = completed_additional;
}
public int getStarted_additional() {
return started_additional;
}
public void setStarted_additional(int started_additional) {
this.started_additional = started_additional;
}
public String getRegionAsString() {
return regionAsString;
}
public void setRegionAsString(String regionAsString) {
this.regionAsString = regionAsString;
}
public String getCityAsString() {
return cityAsString;
}
public void setCityAsString(String cityAsString) {
this.cityAsString = cityAsString;
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/fragments/PreferenceFragment.java
package cl.activaresearch.android_app.Dooit.fragments;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.ToggleButton;
import com.google.gson.JsonObject;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.activities.HomeActivity;
import cl.activaresearch.android_app.Dooit.activities.PaymentConfigurationActivity;
import cl.activaresearch.android_app.Dooit.activities.SlideShowActivity;
import cl.activaresearch.android_app.Dooit.activities.WebActivity;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiCallback;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiHelper;
import cl.activaresearch.android_app.Dooit.utils.Constants;
import cl.activaresearch.android_app.Dooit.utils.SharedPreferenceUtility;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 16 Jun,2018
*/
public class PreferenceFragment extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private Activity mContext;
private RelativeLayout rlAbout, rlSignOff, rlConfiguration, rlShare, rlCommunity, rlFaq;
private ToggleButton tbNotification;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_preference, container, false);
// Inflate the layout for this fragment
initUI(view);
return view;
}
private void initUI(View view) {
rlSignOff = (RelativeLayout) view.findViewById(R.id.rl_sign_off);
rlConfiguration = (RelativeLayout) view.findViewById(R.id.rl_configuration);
rlAbout = (RelativeLayout) view.findViewById(R.id.rl_about);
rlFaq = (RelativeLayout) view.findViewById(R.id.rl_faq);
rlCommunity = (RelativeLayout) view.findViewById(R.id.rl_community);
rlShare = (RelativeLayout) view.findViewById(R.id.rl_share);
tbNotification = (ToggleButton) view.findViewById(R.id.tgb_notification);
boolean isChecked = SharedPreferenceUtility.getInstance(mContext).getBoolean(Constants.NOTIFICATION);
tbNotification.setChecked(isChecked);
rlAbout.setOnClickListener(this);
rlSignOff.setOnClickListener(this);
rlConfiguration.setOnClickListener(this);
rlShare.setOnClickListener(this);
rlCommunity.setOnClickListener(this);
rlFaq.setOnClickListener(this);
tbNotification.setOnCheckedChangeListener(this);
}
private Intent intent;
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.rl_configuration:
intent = new Intent(mContext, PaymentConfigurationActivity.class);
startActivity(intent);
mContext.overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
break;
case R.id.rl_sign_off:
signOutAlertDialog();
break;
case R.id.rl_about:
((HomeActivity) mContext).loadFragment(new AboutFragment());
break;
case R.id.rl_community:
intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"<EMAIL>"});
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Soporte App Dooit");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "Hi Dooit,");
intent.setType("message/rfc822");
startActivity(Intent.createChooser(intent, "Send email"));
break;
case R.id.rl_share:
String playStore = "https://play.google.com/store/apps/details?id=cl.activaresearch.android_app.Dooit";
intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Dooit (Open it in Google Play Store to Download the Application)");
intent.putExtra(android.content.Intent.EXTRA_TEXT, playStore);
startActivity(Intent.createChooser(intent, "Share via"));
break;
case R.id.rl_faq:
intent = new Intent(mContext, WebActivity.class);
startActivity(intent);
break;
}
}
private void signOutAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle(getString(R.string.sign_off));
// Setting Dialog Message
alertDialog.setMessage(getString(R.string.sign_off_msg));
// Setting Icon to Dialog
alertDialog.setIcon(R.mipmap.ic_pref_logout);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferenceUtility.getInstance(mContext).putBoolean(Constants.IS_LOGIN, false);
Intent intent = new Intent(mContext, SlideShowActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
mContext.finish();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferenceUtility.getInstance(mContext).putBoolean(Constants.NOTIFICATION, isChecked);
String token = SharedPreferenceUtility.getInstance(mContext).getString(Constants.TOKEN);
String android_id = Settings.Secure.getString(mContext.getContentResolver(),
Settings.Secure.ANDROID_ID);
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("identifier", android_id);
if (isChecked) {
jsonObject.addProperty("enabled", "1");
} else {
jsonObject.addProperty("enabled", "0");
}
ApiHelper.getInstance().toggleNotifications(token, jsonObject, new ApiCallback.Listener() {
@Override
public void onSuccess(String result) {
Log.d("", "");
}
@Override
public void onFailure(String error) {
Log.d("", "");
}
});
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/fragments/BankFragment.java
package cl.activaresearch.android_app.Dooit.fragments;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.activities.HomeActivity;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 13 Jun,2018
*/
public class BankFragment extends Fragment implements View.OnClickListener {
private Activity mContext;
private TextView tvBalanceTab, tvHistoryTab;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_bank, container, false);
// Inflate the layout for this fragment
initUI(view);
tvBalanceTab.setOnClickListener(this);
tvHistoryTab.setOnClickListener(this);
return view;
}
private void initUI(View view) {
tvBalanceTab = (TextView) view.findViewById(R.id.tv_balance_tab);
tvHistoryTab = (TextView) view.findViewById(R.id.tv_history_tab);
if (HomeActivity.TAB_NO == 0) {
tvBalanceTab.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.left_selected));
tvHistoryTab.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.right_un_selected));
tvBalanceTab.setTextColor(mContext.getResources().getColor(R.color.colorPrimaryDark));
tvHistoryTab.setTextColor(mContext.getResources().getColor(R.color.colorWhite));
loadFragment(new CurrentBalanceFragment());
} else {
tvBalanceTab.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.left_un_selected));
tvHistoryTab.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.right_selected));
tvHistoryTab.setTextColor(mContext.getResources().getColor(R.color.colorPrimaryDark));
tvBalanceTab.setTextColor(mContext.getResources().getColor(R.color.colorWhite));
loadFragment(new PaymentHistoryFragment());
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_history_tab:
tvBalanceTab.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.left_un_selected));
tvHistoryTab.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.right_selected));
tvHistoryTab.setTextColor(mContext.getResources().getColor(R.color.colorPrimaryDark));
tvBalanceTab.setTextColor(mContext.getResources().getColor(R.color.colorWhite));
loadFragment(new PaymentHistoryFragment());
break;
case R.id.tv_balance_tab:
tvBalanceTab.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.left_selected));
tvHistoryTab.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.right_un_selected));
tvBalanceTab.setTextColor(mContext.getResources().getColor(R.color.colorPrimaryDark));
tvHistoryTab.setTextColor(mContext.getResources().getColor(R.color.colorWhite));
loadFragment(new CurrentBalanceFragment());
break;
}
}
/**
* Loading fragment
*
* @param fragment
*/
private void loadFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.bank_container, fragment);
fragmentTransaction.commit();
}
}<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/activities/ForgotActivity.java
package cl.activaresearch.android_app.Dooit.activities;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONObject;
import java.util.HashMap;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.recievers.NetworkRecognizer;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiClient;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiInterface;
import cl.activaresearch.android_app.Dooit.utils.Validation;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 05 Jul,2018
*/
public class ForgotActivity extends BaseActivity implements View.OnClickListener {
private EditText edtEmail;
private TextView tvRecover;
private ImageView ivBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot);
edtEmail = (EditText) findViewById(R.id.edt_email);
ivBack = (ImageView) findViewById(R.id.iv_back);
ivBack.setOnClickListener(this);
tvRecover = (TextView) findViewById(R.id.tv_recover);
tvRecover.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_recover:
String strEmail = edtEmail.getText().toString().trim();
if (strEmail.equalsIgnoreCase("")) {
showToast(getString(R.string.emp_email));
} else if (!Validation.isEmailValid(strEmail)) {
showToast(getString(R.string.invalid_email));
} else if (!NetworkRecognizer.isNetworkAvailable(this)) {
showNetwork();
} else {
forgotProcess(strEmail);
//intent = new Intent(this, HomeActivity.class);
//startActivity(intent);
}
break;
case R.id.iv_back:
onBackPressed();
break;
}
}
private void forgotProcess(String strEmail) {
showProgress();
HashMap<String, String> body = new HashMap<>();
body.put("email", strEmail);
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiService.forgot(body);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
String body = response.body().string();
JSONObject jsonObject1 = new JSONObject(body);
String message = jsonObject1.getString("message");
boolean success = jsonObject1.getBoolean("success");
showToast(message);
dismissProgress();
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
dismissProgress();
Log.d("", "");
}
} else {
dismissProgress();
Log.d("", "");
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
dismissProgress();
Log.d("", "");
}
});
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/activities/InstructionsActivity.java
package cl.activaresearch.android_app.Dooit.activities;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.models.TaskBean;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiCallback;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiHelper;
import cl.activaresearch.android_app.Dooit.utils.Constants;
import cl.activaresearch.android_app.Dooit.utils.SharedPreferenceUtility;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 05 Jul,2018
*/
public class InstructionsActivity extends BaseActivity implements View.OnClickListener {
LinearLayout sliderDotspanel;
private TextView tvAccept, tvTitle, tvCancel;
private ViewPager mViewPager;
private String[] instructions = new String[3];
private TaskBean taskBean;
private String strToken;
private Intent intent;
private int dotscount;
private ImageView[] dots;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_instructions);
initUI();
InstructionAdapter mCustomPagerAdapter = new InstructionAdapter(instructions, this);
mViewPager.setAdapter(mCustomPagerAdapter);
dotscount = mCustomPagerAdapter.getCount();
dots = new ImageView[dotscount];
for (int i = 0; i < dotscount; i++) {
dots[i] = new ImageView(this);
if (i == 0) {
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.purple_circle));
} else {
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.gray_circle));
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.purple_circle));
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if (position == (instructions.length - 1)) {
tvAccept.setEnabled(true);
tvAccept.setTextColor(Color.WHITE);
}
for (int i = 0; i < dotscount; i++) {
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.gray_circle));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.purple_circle));
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void initUI() {
tvAccept = (TextView) findViewById(R.id.tv_accept);
tvTitle = (TextView) findViewById(R.id.tv_title);
tvCancel = (TextView) findViewById(R.id.tv_cancel);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
sliderDotspanel = (LinearLayout) findViewById(R.id.slider_dots);
taskBean = (TaskBean) getIntent().getSerializableExtra(Constants.TASK);
tvTitle.setText(taskBean.getNombre());
try {
if (taskBean.getStatus() > 1) {
tvAccept.setVisibility(View.GONE);
} else {
tvAccept.setVisibility(View.VISIBLE);
}
if (taskBean.getPaso1() != null & !taskBean.getPaso1().equalsIgnoreCase("")) {
instructions[0] = taskBean.getPaso1();
if (taskBean.getPaso2() != null & !taskBean.getPaso2().equalsIgnoreCase("")) {
instructions[1] = taskBean.getPaso2();
if (taskBean.getPaso3() != null & !taskBean.getPaso3().equalsIgnoreCase("")) {
instructions[2] = taskBean.getPaso3();
}
} else {
if (taskBean.getPaso3() != null & !taskBean.getPaso3().equalsIgnoreCase("")) {
instructions[1] = taskBean.getPaso3();
}
}
} else {
if (taskBean.getPaso2() != null & !taskBean.getPaso2().equalsIgnoreCase("")) {
instructions[0] = taskBean.getPaso2();
if (taskBean.getPaso3() != null & !taskBean.getPaso3().equalsIgnoreCase("")) {
instructions[1] = taskBean.getPaso3();
}
} else {
if (taskBean.getPaso3() != null & !taskBean.getPaso3().equalsIgnoreCase("")) {
instructions[0] = taskBean.getPaso3();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
tvCancel.setOnClickListener(this);
tvAccept.setOnClickListener(this);
strToken = SharedPreferenceUtility.getInstance(this).getString(Constants.TOKEN);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_cancel:
finish();
break;
case R.id.tv_accept:
showProgress();
ApiHelper.getInstance().claimForTask(strToken, taskBean.getCod_tarea() + "", new ApiCallback.Listener() {
@Override
public void onSuccess(String result) {
Log.d("", "");
finish();
dismissProgress();
}
@Override
public void onFailure(String error) {
Log.d("", "");
dismissProgress();
showToast(error);
}
});
break;
}
}
class InstructionAdapter extends PagerAdapter {
private Context mContext;
private LayoutInflater mLayoutInflater;
private String[] mResources;
public InstructionAdapter(String[] mResources, Context context) {
mContext = context;
this.mResources = mResources;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return mResources.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = mLayoutInflater.inflate(R.layout.instruction_item, container, false);
TextView tvInstruction = (TextView) itemView.findViewById(R.id.tv_instruction);
tvInstruction.setText(mResources[position]);
container.addView(itemView);
return itemView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/fragments/SurveyFragment.java
package cl.activaresearch.android_app.Dooit.fragments;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.Serializable;
import java.util.List;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.activities.HomeActivity;
import cl.activaresearch.android_app.Dooit.activities.questions.LocationActivity;
import cl.activaresearch.android_app.Dooit.activities.questions.MultiAlternativeActivity;
import cl.activaresearch.android_app.Dooit.activities.questions.MultiLineActivity;
import cl.activaresearch.android_app.Dooit.activities.questions.PhotoActivity;
import cl.activaresearch.android_app.Dooit.activities.questions.SimpleAlternativeActivity;
import cl.activaresearch.android_app.Dooit.activities.questions.SingleLineActivity;
import cl.activaresearch.android_app.Dooit.activities.questions.VideoActivity;
import cl.activaresearch.android_app.Dooit.adapter.SurveyAdapter;
import cl.activaresearch.android_app.Dooit.models.SurveyBean;
import cl.activaresearch.android_app.Dooit.models.TaskBean;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiCallback;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiHelper;
import cl.activaresearch.android_app.Dooit.utils.Constants;
import cl.activaresearch.android_app.Dooit.utils.SharedPreferenceUtility;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 05 Jul,2018
*/
public class SurveyFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener, HomeActivity.BackPressed {
private Activity mContext;
private ImageView ivBack;
private TextView tvTitle, tvFinish;
private ListView listView;
private SurveyAdapter mAdapter;
private String strToken;
private TaskBean taskBean;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_survey, container, false);
// Inflate the layout for this fragment
Bundle bundle = this.getArguments();
if (bundle != null) {
taskBean = (TaskBean) bundle.getSerializable(Constants.TASK);
}
initUI(view);
HomeActivity.setOnBackPressed(this);
return view;
}
private void initUI(View view) {
ivBack = (ImageView) view.findViewById(R.id.iv_back);
tvTitle = (TextView) view.findViewById(R.id.tv_title);
listView = (ListView) view.findViewById(R.id.lv_survey);
// FooterView when the list is smaller than the screen
final View footerView = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_layout, null, false);
tvFinish = (TextView) footerView.findViewById(R.id.tv_finish); // How you reference the textview in the footer
if(taskBean.getCod_tarea()==0){
tvFinish.setText(getResources().getString(R.string.finish_survey));
}else {
tvFinish.setText(getResources().getString(R.string.confirm_survey));
}
listView.addFooterView(footerView);
tvTitle.setText(taskBean.getNombre());
ivBack.setOnClickListener(this);
tvFinish.setOnClickListener(this);
mAdapter = new SurveyAdapter(mContext);
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(this);
strToken = SharedPreferenceUtility.getInstance(mContext).getString(Constants.TOKEN);
}
@Override
public void onResume() {
super.onResume();
((HomeActivity) mContext).showProgress();
if (taskBean.getCod_tarea() == 0) {
ApiHelper.getInstance().getTaskShopperSurvey(strToken, new ApiCallback.SurveyListener() {
@Override
public void onSuccess(List<SurveyBean> surveyBeans) {
mAdapter.addAllTask(surveyBeans);
boolean isComplete = true;
((HomeActivity) mContext).dismissProgress();
for (int i = 0; i < surveyBeans.size(); i++) {
SurveyBean surveyBean = surveyBeans.get(i);
if (!surveyBean.isAnswered()) {
isComplete = false;
}
}
if (isComplete) {
tvFinish.setEnabled(true);
tvFinish.setTextColor(mContext.getResources().getColor(R.color.colorWhite));
}
}
@Override
public void onFailure(String error) {
((HomeActivity) mContext).dismissProgress();
((HomeActivity) mContext).showToast(error);
}
});
} else {
ApiHelper.getInstance().getTaskSurvey(strToken, taskBean.getCod_tarea() + "", new ApiCallback.SurveyListener() {
@Override
public void onSuccess(List<SurveyBean> surveyBeans) {
mAdapter.addAllTask(surveyBeans);
boolean isComplete = true;
((HomeActivity) mContext).dismissProgress();
for (int i = 0; i < surveyBeans.size(); i++) {
SurveyBean surveyBean = surveyBeans.get(i);
if (!surveyBean.isAnswered()) {
isComplete = false;
}
}
if (isComplete) {
tvFinish.setEnabled(true);
tvFinish.setTextColor(mContext.getResources().getColor(R.color.colorWhite));
}
}
@Override
public void onFailure(String error) {
((HomeActivity) mContext).dismissProgress();
((HomeActivity) mContext).showToast(error);
}
});
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_back:
Fragment fragment = new TaskDetailFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(Constants.TASK, taskBean);
fragment.setArguments(bundle);
((HomeActivity) mContext).loadFragment(fragment);
break;
case R.id.tv_finish:
completeTaskDialog();
break;
}
}
private void completeTaskDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
//alertDialog.setTitle(getString(R.string.sure_finish));
// Setting Dialog Message
alertDialog.setMessage(getString(R.string.sure_finish));
// Setting Icon to Dialog
//alertDialog.setIcon(R.mipmap.ic_pref_logout);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton(getString(R.string.finish_survey), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String token = SharedPreferenceUtility.getInstance(mContext).getString(Constants.TOKEN);
ApiHelper.getInstance().completeTask(token, taskBean.getCod_tarea() + "", new ApiCallback.Listener() {
@Override
public void onSuccess(String result) {
Log.d("", "");
((HomeActivity) mContext).setMessageDescription(getString(R.string.about_finished));
((HomeActivity) mContext).setMessageTitle(getString(R.string.finished));
((HomeActivity) mContext).showMessageDialog();
((HomeActivity) mContext).setOnAcceptClick(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment fragment = new TaskDetailFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(Constants.TASK, taskBean);
fragment.setArguments(bundle);
((HomeActivity) mContext).loadFragment(fragment);
((HomeActivity) mContext).hideMessageDialog();
}
});
}
@Override
public void onFailure(String error) {
((HomeActivity) mContext).showToast(error);
Log.d("", "");
}
});
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SurveyBean surveyBean = (SurveyBean) mAdapter.getItem(position);
String title = (position + 1) + " / " + mAdapter.getCount();
Intent intent;
switch (surveyBean.getType()) {
case SingleLineText:
intent = new Intent(mContext, SingleLineActivity.class);
intent.putExtra(Constants.SURVEY, (Serializable) surveyBean);
intent.putExtra(Constants.TITLE, title);
startActivity(intent);
mContext.overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
break;
case MultiLineText:
intent = new Intent(mContext, MultiLineActivity.class);
intent.putExtra(Constants.SURVEY, surveyBean);
intent.putExtra(Constants.TITLE, title);
startActivity(intent);
mContext.overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
break;
case SimpleAlternative:
intent = new Intent(mContext, SimpleAlternativeActivity.class);
intent.putExtra(Constants.SURVEY, surveyBean);
intent.putExtra(Constants.TITLE, title);
startActivity(intent);
mContext.overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
break;
case MultiAlternative:
intent = new Intent(mContext, MultiAlternativeActivity.class);
intent.putExtra(Constants.SURVEY, surveyBean);
intent.putExtra(Constants.TITLE, title);
startActivity(intent);
mContext.overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
break;
case Image:
intent = new Intent(mContext, PhotoActivity.class);
intent.putExtra(Constants.SURVEY, surveyBean);
intent.putExtra(Constants.TITLE, title);
startActivity(intent);
mContext.overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
break;
case Video:
intent = new Intent(mContext, VideoActivity.class);
intent.putExtra(Constants.SURVEY, surveyBean);
intent.putExtra(Constants.TITLE, title);
startActivity(intent);
mContext.overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
break;
case Location:
intent = new Intent(mContext, LocationActivity.class);
intent.putExtra(Constants.SURVEY, surveyBean);
intent.putExtra(Constants.TITLE, title);
startActivity(intent);
mContext.overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
break;
}
}
@Override
public void onBackPress() {
Fragment fragment = new TaskDetailFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(Constants.TASK, taskBean);
fragment.setArguments(bundle);
((HomeActivity) mContext).loadFragment(fragment);
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/utils/Validation.java
package cl.activaresearch.android_app.Dooit.utils;
import android.content.Context;
import android.text.format.DateFormat;
import android.util.Log;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 25 Jul,2018
*/
public class Validation {
private static String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
public static boolean isEmailValid(String email) {
return email.matches(emailPattern);
}
public static boolean isMobileNumberValid(String strContact) {
if ((strContact.length() > 6) && (strContact.length() < 13)) {
return true;
} else {
return false;
}
}
public static String getMonthDate(String strDate) {
String dateDOB = "";
try {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
Date date = sdf1.parse(strDate);
SimpleDateFormat sdf2 = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
dateDOB = sdf2.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return dateDOB;
}
public static String getMonthDate(Date date) {
String myFormat = "dd MMMM yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
String strDate = sdf.format(date);
Log.d("", "");
return strDate;
}
public static String getDateFormat(Date date) {
String myFormat = "yyyy-MM-dd"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
String strDate = sdf.format(date);
Log.d("", "");
return strDate;
}
public static String getFormattedDate(Context context, String someDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(someDate);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar smsTime = Calendar.getInstance();
smsTime.setTimeInMillis(date.getTime());
Calendar now = Calendar.getInstance();
final String timeFormatString = "h:mm aa";
final String dateTimeFormatString = "dd-MMM-yyyy";
final long HOURS = 60 * 60 * 60;
if (now.get(Calendar.DATE) == smsTime.get(Calendar.DATE) ) {
return "Today "/* + DateFormat.format(timeFormatString, smsTime)*/;
} else if (now.get(Calendar.DATE) - smsTime.get(Calendar.DATE) == 1 ){
return "Yesterday "/* + DateFormat.format(timeFormatString, smsTime)*/;
} else if (now.get(Calendar.YEAR) == smsTime.get(Calendar.YEAR)) {
return DateFormat.format(dateTimeFormatString, smsTime).toString();
} else {
return DateFormat.format("MMMM dd yyyy, h:mm aa", smsTime).toString();
}
}
public static double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private static double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/fragments/ProfileFragment.java
package cl.activaresearch.android_app.Dooit.fragments;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.activities.HomeActivity;
import cl.activaresearch.android_app.Dooit.activities.PaymentConfigurationActivity;
import cl.activaresearch.android_app.Dooit.activities.ProfileActivity;
import cl.activaresearch.android_app.Dooit.models.UserBean;
import cl.activaresearch.android_app.Dooit.recievers.NetworkRecognizer;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiCallback;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiHelper;
import cl.activaresearch.android_app.Dooit.utils.Constants;
import cl.activaresearch.android_app.Dooit.utils.SharedPreferenceUtility;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 13 Jun,2018
*/
public class ProfileFragment extends Fragment implements View.OnClickListener {
private Activity mContext;
private TextView tvEdit, tvName, tvEmail, tvCity, tvAddress, tvSex, tvRegion, tvDob;
private CircleImageView ivProfile;
private LinearLayout llDOB, llSex, llAddress, llCity, llRegion;
private View view1, view2, view3, view4, view5;
private Intent intent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
// Inflate the layout for this fragment
tvEdit = (TextView) view.findViewById(R.id.tv_editor);
tvAddress = (TextView) view.findViewById(R.id.tv_address);
tvDob = (TextView) view.findViewById(R.id.tv_dob);
tvCity = (TextView) view.findViewById(R.id.tv_city);
tvSex = (TextView) view.findViewById(R.id.tv_sex);
tvRegion = (TextView) view.findViewById(R.id.tv_region);
tvEmail = (TextView) view.findViewById(R.id.tv_email);
tvName = (TextView) view.findViewById(R.id.tv_name);
llAddress = (LinearLayout) view.findViewById(R.id.ll_address);
llCity = (LinearLayout) view.findViewById(R.id.ll_city);
llDOB = (LinearLayout) view.findViewById(R.id.ll_dob);
llSex = (LinearLayout) view.findViewById(R.id.ll_sex);
llRegion = (LinearLayout) view.findViewById(R.id.ll_region);
ivProfile = (CircleImageView) view.findViewById(R.id.iv_profile);
view1 = (View) view.findViewById(R.id.view1);
view2 = (View) view.findViewById(R.id.view2);
view3 = (View) view.findViewById(R.id.view3);
view4 = (View) view.findViewById(R.id.view4);
view5 = (View) view.findViewById(R.id.view5);
tvEdit.setOnClickListener(this);
return view;
}
@Override
public void onResume() {
super.onResume();
if (NetworkRecognizer.isNetworkAvailable(mContext)) {
((HomeActivity) mContext).showProgress();
ApiHelper.getInstance().getUserProfileDetails(SharedPreferenceUtility.getInstance(mContext).getString(Constants.TOKEN), new ApiCallback.UserListener() {
@Override
public void onSuccess(UserBean userBean) {
updateDetails(userBean);
((HomeActivity) mContext).dismissProgress();
}
@Override
public void onFailure(String error) {
((HomeActivity) mContext).showToast(error);
((HomeActivity) mContext).dismissProgress();
}
});
} else {
((HomeActivity) mContext).showNetwork();
}
}
private void updateDetails(UserBean userBean) {
if (userBean.getSexo() != null) {
llSex.setVisibility(View.VISIBLE);
view2.setVisibility(View.VISIBLE);
tvSex.setText(userBean.getSexo());
} else {
llSex.setVisibility(View.GONE);
view2.setVisibility(View.GONE);
}
if (!SharedPreferenceUtility.getInstance(mContext).getBoolean(Constants.PROFILE_DLG)) {
((HomeActivity) mContext).setMessageTitleInfo("Hola, " + userBean.getNombres() + "@ a Dooit");
((HomeActivity) mContext).setMessageDescriptionInfo(getString(R.string.info_desc));
((HomeActivity) mContext).showInfo();
((HomeActivity) mContext).setOnAcceptInfoClick(new View.OnClickListener() {
@Override
public void onClick(View v) {
((HomeActivity) mContext).hideInfoDialog();
tvEdit.callOnClick();
SharedPreferenceUtility.getInstance(mContext).putBoolean(Constants.PROFILE_DLG, true);
}
});
} else {
if (!SharedPreferenceUtility.getInstance(mContext).getBoolean(Constants.COMPLETE_DLG)) {
((HomeActivity) mContext).setMessageTitleInfo(getString(R.string.info_title1));
((HomeActivity) mContext).setMessageDescriptionInfo(getString(R.string.info_desc1));
((HomeActivity) mContext).showInfo();
((HomeActivity) mContext).setOnAcceptInfoClick(new View.OnClickListener() {
@Override
public void onClick(View v) {
((HomeActivity) mContext).hideInfoDialog();
SharedPreferenceUtility.getInstance(mContext).putBoolean(Constants.COMPLETE_DLG, true);
intent = new Intent(mContext, PaymentConfigurationActivity.class);
startActivity(intent);
mContext.overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
}
});
} else {
if (!SharedPreferenceUtility.getInstance(mContext).getBoolean(Constants.PAYMENT_DLG)) {
((HomeActivity) mContext).setMessageTitleInfo(getString(R.string.info_title2));
((HomeActivity) mContext).setMessageDescriptionInfo(getString(R.string.info_desc2));
((HomeActivity) mContext).showInfo();
((HomeActivity) mContext).setOnAcceptInfoClick(new View.OnClickListener() {
@Override
public void onClick(View v) {
((HomeActivity) mContext).hideInfoDialog();
SharedPreferenceUtility.getInstance(mContext).putBoolean(Constants.PAYMENT_DLG, true);
((HomeActivity) mContext).onClickSeeker(null);
}
});
} else {
}
}
}
((HomeActivity) mContext).setMessageTitleInfo(getString(R.string.info_title2));
((HomeActivity) mContext).setMessageDescriptionInfo(getString(R.string.info_desc2));
((HomeActivity) mContext).showInfo();
((HomeActivity) mContext).setOnAcceptInfoClick(new View.OnClickListener() {
@Override
public void onClick(View v) {
((HomeActivity) mContext).hideInfoDialog();
SharedPreferenceUtility.getInstance(mContext).putBoolean(Constants.PAYMENT_DLG, true);
((HomeActivity) mContext).onClickSeeker(null);
}
});
if (userBean.getDireccion() != null && !userBean.getDireccion().equalsIgnoreCase("")) {
llAddress.setVisibility(View.VISIBLE);
view3.setVisibility(View.VISIBLE);
tvAddress.setText(userBean.getDireccion());
} else {
llAddress.setVisibility(View.GONE);
view3.setVisibility(View.GONE);
}
if (userBean.getFecha_nac() != null) {
try {
llDOB.setVisibility(View.VISIBLE);
view1.setVisibility(View.VISIBLE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(userBean.getFecha_nac());
SimpleDateFormat sdf2 = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
tvDob.setText(sdf2.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
} else {
llDOB.setVisibility(View.GONE);
view1.setVisibility(View.GONE);
}
if (userBean.getCityAsString() != null) {
view4.setVisibility(View.VISIBLE);
tvCity.setText(userBean.getCityAsString());
llCity.setVisibility(View.VISIBLE);
} else {
llCity.setVisibility(View.GONE);
view4.setVisibility(View.GONE);
}
if (userBean.getRegionAsString() != null) {
tvRegion.setText(userBean.getRegionAsString());
view5.setVisibility(View.VISIBLE);
llRegion.setVisibility(View.VISIBLE);
} else {
llRegion.setVisibility(View.GONE);
view5.setVisibility(View.GONE);
}
if (userBean.getFoto_perfil() != null) {
Glide.with(mContext)
.load(userBean.getFoto_perfil())
.into(ivProfile);
} else {
ivProfile.setImageResource(R.drawable.profile_bg);
}
tvName.setText(userBean.getNombres() + " " + userBean.getApellidos());
tvEmail.setText(userBean.getEmail());
}
@Override
public void onClick(View v) {
intent = new Intent(mContext, ProfileActivity.class);
startActivity(intent);
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/activities/questions/MultiLineActivity.java
package cl.activaresearch.android_app.Dooit.activities.questions;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.gson.JsonObject;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.activities.BaseActivity;
import cl.activaresearch.android_app.Dooit.models.SurveyBean;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiCallback;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiHelper;
import cl.activaresearch.android_app.Dooit.utils.Constants;
import cl.activaresearch.android_app.Dooit.utils.SharedPreferenceUtility;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 05 Jun,2018
*/
public class MultiLineActivity extends BaseActivity implements View.OnClickListener, TextWatcher {
private TextView tvTitle, tvQuestion, tvCancel, tvOk;
private SurveyBean surveyBean;
private EditText edtAnswer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multi_line);
tvTitle = (TextView) findViewById(R.id.tv_title);
tvCancel = (TextView) findViewById(R.id.tv_cancel);
tvQuestion = (TextView) findViewById(R.id.tv_question_name);
tvOk = (TextView) findViewById(R.id.tv_ok);
edtAnswer = (EditText) findViewById(R.id.edt_answer);
Intent intent = getIntent();
surveyBean = (SurveyBean) intent.getSerializableExtra(Constants.SURVEY);
edtAnswer.addTextChangedListener(this);
tvQuestion.setText(surveyBean.getQuestion());
tvCancel.setOnClickListener(this);
tvOk.setOnClickListener(this);
if (surveyBean != null) {
tvTitle.setText(intent.getStringExtra(Constants.TITLE));
tvQuestion.setText(surveyBean.getQuestion());
if (surveyBean.getAnswer() != null) {
edtAnswer.setText(surveyBean.getAnswer().getData());
edtAnswer.setSelection(surveyBean.getAnswer().getData().length());
}
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_cancel:
finish();
break;
case R.id.tv_ok:
String token = SharedPreferenceUtility.getInstance(this).getString(Constants.TOKEN);
String ans = edtAnswer.getText().toString().trim();
JsonObject body = new JsonObject();
body.addProperty("answer", ans);
showProgress();
ApiHelper.getInstance().ansSurveyQuestion(token, surveyBean.getTaskId(), surveyBean.getId(), body, new ApiCallback.Listener() {
@Override
public void onSuccess(String result) {
finish();
dismissProgress();
}
@Override
public void onFailure(String error) {
showToast(error);
dismissProgress();
}
});
break;
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String strAns = edtAnswer.getText().toString().trim();
if (!strAns.equalsIgnoreCase("")) {
tvOk.setEnabled(true);
tvOk.setTextColor(getResources().getColor(R.color.colorWhite));
} else {
tvOk.setEnabled(false);
tvOk.setTextColor(getResources().getColor(R.color.colorLight));
}
}
@Override
public void afterTextChanged(Editable s) {
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/servercommunication/ApiHelper.java
package cl.activaresearch.android_app.Dooit.servercommunication;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import cl.activaresearch.android_app.Dooit.models.AccountBean;
import cl.activaresearch.android_app.Dooit.models.BankBean;
import cl.activaresearch.android_app.Dooit.models.CategoryBean;
import cl.activaresearch.android_app.Dooit.models.PaymentBean;
import cl.activaresearch.android_app.Dooit.models.PaymentDetails;
import cl.activaresearch.android_app.Dooit.models.RegionBean;
import cl.activaresearch.android_app.Dooit.models.SurveyBean;
import cl.activaresearch.android_app.Dooit.models.TaskBean;
import cl.activaresearch.android_app.Dooit.models.TaskQuestionType;
import cl.activaresearch.android_app.Dooit.models.UserBean;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 21 Jun,2018
*/
public class ApiHelper {
private static ApiHelper helper;
private static List<RegionBean> regionBeans = new ArrayList<>();
private static List<CategoryBean> categories = new ArrayList<>();
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
public ApiHelper() {
}
public static ApiHelper getInstance() {
if (helper == null) {
helper = new ApiHelper();
}
return helper;
}
public void userLogin(HashMap<String, String> body, final ApiCallback.Listener callback) {
Call<ResponseBody> responseBodyCall = apiService.login(body);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
String body = response.body().string();
JSONObject jsonObject1 = new JSONObject(body);
String message = null;
if (jsonObject1.has("message")) {
message = jsonObject1.getString("message");
}
boolean success = false;
if (jsonObject1.has("success")) {
success = jsonObject1.getBoolean("success");
}
if (jsonObject1.has("error")) {
String error = jsonObject1.getString("error");
callback.onFailure(error);
}
if (success) {
String token = jsonObject1.getString("token");
callback.onSuccess(token);
} else {
callback.onFailure(message);
}
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void userFacebookLogin(HashMap<String, String> body, final ApiCallback.Listener callback) {
Call<ResponseBody> responseBodyCall = apiService.fbLogin(body);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
String body = response.body().string();
JSONObject jsonObject1 = new JSONObject(body);
boolean success = jsonObject1.getBoolean("success");
if (success) {
String id = jsonObject1.getString("identifier");
callback.onSuccess(id);
} else {
callback.onFailure("error");
}
/* boolean success = jsonObject1.getBoolean("success");
if (success) {
String strEmail = edtEmail.getText().toString().trim();
String strPassword = edtPassword.getText().toString().trim();
HashMap<String, String> body1 = new HashMap<>();
body1.put("email", strEmail);
body1.put("password", strPassword);
loginProcess(body1, b);
} else {
showToast(message);
dismissProgress();
}*/
} catch (Exception e) {
e.printStackTrace();
Log.d("", "");
callback.onFailure(e.getMessage());
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
callback.onFailure(e.getMessage());
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
callback.onFailure(t.getMessage());
t.printStackTrace();
Log.d("", "");
}
});
}
public void userForgotPassword(HashMap<String, String> body, final ApiCallback callback) {
}
public void userSignUp(final HashMap<String, String> bodys, final ApiCallback.Listener callback) {
Call<ResponseBody> responseBodyCall = apiService.register(bodys);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
String body = response.body().string();
JSONObject jsonObject1 = new JSONObject(body);
String message = jsonObject1.getString("message");
boolean success = jsonObject1.getBoolean("success");
if (success) {
userLogin(bodys, new ApiCallback.Listener() {
@Override
public void onSuccess(String result) {
callback.onSuccess(result);
}
@Override
public void onFailure(String error) {
callback.onFailure(error);
}
});
} else {
callback.onFailure(message);
}
} catch (Exception e) {
e.printStackTrace();
Log.d("", "");
callback.onFailure(e.getMessage());
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
callback.onFailure(t.getMessage());
t.printStackTrace();
Log.d("", "");
}
});
}
public void updateUserProfileDetails(HashMap<String, String> body, String token, final ApiCallback.Listener callback) {
Call<ResponseBody> responseBodyCall = apiService.update(token, body);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
String body = response.body().string();
JSONObject jsonObject1 = new JSONObject(body);
boolean success = jsonObject1.getBoolean("success");
if (success) {
callback.onSuccess(null);
} else {
callback.onFailure(null);
}
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void getUserProfileDetails(String token, final ApiCallback.UserListener callback) {
Call<UserBean> responseBodyCall = apiService.details(token);
responseBodyCall.enqueue(new Callback<UserBean>() {
@Override
public void onResponse(Call<UserBean> call, Response<UserBean> response) {
if (response.body() != null) {
try {
callback.onSuccess(response.body());
} catch (Exception e) {
callback.onFailure(e.getMessage());
e.printStackTrace();
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<UserBean> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void getRegionAndCity(String token, final ApiCallback.RegionsListener callback) {
if (regionBeans.size() > 0) {
callback.onSuccess(regionBeans);
return;
}
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<List<RegionBean>> responseBodyCall = apiService.city(token);
responseBodyCall.enqueue(new Callback<List<RegionBean>>() {
@Override
public void onResponse(Call<List<RegionBean>> call, Response<List<RegionBean>> response) {
if (response.body() != null) {
try {
regionBeans.clear();
regionBeans.addAll(response.body());
callback.onSuccess(regionBeans);
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<List<RegionBean>> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void getAllCategory(String token, final ApiCallback.CategoryListener callback) {
if (categories.size() > 0) {
callback.onSuccess(categories);
return;
}
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<List<CategoryBean>> responseBodyCall = apiService.category(token);
responseBodyCall.enqueue(new Callback<List<CategoryBean>>() {
@Override
public void onResponse(Call<List<CategoryBean>> call, Response<List<CategoryBean>> response) {
if (response.body() != null) {
try {
categories.clear();
categories.addAll(response.body());
callback.onSuccess(categories);
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<List<CategoryBean>> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void getAllTask(String token, String lat, String lng, String distance, String categories, final ApiCallback.TasksListener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<List<TaskBean>> responseBodyCall = apiService.geo(token, lat, lng, distance, categories);
responseBodyCall.enqueue(new Callback<List<TaskBean>>() {
@Override
public void onResponse(Call<List<TaskBean>> call, Response<List<TaskBean>> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
List<TaskBean> list = response.body();
callback.onSuccess(list);
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<List<TaskBean>> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void getTaskDetails(String token, String taskId, final ApiCallback.TaskListener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<TaskBean> responseBodyCall = apiService.taskDetails(token, taskId);
responseBodyCall.enqueue(new Callback<TaskBean>() {
@Override
public void onResponse(Call<TaskBean> call, Response<TaskBean> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
callback.onSuccess(response.body());
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<TaskBean> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void getCurrentTask(String token, final ApiCallback.TasksListener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<List<TaskBean>> responseBodyCall = apiService.currentTask(token);
responseBodyCall.enqueue(new Callback<List<TaskBean>>() {
@Override
public void onResponse(Call<List<TaskBean>> call, Response<List<TaskBean>> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
callback.onSuccess(response.body());
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<List<TaskBean>> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void getPreviousTask(String token, final ApiCallback.TasksListener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<List<TaskBean>> responseBodyCall = apiService.previousTask(token);
responseBodyCall.enqueue(new Callback<List<TaskBean>>() {
@Override
public void onResponse(Call<List<TaskBean>> call, Response<List<TaskBean>> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
callback.onSuccess(response.body());
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<List<TaskBean>> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void getTaskSurvey(String token, String id, final ApiCallback.SurveyListener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiService.questions(token, id);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
String body = response.body().string();
JSONArray jsonArray = new JSONArray(body);
List<SurveyBean> surveyBeans = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
SurveyBean surveyBean = new SurveyBean();
JSONObject jsonObject = jsonArray.getJSONObject(i);
String question = jsonObject.getString("question");
int type = jsonObject.getInt("type");
String cat = jsonObject.getString("cat");
String id = jsonObject.getString("id");
String studyId = jsonObject.getString("studyId");
String questionnaireId = jsonObject.getString("questionnaireId");
String taskId = jsonObject.getString("taskId");
surveyBean.setType(TaskQuestionType.valueOf(type));
surveyBean.setQuestion(question);
surveyBean.setCat(cat);
surveyBean.setId(id);
surveyBean.setStudyId(studyId);
surveyBean.setQuestionnaireId(questionnaireId);
surveyBean.setTaskId(taskId);
//check alternatives there or not
if (jsonObject.has("alternatives")) {
JSONArray alternatives = jsonObject.getJSONArray("alternatives");
List<SurveyBean.AlternativesBean> alternativesBeans = new ArrayList<>();
for (int j = 0; j < alternatives.length(); j++) {
SurveyBean.AlternativesBean bean = new SurveyBean.AlternativesBean();
JSONObject jsonObject1 = alternatives.getJSONObject(j);
String text = jsonObject1.getString("text");
int id1 = jsonObject1.getInt("id");
String cod = jsonObject1.getString("cod");
bean.setAnswered(false);
bean.setCod(cod);
bean.setId(id1);
bean.setText(text);
alternativesBeans.add(bean);
}
surveyBean.setAlternatives(alternativesBeans);
}
//check answer is there or not
if (jsonObject.has("answer")) {
surveyBean.setAnswered(true);
JSONObject answer = jsonObject.getJSONObject("answer");
String date = answer.getString("date");
SurveyBean.AnswerBean answerBean = new SurveyBean.AnswerBean();
answerBean.setDate(date);
switch (type) {
case 1:
String data = answer.getString("data");
answerBean.setDataBean(data);
break;
case 2:
String data1 = answer.getString("data");
answerBean.setDataBean(data1);
break;
case 3:
JSONObject data3 = answer.getJSONObject("data");
List<Integer> dataBean = new ArrayList<>();
int alternative = data3.getInt("alternative");
dataBean.add(alternative);
answerBean.setDataBean(dataBean);
break;
case 4:
JSONArray data4 = answer.getJSONArray("data");
List<Integer> dataBean1 = new ArrayList<>();
for (int j = 0; j < data4.length(); j++) {
JSONObject object = data4.getJSONObject(j);
int alternative1 = object.getInt("alternative");
dataBean1.add(alternative1);
}
answerBean.setDataBean(dataBean1);
break;
case 5:
String data5 = answer.getString("data");
answerBean.setDataBean(data5);
break;
case 6:
String data6 = answer.getString("data");
answerBean.setDataBean(data6);
break;
case 7:
String data7 = answer.getString("data");
answerBean.setDataBean(data7);
break;
}
surveyBean.setAnswer(answerBean);
} else {
surveyBean.setAnswered(false);
}
surveyBeans.add(surveyBean);
}
callback.onSuccess(surveyBeans);
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void getTaskShopperSurvey(String token, final ApiCallback.SurveyListener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiService.shopperQuestions(token);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
String body = response.body().string();
JSONArray jsonArray = new JSONArray(body);
List<SurveyBean> surveyBeans = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
SurveyBean surveyBean = new SurveyBean();
JSONObject jsonObject = jsonArray.getJSONObject(i);
String question = jsonObject.getString("question");
String id = jsonObject.getString("id");
surveyBean.setId(id);
surveyBean.setType(TaskQuestionType.valueOf(3));
surveyBean.setQuestion(question); //check alternatives there or not
if (jsonObject.has("alternatives")) {
JSONArray alternatives = jsonObject.getJSONArray("alternatives");
List<SurveyBean.AlternativesBean> alternativesBeans = new ArrayList<>();
for (int j = 0; j < alternatives.length(); j++) {
SurveyBean.AlternativesBean bean = new SurveyBean.AlternativesBean();
JSONObject jsonObject1 = alternatives.getJSONObject(j);
String text = jsonObject1.getString("text");
int id1 = jsonObject1.getInt("id");
boolean checked = jsonObject1.getBoolean("checked");
if (checked) {
surveyBean.setAnswered(checked);
}
bean.setId(id1);
bean.setText(text);
bean.setAnswered(checked);
alternativesBeans.add(bean);
}
surveyBean.setAlternatives(alternativesBeans);
}
surveyBeans.add(surveyBean);
}
callback.onSuccess(surveyBeans);
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void ansShopperSurveyQuestion(String token, String qid, JsonObject body, final ApiCallback.Listener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiService.shopperAnswer(token, qid, body);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
String body = response.body().string();
JSONObject jsonObject = new JSONObject(body);
boolean success = jsonObject.getBoolean("success");
if (success) {
String message = jsonObject.getString("message");
callback.onSuccess(message);
} else {
String error = jsonObject.getString("error");
callback.onFailure(error);
}
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void ansSurveyQuestion(String token, String id, String qid, JsonObject body, final ApiCallback.Listener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiService.answer(token, id, qid, body);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
String body = response.body().string();
JSONObject jsonObject = new JSONObject(body);
boolean success = jsonObject.getBoolean("success");
if (success) {
String message = jsonObject.getString("message");
callback.onSuccess(message);
} else {
String error = jsonObject.getString("error");
callback.onFailure(error);
}
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void getBalance(String token, final ApiCallback.Listener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiService.currentBalance(token);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
String body = response.body().string();
JSONObject jsonObject = new JSONObject(body);
callback.onSuccess(jsonObject.getString("balance"));
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void claimForTask(String token, String id, final ApiCallback.Listener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiService.taskClaim(token, id);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
String body = response.body().string();
JSONObject jsonObject = new JSONObject(body);
callback.onSuccess("Claim successfully");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void completeTask(String token, String id, final ApiCallback.Listener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiService.complete(token, id);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
String body = response.body().string();
JSONObject jsonObject = new JSONObject(body);
boolean success = jsonObject.getBoolean("success");
if (success) {
callback.onSuccess(null);
} else {
callback.onFailure(null);
}
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void getPaymentHistory(String token, final ApiCallback.PaymentListener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiService.payHistory(token);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
String body = response.body().string();
JSONObject jsonObject = new JSONObject(body);
List<PaymentBean> paymentBeans = new ArrayList<>();
JSONArray pending = jsonObject.getJSONArray("pending");
for (int i = 0; i < pending.length(); i++) {
JSONObject jsonObject1 = pending.getJSONObject(i);
PaymentBean paymentBean = new Gson().fromJson(jsonObject1.toString(), PaymentBean.class);
paymentBeans.add(paymentBean);
}
JSONArray paid = jsonObject.getJSONArray("paid");
JSONArray rejected = jsonObject.getJSONArray("rejected");
callback.onSuccess(paymentBeans);
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void paymentDetails(String token, String id, final ApiCallback.PaymentDetailsListener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<PaymentDetails> responseBodyCall = apiService.payDetails(token, id);
responseBodyCall.enqueue(new Callback<PaymentDetails>() {
@Override
public void onResponse(Call<PaymentDetails> call, Response<PaymentDetails> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
callback.onSuccess(response.body());
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<PaymentDetails> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void registerDevice(String token, JsonObject body, final ApiCallback.Listener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiService.register(token, body);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
String body = response.body().string();
JSONObject jsonObject = new JSONObject(body);
boolean success = jsonObject.getBoolean("success");
String message = jsonObject.getString("message");
if (success) {
callback.onSuccess(message);
} else {
callback.onFailure(message);
}
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void toggleNotifications(String token, JsonObject body, final ApiCallback.Listener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiService.toggle(token, body);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
String body = response.body().string();
JSONObject jsonObject = new JSONObject(body);
boolean success = jsonObject.getBoolean("success");
if (success) {
String message = jsonObject.getString("message");
callback.onSuccess(message);
} else {
callback.onFailure("");
}
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void withdrawFund(String token, final ApiCallback.Listener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiService.cashout(token);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
String body = response.body().string();
JSONObject jsonObject = new JSONObject(body);
boolean success = jsonObject.getBoolean("success");
if (success) {
callback.onSuccess(null);
} else {
String error = jsonObject.getString("error");
callback.onFailure(error);
}
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
private static List<BankBean> banks = new ArrayList<>();
public void getBanks(String token, final ApiCallback.BanksListener callback) {
if (banks.size() > 0) {
callback.onSuccess(banks);
return;
}
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<List<BankBean>> responseBodyCall = apiService.banks(token);
responseBodyCall.enqueue(new Callback<List<BankBean>>() {
@Override
public void onResponse(Call<List<BankBean>> call, Response<List<BankBean>> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
callback.onSuccess(response.body());
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<List<BankBean>> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void getBankAccount(String token, final ApiCallback.AccountListener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<AccountBean> responseBodyCall = apiService.account(token);
responseBodyCall.enqueue(new Callback<AccountBean>() {
@Override
public void onResponse(Call<AccountBean> call, Response<AccountBean> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
callback.onSuccess(response.body());
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<AccountBean> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
public void setBankAccount(String token, JsonObject jsonObject, final ApiCallback.Listener callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiService.addAccount(token, jsonObject);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body() != null) {
try {
Log.d("", response.body() + "");
JSONObject jsonObject = new JSONObject(response.body().string());
boolean success = jsonObject.getBoolean("success");
if (success) {
callback.onSuccess("");
} else {
String message = jsonObject.getString("message");
callback.onFailure(message);
}
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
Log.d("", "");
}
} else {
try {
String body = response.errorBody().string();
JSONObject jsonObject = new JSONObject(body);
String message = jsonObject.getString("message");
callback.onFailure(message);
Log.d("", "");
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
callback.onFailure(t.getMessage());
Log.d("", "");
}
});
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/activities/PaymentConfigurationActivity.java
package cl.activaresearch.android_app.Dooit.activities;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.NumberPicker;
import android.widget.TextView;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.models.AccountBean;
import cl.activaresearch.android_app.Dooit.models.BankBean;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiCallback;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiHelper;
import cl.activaresearch.android_app.Dooit.utils.Constants;
import cl.activaresearch.android_app.Dooit.utils.SharedPreferenceUtility;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 05 Jul,2018
*/
public class PaymentConfigurationActivity extends BaseActivity implements TextWatcher, View.OnClickListener {
private EditText edtAccNumber, edtName, edtRUT;
private TextView tvAccType, tvCancel, tvBank, tvOk;
private String strAccNumber, strAccType, strRUT, strName, strBank;
private String TAG = PaymentConfigurationActivity.class.getName();
private String token;
private List<BankBean> banks = new ArrayList<>();
private int position;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_configuration);
initUI();
token = SharedPreferenceUtility.getInstance(this).getString(Constants.TOKEN);
showProgress();
ApiHelper.getInstance().getBanks(token, new ApiCallback.BanksListener() {
@Override
public void onSuccess(List<BankBean> result) {
banks = result;
ApiHelper.getInstance().getBankAccount(token, new ApiCallback.AccountListener() {
@Override
public void onSuccess(AccountBean account) {
edtAccNumber.setText(account.getAccountNumber());
edtName.setText(account.getAccountHolderName());
edtRUT.setText(account.getAccountHolderRUT());
tvAccType.setText(account.getAccountType());
tvAccType.setTextColor(getResources().getColor(R.color.colorBlack));
for (BankBean bank : banks) {
if (bank.getId() == account.getAccountBank()) {
tvBank.setText(bank.getName());
tvBank.setTextColor(getResources().getColor(R.color.colorBlack));
break;
}
}
dismissProgress();
}
@Override
public void onFailure(String error) {
Log.d(TAG, error);
dismissProgress();
showToast(error);
}
});
}
@Override
public void onFailure(String error) {
dismissProgress();
Log.d(TAG, error);
showToast(error);
}
});
}
private void dialogAccountTypePicker(final String[] arrayString) {
final NumberPicker picker = new NumberPicker(this);
picker.setMinValue(0);
picker.setMaxValue(arrayString.length - 1);
picker.setDisplayedValues(arrayString);
FrameLayout layout = new FrameLayout(this);
layout.addView(picker, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT,
Gravity.CENTER));
new AlertDialog.Builder(this)
.setView(layout)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int position = picker.getValue();
tvAccType.setText(arrayString[position] + "");
tvAccType.setTextColor(getResources().getColor(R.color.colorBlack));
isOkEnable();
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
private void dialogBankPicker(final String[] arrayString) {
final NumberPicker picker = new NumberPicker(this);
picker.setMinValue(0);
picker.setMaxValue(arrayString.length - 1);
picker.setDisplayedValues(arrayString);
FrameLayout layout = new FrameLayout(this);
layout.addView(picker, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT,
Gravity.CENTER));
new AlertDialog.Builder(this)
.setView(layout)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
position = picker.getValue();
tvBank.setText(arrayString[position] + "");
tvBank.setTextColor(getResources().getColor(R.color.colorBlack));
isOkEnable();
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
private void initUI() {
edtAccNumber = (EditText) findViewById(R.id.edt_acc_number);
tvAccType = (TextView) findViewById(R.id.tv_acc_type);
edtName = (EditText) findViewById(R.id.edt_acc_name);
tvBank = (TextView) findViewById(R.id.tv_bank);
edtRUT = (EditText) findViewById(R.id.edt_rut);
tvOk = (TextView) findViewById(R.id.tv_ok);
tvCancel = (TextView) findViewById(R.id.tv_cancel);
edtAccNumber.addTextChangedListener(this);
tvAccType.setOnClickListener(this);
edtName.addTextChangedListener(this);
edtRUT.addTextChangedListener(this);
tvCancel.setOnClickListener(this);
tvBank.setOnClickListener(this);
tvOk.setOnClickListener(this);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
isOkEnable();
}
private void isOkEnable() {
strAccType = tvAccType.getText().toString().trim();
strRUT = edtRUT.getText().toString().trim();
strBank = tvBank.getText().toString().trim();
strName = edtName.getText().toString().trim();
strAccNumber = edtAccNumber.getText().toString().trim();
if (!strAccType.equalsIgnoreCase("") && !strRUT.equalsIgnoreCase("") &&
!strBank.equalsIgnoreCase("") && !strName.equalsIgnoreCase("")
&& !strAccNumber.equalsIgnoreCase("")) {
tvOk.setTextColor(getResources().getColor(R.color.colorWhite));
tvOk.setEnabled(true);
} else {
tvOk.setTextColor(getResources().getColor(R.color.colorLight));
tvOk.setEnabled(false);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_ok:
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("accountHolderName", edtName.getText().toString().trim());
jsonObject.addProperty("accountHolderRUT", edtRUT.getText().toString().trim());
jsonObject.addProperty("accountNumber", edtAccNumber.getText().toString().trim());
jsonObject.addProperty("accountBank", banks.get(position).getId());
jsonObject.addProperty("accountType", tvAccType.getText().toString().trim());
showProgress();
ApiHelper.getInstance().setBankAccount(token, jsonObject, new ApiCallback.Listener() {
@Override
public void onSuccess(String result) {
Log.d(TAG, result);
dismissProgress();
finish();
}
@Override
public void onFailure(String error) {
Log.d(TAG, error);
dismissProgress();
showToast(error);
}
});
break;
case R.id.tv_cancel:
finish();
break;
case R.id.tv_acc_type:
String[] type = {"Cuenta Corriente", "Cuenta Vista", "Cuenta de Ahorro"};
dialogAccountTypePicker(type);
break;
case R.id.tv_bank:
if (banks.size() >= 0) {
Log.d(TAG, banks.size() + "");
String[] bankName = new String[banks.size()];
for (int i = 0; i < banks.size(); i++) {
BankBean bank = banks.get(i);
bankName[i] = bank.getName();
}
dialogBankPicker(bankName);
} else {
showProgress();
ApiHelper.getInstance().getBanks(token, new ApiCallback.BanksListener() {
@Override
public void onSuccess(List<BankBean> result) {
dismissProgress();
banks = result;
Log.d(TAG, result.size() + "");
String[] bankName = new String[result.size()];
for (int i = 0; i < result.size(); i++) {
BankBean bank = result.get(i);
bankName[i] = bank.getName();
}
dialogBankPicker(bankName);
}
@Override
public void onFailure(String error) {
dismissProgress();
Log.d(TAG, error);
showToast(error);
}
});
}
break;
}
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/adapter/PaymentTaskAdapter.java
package cl.activaresearch.android_app.Dooit.adapter;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.models.PaymentDetails;
import cl.activaresearch.android_app.Dooit.utils.Validation;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 24 Jul,2018
*/
public class PaymentTaskAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private Activity mContext;
private List<PaymentDetails.TasksBean> filteredData = null;
public PaymentTaskAdapter(Activity mContext, List<PaymentDetails.TasksBean> taskBeans) {
this.mContext = mContext;
this.filteredData = taskBeans;
inflater = LayoutInflater.from(this.mContext);
}
@Override
public int getCount() {
return filteredData.size();
}
@Override
public Object getItem(int i) {
return filteredData.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View convertView, ViewGroup parent) {
ViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.payment_details_row, parent, false);
mViewHolder = new ViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
final PaymentDetails.TasksBean taskBean = filteredData.get(i);
mViewHolder.tvTaskName.setText(taskBean.getName());
mViewHolder.tvDate.setText(Validation.getFormattedDate(mContext, taskBean.getValidatedOn()));
mViewHolder.tvPayment.setText("$"+taskBean.getPayment());
return convertView;
}
private class ViewHolder {
private TextView tvTaskName, tvDate, tvPayment;
public ViewHolder(View item) {
tvDate = (TextView) item.findViewById(R.id.tv_date);
tvTaskName = (TextView) item.findViewById(R.id.tv_task_name);
tvPayment = (TextView) item.findViewById(R.id.tv_bal);
}
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/models/PaymentBean.java
package cl.activaresearch.android_app.Dooit.models;
import java.io.Serializable;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 21 Jul,2018
*/
public class PaymentBean implements Serializable{
/**
* id : 28
* requestedOn : 2018-07-21
* validatedOn : null
* paidOn : null
* total : 5000
* status : 1
* account : {"accountHolderName":"Pradeep","accountHolderRUT":"ssdsd","accountNumber":"12312124124","accountBank":1,"accountType":"sdfsdf","accountBankName":"Banco BBVA"}
*/
private int id;
private String requestedOn;
private Object validatedOn;
private Object paidOn;
private int total;
private int status;
private AccountBean account;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRequestedOn() {
return requestedOn;
}
public void setRequestedOn(String requestedOn) {
this.requestedOn = requestedOn;
}
public Object getValidatedOn() {
return validatedOn;
}
public void setValidatedOn(Object validatedOn) {
this.validatedOn = validatedOn;
}
public Object getPaidOn() {
return paidOn;
}
public void setPaidOn(Object paidOn) {
this.paidOn = paidOn;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public AccountBean getAccount() {
return account;
}
public void setAccount(AccountBean account) {
this.account = account;
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/utils/Constants.java
package cl.activaresearch.android_app.Dooit.utils;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 13 Jun,2018
*/
public final class Constants {
public static final String IS_LOGIN = "is_login";
public static final String TOKEN = "token";
public static final String TASK = "task";
public static final String PAYMENT = "payment";
public static final String TITLE = "title";
public static final String SURVEY = "survey";
public static final String BALANCE = "balance";
public static final String DISTANCE = "distance";
public static final String NOTIFICATION = "notification";
public static final String CATEGORIES = "categories";
public static final String PROFILE_DLG = "profile_dlg";
public static final String COMPLETE_DLG = "task_dlg";
public static final String PAYMENT_DLG = "payment_dlg";
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/activities/questions/VideoActivity.java
package cl.activaresearch.android_app.Dooit.activities.questions;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.google.gson.JsonObject;
import java.io.File;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.activities.BaseActivity;
import cl.activaresearch.android_app.Dooit.models.SurveyBean;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiCallback;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiHelper;
import cl.activaresearch.android_app.Dooit.utils.Constants;
import cl.activaresearch.android_app.Dooit.utils.FilePathManager;
import cl.activaresearch.android_app.Dooit.utils.SharedPreferenceUtility;
import cl.activaresearch.android_app.Dooit.utils.Utility;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 05 Jun,2018
*/
public class VideoActivity extends BaseActivity implements View.OnClickListener {
private TextView tvTitle, tvCancel, tvCapture, tvOk, tvQuestion;
private SurveyBean surveyBean;
private VideoView vvCaptured;
private int REQUEST_VIDEO = 0, SELECT_FILE = 1;
private String selectedVideoPath = "null", videoUrl;
private StorageReference mStorageRef;
private ImageView ivFile, ivPlay;
private RelativeLayout rlVideo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
tvTitle = (TextView) findViewById(R.id.tv_title);
tvCancel = (TextView) findViewById(R.id.tv_cancel);
tvQuestion = (TextView) findViewById(R.id.tv_question_name);
tvCapture = (TextView) findViewById(R.id.tv_update_video);
rlVideo = (RelativeLayout) findViewById(R.id.rl_video);
ivPlay = (ImageView) findViewById(R.id.iv_play);
ivFile = (ImageView) findViewById(R.id.iv_file);
vvCaptured = (VideoView) findViewById(R.id.vv_captured_video);
tvOk = (TextView) findViewById(R.id.tv_ok);
Intent intent = getIntent();
surveyBean = (SurveyBean) intent.getSerializableExtra(Constants.SURVEY);
tvTitle.setText(getIntent().getStringExtra(Constants.TITLE));
tvQuestion.setText(surveyBean.getQuestion());
tvCancel.setOnClickListener(this);
tvOk.setOnClickListener(this);
tvCapture.setOnClickListener(this);
ivPlay.setOnClickListener(this);
rlVideo.setVisibility(View.GONE);
ivFile.setVisibility(View.VISIBLE);
vvCaptured.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
ivPlay.setVisibility(View.VISIBLE);
}
});
mStorageRef = FirebaseStorage.getInstance().getReference();
if (surveyBean != null) {
tvTitle.setText(intent.getStringExtra(Constants.TITLE));
tvQuestion.setText(surveyBean.getQuestion());
if (surveyBean.getAnswer() != null) {
Uri uriVideo = Uri.parse(surveyBean.getAnswer().getData());
vvCaptured.setVideoURI(uriVideo);
if (uriVideo != null) {
rlVideo.setVisibility(View.VISIBLE);
ivFile.setVisibility(View.GONE);
} else {
rlVideo.setVisibility(View.GONE);
ivFile.setVisibility(View.VISIBLE);
}
}
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_cancel:
finish();
break;
case R.id.tv_ok:
updateVideo();
break;
case R.id.tv_update_video:
selectVideo();
break;
case R.id.iv_play:
vvCaptured.start();
ivPlay.setVisibility(View.GONE);
break;
}
}
/**
* Selecting image form Gallery or Camera
*/
private void selectVideo() {
final CharSequence[] items = {getString(R.string.record_video), getString(R.string.select_video_fr_galery),
getString(R.string.cancel)};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(VideoActivity.this);
if (items[item].equals(getString(R.string.record_video))) {
if (result)
videoIntent();
} else if (items[item].equals(getString(R.string.select_video_fr_galery))) {
if (result)
galleryIntent();
} else if (items[item].equals(getString(R.string.cancel))) {
dialog.dismiss();
}
}
});
builder.show();
}
/**
* Fire intent for gallery
*/
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_file)), SELECT_FILE);
}
/**
* Fire intent for camera
*/
private void videoIntent() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent, REQUEST_VIDEO);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE) {
Uri uriVideo = data.getData();
vvCaptured.setVideoURI(uriVideo);
if (uriVideo != null) {
rlVideo.setVisibility(View.VISIBLE);
ivFile.setVisibility(View.GONE);
} else {
rlVideo.setVisibility(View.GONE);
ivFile.setVisibility(View.VISIBLE);
}
// OI FILE Manager
String filemanagerstring = uriVideo.getPath();
// MEDIA GALLERY
selectedVideoPath = FilePathManager.getVideoPath(this, uriVideo);
Log.d("", "");
} else if (requestCode == REQUEST_VIDEO) {
Uri uriVideo = data.getData();
// MEDIA GALLERY
selectedVideoPath = FilePathManager.getVideoPath(this, uriVideo);
vvCaptured.setVideoURI(uriVideo);
if (uriVideo != null) {
rlVideo.setVisibility(View.VISIBLE);
ivFile.setVisibility(View.GONE);
tvOk.setEnabled(true);
tvOk.setTextColor(getResources().getColor(R.color.colorWhite));
} else {
rlVideo.setVisibility(View.GONE);
ivFile.setVisibility(View.VISIBLE);
}
}
}
}
private void updateVideo() {
Uri filePath = Uri.fromFile(new File(selectedVideoPath));
//if there is a file to upload
try {
//displaying a progress dialog while upload is going on
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle(getString(R.string.uploading));
//progressDialog.show();
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
showProgress();
StorageReference riversRef = mStorageRef.child("videos/" + ts + "_dooit.mp4");
riversRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//if the upload is successfull
//hiding the progress dialog
progressDialog.dismiss();
Uri uri = taskSnapshot.getDownloadUrl();
//and displaying a success toast
videoUrl = String.valueOf(uri);
// Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
// body.put("profilePictureURL", imageUrl);
setAnswerForQuestion(videoUrl);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
//if the upload is not successfull
//hiding the progress dialog
progressDialog.dismiss();
dismissProgress();
//and displaying error message
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//calculating progress percentage
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//displaying percentage in progress dialog
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
} catch (Exception e) {
dismissProgress();
e.printStackTrace();
}
}
private void setAnswerForQuestion(String imageUrl) {
String token = SharedPreferenceUtility.getInstance(this).getString(Constants.TOKEN);
JsonObject body = new JsonObject();
body.addProperty("answer", imageUrl);
ApiHelper.getInstance().ansSurveyQuestion(token, surveyBean.getTaskId(), surveyBean.getId(), body, new ApiCallback.Listener() {
@Override
public void onSuccess(String result) {
finish();
dismissProgress();
}
@Override
public void onFailure(String error) {
showToast(error);
dismissProgress();
}
});
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/servercommunication/ApiClient.java
package cl.activaresearch.android_app.Dooit.servercommunication;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 05 Jul,2018
*/
public class ApiClient {
public static final String BASE_URL = "http://api.dooit-app.com:4300";
private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(180, TimeUnit.SECONDS)
.writeTimeout(180, TimeUnit.SECONDS)
.connectTimeout(180, TimeUnit.SECONDS)
.build();
private static Retrofit retrofit = null, retrofit1 = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL).client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/activities/PermissionActivity.java
package cl.activaresearch.android_app.Dooit.activities;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cl.activaresearch.android_app.Dooit.R;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 05 Jul,2018
*/
public class PermissionActivity extends AppCompatActivity implements View.OnClickListener {
private static final int ACCESS_FINE_LOCATION = 1001, CAMERA = 1002, READ_EXTERNAL_STORAGE = 1003, RECORD_AUDIO = 1004;
private RelativeLayout rlNotification, rlPhoto, rlCamera, rlLocation, rlMicrophone;
private TextView tvFinalizer;
private ImageView ivCamera, ivLocation, ivNotification, ivMice, ivPhoto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permission);
initUI();
isAllPermissionAvailable();
}
private void initUI() {
rlCamera = (RelativeLayout) findViewById(R.id.rl_camera);
rlLocation = (RelativeLayout) findViewById(R.id.rl_location);
rlMicrophone = (RelativeLayout) findViewById(R.id.rl_microphone);
rlNotification = (RelativeLayout) findViewById(R.id.rl_notification);
rlPhoto = (RelativeLayout) findViewById(R.id.rl_photo);
tvFinalizer = (TextView) findViewById(R.id.tv_finalizar);
ivCamera = (ImageView) findViewById(R.id.iv_camera_check);
ivLocation = (ImageView) findViewById(R.id.iv_location_check);
ivMice = (ImageView) findViewById(R.id.iv_mice_check);
ivPhoto = (ImageView) findViewById(R.id.iv_photo_check);
ivNotification = (ImageView) findViewById(R.id.iv_notification_check);
rlPhoto.setOnClickListener(this);
rlLocation.setOnClickListener(this);
rlMicrophone.setOnClickListener(this);
rlNotification.setOnClickListener(this);
rlCamera.setOnClickListener(this);
tvFinalizer.setOnClickListener(this);
if (isAllPermissionAvailable()) {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorWhite));
tvFinalizer.setEnabled(true);
Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
finish();
} else {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorLight));
tvFinalizer.setEnabled(false);
}
}
/**
* Verify all required permissions
*
* @return
*/
private boolean isAllPermissionAvailable() {
if (!isReadCameraAllowed()) {
return false;
} else if (!isReadStorageAllowed()) {
return false;
} else if (!isReadLocationAllowed()) {
return false;
} else if (!isReadMiceAllowed()) {
return false;
} else {
return true;
}
}
/**
* check camera permission granted or not
*
* @return
*/
private boolean isReadCameraAllowed() {
//Getting the permission status
int result = ContextCompat.checkSelfPermission(PermissionActivity.this, Manifest.permission.CAMERA);
//If permission is granted returning true
if (result == PackageManager.PERMISSION_GRANTED) {
ivCamera.setImageResource(R.mipmap.ic_white_check);
return true;
}
//If permission is not granted returning false
return false;
}
/**
* request to camera permission
*/
private void requestCameraPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(PermissionActivity.this, Manifest.permission.CAMERA)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(PermissionActivity.this, new String[]{Manifest.permission.CAMERA}, CAMERA);
}
/**
* request to camera permission
*/
private void requestMicePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(PermissionActivity.this, Manifest.permission.RECORD_AUDIO)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(PermissionActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, RECORD_AUDIO);
}
/**
* check location permission granted or not
*
* @return
*/
private boolean isReadLocationAllowed() {
//Getting the permission status
int result = ContextCompat.checkSelfPermission(PermissionActivity.this, Manifest.permission.ACCESS_FINE_LOCATION);
//If permission is granted returning true
if (result == PackageManager.PERMISSION_GRANTED) {
ivLocation.setImageResource(R.mipmap.ic_white_check);
return true;
}
//If permission is not granted returning false
return false;
}
/**
* check location permission granted or not
*
* @return
*/
private boolean isReadMiceAllowed() {
//Getting the permission status
int result = ContextCompat.checkSelfPermission(PermissionActivity.this, Manifest.permission.RECORD_AUDIO);
//If permission is granted returning true
if (result == PackageManager.PERMISSION_GRANTED) {
ivLocation.setImageResource(R.mipmap.ic_white_check);
return true;
}
//If permission is not granted returning false
return false;
}
/**
* request to location permission
*/
private void requestLocationPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(PermissionActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(PermissionActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION);
}
/**
* check storage permission granted or not
*
* @return
*/
private boolean isReadStorageAllowed() {
//Getting the permission status
int result = ContextCompat.checkSelfPermission(PermissionActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
//If permission is granted returning true
if (result == PackageManager.PERMISSION_GRANTED) {
ivPhoto.setImageResource(R.mipmap.ic_white_check);
return true;
}
//If permission is not granted returning false
return false;
}
/**
* request to storage permission
*/
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(PermissionActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(PermissionActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE);
}
/**
* Result of runtime permission request
*/
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
boolean is = isAllPermissionAvailable();
if (is) {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorWhite));
tvFinalizer.setEnabled(true);
} else {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorLight));
tvFinalizer.setEnabled(false);
}
switch (requestCode) {
case ACCESS_FINE_LOCATION:
try {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ivLocation.setImageResource(R.mipmap.ic_white_check);
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
ivLocation.setImageResource(R.mipmap.ic_white_uncheck);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case CAMERA:
try {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ivCamera.setImageResource(R.mipmap.ic_white_check);
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
ivCamera.setImageResource(R.mipmap.ic_white_uncheck);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case READ_EXTERNAL_STORAGE:
try {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ivPhoto.setImageResource(R.mipmap.ic_white_check);
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
ivPhoto.setImageResource(R.mipmap.ic_white_uncheck);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case RECORD_AUDIO:
try {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ivMice.setImageResource(R.mipmap.ic_white_check);
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
ivMice.setImageResource(R.mipmap.ic_white_uncheck);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.rl_camera:
if (isReadCameraAllowed()) {
if (isAllPermissionAvailable()) {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorWhite));
tvFinalizer.setEnabled(true);
} else {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorLight));
tvFinalizer.setEnabled(false);
}
} else {
requestCameraPermission();
}
break;
case R.id.rl_location:
if (isReadLocationAllowed()) {
if (isAllPermissionAvailable()) {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorWhite));
tvFinalizer.setEnabled(true);
} else {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorLight));
tvFinalizer.setEnabled(false);
}
} else {
requestLocationPermission();
}
break;
case R.id.rl_microphone:
if (isReadMiceAllowed()) {
if (isAllPermissionAvailable()) {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorWhite));
tvFinalizer.setEnabled(true);
} else {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorLight));
tvFinalizer.setEnabled(false);
}
} else {
requestMicePermission();
}
break;
case R.id.rl_notification:
if (isReadCameraAllowed()) {
if (isAllPermissionAvailable()) {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorWhite));
tvFinalizer.setEnabled(true);
} else {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorLight));
tvFinalizer.setEnabled(false);
}
} else {
}
break;
case R.id.rl_photo:
if (isReadStorageAllowed()) {
if (isAllPermissionAvailable()) {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorWhite));
tvFinalizer.setEnabled(true);
} else {
tvFinalizer.setTextColor(getResources().getColor(R.color.colorLight));
tvFinalizer.setEnabled(false);
}
} else {
requestStoragePermission();
}
break;
case R.id.tv_finalizar:
Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
finish();
break;
}
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/activities/HomeActivity.java
package cl.activaresearch.android_app.Dooit.activities;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.gson.JsonObject;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.fragments.AboutFragment;
import cl.activaresearch.android_app.Dooit.fragments.BankFragment;
import cl.activaresearch.android_app.Dooit.fragments.MyTaskFragment;
import cl.activaresearch.android_app.Dooit.fragments.PaymentDetailFragment;
import cl.activaresearch.android_app.Dooit.fragments.PreferenceFragment;
import cl.activaresearch.android_app.Dooit.fragments.ProfileFragment;
import cl.activaresearch.android_app.Dooit.fragments.SeekerFragment;
import cl.activaresearch.android_app.Dooit.fragments.SurveyFragment;
import cl.activaresearch.android_app.Dooit.fragments.TaskDetailFragment;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiCallback;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiHelper;
import cl.activaresearch.android_app.Dooit.utils.Constants;
import cl.activaresearch.android_app.Dooit.utils.SharedPreferenceUtility;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 05 Jul,2018
*/
public class HomeActivity extends BaseActivity {
public static Fragment fragment;
public static int FROM_WHERE = 0, TAB_NO = 0;
private static BackPressed backPressed;
private TextView tvBank, tvTask, tvSeeker, tvPref, tvProf;
private ImageView ivBank, ivTask, ivSeeker, ivPref, ivProf;
private final String TAG = HomeActivity.class.getName();
public static void setOnBackPressed(BackPressed backPressed1) {
backPressed = backPressed1;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
initUI();
tvProf.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
ivProf.setImageResource(R.mipmap.ic_profile);
loadFragment(new ProfileFragment());
final String refreshedToken = FirebaseInstanceId.getInstance().getToken();
final String token = SharedPreferenceUtility.getInstance(this).getString(Constants.TOKEN);
if (!refreshedToken.equalsIgnoreCase("")) {
final String android_id = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("token", refreshedToken);
jsonObject.addProperty("identifier", android_id);
jsonObject.addProperty("os", "android");
ApiHelper.getInstance().registerDevice(token, jsonObject, new ApiCallback.Listener() {
@Override
public void onSuccess(String result) {
Log.d(TAG, result);
SharedPreferenceUtility.getInstance(HomeActivity.this).putBoolean(Constants.NOTIFICATION, true);
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("identifier", android_id);
jsonObject.addProperty("enabled", "1");
ApiHelper.getInstance().toggleNotifications(token, jsonObject, new ApiCallback.Listener() {
@Override
public void onSuccess(String result) {
Log.d("Enable result: ", result);
}
@Override
public void onFailure(String error) {
Log.d("onFailure:", error + "");
}
});
}
@Override
public void onFailure(String error) {
Log.d(TAG, error);
}
});
}
}
private void initUI() {
tvBank = (TextView) findViewById(R.id.tv_tab_bank);
tvTask = (TextView) findViewById(R.id.tv_tab_task);
tvSeeker = (TextView) findViewById(R.id.tv_tab_seeker);
tvPref = (TextView) findViewById(R.id.tv_tab_plus);
tvProf = (TextView) findViewById(R.id.tv_tab_profile);
ivBank = (ImageView) findViewById(R.id.iv_tab_bank);
ivTask = (ImageView) findViewById(R.id.iv_tab_task);
ivSeeker = (ImageView) findViewById(R.id.iv_tab_seeker);
ivPref = (ImageView) findViewById(R.id.iv_tab_plus);
ivProf = (ImageView) findViewById(R.id.iv_tab_profile);
}
/**
* Loading fragment
*
* @param fragment1
*/
public void loadFragment(Fragment fragment1) {
fragment = fragment1;
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentTransaction.commit();
}
public void onClickPreference(View v) {
setDeactivatedTab();
tvPref.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
ivPref.setImageResource(R.mipmap.ic_pref);
loadFragment(new PreferenceFragment());
}
public void onClickBank(View v) {
setDeactivatedTab();
tvBank.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
ivBank.setImageResource(R.mipmap.ic_bank);
TAB_NO = 0;
loadFragment(new BankFragment());
}
@Override
protected void onResume() {
super.onResume();
}
private void setDeactivatedTab() {
tvBank.setTextColor(getResources().getColor(R.color.colorDarkGray));
ivBank.setImageResource(R.mipmap.ic_bank_deactivate);
tvProf.setTextColor(getResources().getColor(R.color.colorDarkGray));
ivProf.setImageResource(R.mipmap.ic_profile_deactivate);
tvSeeker.setTextColor(getResources().getColor(R.color.colorDarkGray));
ivSeeker.setImageResource(R.mipmap.ic_seeker_deactivate);
tvTask.setTextColor(getResources().getColor(R.color.colorDarkGray));
ivTask.setImageResource(R.mipmap.ic_task_deactivate);
tvPref.setTextColor(getResources().getColor(R.color.colorDarkGray));
ivPref.setImageResource(R.mipmap.ic_pref_deactivate);
}
public void onClickProfile(View v) {
setDeactivatedTab();
tvProf.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
ivProf.setImageResource(R.mipmap.ic_profile);
loadFragment(new ProfileFragment());
}
public void onClickSeeker(View v) {
setDeactivatedTab();
tvSeeker.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
ivSeeker.setImageResource(R.mipmap.ic_seeker);
TAB_NO = 0;
loadFragment(new SeekerFragment());
}
public void selectBackFragment() {
switch (FROM_WHERE) {
case 1:
onClickSeeker(null);
break;
case 2:
onClickMyTask(null);
break;
case 3:
onClickMyTask(null);
break;
}
}
public void onClickMyTask(View v) {
setDeactivatedTab();
tvTask.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
ivTask.setImageResource(R.mipmap.ic_task);
loadFragment(new MyTaskFragment());
}
public void onClickSurvey() {
setDeactivatedTab();
tvTask.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
ivTask.setImageResource(R.mipmap.ic_task);
loadFragment(new SurveyFragment());
}
@Override
public void onBackPressed() {
if (fragment instanceof ProfileFragment) {
super.onBackPressed();
finish();
} else if (fragment instanceof TaskDetailFragment) {
selectBackFragment();
} else if (fragment instanceof AboutFragment) {
onClickPreference(null);
} else if (fragment instanceof SurveyFragment) {
if (backPressed != null) {
backPressed.onBackPress();
}
} else if (fragment instanceof PaymentDetailFragment) {
if (backPressed != null) {
backPressed.onBackPress();
}
} else {
setDeactivatedTab();
fragment = new ProfileFragment();
tvProf.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
ivProf.setImageResource(R.mipmap.ic_profile);
loadFragment(fragment);
}
}
public interface BackPressed {
void onBackPress();
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/fragments/AboutFragment.java
package cl.activaresearch.android_app.Dooit.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.activities.HomeActivity;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 24 Jun,2018
*/
public class AboutFragment extends Fragment implements View.OnClickListener {
public static final int FILTER_CODE = 1022;
private Activity mContext;
private ImageView ivBack;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_about, container, false);
initUI(view);
return view;
}
private void initUI(View view) {
ivBack = (ImageView) view.findViewById(R.id.iv_back);
ivBack.setOnClickListener(this);
}
@Override
public void onClick(View v) {
((HomeActivity) mContext).onClickPreference(null);
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/servercommunication/ApiCallback.java
package cl.activaresearch.android_app.Dooit.servercommunication;
import java.util.List;
import cl.activaresearch.android_app.Dooit.models.BankBean;
import cl.activaresearch.android_app.Dooit.models.AccountBean;
import cl.activaresearch.android_app.Dooit.models.CategoryBean;
import cl.activaresearch.android_app.Dooit.models.PaymentBean;
import cl.activaresearch.android_app.Dooit.models.PaymentDetails;
import cl.activaresearch.android_app.Dooit.models.RegionBean;
import cl.activaresearch.android_app.Dooit.models.SurveyBean;
import cl.activaresearch.android_app.Dooit.models.TaskBean;
import cl.activaresearch.android_app.Dooit.models.UserBean;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 17 Jul,2018
*/
public class ApiCallback {
public interface CategoryListener {
void onSuccess(List<CategoryBean> categories);
void onFailure(String error);
}
public interface SurveyListener {
void onSuccess(List<SurveyBean> surveyBeans);
void onFailure(String error);
}
public interface UserListener {
void onSuccess(UserBean userBean);
void onFailure(String error);
}
public interface TasksListener {
void onSuccess(List<TaskBean> taskBeans);
void onFailure(String error);
}
public interface TaskListener {
void onSuccess(TaskBean taskBean);
void onFailure(String error);
}
public interface BanksListener {
void onSuccess(List<BankBean> task);
void onFailure(String error);
}
public interface Listener {
void onSuccess(String result);
void onFailure(String error);
}
public interface AccountListener {
void onSuccess(AccountBean account);
void onFailure(String error);
}
public interface PaymentDetailsListener {
void onSuccess(PaymentDetails details);
void onFailure(String error);
}
public interface RegionsListener {
void onSuccess(List<RegionBean> regionBeanList);
void onFailure(String error);
}
public interface PaymentListener {
void onSuccess(List<PaymentBean> regionBeanList);
void onFailure(String error);
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/adapter/TaskAdapter.java
package cl.activaresearch.android_app.Dooit.adapter;
import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.models.TaskBean;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiClient;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 19 Jun,2018
*/
public class TaskAdapter extends BaseAdapter implements Filterable {
private final LayoutInflater inflater;
private Activity mContext;
private List<TaskBean> originalData = null;
private List<TaskBean> filteredData = null;
private ItemFilter mFilter = new ItemFilter();
public TaskAdapter(Activity mContext, List<TaskBean> taskBeans) {
this.mContext = mContext;
this.filteredData = taskBeans;
this.originalData = taskBeans;
inflater = LayoutInflater.from(this.mContext);
}
@Override
public int getCount() {
return filteredData.size();
}
@Override
public Object getItem(int i) {
return filteredData.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View convertView, ViewGroup parent) {
ViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.task_row, parent, false);
mViewHolder = new ViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
final TaskBean taskBean = filteredData.get(i);
mViewHolder.tvTaskName.setText(taskBean.getNombre());
mViewHolder.tvCategory.setText(taskBean.getCategoria() + "");
mViewHolder.viewLine.setBackgroundColor(Color.parseColor(taskBean.getColor()));
mViewHolder.tvPayment.setText(taskBean.getPago() + " - ");
mViewHolder.tvTime.setText(taskBean.getHoras() + "m - ");
double roundOff = Math.round(taskBean.getDistancia() * 100.0) / 100.0;
mViewHolder.tvDistance.setText(roundOff + "km");
if (taskBean.getFoto() != null) {
Glide.with(mContext)
.load(ApiClient.BASE_URL + taskBean.getFoto())
.into(mViewHolder.ivPhoto);
}
return convertView;
}
@Override
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<TaskBean> list = originalData;
int count = list.size();
final ArrayList<TaskBean> nlist = new ArrayList<TaskBean>(count);
String filterableString;
for (int i = 0; i < count; i++) {
TaskBean taskBean = list.get(i);
filterableString = taskBean.getNombre();
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(taskBean);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<TaskBean>) results.values;
notifyDataSetChanged();
}
}
private class ViewHolder {
private TextView tvTaskName, tvCategory, tvTime, tvDistance, tvPayment;
private ImageView ivPhoto;
private View viewLine;
public ViewHolder(View item) {
tvTaskName = (TextView) item.findViewById(R.id.tv_task_name);
ivPhoto = (ImageView) item.findViewById(R.id.iv_photo);
tvCategory = (TextView) item.findViewById(R.id.tv_address);
tvPayment = (TextView) item.findViewById(R.id.tv_payment);
viewLine = (View) item.findViewById(R.id.view_line);
tvTime = (TextView) item.findViewById(R.id.tv_time);
tvDistance = (TextView) item.findViewById(R.id.tv_distance);
}
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/fragments/ListaFragment.java
package cl.activaresearch.android_app.Dooit.fragments;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.activities.FilterActivity;
import cl.activaresearch.android_app.Dooit.activities.HomeActivity;
import cl.activaresearch.android_app.Dooit.adapter.TaskAdapter;
import cl.activaresearch.android_app.Dooit.models.CategoryBean;
import cl.activaresearch.android_app.Dooit.models.TaskBean;
import cl.activaresearch.android_app.Dooit.recievers.LocationTrack;
import cl.activaresearch.android_app.Dooit.recievers.NetworkRecognizer;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiCallback;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiHelper;
import cl.activaresearch.android_app.Dooit.utils.Constants;
import cl.activaresearch.android_app.Dooit.utils.SharedPreferenceUtility;
import static android.app.Activity.RESULT_OK;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 18 Jun,2018
*/
public class ListaFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener, SearchView.OnQueryTextListener, SwipeRefreshLayout.OnRefreshListener {
private final int FILTER_CODE = 1022;
private Activity mContext;
private ListView lvTask;
private TaskAdapter taskAdapter;
private ImageView ivFilter;
private List<TaskBean> taskBeans;
private int distance;
private String category;
private SearchView searchList;
private RelativeLayout tvEmpty;
private SwipeRefreshLayout swipeRefresh;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
taskBeans = new ArrayList<>();
mContext = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_lista, container, false);
// Inflate the layout for this fragment
lvTask = (ListView) view.findViewById(R.id.lv_task);
searchList = (SearchView) view.findViewById(R.id.search_list);
swipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
ivFilter = (ImageView) view.findViewById(R.id.iv_filter);
ivFilter.setOnClickListener(this);
tvEmpty = (RelativeLayout) view.findViewById(R.id.tv_empty);
searchList.setOnQueryTextListener(this);
lvTask.setOnItemClickListener(this);
swipeRefresh.setOnRefreshListener(this);
getCategory();
return view;
}
private void getCategory() {
String cat = "[";
for (CategoryBean categoryBean : FilterActivity.categories) {
if (categoryBean.isSelect()) {
cat = cat + categoryBean.getId() + ",";
}
}
if (!cat.equalsIgnoreCase("[")) {
cat = cat.substring(0, cat.length() - 1);
}
cat = cat + "]";
category = cat;
distance = FilterActivity.distance;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_filter:
Intent intent = new Intent(mContext, FilterActivity.class);
startActivityForResult(intent, FILTER_CODE);
mContext.overridePendingTransition(R.anim.right_to_left, R.anim.left_to_right);
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FILTER_CODE) {
if (resultCode == RESULT_OK) {
distance = data.getIntExtra(Constants.DISTANCE, 0);
category = data.getStringExtra(Constants.CATEGORIES);
Log.d("", "");
}
}
}
@Override
public void onResume() {
super.onResume();
String token = SharedPreferenceUtility.getInstance(mContext).getString(Constants.TOKEN);
Location location = new LocationTrack(getActivity()).getLocation();
if (NetworkRecognizer.isNetworkAvailable(mContext)) {
if (location != null) {
((HomeActivity) mContext).showProgress();
ApiHelper.getInstance().getAllTask(token, location.getLatitude() + "", location.getLongitude() + "", distance + "", category, new ApiCallback.TasksListener() {
@Override
public void onSuccess(List<TaskBean> tasks1) {
taskBeans = tasks1;
taskAdapter = new TaskAdapter(mContext, taskBeans);
lvTask.setAdapter(taskAdapter);
lvTask.setEmptyView(tvEmpty);
((HomeActivity) mContext).dismissProgress();
}
@Override
public void onFailure(String error) {
taskAdapter = new TaskAdapter(mContext, taskBeans);
lvTask.setAdapter(taskAdapter);
lvTask.setEmptyView(tvEmpty);
((HomeActivity) mContext).dismissProgress();
}
});
}
} else {
((HomeActivity) mContext).showNetwork();
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TaskBean taskBean = (TaskBean) parent.getAdapter().getItem(position);
Fragment fragment = new TaskDetailFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(Constants.TASK, taskBean);
HomeActivity.FROM_WHERE = 1;
fragment.setArguments(bundle);
((HomeActivity) mContext).loadFragment(fragment);
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
taskAdapter.getFilter().filter(newText.toString());
return false;
}
@Override
public void onRefresh() {
String token = SharedPreferenceUtility.getInstance(mContext).getString(Constants.TOKEN);
Location location = new LocationTrack(getActivity()).getLocation();
if (NetworkRecognizer.isNetworkAvailable(mContext)) {
if (location != null) {
ApiHelper.getInstance().getAllTask(token, location.getLatitude() + "", location.getLongitude() + "", distance + "", category, new ApiCallback.TasksListener() {
@Override
public void onSuccess(List<TaskBean> tasks1) {
taskBeans = tasks1;
taskAdapter = new TaskAdapter(mContext, taskBeans);
lvTask.setAdapter(taskAdapter);
lvTask.setEmptyView(tvEmpty);
swipeRefresh.setRefreshing(false);
}
@Override
public void onFailure(String error) {
taskAdapter = new TaskAdapter(mContext, taskBeans);
lvTask.setAdapter(taskAdapter);
lvTask.setEmptyView(tvEmpty);
swipeRefresh.setRefreshing(false);
}
});
}
} else {
((HomeActivity) mContext).showNetwork();
swipeRefresh.setRefreshing(false);
}
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/activities/SignUpActivity.java
package cl.activaresearch.android_app.Dooit.activities;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import java.util.Arrays;
import java.util.HashMap;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.recievers.NetworkRecognizer;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiCallback;
import cl.activaresearch.android_app.Dooit.servercommunication.ApiHelper;
import cl.activaresearch.android_app.Dooit.utils.Constants;
import cl.activaresearch.android_app.Dooit.utils.SharedPreferenceUtility;
import cl.activaresearch.android_app.Dooit.utils.Validation;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 05 Jul,2018
*/
public class SignUpActivity extends BaseActivity implements View.OnClickListener, TextWatcher {
private EditText edtEmail, edtFName, edtLName, edtPassword;
private TextView tvFacebook, tvSignUp, tvLogin;
private LoginButton loginButton;
private CallbackManager callbackManager;
private String TAG = SignUpActivity.class.getName();
private String strEmail, strPassword, strFName, strLName;
private ImageView ivBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
initUI();
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// App code
final String accessToken = loginResult.getAccessToken().getToken();
Log.d("", "");
//<KEY>
HashMap<String, String> body = new HashMap<>();
body.put("token", accessToken);
showProgress();
ApiHelper.getInstance().userFacebookLogin(body, new ApiCallback.Listener() {
@Override
public void onSuccess(String id) {
SharedPreferenceUtility.getInstance(SignUpActivity.this).putString(Constants.TOKEN, "facebook " + accessToken);
SharedPreferenceUtility.getInstance(SignUpActivity.this).putBoolean(Constants.IS_LOGIN, true);
Intent intent = new Intent(SignUpActivity.this, PermissionActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
dismissProgress();
LoginManager.getInstance().logOut();
}
@Override
public void onFailure(String error) {
dismissProgress();
showToast(error);
LoginManager.getInstance().logOut();
}
});
}
@Override
public void onCancel() {
// App code
Log.d("", "");
}
@Override
public void onError(FacebookException exception) {
// App code
Log.d("", "");
}
});
/* try {
PackageInfo info = getPackageManager().getPackageInfo(
"cl.activaresearch.android_app.Dooit",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String hash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
Log.d("KeyHash:", hash);
}
} catch (Exception e) {
e.getStackTrace();
}
*/
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
private void initUI() {
edtEmail = (EditText) findViewById(R.id.edt_email);
edtFName = (EditText) findViewById(R.id.edt_f_name);
edtLName = (EditText) findViewById(R.id.edt_l_name);
edtPassword = (EditText) findViewById(R.id.edt_password);
ivBack = (ImageView) findViewById(R.id.iv_back);
tvFacebook = (TextView) findViewById(R.id.tv_facebook);
tvLogin = (TextView) findViewById(R.id.tv_login);
tvSignUp = (TextView) findViewById(R.id.tv_sign_up);
tvLogin.setOnClickListener(this);
tvSignUp.setOnClickListener(this);
tvFacebook.setOnClickListener(this);
ivBack.setOnClickListener(this);
edtFName.addTextChangedListener(this);
edtEmail.addTextChangedListener(this);
edtPassword.addTextChangedListener(this);
edtLName.addTextChangedListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_login:
Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);
finish();
break;
case R.id.tv_facebook:
loginButton.performClick();
break;
case R.id.tv_sign_up:
if (strEmail.equalsIgnoreCase("")) {
showToast(getString(R.string.emp_email));
} else if (!Validation.isEmailValid(strEmail)) {
showToast(getString(R.string.invalid_email));
} else if (strPassword.equalsIgnoreCase("")) {
showToast(getString(R.string.emp_pass));
} else if (strFName.equalsIgnoreCase("")) {
showToast(getString(R.string.emp_first_name));
} else if (!NetworkRecognizer.isNetworkAvailable(this)) {
showNetwork();
} else {
HashMap<String, String> body = new HashMap<>();
body.put("nombres", strFName);
body.put("apellidos", strLName);
body.put("email", strEmail);
body.put("password", strPassword);
showProgress();
ApiHelper.getInstance().userSignUp(body, new ApiCallback.Listener() {
@Override
public void onSuccess(String token) {
SharedPreferenceUtility.getInstance(SignUpActivity.this).putString(Constants.TOKEN, "login " + token);
SharedPreferenceUtility.getInstance(SignUpActivity.this).putBoolean(Constants.IS_LOGIN, true);
Intent intent = new Intent(SignUpActivity.this, PermissionActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
dismissProgress();
}
@Override
public void onFailure(String error) {
dismissProgress();
showToast(error);
}
});
}
break;
case R.id.iv_back:
onBackPressed();
break;
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
strEmail = edtEmail.getText().toString().trim();
strPassword = edtPassword.getText().toString().trim();
strFName = edtFName.getText().toString().trim();
strLName = edtLName.getText().toString().trim();
if (!strEmail.equalsIgnoreCase("") && !strFName.equalsIgnoreCase("") &&
!strLName.equalsIgnoreCase("") && !strPassword.equalsIgnoreCase("")) {
tvSignUp.setTextColor(getResources().getColor(R.color.colorWhite));
tvSignUp.setEnabled(true);
} else {
tvSignUp.setTextColor(getResources().getColor(R.color.colorLight));
tvSignUp.setEnabled(false);
}
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/activities/WebActivity.java
package cl.activaresearch.android_app.Dooit.activities;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import cl.activaresearch.android_app.Dooit.R;
public class WebActivity extends AppCompatActivity implements View.OnClickListener {
private WebView webView;
private TextView tvDone;
private String postUrl = "http://www.dooit-app.com/faq";
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
webView = (WebView) findViewById(R.id.webView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
tvDone = (TextView) findViewById(R.id.tv_done);
webView.setWebViewClient(new CustomWebViewClient());
WebSettings webSetting = webView.getSettings();
webSetting.setJavaScriptEnabled(true);
webSetting.setDisplayZoomControls(true);
webView.loadUrl(postUrl);
webView.setHorizontalScrollBarEnabled(false);
tvDone.setOnClickListener(this);
}
@Override
public void onClick(View v) {
finish();
}
public class CustomWebViewClient extends WebViewClient {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
progressBar.setVisibility(View.VISIBLE);
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
<file_sep>/app/src/main/java/cl/activaresearch/android_app/Dooit/fcm/DooitFirebaseMessagingService.java
package cl.activaresearch.android_app.Dooit.fcm;
import android.app.NotificationManager;
import android.content.Context;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import cl.activaresearch.android_app.Dooit.R;
import cl.activaresearch.android_app.Dooit.utils.Constants;
import cl.activaresearch.android_app.Dooit.utils.SharedPreferenceUtility;
/**
* This class is used as
*
* @author DreamWorksSoftwares
* @version 1.0
* @since 20 Jul,2018
*/
public class DooitFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (SharedPreferenceUtility.getInstance(this).getBoolean(Constants.NOTIFICATION)) {
try {
RemoteMessage.Notification notification = remoteMessage.getNotification();
String body = notification.getBody();
String title = notification.getTitle();
sendMyNotification(title, body);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void sendMyNotification(String title, String message) {
try {
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_app)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
74f48331208d6691f9c10dbb0e5c5f5d58ee659f
|
[
"Java"
] | 26 |
Java
|
VirendraDeveloper/Dooooit
|
0cb91cd4be149df8133cd28c46f0e18f7964eb38
|
373a996a72b9db85468364c45e50de90510eb8bf
|
refs/heads/main
|
<file_sep>
Features:
- Symmetric modifiers (CMD/Super, Alt/Opt, Ctrl, Shift)
- Various modes, can be switched (using Adjust layer and the selected one is stored in EEPROM.
- Modes for Qwerty and Colemak support
- Modes for Mac vs Linux/Win support -> different order of modifiers and different action shortcuts on the "UPPER" layer (the red one in the image). Designed to simplify transtions when switching between operating systems often.
- The OLED on master half shows selected mode and caps lock state and is rotated.
- Left encoder controls volume up/down/mute. Right encoder UP/DOWN.
|
aff2065ca15b9adb26aea8d13f69d96ca34b286d
|
[
"Markdown"
] | 1 |
Markdown
|
pzohaycuoi/nam-sofle-keymap
|
1a83772ffc7f514e6f42a8a6752653697d235ebd
|
c8cc01f8a423f028ff6cd47c8fd101d00fc36fb0
|
refs/heads/master
|
<repo_name>khalilbego1/angular-56ntwg<file_sep>/README.md
# angular-56ntwg
[Edit on StackBlitz ⚡️](https://stackblitz.com/edit/angular-56ntwg)
|
520702988457e3282a6960ee16c40d3d9775f904
|
[
"Markdown"
] | 1 |
Markdown
|
khalilbego1/angular-56ntwg
|
ecc14a7837102ded046292497881e39330b7f8e1
|
6145067e63b85f4e0a3e935459a5b672917efdae
|
refs/heads/master
|
<repo_name>piovani/laravel_api<file_sep>/app/Domain/School/Aluno/Aluno.php
<?php
namespace App\Domain\School\Aluno;
use App\Domain\Localization\City\City;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use OwenIt\Auditing\Contracts\Auditable;
use Spatie\Activitylog\Traits\LogsActivity;
class Aluno extends Model implements Auditable
{
use SoftDeletes;
use \OwenIt\Auditing\Auditable;
use LogsActivity;
public $incrementing = false;
protected $fillable = [
'name',
'cpf',
'curso_id',
'city_id',
'state_id',
'faltas',
];
protected $auditInclude = [
'name',
'curso_id',
];
protected static $logAttributes = [
'name',
'curso_id',
];
public function curso()
{
return $this->belongsTo('App\Domain\School\Curso\Curso');
}
public function city()
{
return $this->belongsTo(City::class);
}
}
<file_sep>/tests/Feature/StateControllerTest.php
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;
use App\Domain\Localization\State\State;
/*
* @group states
* @group Localization
*/
class StateControllerTest extends TestCase
{
use DatabaseTransactions;
public function test_deve_retornar_a_quantidade_de_registros_no_banco()
{
$states = State::all();
$this->assertAttributeCount(27, $states);
}
public function test_deve_retornar_uma_paginacao_de_states()
{
$response = $this->json('GET', 'api/state');
$response
->assertStatus(200)
->assertJsonStructure([
'data' => [
'*' => State::COLUMNS,
],
]);
}
public function test_deve_retornar_um_state_especificado()
{
$state = State::all()->first();
dd($state->id);
$response = $this->json('GET', 'api/state/' . $state->id);
$response
->assertStatus(200)
->assertJsonStructure([
'*' => State::COLUMNS,
]);
}
}
<file_sep>/app/Domain/School/Curso/CursoController.php
<?php
namespace App\Domain\School\Curso;
use App\Http\Controllers\Controller;
use App\Domain\School\Curso\CursoResource;
use App\Domain\School\Curso\CursoRequest;
class CursoController extends Controller
{
public function index(Request $request)
{
return CursoResource::collection(
Curso::where('name', 'like', "%{$request->search}%")
->paginate()
);
}
public function store(CursoRequest $cursoRequest)
{
$curso = factory(Curso::class)->create([
'name' => $cursoRequest->name,
'media_aprovacao' => $cursoRequest->media_aprovacao ?? 0,
'numero_alunos' => $cursoRequest->numero_alunos ?? 0,
]);
return response(new CursoResource($curso), 201);
}
public function show(Curso $curso)
{
return new CursoResource($curso);
}
public function update(CursoRequest $cursoRequest, Curso $curso)
{
$curso->update([
'name' => $cursoRequest->name,
'media_aprovacao' => $cursoRequest->media_aprovacao,
'numero_alunos' => $cursoRequest->numero_alunos,
]);
return response(new CursoResource($curso), 200);
}
public function destroy(Curso $curso)
{
$curso->delete();
return response(null, 204);
}
}
<file_sep>/app/Domain/User/UserController.php
<?php
namespace App\Domain\User;
use App\Http\Controllers\Controller;
use JWTAuth;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function show()
{
$user = JWTAuth::parseToken()->authenticate();
return $user;
}
}
<file_sep>/tests/Feature/AuthTest.php
<?php
namespace App\Domain\Tests\Controllers;
use App\Domain\User\User;
use Tests\TestCase;
class AuthTest extends TestCase
{
public function testAutenticacaoComSucesso()
{
$user = factory(User::class)->create([
'email' => '<EMAIL>',
'password' => '<PASSWORD>',
]);
dd($user);
$email = '<EMAIL>';
$password = '<PASSWORD>';
factory(User::class)->create([
'email' => $email,
'password' => $password,
]);
$payload['email'] = $email;
$payload['password'] = $password;
$response = $this->json('POST', '/api/auth', $payload);
$response->assertStatus(200)
->assertJsonStructure(['token']);
}
}
<file_sep>/routes/api.php
<?php
Route::post('auth', 'Auth\AuthController@authenticate');
Route::group(['middleware' => ['jwt.verify']], function() {
Route::post('refresh', 'Auth\AuthController@refresh');
Route::get('user','User\UserController@show');
//Localization
Route::resource('state', 'Localization\State\StateController')->only('index', 'show');
Route::get('state/{id}/cities', 'Localization\State\StateController@cities');
Route::resource('city', 'Localization\City\CityController')->except('edit', 'store', 'create', 'update', 'destroy');
//School
Route::resource('curso', 'School\Curso\CursoController')->except('edit', 'create');
Route::resource('aluno', 'School\Aluno\AlunoController')->except('edit', 'create');
});
<file_sep>/database/factories/AlunoFactory.php
<?php
use App\Domain\School\Aluno\Aluno;
use Faker\Generator as Faker;
use App\Domain\School\Curso\Curso;
use App\Domain\Localization\State\State;
use App\Domain\Localization\City\City;
$factory->define(Aluno::class, function (Faker $faker) {
$faker->addProvider(new \JansenFelipe\FakerBR\FakerBR($faker));
$curso = Curso::inRandomOrder()->first();
if ($curso) {
$curso->numero_alunos++;
$curso->save();
}
return [
'id' => $faker->uuid,
'name' => $faker->name,
'cpf' => $faker->cpf,
'curso_id' => $curso->id ?? factory(Curso::class)->create(['numero_alunos' => 1])->id,
'state_id' => $state_id ?? State::inRandomOrder()->first()->id,
'city_id' => $city_id ?? City::inRandomOrder()->first()->id,
'faltas' => 0,
];
});
<file_sep>/database/factories/CursoFactory.php
<?php
use Faker\Generator as Faker;
use App\Domain\School\Curso\Curso;
$factory->define(Curso::class, function (Faker $faker){
return [
'id' => $faker->uuid,
'name' => $faker->name,
'media_aprovacao' => 0,
'numero_alunos' => 0,
];
});<file_sep>/database/seeds/AlunoSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use App\Domain\School\Aluno\Aluno;
class AlunoSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('alunos')->truncate();
factory(Aluno::class, 200)->create();
}
}
<file_sep>/README.md
# laravel_api
This repository is a test lab.
<b>P.S.:</b> No need to have PHP or Composer installed, just Docker and Docker-Compose. Docker: 19.03.2, Docker-Compose: 1.21.0 or higher.
## Commands with Docker (Recommended)
```
docker-compose up -d
```
```
docker-compose run laravel-api bash
```
```
composer install
```
```
cp .env.example .env
```
```
php artisan migrate --seed
```
## Commands without Docker
```
composer install
```
```
cp .env.example .env
```
```
php artisan migrate
```
```
php artisan db:seed
```
## Technologies Used
* Cors
* Faker BR
* Auditing
* Activitylog
* JWT Auth
* GraphQL
## Lista do que pode ser add ao projeto
* Intervention Image - https://github.com/intervention/image (tratamento de imagens)
* Horizon - https://github.com/laravel/horizon (Gerenciamento de filas de Jobs)
* Laravel Socialite - https://github.com/laravel/socialite (Autenticação com redes sociais)
* Laravel Activity Log - https://github.com/spatie/laravel-activitylog (Sistema de Log)
* Laravel Backup - https://github.com/spatie/laravel-backup (Backup arquivos do projeto e BD)
* Laravel Responsecache - https://github.com/spatie/laravel-responsecache (chace response, auta performace)
<file_sep>/app/GraphQL/Queries/StatePaginateQuery.php
<?php
declare(strict_types=1);
namespace App\GraphQL\Queries;
use App\Domain\Localization\State\State;
use Closure;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Rebing\GraphQL\Support\Query;
use Rebing\GraphQL\Support\SelectFields;
class StatePaginateQuery extends Query
{
protected $attributes = [
'name' => 'statePaginate',
'description' => 'A query of pagination'
];
public function type(): Type
{
return GraphQl::paginate('state_type');
}
public function args(): array
{
return [
'page' => [
'type' => type::int(),
'description' => 'Pagination definida para consulta',
],
'paginate' => [
'type' => type::int(),
'description' => 'Quatidadde de registro por consulta',
],
];
}
public function resolve($root, $args, $context, ResolveInfo $resolveInfo, Closure $getSelectFields)
{
$page = $args['page'] ?? 1;
$paginate = 5;
if ($args['paginate'] <= 100) {
$paginate = $args['paginate'];
}
return State::paginate($paginate, ['*'], 'page', $page);
}
}
<file_sep>/tests/Feature/CursoControllerTest.php
<?php
namespace App\Domain\Tests;
use App\Domain\School\Curso\Curso;
use Tests\TestCase;
class CursoControllerTest extends TestCase
{
public function deveRetornarAprimeiraPaginaDaListagemDeArquivo()
{
factory(Curso::class, 16)->create();
$curso = Curso::first();
$response = $this->json('GET', 'api/curso');
$response
->assertStatus(200)
->assertJson([
"current_page" => 1,
"data" => [
"id" => $curso->id,
"name" => $curso->name,
"media_aprovacao" => $curso->media_aprovacao,
"numero_alunos" => $curso->numero_alunos,
"deleted" => $curso->deleted,
"created_at" => $curso->created_at,
"updated_at" => $curso->updated_at,
]
]);
}
//NECESSARIO FINALIZAR O TESTE
public function deveTestarAlteracaoDoRegistroCurso()
{
$curso = factory(Curso::class)->create();
dd($curso);
$response = $this->json('GET', 'api/curso');
$response
->assertStatus(200)
->assertJson([
"current_page" => 1,
"data" => [
"id" => $curso->id,
"name" => $curso->name,
"media_aprovacao" => $curso->media_aprovacao,
"numero_alunos" => $curso->numero_alunos,
"deleted" => $curso->deleted,
"created_at" => $curso->created_at,
"updated_at" => $curso->updated_at,
]
]);
}
}<file_sep>/database/factories/CityFactory.php
<?php
use Faker\Generator as Faker;
use App\Domain\Localization\State\State;
$factory->define(App\Domain\Localization\City\City::class, function (Faker $faker) {
return [
'id' => $faker->uuid,
'name' => $faker->name,
'state_id' => State::inRandomOrder()->first()->id,
];
});
<file_sep>/app/Domain/School/Aluno/AlunoResource.php
<?php
namespace App\Domain\School\Aluno;
use App\Domain\Localization\City\CityResource;
use App\Domain\School\Curso\CursoResource;
use Illuminate\Http\Resources\Json\JsonResource;
class AlunoResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'cpf' => $this->cpf,
'curso' => new CursoResource($this->curso),
'city' => new CityResource($this->city),
'faltas' => $this->faltas,
];
}
}
<file_sep>/app/Http/Controllers/Controller.php
<?php
namespace App\Http\Controllers;
use http\Env\Response;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
protected const messageSuccess = 'Operação efetuada com sucesso.';
protected const messageError = 'Não foi possível efetuar a operação.';
protected const messsages = [
200 => self::messageSuccess,
500 => self::messageError,
];
protected function messageResponse($message = null, $status = 200)
{
return Response()->json([
'Messagem' => self::messsages[$status],
], $status);
}
}
<file_sep>/app/GraphQL/Queries/StateQuery.php
<?php
declare(strict_types=1);
namespace App\GraphQL\Queries;
use App\Domain\Localization\State\State;
use Closure;
use Rebing\GraphQL\Support\Facades\GraphQL;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Query;
class StateQuery extends Query
{
protected $attributes = [
'name' => 'state',
'description' => 'A query'
];
public function type(): Type
{
// return Type::listOf(Type::string());
return Type::listOf(GraphQL::type('state_type'));
}
public function args(): array
{
return [
'id' => [
// 'type' => Type::nonNull(Type::string()),
'type' => Type::string(),
'description' => 'Id uuid',
]
];
}
public function resolve($root, $args, $context, ResolveInfo $resolveInfo, Closure $getSelectFields)
{
// /** @var SelectFields $fields */
// $fields = $getSelectFields();
// $select = $fields->getSelect();
// $with = $fields->getRelations();
// if (isset($args['id'])) {
// return [
// 'id' => $args['id']
// ];
// }
//
// return [
// 'id' => 10
// ];
if (isset($args['id'])) {
return State::where('id', $args['id'])->get();
}
return State::all();
}
}
<file_sep>/app/Domain/Auth/AuthService.php
<?php
namespace App\Domain\Auth;
use JWTAuth;
use App\Domain\User\User;
use Tymon\JWTAuth\Exceptions\JWTException as Exception;
class AuthService
{
public function gerarToken($email, $password)
{
$user = User::where('email', $email)->first();
if (!$user) {
throw new Exception('Usuário não encontrado');
}
if ($user->password !== $password) {
throw new Exception('Senha não confere');
}
return JWTAuth::fromUser($user);
}
}<file_sep>/app/Domain/Auth/AuthController.php
<?php
namespace App\Domain\Auth;
use Illuminate\Http\Request;
use JWTAuth;
use Exception;
class AuthController
{
protected $service;
public function __construct()
{
$this->service = new AuthService();
}
public function authenticate(Request $request)
{
$token = $this->service->gerarToken($request->email, $request->password);
try {
return response(compact('token'));
} catch (Exception $e) {
return response('Verifique o seu E-Mail ou/e Senha');
}
}
public function refresh()
{
$token = JWTAuth::refresh(JWTAuth::getToken());
return response(compact('token'));
}
}
<file_sep>/database/seeds/StateSeeder.php
<?php
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use App\Domain\Localization\State\State;
class StateSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('states')->delete();
$faker = Faker::create();
$states = collect([
["Acre", "ac"],
["Alagoas", "al"],
["Amazonas", "am"],
["Amapá", "ap"],
["Bahia", "ba"],
["Ceará", "ce"],
["Destrito Federal", "df"],
["Espírito Santo", "es"],
["Goiás", "go"],
["Maranhão", "ma"],
["Mato Grosso", "mt"],
["Mato Grosso do Sul", "ms"],
["Minas Gerais", "mg"],
["Pará", "pa"],
["Paraíba", "pb"],
["Paraná", "pr"],
["Pernambuco", "pe"],
["Piauí", "pi"],
["Rio de Janeiro", "rj"],
["Rio Grande do Norte", "rn"],
["Rondônia", "ro"],
["Rio Grande do Sul", "rs"],
["Roraima", "rr"],
["Santa Catarina", "sc"],
["Segipe", "se"],
["São Paulo", "sp"],
["Tocantins", "to"]
]);
$states->each(function ($array) use ($faker) {
State::create([
'id' => $faker->uuid,
'name' => $array[0],
'initials' => $array[1],
]);
});
}
}
<file_sep>/app/Domain/School/Aluno/AlunoController.php
<?php
namespace App\Domain\School\Aluno;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AlunoController extends Controller
{
public function index(Request $request)
{
return AlunoResource::collection(
Aluno::where(function ($query) use ($request) {
$query->where('name', 'like', "%{$request->search}%")
->orWhere('cpf', 'like', "%{$request->search}%");
})->paginate()
);
}
public function store(AlunoRequest $alunoRequest)
{
$aluno = factory(Aluno::class)->create([
'name' => $alunoRequest->name,
'cpf' => $alunoRequest->cpf,
'curso_id' => $alunoRequest->curso_id,
'city_id' => $alunoRequest->city_id,
'state_id' => $alunoRequest->state_id,
'faltas' => $alunoRequest ?? 0,
]);
return response(new AlunoResource($aluno), 201);
}
public function show(Aluno $aluno)
{
return response(new AlunoResource($aluno), 200);
}
public function update(AlunoRequest $alunoRequest, Aluno $aluno)
{
$aluno->update([
'name' => $alunoRequest->name,
'cpf' => $alunoRequest->cpf,
'curso_id' => $alunoRequest->curso_id,
'city_id' => $alunoRequest->city_id,
'state_id' => $alunoRequest->state_id,
'faltas' => $alunoRequest->faltas ?? 0,
]);
return response(new AlunoResource($aluno), 200);
}
public function destroy(Aluno $aluno)
{
$aluno->delete();
return response('', 204);
}
}
<file_sep>/app/Http/Controllers/PeopleController.php
<?php
namespace App\Http\Controllers;
use App\People;
use http\Env\Response;
use Illuminate\Http\Request;
use Webpatser\Uuid\Uuid;
class PeopleController extends Controller
{
public function index()
{
$people = People::all();
return Response()->json([
'people' => $people,
]);
}
public function show(String $id)
{
$people = People::findOrFail($id);
return Response()->json([
'people' => $people,
]);
}
public function update(Request $request)
{
$request->validate([
'id' => 'required',
]);
$people = People::findOrFail($request->id);
$people->first_name = isset($request->first_name) ? $request->first_name : $people->first_name;
$people->last_name = isset($request->last_name) ? $request->last_name : $people->last_name;
$people->bith_date = isset($request->bith_date) ? $request->bith_date : $people->bith_date;
if (!$people->save()) return $this->messageResponse( 500);
$this->messageResponse(200);
}
public function destroy(String $id)
{
$people = People::findOrFail($id);
if (!$people->delete()) return $this->messageResponse(500);
return $this->messageSuccess(200);
}
}
<file_sep>/app/Domain/Localization/State/State.php
<?php
namespace App\Domain\Localization\State;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class State extends Model
{
use SoftDeletes;
public $incrementing = false;
protected $keyType = 'string';
protected $fillable = [
'name',
'initials',
];
const COLUMNS = [
'id',
'name',
'initials',
'created_at',
'updated_at',
];
protected $hidden = [
'created_at',
'updated_at',
'deleted_at',
];
public static function initial ($initials)
{
return State::where('initials', $initials)->first();
}
public function cities()
{
return $this->hasMany('App\Domain\Localization\City\City');
}
}
<file_sep>/app/Others/Debug/DB/UltimoScriptRodadoEloquent.php
<?php
//1º Mais usado funciona 80% das vezes.
\DB::listen(function ($sql) {
$pattern = str_replace('?', '%s', $sql->sql);
$bindings = array_map(function ($binding) {
if (is_bool($binding)) {
return var_export($binding, true);
}
return sprintf("'%s'", $binding);
}, $sql->bindings);
$data = vsprintf($pattern, $bindings);
dd($data);
echo '<pre>';
print_r($data);
echo PHP_EOL . '##########' . PHP_EOL;
});
//2º Funcionou em alguma vezes que o primeiro falhou.
DB::enableQueryLog();
$queries = DB::getQueryLog();
dd($queries);
<file_sep>/app/Service/Statistics.php
<?php
namespace Modules\CRM\Services\Statistics;
use App\Helpers\Helper;
use Carbon\Carbon;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Collection;
class Statistics
{
const DAILY = 'daily';
const WEEKLY = 'weekly';
const MONTHLY = 'monthly';
const RETURN_PERIOD_AS_STRING = 'string';
/** @var Builder */
private $query;
/** @var string */
private $dateColumn = 'created_at';
/** @var int */
private $quantidadePeriodos = 6;
/** @var string */
private $periodo;
/** @var Carbon */
private $dataFinal;
/** @var Carbon */
private $dataInicial;
/** @var array */
private $indicadores = [];
/** @var Collection */
private $data;
/** @var Collection */
private $rowsByPeriod;
/** @var string */
private $returnPeriodAs;
/** @var Collection */
private $dataWithIndicadors;
public function __construct($query)
{
$this->data = new Collection();
$this->rowsByPeriod = new Collection();
$this->dataWithIndicadors = new Collection();
$this->query = $query;
$this->setDataFinal(Carbon::now());
}
public function setDataFinal($dataFinal)
{
$this->dataFinal = $dataFinal;
}
public static function ofQuery($query)
{
return new self($query);
}
public function setInterval($periodoEscolhido, $quantidadePeriodo, $returnPeriodAs = 'default')
{
$this->setPeriodo($periodoEscolhido);
$this->quantidadePeriodos = $quantidadePeriodo;
$this->setReturnAs($returnPeriodAs);
$this->setDataInicial($this->getDataAtualMenosPeriodos());
}
/**
* @return Carbon
*/
private function getDataAtualMenosPeriodos()
{
$subPeriodos = [
self::DAILY => 'subDays',
self::WEEKLY => 'subWeeks',
self::MONTHLY => 'subMonths',
];
$periodoEscolhido = $subPeriodos[$this->periodo];
return Carbon::today()->$periodoEscolhido($this->quantidadePeriodos - 1);
}
public function addIndicador($nomeIndicador, $closure)
{
$this->indicadores[$nomeIndicador] = $closure;
}
public function make()
{
$this->getDataFromQuery();
$this->setRowsByPeriod();
$this->runIndicadorsOnPeriod();
return $this->dataWithIndicadors;
}
private function getDataFromQuery()
{
$this->setDateBetween($this->dataInicial, $this->dataFinal);
$this->data = $this->query->get();
}
private function setRowsByPeriod()
{
$column = $this->dateColumn;
$carbonPeriod = $this->getCarbonPeriod();
$this->rowsByPeriod = $this
->data
->groupBy(function ($row) use ($column, $carbonPeriod) {
$period = Carbon::parse($row->$column)->$carbonPeriod;
return $this->transformPeriodIfNeeded($period);
});
}
/**
* @return mixed
*/
private function getCarbonPeriod()
{
$periodosDisponiveis = [
'daily' => 'dayOfWeek',
'weekly' => 'weekOfYear',
'monthly' => 'month',
];
return $periodosDisponiveis[$this->periodo];
}
private function transformPeriodIfNeeded($period)
{
if ($this->returnPeriodAs == self::RETURN_PERIOD_AS_STRING) {
return $this->getPeriodAsString($period);
}
return $period;
}
/**
* @param $period
*
* @return mixed|string
*/
private function getPeriodAsString($period)
{
if ($this->periodo == self::DAILY) {
return Helper::converteDiaDaSemanaParaString($period);
}
if ($this->periodo == self::MONTHLY) {
return Helper::converteMesParaString($period);
}
return $period;
}
private function runIndicadorsOnPeriod()
{
$this->dataWithIndicadors = $this
->rowsByPeriod
->map(function ($periodo) {
$indicadors = [];
foreach ($this->indicadores as $indicador => $closure) {
$indicadors[$indicador] = call_user_func($closure, $periodo);
}
return collect($indicadors);
});
}
public function getPeriods()
{
return $this
->dataWithIndicadors
->keys();
}
/**
* @param string $dateColumn
*/
public function setDateColumn($dateColumn)
{
$this->dateColumn = $dateColumn;
}
/**
* @param $startDate
* @param $endDate
*/
public function setDateBetween($startDate, $endDate)
{
$this
->query
->whereBetween($this->dateColumn, [$startDate, $endDate])
->oldest($this->dateColumn);
}
/**
* @param $carbon
*/
public function setDataInicial($carbon)
{
$this->dataInicial = $carbon;
}
/**
* @param $periodoEscolhido
*/
public function setPeriodo($periodoEscolhido)
{
$this->periodo = $periodoEscolhido;
}
/**
* @param $returnPeriodAs
*/
public function setReturnAs($returnPeriodAs)
{
$this->returnPeriodAs = $returnPeriodAs;
}
}
<file_sep>/tests/Feature/CityControllerTest.php
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;
/*
* @group city
* @group Localization
*/
class CityControllerTest extends TestCase
{
use DatabaseTransactions;
private $routeBase = 'api/city';
public function deveRetornarAPrimeiraPagina()
{
$response = $this->json('GET', $this->routeBase);
$response
->assertStatus(200)
->assertJson([
"current_page",
"data",
"first_page_url",
"from",
"last_page",
"last_page_url",
"next_page_url",
"path",
"per_page",
"prev_page_url",
"to",
"total"
]);
}
}
<file_sep>/.env.example
APP_NAME=Laravel
APP_ENV=local
APP_KEY=<KEY>
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=laravel-api-database
DB_PORT=3306
DB_USERNAME=user
DB_PASSWORD=<PASSWORD>
DB_DATABASE=database
BROADCAST_DRIVER=log
CACHE_DRIVER=redis
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=<PASSWORD>
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=<PASSWORD>
MAIL_ENCRYPTION=null
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
JWT_SECRET=<KEY>
<file_sep>/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call('UserSeeder');
//LOCALIZATION
$this->call('StateSeeder');
$this->call('CitySeeder');
//SCHOOL
$this->call('CursoSeeder');
$this->call('AlunoSeeder');
}
}
<file_sep>/app/Domain/School/Aluno/AlunoRequest.php
<?php
namespace App\Domain\School\Aluno;
use Illuminate\Foundation\Http\FormRequest;
class AlunoRequest 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 [
'name' => 'required|max:255',
'cpf' => 'required|min:11|max:11',
'curso_id' => 'required|exists:cursos,id',
'city_id' => 'required|exists:cities,id',
'state_id' => 'required|exists:states,id',
];
}
}
<file_sep>/app/Domain/School/Curso/Curso.php
<?php
namespace App\Domain\School\Curso;
use App\Domain\School\Aluno\Aluno;
use Illuminate\Database\Eloquent\Model;
class Curso extends Model
{
public $incrementing = false;
protected $fillable = [
'name',
'media_aprovacao',
'numero_alunos',
];
public function alunos()
{
return $this->hasMany(Aluno::class);
}
}
<file_sep>/run.sh
!/bin/bash
echo Uploading Application container
docker-compose up -d
echo Copying the configuration example file
docker exec -it laravel_api-app cp .env.example .env
echo Install dependencies
docker exec -it laravel_api-app composer install
echo Generate key
docker exec -it laravel_api-app php artisan key:generate
echo Make migrations
docker exec -it laravel_api-app php artisan migrate
echo Make seeds
docker exec -it laravel_api-app php artisan db:seed
echo Information of new containers
docker ps -a<file_sep>/app/Core/Model.php
<?php
namespace App\Core;
use Illuminate\Database\Eloquent\Model as BaseModel;
class Model extends BaseModel
{
public function scopeFilter($query, $order = true)
{
$filters = request()->all();
$filterClass = get_class($this) . 'Filter';
if (count($filters) > 0 && class_exists($filterClass)) {
$filter = new $filterClass();
$query = $filter->apply($query, $filters, $order);
}
return $query;
}
}<file_sep>/app/Domain/Localization/State/StateController.php
<?php
namespace App\Domain\Localization\State;
use App\Domain\Localization\State\State;
use App\Http\Controllers\Controller;
use App\Domain\Localization\State\StateResource;
use App\Domain\Localization\City\CityResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class StateController extends Controller
{
public function index(Request $request)
{
$states = Cache::remember('states', 1, function () use ($request) {
return State::where('name', 'like', "%{$request->seach}%")
->orWhere('initials', 'like', "%{$request->seach}%");
}
);
return StateResource::collection($states);
}
public function show(State $state)
{
return new StateResource($state);
}
public function cities(Request $request)
{
return CityResource::collection(
State::findOrFail($request->id)
->cities()
->paginate()
);
}
}
<file_sep>/app/GraphQL/Mutations/StateMutation.php
<?php
declare(strict_types=1);
namespace App\GraphQL\Mutations;
use App\Domain\Localization\State\State;
use App\GraphQL\Types\StateType;
use Closure;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Mutation;
use Rebing\GraphQL\Support\SelectFields;
use Rebing\GraphQL\Support\Facades\GraphQL;
class StateMutation extends Mutation
{
protected $attributes = [
'name' => 'state',
'description' => 'A mutation'
];
public function type(): Type
{
return GraphQL::type('state_type');
}
public function args(): array
{
return [
'name' => [
'type' => Type::nonNull(Type::string()),
'description' => 'Nome do estado',
],
'initials' => [
'type' => Type::nonNull(Type::string()),
'description' => 'Initials do estado',
],
];
}
public function resolve($root, $args, $context, ResolveInfo $resolveInfo, Closure $getSelectFields)
{
// $fields = $getSelectFields();
// $select = $fields->getSelect();
// $with = $fields->getRelations();
$state = factory(State::class)->create([
'name' => $args['name'],
'initials' => $args['initials'],
]);
return $state;
}
}
<file_sep>/database/seeds/CursoSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use App\Domain\School\Curso\Curso;
class CursoSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('cursos')->truncate();
factory(Curso::class, 20)->create();
}
}
<file_sep>/tests/Feature/AlunoControllerTest.php
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Domain\User\User;
class AlunoControllerTest extends TestCase
{
private $urlBase = "aluno";
public function __construct()
{
$user = factory(User::class)->create();
dd('qwui');
}
public function test_list_alunos()
{
$response = $this->json('GET', $this->urlBase);
$response->assertStatus(200);
}
}
<file_sep>/app/Domain/Localization/City/CityController.php
<?php
namespace App\Domain\Localization\City;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Domain\Localization\City\CityResource;
class CityController extends Controller
{
public function index(Request $request)
{
return CityResource::collection(
City::where('name', 'like', "%{$request->search}%")
->paginate()
);
}
public function show(City $city)
{
return new CityResource($city);
}
}
<file_sep>/app/Core/RedmineModel.php
<?php
namespace App\Core;
abstract class RedmineModel extends Model
{
const CREATED_AT = 'created_on';
const UPDATED_AT = 'updated_on';
protected $connection = 'redmine';
}<file_sep>/app/Others/Utils/GeradorDocuments.php
<?php
namespace App\Others\Utils;
class GeradorDocuments
{
public static function cnpj($verdadeiro = true)
{
$cnpj = rand(10000000, 99999999) . '0001';
//Primeiro digito verificador
$aux = [5,4,3,2,9,8,7,6,5,4,3,2];
$total = 0;
foreach(str_split($cnpj) as $key => $char)
$total += $char * $aux[$key];
$d1 = 11 - ($total % 11);
$cnpj .= ($d1 >= 10)?'0':$d1;
//Segundo digito verificador
$aux = [6,5,4,3,2,9,8,7,6,5,4,3,2];
$total = 0;
foreach(str_split($cnpj) as $key => $char)
$total += $char * $aux[$key];
$d2= 11 - ($total % 11);
$cnpj .= ($d2 >= 10)?'0':$d2;
if(!$verdadeiro)
return self::shuffleString($cnpj);
return $cnpj;
}
public static function cpf($verdadeiro = true)
{
$cpf = rand(100000000, 999999999);
//Primeiro digito verificador
$aux = [10,9,8,7,6,5,4,3,2];
$total = 0;
foreach(str_split($cpf) as $key => $char)
$total += $char * $aux[$key];
$d1 = 11 - ($total % 11);
$cpf .= ($d1 >= 10)?'0':$d1;
//Segundo digito verificador
$aux = [11,10,9,8,7,6,5,4,3,2];
$total = 0;
foreach(str_split($cpf) as $key => $char)
$total += $char * $aux[$key];
$d2= 11 - ($total % 11);
$cpf .= ($d2 >= 10)?'0':$d2;
if(!$verdadeiro)
return self::shuffleString($cpf);
return $cpf;
}
}<file_sep>/tests/Feature/ModuleTestCase.php
<?php
namespace Modules\ModuleControl\Tests;
use JWTAuth;
use Tests\TestCase;
use Modules\ModuleControl\Entities\Action;
use Modules\ModuleControl\Entities\User;
use Modules\ModuleControl\Traits\ModuleDatabaseMigrations;
abstract class ModuleTestCase extends TestCase
{
use ModuleDatabaseMigrations;
protected $loggedUser;
public function setup()
{
parent::setup();
$this->loggedUser = factory(User::class)->create();
}
private function headers()
{
$token = JWTAuth::fromUser($this->loggedUser);
JWTAuth::setToken($token);
return [
'Accept' => 'application/json',
'Authorization' => sprintf('Bearer %s', $token),
];
}
public function json($method, $uri, array $data = [], array $headers = [])
{
$headers = array_merge($headers, $this->headers());
return parent::json($method, $uri, $data, $headers);
}
/**
* Este método insere a permissão de acesso nescessária para executar a
* operação desejada.
*
* @param string $title Título da Action
* @param string $description Descrição da Action
* @param string $method Método HTTP usado
* @param string $to URL de destino usada nas rotas
*/
public function setAccessPermission(
$title,
$description,
$method,
$to,
$module = 'Sebrae',
$allow_access = 0
) {
$action = Action::create([
'title' => $title,
'description' => $description,
'icon' => 'filter_list',
'to' => $to,
]);
$action->rules()->create([
'module_name' => $module,
'route_uri' => $to,
'route_method' => $method,
'allow_access' => $allow_access,
]);
$this->loggedUser->permissions()->attach([
$action->id
]);
}
}
<file_sep>/app/Core/Filter.php
<?php
namespace App\Core;
abstract class Filter
{
/**
* Query order by field name.
*
* @var string
*/
protected $orderKey;
/**
* Query order by direction.
*
* @var string
*/
protected $orderDirection;
/**
* Query filters values.
*
* @var array
*/
protected $filters;
/**
* Allow to set order by.
*
* @var boolean
*/
protected $allowOrder;
/**
* Aplly filters to the query.
*
* @param Illuminate\Database\Query\Builder $query
* @param array $filters
* @param boolean $order
* @return Illuminate\Database\Query\Builder
*/
public function apply($query, array $filters = [], $allowOrder = true)
{
$this->allowOrder = $allowOrder;
$this->filters = $filters;
foreach ($this->filters as $methodName => $filter) {
if ($filter && method_exists($this, $methodName)) {
$query = $this->{$methodName}($query, $filter);
}
}
return $query;
}
/**
* Change the query order field.
*
* @param Illuminate\Database\Query\Builder $query
* @param string $key
* @return Illuminate\Database\Query\Builder
*/
public function order($query, $key)
{
if (!$this->allowOrder) {
return $query;
}
$direction = isset($this->filters['direction']) ? $this->filters['direction'] : 'asc';
return $query->orderByRaw($key.' '.strtoupper($direction));
}
}
<file_sep>/app/Domain/Localization/City/City.php
<?php
namespace App\Domain\Localization\City;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class City extends Model
{
use SoftDeletes;
public $incrementing = false;
protected $primaryKey = 'id';
const COLUMNS = [
'id',
'name',
'created_at',
'updated_at',
];
protected $hidden = [
'created_at',
'updated_at',
'deleted_at',
];
public function scopeState($query)
{
return $query->where('state_id');
}
}
|
862009cb51484a55b35104e4f4310d9a603b3871
|
[
"Markdown",
"Shell",
"PHP"
] | 41 |
Markdown
|
piovani/laravel_api
|
78b25b7032ef8486bd19ebf7e4b7a2efbf39c78f
|
27e197db919b652b9101213c14b67ebe2b16d9fe
|
refs/heads/master
|
<file_sep>//Click the link below to check out the animation
//https://editor.p5js.org/Bhargavi_Ch/sketches/_Vrrc50S9
var n = 0;
var c = 4;
function setup() {
createCanvas(600, 600);
background(0);
angleMode(DEGREES);
colorMode(HSB);
}
function draw() {
//Formulas taken from the book
//http://algorithmicbotany.org/papers/abop/abop-ch4.pdf
var a = n * 137.5;
var r = c * sqrt(n);
var x = r * cos(a) + width / 2;
var y = r * sin(a) + height / 2;
noStroke();
fill(n % 256, 255, 255);
circle(x, y, 7);
n++;
}<file_sep># Phyllotaxis-Animation-using-p5js
A cool animation of Phyllotaxis pattern using p5js, created by following a tutorial from The coding train
|
f9c2dc8e730e271ea0d55826b4f3259d1518f75e
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
BhargaviChada/Phyllotaxis-Animation-using-p5js
|
36d21f4ea1efa97378e4a2efd0521c8b24b09279
|
84ee93c44748071f11d971ecdceafa902eca8d1f
|
refs/heads/master
|
<repo_name>Gameford/Shematech<file_sep>/game/Assets/Engine/Extensions.cs
using System.Linq;
namespace Engine
{
public static class Extensions
{
/// <summary>
/// Отцентрировать текст в ячейки заданной ширины.
/// </summary>
/// <param name="s">Текст.</param>
/// <param name="desiredLength">Ширина ячейки.</param>
/// <returns>Текст.</returns>
public static string Center(this string s, int desiredLength)
{
if (s.Length >= desiredLength) return s;
var firstpad = (s.Length + desiredLength) / 2;
return s.PadLeft(firstpad).PadRight(desiredLength);
}
/// <summary>
/// Преобразовать цвет в строку и взять первые 2 буквы.
/// </summary>
/// <param name="c">Цвет.</param>
/// <returns>Обрезаный строковой эквивалент цвета.</returns>
public static string ShortFormat(this Color c)
{
return c.ToString().Take(2).Aggregate("", (acc, x) => acc + x);
}
}
}<file_sep>/game/Assets/Engine/ColorCondition.cs
using System.Collections.Generic;
namespace Engine
{
/// <summary>
/// Условный блок, оператор условного перехода. Перемещает шарик влево или вправо,
/// в зависимости от цвета шарика.
/// </summary>
public class ColorCondition : BaseStepable, IInteract
{
/// <summary>
/// Цвет шарика, для перемещения влево.
/// </summary>
public Color MatchColor { get; set; }
/// <summary>
/// Вектор движения в случае совпадения цвета.
/// Если цвет не совпал, движения будет в обратную сторону.
/// </summary>
public Point MoveVector { get; set; }
/// <summary>
/// Создать новый условного блока.
/// </summary>
/// <param name="matchColor">Цвет шариков для совпадения.</param>
/// <param name="moveVector">Вектор движения в случае совпадения цвета.</param>
/// <param name="position">Позиция шарика.</param>
public ColorCondition(Color matchColor, Point moveVector, Point position)
{
MatchColor = matchColor;
MoveVector = moveVector;
_position = position;
_actions = new List<StepAction>();
}
/// <summary>
/// Создать новый условного блока.
/// </summary>
/// <param name="matchColor">Цвет шариков для совпадения.</param>
/// <param name="moveVector">Вектор движения в случае совпадения цвета.</param>
/// <param name="x">Координата по X.</param>
/// <param name="y">Координа по Y.</param>
public ColorCondition(Color matchColor, Point moveVector, int x, int y)
: this(matchColor, moveVector, new Point(x, y))
{
}
public void Interact(Ball ball)
{
if (!ball.Color.Equals(MatchColor))
{
_actions.Add(new StepAction(ActionType.ConditionFalse, null, GetPosition()));
// Движение в другую сторону.
var newPoint = new Point(MoveVector.X * -1, MoveVector.Y);
ball.Move(newPoint);
return;
}
_actions.Add(new StepAction(ActionType.ConditionTrue, null, GetPosition()));
ball.Move(MoveVector);
}
public override string DebugPrint()
{
if (MoveVector.X >= 0)
{
return string.Format(
"-IF|{0}+",
MatchColor.ShortFormat()
).Center(10);
}
return string.Format(
"+IF|{0}-",
MatchColor.ShortFormat()
).Center(10);
}
}
}<file_sep>/game/Assets/EngineFrontend/Generator.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using e = Engine;
public class Generator : MonoBehaviour {
public e.BallGenerator BallGenerator;
public float time = 0;
public int step = 0;
private bool active = false;
void Update () {
if (!this.active) { return; }
time += Time.deltaTime;
if (time >= 1) {
time = 0;
var actions = this.BallGenerator.GetActions()[step];
if (actions.Type == e.ActionType.Nope) { return; }
this.transform.position = new Vector2(actions.Position.X, actions.Position.Y);
Debug.Log("Generator: " + actions.Type);
switch (actions.Type) {
case e.ActionType.GenerateNewBall:
Debug.Log("GENERATE NEW BALL!!!!");
break;
}
step++;
}
}
}
<file_sep>/game/Assets/Engine/Game.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Engine
{
[System.Serializable]
public class BallHistory
{
private List<Ball> _balls;
private BallHistory()
{
_balls = new List<Ball>();
}
public List<Ball> GetList () {
return this._balls;
}
private static BallHistory _instance;
public static BallHistory GetInstance()
{
if (_instance == null) {
_instance = new BallHistory();
}
return _instance;
}
public void AddBall(Ball ball)
{
var findBall = _balls.FindIndex(b => b.ID == ball.ID);
if (findBall == -1)
{
_balls.Add(ball);
}
else
{
_balls.RemoveAt(findBall);
_balls.Add(ball);
}
}
public void Clear() {
this._balls.Clear();
}
}
public class StepCounter
{
private int _counter;
public void Inc()
{
_counter++;
}
public int GetCounter()
{
return _counter;
}
private StepCounter()
{}
private static StepCounter _instance;
public static StepCounter GetInstance()
{
return _instance ?? (_instance = new StepCounter());
}
}
public class Game
{
private IList<IStepable> currentWorld;
/// <summary>
/// Создать экземпляр пустого мира.
/// </summary>
public Game()
{
currentWorld = new List<IStepable>();
}
/// <summary>
/// Получить обьект на позиции, за исключением шарика.
/// </summary>
/// <param name="point">Точка в которой необходимо получить обьект.</param>
/// <param name="world">Мир в котором будет выполнен поиск.</param>
/// <returns></returns>
public static IStepable GetByPos(Point point, IEnumerable<IStepable> world)
{
if (world == null) throw new ArgumentNullException("world");
return world.FirstOrDefault(e => e.GetPosition().Equals(point) && !(e is Ball));
}
/// <summary>
/// Выполнить один шаг игрового мира.
/// </summary>
/// <returns>Новый мир.</returns>
public IList<IStepable> Step()
{
var newWorld = new List<IStepable>();
foreach (var elem in currentWorld) elem.Step(currentWorld, newWorld);
StepCounter.GetInstance().Inc();
currentWorld = newWorld;
return newWorld;
}
/// <summary>
/// Добавить новый обьект в текущий мир.
/// </summary>
/// <param name="obj">Добавляемый обьект.</param>
public void AddObject(IStepable obj)
{
currentWorld.Add(obj);
}
/// <summary>
/// Удалить обьект из мира.
/// </summary>
/// <param name="obj">Удаляемый обьект.</param>
public void RemoveObject(IStepable obj)
{
currentWorld.Remove(obj);
}
/// <summary>
/// Получить обьекты в позиции.
/// </summary>
/// <param name="pos">Позиция.</param>
/// <returns>Массив обьектов.</returns>
public IList<IStepable> GetObjectsByPos(Point pos)
{
return currentWorld.Where(x => x.GetPosition().Equals(pos)).ToList();
}
/// <summary>
/// Получить текущий мир.
/// </summary>
public IList<IStepable> GetCurrentWorld()
{
return currentWorld;
}
public override string ToString()
{
var items = GetCurrentWorld();
var worldWidth = items.Max(x => x.GetPosition().X);
var worldHeight = items.Max(x => x.GetPosition().Y);
worldWidth = worldWidth == 0 ? 1 : worldWidth + 1;
worldHeight = worldHeight == 0 ? 1 : worldHeight + 1;
var all = "";
for (var i = 0; i < worldHeight + 1; i++)
{
var line = "";
for (var j = 0; j < worldWidth + 1; j++)
{
var item = GetObjectsByPos(new Point(j, i));
if (item.Count == 0)
{
line += String.Format("{0},{1}", i, j).Center(10);
continue;
}
line += item.First().ToString();
}
all += String.Format("{0}\n", line);
}
return all;
}
}
}<file_sep>/game/Assets/Scripts/MainMenuEvents.cs
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenuEvents : MonoBehaviour {
public void StartGame() {
SceneManager.LoadScene("MainGameScene");
}
}
<file_sep>/game/Assets/EngineFrontend/ColorSwitch.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using e = Engine;
public class ColorSwitch : MonoBehaviour {
public e.ColorSwitch ColorSwitcher;
public Sprite[] sprites;
public Dictionary<e.Color, Sprite> spritesDict = null;
public float time = 0;
public int step = 0;
public e.Color color;
public bool active = false;
void Awake(){
spritesDict = new Dictionary<e.Color, Sprite> {
{e.Color.Green, sprites[0]},
{e.Color.Purple, sprites[1]},
{e.Color.Blue, sprites[2]},
{e.Color.Yellow, sprites[3]},
{e.Color.Red, sprites[4]}
};
}
}
<file_sep>/game/Assets/EngineFrontend/ConditionBlock.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using e = Engine;
public class ConditionBlock : MonoBehaviour
{
public e.Color color;
public Sprite[] sprites;
public Dictionary<e.Color, Sprite> spritesDict = null;
public float time = 0;
public int step = 0;
public bool active = false;
void Awake(){
spritesDict = new Dictionary<e.Color, Sprite> {
{e.Color.Green, sprites[0]},
{e.Color.Purple, sprites[1]},
{e.Color.Blue, sprites[2]},
{e.Color.Yellow, sprites[3]},
{e.Color.Red, sprites[4]}
};
}
}
<file_sep>/game/Assets/Scripts/Extenstions.cs
using Unity;
using UnityEngine;
public static class Extensions {
public static void MoveTo(this Transform transform, Vector2 pos, float zIndex = 0f) {
transform.SetPositionAndRotation(new Vector3(pos.x, pos.y, zIndex), new Quaternion (0,0,0,0));
}
public static void MoveTo(this Transform transform, Vector3 pos, float zIndex = 0f) {
transform.MoveTo(new Vector2(pos.x, pos.y), zIndex);
}
public static void MoveTo(this Transform transform, float x, float y, float z = 0f) {
transform.MoveTo(new Vector3(x, y, z));
}
}<file_sep>/game/Assets/Engine/Core.cs
using System.Collections.Generic;
using System.Diagnostics;
namespace Engine
{
/// <summary>
/// Интерфейс взаимодействия блока с шариком.
/// </summary>
public interface IInteract
{
/// <summary>
/// Производит взаимодействие с шариком, путем изменения состояния шара.
/// </summary>
/// <param name="ball">Шарик для изменений.</param>
void Interact(Ball ball);
}
/// <summary>
/// Интерфейс определяющий действия, которые обьект выполняет на одном шаге.
/// </summary>
public interface IStepable
{
void Step(IList<IStepable> oldWorld, IList<IStepable> newWorld);
/// <summary>
/// Получить текущую позицию.
/// </summary>
/// <returns>Позиция в мире.</returns>
Point GetPosition();
/// <summary>
/// Установить новую позицию.
/// </summary>
/// <param name="point">Новая позиция.</param>
void SetPosition(Point point);
/// <summary>
/// Установить новую позицию.
/// </summary>
/// <param name="x">Позиция по X.</param>
/// <param name="y">Позиция по Y.</param>
void SetPosition(int x, int y);
/// <summary>
/// Вывести в консоль внутреннее представление обьекта.
/// </summary>
/// <returns></returns>
string DebugPrint();
IList<StepAction> GetActions();
}
public abstract class BaseStepable : IStepable
{
protected IList<StepAction> _actions;
protected Point _position;
public virtual Point GetPosition()
{
return _position;
}
public virtual void SetPosition(Point point)
{
_position = point;
}
public virtual void SetPosition(int x, int y)
{
_position = new Point(x, y);
}
public virtual IList<StepAction> GetActions()
{
return _actions;
}
public virtual void Step(IList<IStepable> oldWorld, IList<IStepable> newWorld)
{
_actions.Add(new StepAction(ActionType.Nope, null, GetPosition()));
newWorld.Add(this);
}
public override string ToString()
{
return DebugPrint();
}
public abstract string DebugPrint();
}
}<file_sep>/game/Assets/Scripts/Level.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using e = Engine;
[System.Serializable]
public class Level : MonoBehaviour {
public e.Game game;
private e.BallHistory ballHistory;
public int yellowBallsCount;
public int redBallsCount;
public int blueBallsCount;
public int greenBallsCount;
public int purpleBallsCount;
private Dictionary<e.Color, int> balls = null;
public GameObject GeneratorPrefab;
public GameObject ColorSwitchPrefab;
public GameObject BallPrefab;
private bool isPlay;
void Start () {
balls = new Dictionary<e.Color, int> {
{e.Color.Red, redBallsCount},
{e.Color.Green, greenBallsCount},
{e.Color.Blue, blueBallsCount},
{e.Color.Purple, purpleBallsCount},
{e.Color.Yellow, yellowBallsCount}
};
ballHistory = e.BallHistory.GetInstance();
ballHistory.Clear();
var basket = new e.Bascket(e.Color.Green, 3, 7);
var basket2 = new e.Bascket(e.Color.Green, 1, 7);
var basket3 = new e.Bascket(e.Color.Green, 2, 7);
var dog = new e.Dog(2, 1);
this.game = new e.Game();
game.AddObject(basket);
game.AddObject(basket2);
game.AddObject(basket3);
game.AddObject(dog);
}
float time = 0.0F;
public void Play () {
var g = new e.BallGenerator(balls, 2, -1);
game.AddObject(g);
for (var i = 0; i < 350; i++) {
game.Step();
}
foreach(var obj in game.GetCurrentWorld()) {
if (obj is e.ColorSwitch) {
var clone = Instantiate(this.ColorSwitchPrefab);
clone.GetComponent<ColorSwitch>().ColorSwitcher = obj as e.ColorSwitch;
clone.GetComponent<ColorSwitch>().active = true;
}
}
for (var i = 0; i < ballHistory.GetList().Count; i++ ) {
var ball = ballHistory.GetList()[i];
var clone = Instantiate(this.BallPrefab, GeneratorPrefab.transform.position, GeneratorPrefab.transform.rotation);
clone.GetComponent<Ball>().eBall = ball;
e.Color originColor = ball.GetActions()[0].Color;
clone.GetComponent<SpriteRenderer>().sprite = clone.GetComponent<Ball>().GetSpriteByColor(originColor);
}
var grid = GameObject.Find("Grid").GetComponent<GridInit>();
int height = grid.height;
int width = grid.width;
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
grid.cellsArray[i,j].GetComponent<SpriteRenderer>().enabled = false;
}
}
}
}
<file_sep>/game/Assets/LevelDescription.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelDescription : MonoBehaviour {
[Header("Green Switchers")] public int GreenSwitchersCount;
[Header("Red Switchers")] public int RedSwitchersCount;
[Header("Purple Switchers")] public int PurpleSwitchersCount;
[Header("Green Conditions")] public int GreenConditionsCount;
[Header("Red Conditions")] public int RedConditionsCount;
[Header("Purple Conditions")] public int PurpleConditionsCount;
[Header("Base scene")] int[,] width;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/game/Assets/Scripts/ControlBlock.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ControlBlock : MonoBehaviour {
public enum BlockType
{
cbCondition = 0,
cbAction = 1,
cbCicle = 2
}
[Header("BlockType")]
public BlockType blockType;
public BlockType GetBlockType(){
return blockType;
}
}
<file_sep>/game/Assets/Engine/ColorSwitch.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Engine
{
/// <summary>
/// Блок смены цвета.
/// </summary>
public class ColorSwitch : BaseStepable, IInteract
{
/// <summary>
/// Цвет, для которого будет выполнена смена.
/// Если цвет отличается от данного, то смена цвета не будет
/// произведена.
/// </summary>
public Color FromColor { get; set; }
/// <summary>
/// Цвет замены, шарик после прохода блока сменит цвет на данный.
/// </summary>
public Color ToColor { get; set; }
/// <summary>
/// Создать новый экземпляр блока смены цвета.
/// </summary>
/// <param name="fromColor">Необходимый цвет для смены.</param>
/// <param name="toColor">Цвет после смены.</param>
/// <param name="position">Позиция.</param>
public ColorSwitch(Color fromColor, Color toColor, Point position)
{
FromColor = fromColor;
ToColor = toColor;
_position = position;
_actions = new List<StepAction>();
}
/// <summary>
/// Создать новый экземпляр блока смены цвета.
/// </summary>
/// <param name="fromColor">Необходимый цвет для смены.</param>
/// <param name="toColor">Цвет после смены.</param>
/// <param name="x">Координата по X</param>
/// <param name="y">Координата по Y</param>
public ColorSwitch(Color fromColor, Color toColor, int x, int y)
: this(fromColor, toColor, new Point(x, y))
{
}
/// <summary>
/// Создать новый экземпляр блока смены цвета.
/// Блок смены цвета будет иметь начальные значения:
/// Необходимый цвет - Green;
/// Цвет после смены - Green;
/// Позиция - X: 0, Y: 0;
/// </summary>
public ColorSwitch()
: this(default(Color), default(Color), default(Point))
{
}
public void Interact(Ball ball)
{
if (false && !ball.Color.Equals(FromColor))
{
_actions.Add(new StepAction(ActionType.SwitcherNope, null, GetPosition()));
return;
}
ball.Color = ToColor;
ball.GetActions().Add(new Ball.StepAction(ActionType.BallChangeColor, this, ball.GetPosition(), ball.Color));
ball.Move(0, 1);
ball.GetActions().Add(new Ball.StepAction(ActionType.BallMove, this, ball.GetPosition(), ball.Color));
}
public override string DebugPrint()
{
return string.Format(
"C|{0}>{1}",
FromColor.ShortFormat(),
ToColor.ShortFormat()).Center(10
);
}
}
}<file_sep>/game/Assets/LevelChangeEvents.cs
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelChangeEvents : MonoBehaviour
{
public void StartGame(int level_number){
SceneManager.LoadScene(string.Format("Level_{0}", level_number));
}
}
<file_sep>/game/Assets/Engine/Point.cs
namespace Engine
{
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
/// <summary>
/// Создать новый экземпляр точки.
/// </summary>
/// <param name="x">Координата по X</param>
/// <param name="y">Координата по Y</param>
public Point(int x, int y)
{
X = x;
Y = y;
}
/// <summary>
/// Создать новый экземпляр точки на основе существующей.
/// </summary>
/// <param name="other">Существующая точка.</param>
public Point(Point other)
{
X = other.X;
Y = other.Y;
}
public override bool Equals(object other)
{
if (!(other is Point)) return false;
var otherPoint = (Point) other;
return X == otherPoint.X && Y == otherPoint.Y;
}
public override int GetHashCode()
{
unchecked
{
return (X * 397) ^ Y;
}
}
public override string ToString()
{
return string.Format(
"X: {0}, Y: {1}",
X,
Y
);
}
}
}<file_sep>/game/Assets/Engine/Dog.cs
using System.Collections.Generic;
namespace Engine
{
public class Dog : BaseStepable, IInteract
{
/// <summary>
/// Создать собачку.
/// </summary>
/// <param name="position">Позиция собаки.</param>
public Dog(Point position)
{
_position = position;
_actions = new List<StepAction>();
}
/// <summary>
/// Создать собачку.
/// </summary>
/// <param name="x">Координата по X.</param>
/// <param name="y">Координа по Y.</param>
public Dog(int x, int y)
: this(new Point(x,y))
{
}
public void Interact(Ball ball)
{
_actions.Add(new StepAction(ActionType.BallInteract, null, GetPosition()));
var newPoint = new Point(_position.X - 1, _position.Y);
ball.Move(newPoint);
}
public override string DebugPrint()
{
return "test";
}
}
}
<file_sep>/game/Assets/Scripts/GridInit.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GridInit : MonoBehaviour {
[Header("Ширина")] public int width;
[Header("Высота")] public int height;
[Header("Ширина рамки")] public float border;
[Header("х между клетками")] public float HSpace;
[Header("y между клетками")] public float VSpace;
public Cell[,] cellsArray;
void Start () {
cellsArray = new Cell[height + 1, width];
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
Cell cell = this.gameObject.GetComponentInChildren<Cell>();
float xBase = this.transform.position.x + cell.GetComponent<SpriteRenderer>().bounds.size.x / 2 + border;
float yBase = this.transform.position.y - cell.GetComponent<SpriteRenderer>().bounds.size.y / 2 - border;
float xPos = xBase + (cell.GetComponent<SpriteRenderer>().bounds.size.x + HSpace) * j;
float yPos = yBase - (cell.GetComponent<SpriteRenderer>().bounds.size.y + VSpace) * i ;
Vector3 cellPos = new Vector3(xPos, yPos, 0);
Cell newCell = Instantiate(cell, cellPos, new Quaternion (0,0,0,0));
newCell.GetComponent<SpriteRenderer>().enabled = true;
newCell.GetComponent<CircleCollider2D>().enabled = true;
newCell.transform.parent = this.transform;
newCell.SetPosInGrid(i,j);
cellsArray[i,j] = newCell;
}
}
// Создаем дополнительный ряд, для Корзин
for (int j = 0; j < width; j++){
Cell cell = this.gameObject.GetComponentInChildren<Cell>();
float xBase = this.transform.position.x + cell.GetComponent<SpriteRenderer>().bounds.size.x / 2 + border;
float yBase = this.transform.position.y - cell.GetComponent<SpriteRenderer>().bounds.size.y / 2 - border;
float xPos = xBase + (cell.GetComponent<SpriteRenderer>().bounds.size.x + HSpace) * j;
float yPos = yBase - (cell.GetComponent<SpriteRenderer>().bounds.size.y + VSpace) * height ;
Vector3 cellPos = new Vector3(xPos, yPos, 0);
Cell newCell = Instantiate(cell, cellPos, new Quaternion (0,0,0,0));
newCell.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("Graphics/GameField/ball_exit");
newCell.GetComponent<SpriteRenderer>().enabled = true;
newCell.GetComponent<SpriteRenderer>().sortingLayerName = "UI";
newCell.GetComponent<SpriteRenderer>().sortingOrder = 0;
newCell.GetComponent<CircleCollider2D>().enabled = false;
newCell.transform.parent = this.transform;
newCell.SetPosInGrid(height,j);
cellsArray[height,j] = newCell;
}
}
public bool DropBlock(GameObject block){
Cell rightCell = null;
float minDistance = 999;
foreach(Cell cell in cellsArray){
if(cell.isCollision){
float newDistance = Vector3.Distance(cell.transform.position, block.transform.position);
if(newDistance < minDistance){
minDistance = newDistance;
rightCell = cell;
}
}
}
if (rightCell){
rightCell.isRightCell = true;
block.GetComponent<Dragger>().SetRightCell(rightCell);
return true;
}
return false;
}
}
<file_sep>/README.md
# gameford
Тут будет что-то
Access test
<file_sep>/game/Assets/Scripts/MainGameEvents.cs
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainGameEvents : MonoBehaviour {
public void SwitchToMainMenu() {
SceneManager.LoadScene("MainMenuScene");
}
}
<file_sep>/game/Assets/Scripts/InventorySlot.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class InventorySlot : MonoBehaviour {
public GameObject ColorSwitch;
}
<file_sep>/game/Assets/LevelButtton.cs
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelButtton : MonoBehaviour
{
public int LevelNumber = 0;
}
<file_sep>/game/Assets/EngineFrontend/Ball.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using e = Engine;
public class Ball : MonoBehaviour {
public e.Ball eBall = null;
public Sprite[] sprites;
private Dictionary<e.Color, Sprite> spritesDict = null;
public float time = 0;
public int step = 0;
private Vector3 step_position = Vector3.zero;
void Awake(){
spritesDict = new Dictionary<e.Color, Sprite> {
{e.Color.Green, sprites[0]},
{e.Color.Purple, sprites[1]},
{e.Color.Blue, sprites[2]},
{e.Color.Yellow, sprites[3]},
{e.Color.Red, sprites[4]}
};
step_position = this.transform.position;
}
public Sprite GetSpriteByColor(e.Color color){
return spritesDict[color];
}
// Update is called once per frame
void Update () {
time += Time.deltaTime;
var actions = this.eBall.GetMoveActions();
if (actions.Count > step) {
var action = actions[step];
var grid = GameObject.Find("Grid").GetComponent<GridInit>();
Cell cell = null;
var pos = action.Position;
if (pos.X >= 0 && pos.Y >= 0) {
cell = grid.cellsArray[pos.Y, pos.X];
var cell_actions = this.eBall.GetActionsByCell(pos.X, pos.Y);
foreach(var cell_action in cell_actions) {
switch (cell_action.Type) {
case e.ActionType.BallProduced:
break;
case e.ActionType.BallMove:
if (cell) {
this.transform.position = Vector3.Lerp(this.step_position, cell.transform.position, time);
Vector3 difference = this.step_position - cell.transform.position;
difference.Normalize();
// вычисляемый необходимый угол поворота
float rotation_z = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg - 90;
// Применяем поворот вокруг оси Z
this.transform.rotation = Quaternion.Euler(0f, 0f, rotation_z);
}
else if(false) {
}
break;
case e.ActionType.BallChangeColor:
if(time >= 1){
// TODO Механика получения нужного цвета.
// При расстановке блоков надо сохранять цвет и от бэка получать цвет на который поменяли.
// Для этого при выставлении блока надо сохранять его цвет в бэк
// А для этого цвет надо хранить в экземпляре блока.
e.Color color = cell_action.Color;
this.GetComponent<SpriteRenderer>().sprite = spritesDict[color];
}
break;
}
}
if(this.transform.position == cell.transform.position){
this.step_position = this.transform.position;
step++;
time = 0;
}
}
else {
if(time >= 1){
step++;
time = 0;
}
}
}
}
}
<file_sep>/game/Assets/Scripts/Cell.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cell : MonoBehaviour {
public bool isCollision = false;
public bool isRightCell = false;
public int posInGridX = 0;
public int posInGridY = 0;
void OnTriggerEnter2D(Collider2D collider) {
isCollision = true;
}
void OnTriggerExit2D(Collider2D collider) {
isCollision = false;
}
public void SetPosInGrid(int y, int x){
posInGridX = x;
posInGridY = y;
}
public int[] PosInGrid => new int[2] { posInGridX, posInGridY };
}
<file_sep>/game/Assets/Engine/BallBasket.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Engine
{
[System.Serializable]
/// <summary>
/// Корзина.
/// </summary>
public class Bascket : BaseStepable, IInteract
{
public Color Color { get; set; }
public int CountBall { get; set; }
public int Score { get; set; }
/// <summary>
/// Создать новую корзину.
/// </summary>
/// <param name="color">Цвет шариков попадающих в корзину.</param>
/// <param name="position">Позиция шарика.</param>
public Bascket(Color color, Point position)
{
Color = color;
_position = position;
_actions = new List<StepAction>();
}
/// <summary>
/// Создать новую корзину.
/// </summary>
/// /// <param name="color">Цвет шариков попадающих в корзину.</param>
/// <param name="x">Координата по X.</param>
/// <param name="y">Координа по Y.</param>
public Bascket(Color color, int x, int y)
: this(color, new Point(x, y))
{
}
public void Interact(Ball ball)
{
if (Color.Equals(ball.Color))
{
_actions.Add(new StepAction(ActionType.BascketColorMatched, null, GetPosition()));
Score++;
}
else
{
Score--;
_actions.Add(new StepAction(ActionType.BascketColorMissing, null, GetPosition()));
}
ball.GetActions().Add(new Ball.StepAction(ActionType.BallConsumed, this, GetPosition(), ball.Color));
}
public override string DebugPrint()
{
return String.Format("\\{0}|{1}/", Color.ShortFormat(), Score).Center(10);
}
}
}<file_sep>/game/Assets/Engine/Ball.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Engine
{
[System.Serializable]
/// <summary>
/// Шарик.
/// </summary>
public class Ball : BaseStepable, ICloneable
{
protected bool Equals(Ball other)
{
return ID.Equals(other.ID);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Ball) obj);
}
public override int GetHashCode()
{
return ID.GetHashCode();
}
/// <summary>
/// Цвет шарика.
/// </summary>
public Color Color;
/// <summary>
/// Порядковый номер шаирка
/// </summary>
public int Count;
/// <summary>
/// Уникальный GUID для шарика, необходим для отслеживания истории.
/// </summary>
public Guid ID;
/// <summary>
/// Создать новый экземпляр шарика.
/// </summary>
/// <param name="color">Цвет шарика.</param>
/// <param name="position">Позиция шарика.</param>
public Ball(Color color, Point position, Guid id, int count)
{
Color = color;
_position = position;
ID = id;
_actions = new List<StepAction>();
Count = count;
}
/// <summary>
/// Создать новый экземпляр шарика.
/// </summary>
/// <param name="color">Цвет шарика.</param>
/// <param name="x">Координата по X.</param>
/// <param name="y">Координа по Y.</param>
public Ball(Color color, int x, int y)
: this(color, new Point(x, y), Guid.NewGuid(), 0)
{
}
/// <summary>
/// Создать новый экземпляр шарика.
/// Шарик будет иметь начальные значения:
/// Цвет - Green;
/// Позиция - X: 0, Y: 0;
/// </summary>
public Ball(Guid id) : this(default(Color), default(Point), id, 0)
{
}
/// <summary>
/// Создать новый экземпляр шарика.
/// Шарик будет иметь начальные значения:
/// Цвет - Green;
/// Позиция - X: 0, Y: 0;
/// </summary>
public Ball(Guid id, int count) : this(default(Color), default(Point), id, 0)
{
}
/// <summary>
/// Создать новый экземпляр шарика.
/// Шарик будет иметь начальные значения:
/// Цвет - Green;
/// Позиция - X: 0, Y: 0;
/// </summary>
public Ball() : this(default(Color), default(Point), Guid.NewGuid(), 0)
{
}
/// <summary>
/// Создать новый экземпляр шарика.
/// Шарик будет иметь начальные значения:
/// Цвет - Green;
/// Позиция - X: 0, Y: 0;
/// </summary>
public Ball(int count) : this(default(Color), default(Point), Guid.NewGuid(), count)
{
}
/// <summary>
/// Склонировать текущий шарик.
/// </summary>
/// <returns>Новый обьект шарика.</returns>
public object Clone()
{
var newBall = new Ball(ID);
newBall.SetPosition(GetPosition());
newBall.Color = Color;
newBall._actions = _actions.ToList();
return newBall;
}
public override string DebugPrint()
{
return string.Format("B-{0}", Color.ShortFormat()).Center(10);
}
public override void Step(IList<IStepable> oldWorld, IList<IStepable> newWorld)
{
if (_actions.Last().Type == ActionType.BallConsumed)
{
return;
}
var ball = Clone() as Ball;
Debug.Assert(ball != null, "ball != null");
while(Count>0){
ball.GetActions().Add(new StepAction(ActionType.Nope, null, ball.GetPosition(), ball.Color));
Count--;
}
var otherBlock = Game.GetByPos(ball.GetPosition(), oldWorld) as IInteract;
if (otherBlock != null)
{
ball.GetActions().Add(new StepAction(ActionType.BallInteract, otherBlock, ball.GetPosition(), ball.Color));
otherBlock.Interact(ball);
}
else
{
ball.Move(0, 1);
ball.GetActions().Add(new StepAction(ActionType.BallMove, null, ball.GetPosition(), ball.Color));
}
BallHistory.GetInstance().AddBall(ball);
newWorld.Add(ball);
}
/// <summary>
/// Сдвинуть шарик на определенное кол-во клеток.
/// </summary>
/// <param name="offsetX">Сдвиг по X.</param>
/// <param name="offsetY">Сдвиг по Y.</param>
public void Move(int offsetX, int offsetY)
{
_position.X += offsetX;
_position.Y += offsetY;
}
/// <summary>
/// Сдвинуть шарик на определенное кол-во клеток.
/// </summary>
/// <param name="point">Вектор движения.</param>
public void Move(Point point)
{
_position.X += point.X;
_position.Y += point.Y;
}
public class StepAction
{
public StepAction(ActionType type, IInteract subject, Point position, Color color)
{
Type = type;
Subject = subject;
Position = position;
CurrentStep = StepCounter.GetInstance().GetCounter();
Color = color;
}
/// <summary>
/// Номер текущего шага.
/// </summary>
public int CurrentStep { get; set; }
/// <summary>
/// Тип действия.
/// </summary>
public ActionType Type { get; set; }
/// <summary>
/// Если тип действия не взаимодействие, то поля не будет (null).
/// </summary>
public IInteract Subject { get; set; }
/// <summary>
/// Позиция в которой произшло событие.
/// </summary>
public Point Position { get; set; }
/// <summary>
/// Цвет в момент события
/// </summary>
public Color Color { get; set; }
}
new protected IList<StepAction> _actions;
new public IList<StepAction> GetActions()
{
return _actions;
}
public IList<StepAction> GetMoveActions()
{
IList<StepAction> move_actions = new List<StepAction>();
foreach (var action in _actions)
{
if (action.Type == ActionType.BallMove || action.Type == ActionType.Nope){
move_actions.Add(action);
}
}
return move_actions;
}
public IList<StepAction> GetActionsByCell(int x, int y)
{
IList<StepAction> cell_actions = new List<StepAction>();
foreach (var action in _actions)
{
if(action.Position.X == x && action.Position.Y == y) {
cell_actions.Add(action);
}
}
return cell_actions;
}
}
}<file_sep>/game/Assets/Engine/StepAction.cs
namespace Engine
{
public enum ActionType
{
/// <summary>
/// Ничего...
/// </summary>
Nope,
/// <summary>
/// Простое движение.
/// </summary>
BallMove,
/// <summary>
/// Взаимодействие с блоком.
/// </summary>
BallInteract,
/// <summary>
/// Появление из генератора.
/// </summary>
BallProduced,
/// <summary>
/// Шарик упал в корзину.
/// </summary>
BallConsumed,
/// <summary>
/// Шарик изменил цвет.
/// </summary>
BallChangeColor,
/// <summary>
/// Генератор создал новый шарик.
/// </summary>
GenerateNewBall,
/// <summary>
/// Условный блок пропустил ширик через себя.
/// </summary>
ConditionNope,
/// <summary>
/// Условный блок толкнул шарик влево.
/// </summary>
ConditionTrue,
/// <summary>
/// Условный блок толкнул шарик право.
/// </summary>
ConditionFalse,
/// <summary>
/// Блок смены цветы не поменял цвет шарику.
/// </summary>
SwitcherNope,
/// <summary>
/// В корзину попал нужный цвет.
/// </summary>
BascketColorMatched,
/// <summary>
/// В корзину попал шарик не того цвета.
/// </summary>
BascketColorMissing
}
public class StepAction
{
public StepAction(ActionType type, IInteract subject, Point position)
{
Type = type;
Subject = subject;
Position = position;
CurrentStep = StepCounter.GetInstance().GetCounter();
}
/// <summary>
/// Номер текущего шага.
/// </summary>
public int CurrentStep { get; set; }
/// <summary>
/// Тип действия.
/// </summary>
public ActionType Type { get; set; }
/// <summary>
/// Если тип действия не взаимодействие, то поля не будет (null).
/// </summary>
public IInteract Subject { get; set; }
/// <summary>
/// Позиция в которой произшло событие.
/// </summary>
public Point Position { get; set; }
}
}<file_sep>/game/Assets/Scripts/Inventory.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using e = Engine;
using cb = ControlBlock;
public class Inventory : MonoBehaviour {
Vector3 switcherItemPosition = new Vector3(0F, 0F, 0F);
Vector3 counterItemPosition = new Vector3(0F, 0F, 0F);
private GameObject [] switcherInInventoryArray = null;
Vector3 conditionItemPosition = new Vector3(0F, 0F, 0F);
private GameObject [] conditionInInventoryArray = null;
private int redSwitcherCounter = 2;
private int greenSwitcherCounter = 2;
private int yellowSwitcherCounter = 2;
private int purpleSwitcherCounter = 2;
private int blueSwitcherCounter = 2;
private int switcherCounter = 0;
private int redConditionCounter = 1;
private int greenConditionCounter = 1;
private int yellowConditionCounter = 1;
private int purpleConditionCounter = 1;
private int blueConditionCounter = 1;
private int conditionCounter = 0;
GameObject draggedBlock = null;
public void OnBlockUp(GameObject block){
this.draggedBlock = block;
}
public void OnBlockDown(GameObject block){
this.draggedBlock = null;
}
void Start(){
switcherCounter = redSwitcherCounter + greenSwitcherCounter + yellowSwitcherCounter + purpleSwitcherCounter + blueSwitcherCounter;
conditionCounter = redConditionCounter + greenConditionCounter + yellowConditionCounter + purpleConditionCounter + blueConditionCounter;
this.switcherInInventoryArray = new GameObject[switcherCounter];
this.conditionInInventoryArray = new GameObject[conditionCounter];
var tmp_switncher = GameObject.Find("Switcher");
tmp_switncher.GetComponent<SpriteRenderer>().enabled = false;
tmp_switncher.GetComponent<Collider2D>().enabled = false;
switcherItemPosition = tmp_switncher.GetComponent<SpriteRenderer>().transform.position;
for (var i=0; i<switcherCounter; i++){
e.Color color = GetSwitcherColor();
tmp_switncher.GetComponent<ColorSwitch>().color = color;
tmp_switncher.GetComponent<SpriteRenderer>().sprite = tmp_switncher.GetComponent<ColorSwitch>().spritesDict[color];
var clone = Instantiate(tmp_switncher);
clone.transform.position = switcherItemPosition;
clone.transform.parent = this.transform;
clone.GetComponent<SpriteRenderer>().enabled = false;
clone.GetComponent<Collider2D>().enabled = false;
this.switcherInInventoryArray[i] = clone;
}
var tmpCondition = GameObject.Find("Condition");
tmpCondition.GetComponent<SpriteRenderer>().enabled = false;
tmpCondition.GetComponent<Collider2D>().enabled = false;
counterItemPosition = tmpCondition.GetComponent<SpriteRenderer>().transform.position;
for (var i=0; i<conditionCounter; i++){
e.Color color = GetConditionColor();
tmpCondition.GetComponent<ConditionBlock>().color = color;
tmpCondition.GetComponent<SpriteRenderer>().sprite = tmpCondition.GetComponent<ConditionBlock>().spritesDict[color];
var clone = Instantiate(tmpCondition);
clone.transform.position = counterItemPosition;
clone.transform.parent = this.transform;
clone.GetComponent<SpriteRenderer>().enabled = false;
clone.GetComponent<Collider2D>().enabled = false;
this.conditionInInventoryArray[i] = clone;
}
ShowNextChangeBlock();
ShowNextConditionBlock();
}
public void FailDropBlock(GameObject block){
switch (block.GetComponent<ControlBlock>().GetBlockType()){
case cb.BlockType.cbAction:
block.transform.position = switcherItemPosition;
ReturnBlockToInventory(block);
break;
case cb.BlockType.cbCondition:
block.transform.position = conditionItemPosition;
//ReturnBlockToInventory(block);
break;
case cb.BlockType.cbCicle:
Debug.Log("Cicle");
break;
}
}
public void SuccedDropBlock(GameObject block){
switch (block.GetComponent<ControlBlock>().GetBlockType()){
case cb.BlockType.cbAction:
ShowNextChangeBlock();
break;
case cb.BlockType.cbCondition:
ShowNextConditionBlock();
break;
case cb.BlockType.cbCicle:
break;
}
}
void ShowNextChangeBlock(){
if (switcherCounter == 0) { return; }
GameObject next_item = this.switcherInInventoryArray[switcherCounter - 1];
next_item.GetComponent<SpriteRenderer>().enabled = true;
next_item.GetComponent<Collider2D>().enabled = true;
switcherCounter--;
}
void ShowNextConditionBlock(){
if (conditionCounter == 0) { return; }
GameObject next_item = this.conditionInInventoryArray[conditionCounter - 1];
next_item.GetComponent<SpriteRenderer>().enabled = true;
next_item.GetComponent<Collider2D>().enabled = true;
conditionCounter--;
}
void ReturnBlockToInventory(GameObject block){
if (switcherCounter > 0){
block.GetComponent<SpriteRenderer>().enabled = false;
block.GetComponent<Collider2D>().enabled = false;
}
this.switcherInInventoryArray[switcherCounter] = block;
switcherCounter++;
}
e.Color GetSwitcherColor(){
if (redSwitcherCounter > 0){
redSwitcherCounter--;
return e.Color.Red;
}
if (greenSwitcherCounter > 0){
greenSwitcherCounter--;
return e.Color.Green;
}
if (yellowSwitcherCounter > 0){
yellowSwitcherCounter--;
return e.Color.Yellow;
}
if (purpleSwitcherCounter > 0){
purpleSwitcherCounter--;
return e.Color.Purple;
}
if (blueSwitcherCounter > 0){
blueSwitcherCounter--;
return e.Color.Blue;
}
return e.Color.Red;
}
e.Color GetConditionColor(){
if (redConditionCounter > 0){
redConditionCounter--;
return e.Color.Red;
}
if (greenConditionCounter > 0){
greenConditionCounter--;
return e.Color.Green;
}
if (yellowConditionCounter > 0){
yellowConditionCounter--;
return e.Color.Yellow;
}
if (purpleConditionCounter > 0){
purpleConditionCounter--;
return e.Color.Purple;
}
if (blueConditionCounter > 0){
blueConditionCounter--;
return e.Color.Blue;
}
return e.Color.Red;
}
}
<file_sep>/game/Assets/Scripts/Dragger.cs
using System;
using System.Collections;
using UnityEngine;
using cb = ControlBlock;
using e = Engine;
class Dragger : MonoBehaviour
{
public bool dragging = false;
public Vector3 delta = new Vector3(0F, 0F, 0F);
public Cell rightCell;
void OnMouseDown()
{
dragging = true;
delta = this.transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (rightCell)
{
rightCell.GetComponent<CircleCollider2D>().enabled = true;
}
}
void OnMouseUp()
{
dragging = false;
if ( !GameObject.Find("Grid").GetComponent<GridInit>().DropBlock(this.gameObject) ){
GameObject.Find("Inventory").GetComponent<Inventory>().FailDropBlock(this.gameObject);
}
else{
GameObject.Find("Inventory").GetComponent<Inventory>().SuccedDropBlock(this.gameObject);
};
}
void Update()
{
if (dragging)
{
this.transform.MoveTo(Camera.main.ScreenToWorldPoint(Input.mousePosition) + delta, 0);
}
}
public void SetRightCell(Cell cell)
{
rightCell = cell;
GameObject obj = rightCell.gameObject;
if (rightCell.isRightCell) {
this.transform.Translate( obj.transform.position.x - this.transform.position.x, obj.transform.position.y - this.transform.position.y, 0F);
rightCell.isRightCell = false;
obj.GetComponent<CircleCollider2D>().enabled = false;
// При отпускании блока, нужно добалять соответсвующий блок в game
var cellPos = rightCell.PosInGrid;
var go = this.gameObject;
e.Game game = GameObject.Find("GameField").GetComponent<Level>().game;
switch (go.GetComponent<ControlBlock>().GetBlockType()){
case cb.BlockType.cbAction:
Debug.Log("cdAction");
var new_act = new e.ColorSwitch(0, this.GetComponent<ColorSwitch>().color, rightCell.posInGridX, rightCell.posInGridY);
game.AddObject(new_act);
break;
case cb.BlockType.cbCondition:
Debug.Log("cbCondition");
var new_cond = new e.ColorCondition(go.GetComponent<ConditionBlock>().color, new e.Point(-1, 0), rightCell.posInGridX, rightCell.posInGridY);
game.AddObject(new_cond);
break;
case cb.BlockType.cbCicle:
break;
}
}
}
}<file_sep>/game/Assets/Engine/BallGenerator.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Engine
{
/// <summary>
/// Генерирует заданое кол-во шариков определенных цветов.
/// Позиция шариков устанавливается в позицию генератора.
/// </summary>
public class BallGenerator : BaseStepable
{
/// <summary>
/// Словарь с цветом шарика и количеством.
/// </summary>
private readonly Dictionary<Color, int> _ballsSettings;
/// <summary>
/// Массив шариков которые нужно создать.
/// </summary>
private readonly List<Ball> _genBalls;
/// <summary>
/// Создать новый экземпляр шарика.
/// Шарик будет иметь начальные значения:
/// Цвет - Green;
/// Позиция - X: 0, Y: 0;
/// </summary>
/// <summary>
/// Создать новый экземпляр блока генератора.
/// </summary>
/// <param name="ballsSettings">Настройки блока.</param>
/// <param name="point">Позиция генератора.</param>
public BallGenerator(Dictionary<Color, int> ballsSettings, Point point)
{
_ballsSettings = ballsSettings;
_genBalls = new List<Ball>();
_position = point;
_actions = new List<StepAction>();
_generateBalls();
}
/// <summary>
/// Создать новый экземпляр блока генератора.
/// </summary>
/// <param name="ballsSettings">Настройки блока.</param>
/// <param name="x">Позиция генератора по X.</param>
/// <param name="y">Позиция генератора по Y.</param>
public BallGenerator(Dictionary<Color, int> ballsSettings, int x, int y)
: this(ballsSettings, new Point(x, y))
{
}
/// <summary>
/// Выполнить случайную сортировку списка.
/// </summary>
/// <param name="list">Список.</param>
/// <typeparam name="T">Тип эллементов списка.</typeparam>
public static void Shuffle<T>(IList<T> list)
{
var rnd = new Random();
var n = list.Count;
while (n > 1)
{
n--;
var k = rnd.Next(n + 1);
var value = list[k];
list[k] = list[n];
list[n] = value;
}
}
/// <summary>
/// Произвести заполнение внутренего хранилища шариками
/// в случайном порядке.
/// </summary>
private void _generateBalls()
{
int ballsCount = 0;
foreach (var pair in _ballsSettings)
for (var i = 0; i < pair.Value; i++)
{
var ball = new Ball(ballsCount) {Color = pair.Key};
ball.SetPosition(GetPosition());
_genBalls.Add(ball);
BallHistory.GetInstance().AddBall(ball);
ballsCount++;
}
Shuffle(_genBalls);
}
public override string DebugPrint()
{
if (_genBalls.Count > 0)
return string.Format("G-{0}-{1}", _genBalls.Count, _genBalls.First().Color.ShortFormat()).Center(10);
return string.Format("G-{0}-EM", _genBalls.Count).Center(10);
}
public override void Step(IList<IStepable> oldWorld, IList<IStepable> newWorld)
{
if (_genBalls.Count <= 0)
{
_actions.Add(new StepAction(ActionType.Nope, null, GetPosition()));
newWorld.Add(this);
return;
}
var ball = _genBalls.First();
ball.GetActions().Add(new Ball.StepAction(ActionType.BallProduced, null, GetPosition(), ball.Color));
_genBalls.Remove(ball);
_actions.Add(new StepAction(ActionType.GenerateNewBall, null, GetPosition()));
newWorld.Add(ball);
newWorld.Add(this);
}
}
}
|
59133e8f3a09fd2b35581f735e30b07c4f30bc4e
|
[
"C#",
"Markdown"
] | 29 |
C#
|
Gameford/Shematech
|
836283df297ab43b80744ab370e39b8f97973dec
|
4e97b81092e126dd88eb23c4cf100cdc65b3c689
|
refs/heads/master
|
<file_sep>/*
* @Author: Ethan
* @Date: 2018-12-20 12:07:04
* @Last Modified by: Ethan
* @Last Modified time: 2018-12-20 17:05:42
*/
import { Sprite } from "../base/Sprite";
import { Director } from "../Director";
import { DataStore } from "../base/DateStore";
// 不断移动陆地类
export class Land extends Sprite {
constructor () {
const image = Sprite.getImage('land');
super(image,0,0,
image.width, image.height,
0, DataStore.getInstance().canvas.height-image.height,
image.width, image.height
);
// 地板的水平变化坐标
this.landX = 0;
// 地板的移动速度
this.landSpeed = Director.getInstance().moveSpeed;
}
draw () {
this.landX = this.landX + this.landSpeed;
if (this.landX > (this.img.width - DataStore.getInstance().canvas.width)) {
this.landX = 0;
}
super.draw(
this.img,
this.srcX,
this.srcY,
this.srcW,
this.srcH,
-this.landX,
this.y,
this.width,
this.height
)
}
}<file_sep>import { DataStore } from "../base/DateStore";
// 积分器类
export class Score {
constructor () {
this.ctx = DataStore.getInstance().ctx;
this.scoreNumber = 0;
// 因为canvas刷新的很快,所以需要一个变量控制加分,只加一次
this.isScore = true;
}
draw () {
// console.log(this.ctx)
this.ctx.font = '25px Arial';
this.ctx.fillStyle = "#333";
this.ctx.fillText(`${this.scoreNumber}`, 20,40);
}
}<file_sep>import { Sprite } from "../base/Sprite";
import { DataStore } from '../base/DateStore';
/*
* @Author: Ethan
* @Date: 2018-12-20 12:07:24
* @Last Modified by: Ethan
* @Last Modified time: 2018-12-20 17:06:39
* @Pencil基类
*/
export class Pencil extends Sprite{
constructor (image, top) {
super(image,
0,0,
image.width, image.height,
// 刚好在右侧看不见的位置
DataStore.getInstance().canvas.width, 0,
image.width, image.height
);
this.top = top;
this.moveSpeed = 2;
}
draw () {
this.x -= this.moveSpeed;
super.draw(
this.img,
0,0,
this.width, this.height,
this.x, this.y,
this.width, this.height
)
}
}<file_sep>// 资源文件加载器,确保图片资源加载完成后才进行渲染
import { Resources } from './Resources';
export class ResourcesLoader {
//1.初始化
constructor () {
this.map = new Map(Resources);
for (let [key, value] of this.map) {
const image = wx.createImage();
image.src = value;
this.map.set(key, image);
}
}
// 全部加载结束函数
onLoaded (callback) {
let loadedCount = 0;
for (let value of this.map.values()) {
value.onload = () => {
loadedCount++;
if (loadedCount >= this.map.size) {
callback(this.map);
}
}
}
}
// 静态工厂
static create () {
return new ResourcesLoader();
}
}<file_sep>import { ResourcesLoader } from "./js/base/ResourcesLoader";
import { Director } from "./js/Director";
import { BackGround } from "./js/runtime/BackGround";
import { DataStore } from "./js/base/DateStore";
import { Land } from './js/runtime/Land';
import { Brids } from "./js/player/Brids";
import { StartButton } from "./js/player/StartButton";
import { Score } from "./js/player/Score";
// 初始化整个游戏的精灵,作为游戏开始的入口
export class Main {
constructor () {
this.canvas = wx.createCanvas();
this.ctx = this.canvas.getContext('2d');
this.dataStore = DataStore.getInstance();
this.director = Director.getInstance();
const loader = ResourcesLoader.create();
loader.onLoaded(map => this.onResourcesFirstLoaded(map));
}
onResourcesFirstLoaded (map) {
// 资源第一次加载
// 游戏资源只需要加载一次即可
// 重新开始只需要重置游戏逻辑即可
/**
* 1.直接将变量附在datastore上的变量是要长期保存的,
* 2.而通过put将 变量放置在datastore的map上的变量是需要不断销毁的
*/
this.dataStore.canvas = this.canvas;
this.dataStore.ctx = this.ctx;
this.dataStore.res = map;
this.init();
}
init () {
// 首先重置游戏是没有结束的
this.director.isGameOver = false;
this.dataStore.put('background', BackGround)
.put('land', Land)
.put('pencils', [])
.put('birds', Brids)
.put('startButton', StartButton)
.put('score', Score);
this.registerEvent();
// 要在游戏逻辑运行之前
this.director.createPencil();
this.director.run();
}
reStart (e) {
const startButton = this.dataStore.get('startButton');
// 手指点击的坐标
let x = e.touches[0].clientX
let y = e.touches[0].clientY
// 起始x坐标
let startX = startButton.x;
// 起始y坐标
let startY = startButton.y;
// 结束x坐标
let endX = startButton.x + startButton.width;
// 结束y坐标
let endY = startButton.y + startButton.height;
if (x >= startX && x <= endX && y >= startY && y <= endY) {
// console.log('重新开始');
this.init();
}
}
registerEvent () {
wx.onTouchStart((e) => {
if (this.director.isGameOver) {
// 点击开始按钮,重新开始游戏
this.reStart(e);
} else {
this.director.birdsEvent();
}
})
}
}
|
bfbbda538ef0be76a4a071dec377b998728b0254
|
[
"JavaScript"
] | 5 |
JavaScript
|
songdongdong123/miniGame
|
480c42a4c1b58565939efc91cca0e24cae970fad
|
343c3f3eb466ac5bc5eb7df039db889fa9deba11
|
refs/heads/master
|
<repo_name>zmfkplj/test<file_sep>/README.md
# test
this is test
this is second commit
|
8d66fa65c5671c367ab6253b023bdf5d096d0ae2
|
[
"Markdown"
] | 1 |
Markdown
|
zmfkplj/test
|
94beefa73d354d16b4dec6da9bbff13a36383008
|
80db4092cc9cb910064dce138cd751f28fb10a1c
|
refs/heads/master
|
<file_sep># MVCCRUD
first spring project
|
91b9bdf2b4ecd2c03900560660f6cfc817ad7092
|
[
"Markdown"
] | 1 |
Markdown
|
iammrnoob3/MVCCRUD
|
c5665139eee85b7559ea96094e276da84f84c69c
|
228434fb2a6653bc70ff377fb6394cd5a81da9a2
|
refs/heads/master
|
<file_sep>define(function() {
var obj={
hi:function(){
console.log('hi');
}
};
return obj;
});
|
238a1f6d1cef1d32fdabd5ad1152b26f8323e8d7
|
[
"JavaScript"
] | 1 |
JavaScript
|
zyip/helloRequireJS
|
1f1ee43cea5c5d21d466eac7b5216f87359b7290
|
62b2c0e2d4b844f5808eb382b7cc6dc2e077939f
|
refs/heads/master
|
<file_sep>// 游戏交互逻辑文件
// 游戏的操作主要是依靠键盘的上、下、左、右来完成,捕获键盘事件
$(document).keydown(function(event){
switch(event.keyCode){
case 37://left
if (moveLeft()) {
generateOneNumber();
isgameover();
}
break;
case 38://up
if (moveUp()) {
generateOneNumber();
isgameover();
}
break;
case 39://right
if (moveRight()) {
generateOneNumber();
isgameover();
}
break;
case 40://down
if (moveDown()) {
generateOneNumber();
isgameover();
}
break;
default :
break;
}
});
//左移动
//首先判断是否可以向左移动
function moveLeft(){
if(!canMoveLeft(board)){
return false;
}
// 向左移动
// 第一步,遍历数字格,判断除第一列外有哪些数字格的值是不为0的
// 第二步,遍历当前值不为0的数字格左边数字格
// 第三步,向左移动逻辑还要分成两种情况
//一种是当前值不为0的数字格左边的数字格必须值为0并且中间的数字格必须值也为0
//一种是当前值不为0的数字格与左边的数字格值相等并且中间的数字格必须值也为0
for(var i=0; i<4; i++){
for(var j=1; j<4; j++){
if(board[i][j] != 0){
for(var k=0; k<j; k++){
//判断当前值不为0的数字格左边的数字格必须值为0并且中间的数字格必须值也为0
if (board[i][k] == 0 && noBlokHorizontalCol(i, k, j, board)) {
showMoveAnimation(i, j, i, k);
board[i][k] = board[i][j];
board[i][j] = 0;
continue;
}
//判断当前值不为0的数字格与左边的数字格值相等并且中间的数字格必须值也为0
else if (board[i][k] == board[i][j] && noBlokHorizontalCol(i, k, j, board) && !hasConflicted[i][k]) {
//move
showMoveAnimation(i, j, i, k);
//add
board[i][k] += board[i][j];
board[i][j] = 0;
//add score
score += board[i][k];
updateScore(score);
hasConflicted[i][k] = true;
continue;
}
}
}
}
}
setTimeout("updateBoardView()",200);
return true;
}
//右移动
//首先判断是否可以向右移动
function moveRight(){
if(!canMoveRight(board)){
return false;
}
// 向右移动
// 第一步,遍历数字格,判断除最后一列外有哪些数字格的值是不为0的
// 第二步,遍历当前值不为0的数字格右边数字格
// 第三步,向右移动逻辑还要分成两种情况
//一种是当前值不为0的数字格右边的数字格必须值为0并且中间的数字格必须值也为0
//一种是当前值不为0的数字格与右边的数字格值相等并且中间的数字格必须值也为0
for(var i=0; i<4; i++){
for(var j=2; j>=0; j--){
if(board[i][j] != 0){
for(var k=3; k>j; k--){
//判断当前值不为0的数字格右边的数字格必须值为0并且中间的数字格必须值也为0
if (board[i][k] == 0 && noBlokHorizontalCol(i, j, k, board)) {
showMoveAnimation(i, j, i, k);
board[i][k] = board[i][j];
board[i][j] = 0;
continue;
}
//判断当前值不为0的数字格与右边的数字格值相等并且中间的数字格必须值也为0
else if (board[i][k] == board[i][j] && noBlokHorizontalCol(i, j, k, board) && !hasConflicted[i][k]) {
//move
showMoveAnimation(i, j, i, k);
//add
board[i][k] += board[i][j];
board[i][j] = 0;
//add score
score += board[i][k];
updateScore(score);
hasConflicted[i][k] = true;
continue;
}
}
}
}
}
setTimeout("updateBoardView()",200);
return true;
}
//上移动
//首先判断是否可以向上移动
function moveUp(){
if(!canMoveUp(board)){
return false;
}
// 向上移动
// 第一步,遍历数字格,判断除第一行外有哪些数字格的值是不为0的
// 第二步,遍历当前值不为0的数字格上边数字格
// 第三步,向上移动逻辑还要分成两种情况
//一种是当前值不为0的数字格上边的数字格必须值为0并且中间的数字格必须值也为0
//一种是当前值不为0的数字格与上边的数字格值相等并且中间的数字格必须值也为0
for(var j=0; j<4; j++){
for(var i=1; i<4; i++){
if(board[i][j] != 0){
for(var k=0; k<i; k++){
//判断当前值不为0的数字格上边的数字格必须值为0并且中间的数字格必须值也为0
if (board[k][j] == 0 && noBlokHorizontalRow(i, k, j, board)) {
showMoveAnimation(i, j, k, j);
board[k][j] = board[i][j];
board[i][j] = 0;
continue;
}
//判断当前值不为0的数字格与上边的数字格值相等并且中间的数字格必须值也为0
else if (board[k][j] == board[i][j] && noBlokHorizontalRow(i, k, j, board) && !hasConflicted[k][j]) {
//move
showMoveAnimation(i, j, k, j);
//add
board[k][j] += board[i][j];
board[i][j] = 0;
//add score
score += board[k][j];
updateScore(score);
hasConflicted[k][j] = true;
continue;
}
}
}
}
}
setTimeout("updateBoardView()",200);
return true;
}
//下移动
//首先判断是否可以向下移动
function moveDown(){
if(!canMoveDown(board)){
return false;
}
// 向下移动
// 第一步,遍历数字格,判断除最后一行外有哪些数字格的值是不为0的
// 第二步,遍历当前值不为0的数字格下边数字格
// 第三步,向下移动逻辑还要分成两种情况
//一种是当前值不为0的数字格下边的数字格必须值为0并且中间的数字格必须值也为0
//一种是当前值不为0的数字格与下边的数字格值相等并且中间的数字格必须值也为0
for(var j=0; j<4; j++){
for(var i=2; i>=0; i--){
if(board[i][j] != 0){
for(var k=3; k>i; k--){
//判断当前值不为0的数字格下边的数字格必须值为0并且中间的数字格必须值也为0
if (board[k][j] == 0 && noBlokHorizontalRow(k, i, j, board)) {
showMoveAnimation(i, j, k, j);
board[k][j] = board[i][j];
board[i][j] = 0;
continue;
}
//判断当前值不为0的数字格与下边的数字格值相等并且中间的数字格必须值也为0
else if (board[k][j] == board[i][j] && noBlokHorizontalRow(k, i, j, board) && !hasConflicted[k][j]) {
//move
showMoveAnimation(i, j, k, j);
//add
board[k][j] += board[i][j];
board[i][j] = 0;
//add score
score += board[k][j];
updateScore(score);
hasConflicted[k][j] = true;
continue;
}
}
}
}
}
setTimeout("updateBoardView()",200);
return true;
}
function isgameover() {
if (nospace(board) && nomove(board)) {
gameover();
}
}
function gameover() {
alert("gameover!");
$("#grid-container").append("<div id='gameover' class='gameover'><p>本次得分</p><span>" + score + "</span><a href='javascript:restartgame();' id='restartgamebutton'>Restart</a></div>");
var gameover = $("#gameover");
gameover.css("width", "500px");
gameover.css("height", "500px");
gameover.css("background-color", "rgba(0, 0, 0, 0.5)");
}<file_sep># game
网页小游戏-2048
预览地址:https://gq-orange.github.io/game/index.html
|
f28618168c10ca1e4d904e3d2e708af825fce519
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
gq-orange/game
|
fa75fd50a9a83cab25289b42ceb2dcf8a5c22761
|
64834e55a86b960d95d1b2c5dc7db20be975cfad
|
refs/heads/master
|
<repo_name>Rade58/my_jamstack_site<file_sep>/main.js
const listRepos = async (username) => {
const repos = await fetch(
`https://api.github.com/users/${username}/repos?type=owner&sort=updated`
)
.then((res) => res.json())
.catch((err) => console.error(err));
const markup = repos
.map(
(repo) => `
<li>
<a href="${repo.html_url}">${repo.name}</a>
(⭐ ${repo.stargazers_count})
</li>
`
)
// IMAS NIZ LIST ITEM STRINGOVA, A TI IH SPOJI U SINGLE STRING
.join(""); // separator je prazan string (SECAJ SE KAKO join FUNKCIONISE)
// KREIRAO SAM OVAJ ELEMENT U HTML-U KAO I STO SI VIDEO
const container = document.getElementById("content");
container.innerHTML = `<ul>${markup}</ul>`;
};
// ZELIM DA RENDER-UJEM LISTU REPO-A JEM-A YOUNG-A
listRepos("young");
|
7a0726b5f9e3c36c57015ce064c25bdd1290bf51
|
[
"JavaScript"
] | 1 |
JavaScript
|
Rade58/my_jamstack_site
|
c4d2ba93220a213dff138caab6158bae7c613d2a
|
543315caf5bd926202fb4370c995680ffb299426
|
refs/heads/master
|
<file_sep>// Copyright (c) 2014-2015 The Bitcredit Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCREDIT_QT_BITCREDITADDRESSVALIDATOR_H
#define BITCREDIT_QT_BITCREDITADDRESSVALIDATOR_H
#include <QValidator>
/** Base58 entry widget validator, checks for valid characters and
* removes some whitespace.
*/
class BitcreditAddressEntryValidator : public QValidator
{
Q_OBJECT
public:
explicit BitcreditAddressEntryValidator(QObject *parent);
State validate(QString &input, int &pos) const;
};
/** Bitcredit address widget validator, checks for a valid bitcredit address.
*/
class BitcreditAddressCheckValidator : public QValidator
{
Q_OBJECT
public:
explicit BitcreditAddressCheckValidator(QObject *parent);
State validate(QString &input, int &pos) const;
};
#endif // BITCREDIT_QT_BITCREDITADDRESSVALIDATOR_H
<file_sep>// Copyright (c) 2014 The Memorycoin developers
// Copyright (c) 2015 The Bitcredit developers
#include "voting.h"
#include "base58.h"
#include "utilstrencodings.h"
#include "chain.h"
#include "main.h"
#include "activebasenode.h"
#include <string>
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/thread.hpp>
#include "trust.h"
#include <sys/stat.h>
#include <stdio.h>
using namespace boost;
using namespace std;
CCriticalSection grantdb;
//SECTION: GrantPrefixes and Grant Block Intervals
static string GRANTPREFIX="6BCR";
//static const int64_t GRANTBLOCKINTERVAL = 5; //To be changed to 1
static int numberOfOffices = 5;
string electedOffices[6];
//= {"cdo","cto","cso","bnk","nsr",cmo, "XFT"};
//Implement in memory for now - this will cause slow startup as recalculation of all votes takes place every startup. These should be persisted in a database or on disk
CBlockIndex* gdBlockPointer = NULL;
int64_t grantDatabaseBlockHeight=-1; //How many blocks processed for grant allocation purposes
ofstream grantAwardsOutput;
bool debugVote = false;
bool debugVoteExtra = false;
int64_t numberCandidatesEliminated = 0;
std::map<int, std::string > awardWinners;
std::map<std::string,int64_t > grantAwards;
std::map<std::string,int64_t>::iterator gait;
std::map<std::string,int64_t > preferenceCount;
std::map<std::string,int64_t> balances; //Balances as at grant allocation block point
std::map<std::string,std::map<int64_t,std::string> > votingPreferences[7]; //Voting prefs as at grant allocation block point
std::map<std::string,std::map<int64_t, std::string> >::iterator ballotit;
std::map<std::string,std::map<int64_t, std::string> > ballots;
std::map<std::string,int64_t > ballotBalances;
std::map<std::string,double > ballotWeights;
std::map<int64_t, std::string>::iterator svpit;
std::map<int64_t, std::string>::iterator svpit2;
std::map<std::string, int64_t>::iterator svpit3;
std::map<int64_t, std::string>::iterator svpit4;
std::map<std::string,int64_t>::iterator it;
std::map<int64_t,std::string>::iterator it2;
std::map<std::string,std::map<int64_t,std::string> >::iterator vpit;
std::map<std::string,int64_t > wastedVotes; //Report on Votes that were wasted
std::map<std::string,std::map<int64_t,std::string> > electedVotes; //Report on where votes went
std::map<std::string,std::map<int64_t,std::string> > supportVotes; //Report on support for candidates
bool isGrantAwardBlock(int64_t nHeight){
if (nHeight > 321399){
if(fDebug)LogPrintf(" Is (%ld) a grant block? : Yes \n", nHeight);
return true;
}
else if ((nHeight > 210000 && nHeight < 321400) && (nHeight % 5 == 0)){
if(fDebug)LogPrintf(" Is (%ld) a grant block? : Yes \n", nHeight);
return true;
}
return false;
}
void serializeGrantDB(string filename){
if(fDebug)LogPrintf(" Serialize Grant Info Database: Current Grant Database Block Height: %ld\n",grantDatabaseBlockHeight);
ofstream grantdb;
grantdb.open (filename.c_str(), ios::trunc);
//grantDatabaseBlockHeight
grantdb << grantDatabaseBlockHeight << "\n";
//Balances
grantdb << balances.size()<< "\n";
for(it=balances.begin(); it!=balances.end(); ++it){
grantdb << it->first << "\n" << it->second<< "\n";
}
//votingPreferences
for(int i=0;i<numberOfOffices;i++){
grantdb << votingPreferences[i].size()<< "\n";
for(vpit=votingPreferences[i].begin(); vpit!=votingPreferences[i].end(); ++vpit){
grantdb << vpit->first << "\n";
grantdb << vpit->second.size() << "\n";
for(it2=vpit->second.begin();it2!=vpit->second.end();++it2){
grantdb << it2->first << "\n" << it2->second<< "\n";
}
}
}
grantdb.flush();
grantdb.close();
}
int64_t getGrantDatabaseBlockHeight() {
std::string line;
ifstream myfile;
string filename = (GetDataDir() / "/ratings/grantdb.dat").string().c_str();
myfile.open (filename.c_str());
if (myfile.is_open()) {
getline (myfile,line);
myfile.close();
return atoi64(line.c_str());
} else {
return -1;
}
}
bool deSerializeGrantDB(string filename, int64_t maxWanted){
if(fDebug)LogPrintf(" De-Serialize Grant Info Database\n Max Blocks Wanted: %ld\n", maxWanted);
std::string line;
std::string line2;
ifstream myfile;
myfile.open (filename.c_str());
if (myfile.is_open()){
getline (myfile,line);
grantDatabaseBlockHeight=atoi64(line.c_str());
if(fDebug)LogPrintf("Deserialize Grant Info Database Found Height %ld\n",grantDatabaseBlockHeight);
if(grantDatabaseBlockHeight>maxWanted){
//vote database later than required - don't load
grantDatabaseBlockHeight=-1;
myfile.close();
return false;
}
//Balances
balances.clear();
getline (myfile,line);
int64_t balancesSize=atoi64(line.c_str());
for(int i=0;i<balancesSize;i++){
getline(myfile, line );
getline(myfile, line2 );
balances[line]=atoi64(line2.c_str());
}
//votingPreferences
for(int i=0;i<numberOfOffices;i++){
votingPreferences[i].clear();
getline(myfile,line);
int64_t votingPreferencesSize=atoi64(line.c_str());
for(int k=0;k<votingPreferencesSize;k++){
getline(myfile,line);
std::string vpAddress=line;
getline(myfile,line);
int64_t vpAddressSize=atoi64(line.c_str());
for(int j=0;j<vpAddressSize;j++){
getline(myfile,line);
getline(myfile,line2);
votingPreferences[i][vpAddress][atoi64(line.c_str())]=line2;
}
}
}
myfile.close();
//Set the pointer to next block to process
gdBlockPointer=chainActive.Genesis();
for(int i=0;i<grantDatabaseBlockHeight;i++){
if(gdBlockPointer == NULL ){
LogPrintf("Insufficent number of blocks loaded %s\n",filename.c_str());
return false;
}
gdBlockPointer=chainActive.Tip();
}
return true;
}
return 0;
}
bool getGrantAwards(int64_t nHeight){
//nHeight is the current block height
if(!isGrantAwardBlock(nHeight)){
if(fDebug)LogPrintf("Error - calling getgrantawards for non grant award block, nHeight requested: %ld", nHeight);
return false;
}
return ensureGrantDatabaseUptoDate(nHeight);
}
bool ensureGrantDatabaseUptoDate(int64_t nHeight){
// grantDatabaseBlockHeight = getGrantDatabaseBlockHeight();
if(fDebug)LogPrintf(" === Grant Database Block Height %ld === \n", grantDatabaseBlockHeight);
//This should always be true on startup
if(grantDatabaseBlockHeight==-1){
string newCV=GetArg("-custombankprefix","vte");
electedOffices[0] = "dof";
electedOffices[1] = "tof";
electedOffices[2] = "sof";
electedOffices[3] = "mof";
electedOffices[4] = "bnk";
electedOffices[5] = newCV;
}
//NOTE: requiredgrantdatabaseheight is 5 less than the current block
int64_t requiredGrantDatabaseHeight =nHeight-GRANTBLOCKINTERVAL;
if(fDebug)LogPrintf("Checking GDB is updated...Required Height : %ld, requested from: %ld \n",requiredGrantDatabaseHeight, nHeight);
//Maybe we don't have to count votes from the start - let's check if there's a recent vote database stored
if(grantDatabaseBlockHeight== -1){
deSerializeGrantDB((GetDataDir() / "ratings/grantdb.dat" ).string().c_str(), requiredGrantDatabaseHeight );
}
while(grantDatabaseBlockHeight < requiredGrantDatabaseHeight ){
processNextBlockIntoGrantDatabase();
}
return true;
}
int getOfficeNumberFromAddress(string grantVoteAddress){
if (!startsWith(grantVoteAddress.c_str(),GRANTPREFIX.c_str())){
return -1;
}
for(int i=0;i<numberOfOffices+1;i++){
if(grantVoteAddress.substr(4,3)==electedOffices[i]){
return i;
}
}
return -1;
}
void printVotingPrefs(std::string address){
//This is slow and iterates too much, but on the plus side it doesn't crash the program.
//This crash probably caused by eliminate candidate corrupting the ballot structure.
int pref=1;
for(ballotit=ballots.begin(); ballotit!=ballots.end(); ++ballotit){
if(address==ballotit->first){
for(svpit4=ballotit->second.begin();svpit4!=ballotit->second.end();++svpit4){
grantAwardsOutput<<"--Preference "<<pref<<" "<<svpit4->first<<" "<<svpit4->second.c_str()<<" \n";
pref++;
}
}
}
}
void processNextBlockIntoGrantDatabase(){
CBlock block;
if(gdBlockPointer != NULL){
gdBlockPointer = chainActive.Tip();
}else{
gdBlockPointer = chainActive.Genesis();
}
ReadBlockFromDisk(block, gdBlockPointer);
std::map<std::string,int64_t > votes;
std::map<std::string,int64_t >::iterator votesit;
BOOST_FOREACH(const CTransaction& tx, block.vtx){
for (unsigned int j = 0; j < tx.vout.size();j++){
CTxDestination address;
ExtractDestination(tx.vout[j].scriptPubKey, address);
string receiveAddress = CBitcreditAddress( address ).ToString().c_str();
int64_t theAmount = tx.vout[ j ].nValue;
balances[ receiveAddress ] = balances[ receiveAddress ] + theAmount;
if(theAmount == 1000 && startsWith(receiveAddress.c_str(), GRANTPREFIX.c_str())){
votes[receiveAddress] = theAmount;
}
}
for (size_t i = 0; i < tx.vin.size(); i++){
if (tx.IsCoinBase())
continue;
const CScript &script = tx.vin[i].scriptSig;
opcodetype opcode;
std::vector<unsigned char> vch;
uint256 prevoutHash, blockHash;
string spendAddress;
int64_t theAmount;
for (CScript::const_iterator pc = script.begin(); script.GetOp(pc, opcode, vch); ){
if (opcode == 33){
CPubKey pubKey(vch);
prevoutHash = tx.vin[i].prevout.hash;
CTransaction txOfPrevOutput;
if (!GetTransaction(prevoutHash, txOfPrevOutput, blockHash, true))
{
continue;
}
unsigned int nOut = tx.vin[i].prevout.n;
if (nOut >= txOfPrevOutput.vout.size())
{
continue;
}
const CTxOut &txOut = txOfPrevOutput.vout[nOut];
CTxDestination addressRet;
if (!ExtractDestination(txOut.scriptPubKey, addressRet))
{
continue;
}
spendAddress = CBitcreditAddress(addressRet).ToString().c_str();
theAmount = txOut.nValue;
balances[ spendAddress ] = balances[ spendAddress ] - theAmount;
for( votesit = votes.begin();votesit != votes.end(); ++votesit){
if(fDebug)LogPrintf(" Vote found: %s, %ld\n",votesit->first.c_str(),votesit->second);
string grantVoteAddress = ( votesit->first );
int electedOfficeNumber = getOfficeNumberFromAddress(grantVoteAddress);
if( electedOfficeNumber > -1 ){
votingPreferences[ electedOfficeNumber ][ spendAddress ][ votesit->second ] = grantVoteAddress;
}
}
}
}
}
}
grantDatabaseBlockHeight++;
if(fDebug)LogPrintf("Block has been processed. Grant Database Block Height is now updated to Block # %ld\n", grantDatabaseBlockHeight);
if (isGrantAwardBlock(grantDatabaseBlockHeight + GRANTBLOCKINTERVAL)) {
getGrantAwardsFromDatabaseForBlock( grantDatabaseBlockHeight + GRANTBLOCKINTERVAL );
}
serializeGrantDB( (GetDataDir() / "ratings/grantdb.dat" ).string().c_str() );
}
void printCandidateSupport(){
std::map<int64_t,std::string>::reverse_iterator itpv2;
grantAwardsOutput<<"\nWinner Support: \n";
for(ballotit=supportVotes.begin(); ballotit!=supportVotes.end(); ++ballotit){
grantAwardsOutput<<"\n--"<<ballotit->first<<" \n";
for(itpv2=ballotit->second.rbegin();itpv2!=ballotit->second.rend();++itpv2){
grantAwardsOutput<<"-->("<< itpv2->first/COIN <<"/"<<balances[itpv2->second.c_str()]/COIN <<") "<<itpv2->second.c_str()<<" \n";
}
}
}
void printBalances( int64_t howMany, bool printVoting, bool printWasted ){
grantAwardsOutput<<"---Current Balances------\n";
std::multimap<int64_t, std::string > sortByBalance;
std::map<std::string,int64_t>::iterator itpv;
std::map<int64_t,std::string>::reverse_iterator itpv2;
for(itpv=balances.begin(); itpv!=balances.end(); ++itpv){
if(itpv->second>COIN){
sortByBalance.insert(pair<int64_t, std::string>(itpv->second,itpv->first));
}
}
std::multimap<int64_t, std::string >::reverse_iterator sbbit;
int64_t count = 0;
for (sbbit = sortByBalance.rbegin(); sbbit != sortByBalance.rend();++sbbit){
if(howMany>count){
grantAwardsOutput<<"\n->Balance:"<<sbbit->first/COIN<<" - "<<sbbit->second.c_str()<<"\n";
if(printWasted){
for(itpv2=electedVotes[sbbit->second.c_str()].rbegin(); itpv2!=electedVotes[sbbit->second.c_str()].rend(); ++itpv2){
grantAwardsOutput << "---->" << itpv2->first/COIN << " supported " << itpv2->second << "\n";
}
if(wastedVotes[sbbit->second.c_str()]/COIN>0){
grantAwardsOutput<<"---->"<<wastedVotes[sbbit->second.c_str()]/COIN<<" wasted (Add More Preferences)\n";
}
if(votingPreferences[0].find(sbbit->second.c_str())==votingPreferences[0].end()){
grantAwardsOutput<<"---->No Vote: (Add Some Voting Preferences)\n";
}
}
if(printVoting){
try{
printVotingPrefs(sbbit->second);
}catch (std::exception &e) {
grantAwardsOutput<<"Print Voting Prefs Exception\n";
}
}
count++;
}
}
grantAwardsOutput<<"---End Balances------\n";
}
bool getGrantAwardsFromDatabaseForBlock(int64_t nHeight){
if(fDebug)LogPrintf( "getGrantAwardsFromDatabaseForBlock %ld\n", nHeight );
if(grantDatabaseBlockHeight!=nHeight-GRANTBLOCKINTERVAL){
LogPrintf("getGrantAwardsFromDatabase is being called when no awards are due. %ld %ld\n",grantDatabaseBlockHeight,nHeight);
return false;
}
debugVoteExtra = GetBoolArg("-debugvoteex", false);
debugVote = GetBoolArg("-debugvote", false);
if(debugVote){
std::stringstream sstm;
sstm << "award" << setw(8) << std::setfill('0') << nHeight << ".dat";
string filename = sstm.str();
mkdir((GetDataDir() / "grantawards").string().c_str()
#ifndef _WIN32
,S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH
#endif
);
grantAwardsOutput.open ((GetDataDir() / "grantawards" / filename).string().c_str(), ios::trunc);}
//save to disk
if(debugVote)grantAwardsOutput << "-------------:\nElection Count:\n-------------:\n\n";
//Clear from last time, ensure nothing left over
awardWinners.clear();
grantAwards.clear();
for( int i = 0; i < numberOfOffices + 1;i++ ){
ballots.clear();
ballotBalances.clear();
ballotWeights.clear();
wastedVotes.clear();
electedVotes.clear();
supportVotes.clear();
//Iterate through every vote
for( vpit = votingPreferences[i].begin();vpit != votingPreferences[i].end();++vpit) {
int64_t voterBalance = balances[ vpit->first ];
//Ignore balances of 0 - they play no part.
if( voterBalance > 0 ){
ballotBalances[ vpit->first ] = voterBalance;
ballotWeights[ vpit->first ] = 1.0;
//Order preferences by coins sent - lowest number of coins has top preference
for( it2 = vpit->second.begin();it2 != vpit->second.end(); ++it2){
//Where a voter has voted for more than one preference with the same amount, only the last one (alphabetically) will be valid. The others are discarded.
ballots[ vpit->first ][ it2->first ] = it2->second;
}
}
}
//TODO: decrease intensity of this function.
getWinnersFromBallots( nHeight, i );
//At this point, we know the vote winners - now to see if grants are to be awarded
if( i < numberOfOffices ){
for(int i=0;i<1;i++){
grantAwards[ awardWinners[ i ] ] = grantAwards[ awardWinners[ i ] ] + GetGrantValue( nHeight, 0 );
if( debugVote ){
grantAwardsOutput << "Add grant award to Block "<<awardWinners[0].c_str()<<" ("<<GetGrantValue(nHeight, 0)/COIN<<")\n";
}
}
}
if(debugVote)printCandidateSupport();
}
if(debugVote){grantAwardsOutput.close();}
return true;
}
void getWinnersFromBallots( int64_t nHeight, int officeNumber ){
if(debugVote)grantAwardsOutput <<"\n\n\n--------"<< electedOffices[officeNumber]<<"--------\n";
if(debugVoteExtra)printBallots();
//Calculate Total in all balances
int64_t tally=0;
for(it=balances.begin(); it!=balances.end(); ++it){
tally=tally+it->second;
}
if(debugVote)grantAwardsOutput <<"Total coin issued: " << tally/COIN <<"\n";
//Calculate Total of balances of voters
int64_t totalOfVoterBalances=0;
for( it = ballotBalances.begin();it != ballotBalances.end();++it) {
totalOfVoterBalances = totalOfVoterBalances + it->second;
}
if( debugVote ){
grantAwardsOutput <<"Total of Voters' Balances: "<<totalOfVoterBalances/COIN<<"\n";
}
//Turnout
if( debugVote ){
grantAwardsOutput <<"Percentage of total issued coin voting: "<<(totalOfVoterBalances*100)/tally<<" percent\n";
}
//Calculate Droop Quota
int64_t droopQuota = (totalOfVoterBalances/2) + 1;
if( debugVote ){
grantAwardsOutput <<"Droop Quota: "<<droopQuota/COIN<<"\n";
}
//Conduct voting rounds until all grants are awarded
for(int i = 1;i > 0;i--){
string electedCandidate;
int voteRoundNumber = 0;
if( debugVote ){
grantAwardsOutput <<"-------------:\nRound:"<<1-i<<"\n";
}
if( debugVoteExtra ){
printBallots();
}
do{
electedCandidate = electOrEliminate( droopQuota, i );
voteRoundNumber++;
}while( electedCandidate == "" );
awardWinners[ ( i - 1 ) *- 1 ] = electedCandidate;
}
}
string electOrEliminate( int64_t droopQuota, unsigned int requiredCandidates ){
std::map<std::string,int64_t >::iterator tpcit;
//Recalculate the preferences each time as winners and losers are removed from ballots.
preferenceCount.clear();
//Calculate support for each candidate. The balance X the weighting for each voter is applied to the total for the candidate currently at the top of the voter's ballot
for( ballotit = ballots.begin();ballotit != ballots.end();++ballotit){
//Check: Multiplying int64_t by double here, and representing answer as int64_t.
preferenceCount[ ballotit->second.begin()->second ] += ( ballotBalances[ ballotit->first ] * ballotWeights[ ballotit->first ] );
}
//Find out which remaining candidate has the greatest and least support
string topOfThePoll;
int64_t topOfThePollAmount = 0;
string bottomOfThePoll;
int64_t bottomOfThePollAmount = 9223372036854775807;
for( tpcit = preferenceCount.begin();tpcit != preferenceCount.end();++tpcit){
//Check:When competing candidates have equal votes, the first (sorted by Map) will be chosen for top and bottom of the poll.
if( tpcit->second > topOfThePollAmount ){
topOfThePollAmount = tpcit->second;
topOfThePoll = tpcit->first;
}
if( tpcit->second < bottomOfThePollAmount ){
bottomOfThePollAmount = tpcit->second;
bottomOfThePoll = tpcit->first;
}
}
//Purely for debugging/information
if( topOfThePollAmount >= droopQuota || requiredCandidates >= preferenceCount.size() || bottomOfThePollAmount > droopQuota / 10){
if( debugVote ){
grantAwardsOutput <<"Candidates with votes equalling more than 10% of Droop quota\n";
}
for( tpcit = preferenceCount.begin();tpcit != preferenceCount.end();++tpcit){
if( tpcit->second > droopQuota / 10 ){
if(debugVote)
grantAwardsOutput <<"Support: "<<tpcit->first<<" ("<<tpcit->second/COIN<<")\n";
}
}
}
if(topOfThePollAmount==0){
//No ballots left -end -
if(debugVote)grantAwardsOutput <<"No Candidates with support remaining. Grant awarded to unspendable address 6BCRBKZLmq2JwWLWDtJZL26ao4uHhqG6mH\n";
return "6BCRBKZLmq2JwWLWDtJZL26ao4uHhqG6mH";
}
if(topOfThePollAmount>=droopQuota || requiredCandidates>=preferenceCount.size()){
//Note: This is a simplified Gregory Transfer Value - ignoring ballots where there are no other hopefuls.
double gregorySurplusTransferValue=((double)topOfThePollAmount-(double)droopQuota)/(double)topOfThePollAmount;
//Don't want this value to be negative when candidates are elected with less than a quota
if(gregorySurplusTransferValue<0){gregorySurplusTransferValue=0;}
electCandidate(topOfThePoll,gregorySurplusTransferValue,(requiredCandidates==1));
if(debugVote){
if(numberCandidatesEliminated>0){
grantAwardsOutput <<"Candidates Eliminated ("<<numberCandidatesEliminated<<")\n\n";
numberCandidatesEliminated=0;
}
grantAwardsOutput <<"Candidate Elected: "<<topOfThePoll.c_str()<<" ("<<topOfThePollAmount/COIN<<")\n";
grantAwardsOutput <<"Surplus Transfer Value: "<<gregorySurplusTransferValue<<"\n";
}
return topOfThePoll;
}else{
eliminateCandidate(bottomOfThePoll,false);
if(debugVote){
if(bottomOfThePollAmount>droopQuota/10){
if(numberCandidatesEliminated>0){
grantAwardsOutput <<"Candidates Eliminated ("<<numberCandidatesEliminated<<")\n";
numberCandidatesEliminated=0;
}
grantAwardsOutput <<"Candidate Eliminated: "<<bottomOfThePoll.c_str()<<" ("<<bottomOfThePollAmount/COIN<<")\n\n";
}else{
numberCandidatesEliminated++;
}
}
return "";
}
}
void electCandidate(string topOfThePoll, double gregorySurplusTransferValue,bool isLastCandidate){
//Apply fraction to weights where the candidate was top of the preference list
for(ballotit=ballots.begin(); ballotit!=ballots.end(); ++ballotit){
svpit2=ballotit->second.begin();
if(svpit2->second==topOfThePoll){
//Record how many votes went towards electing this candidate for each user
electedVotes[ballotit->first][balances[ballotit->first]*(ballotWeights[ballotit->first]*(1-gregorySurplusTransferValue))]=svpit2->second;
//Record the support for each candidate elected
supportVotes[topOfThePoll][balances[ballotit->first]*(ballotWeights[ballotit->first]*(1-gregorySurplusTransferValue))]=ballotit->first;
//This voter had the elected candidate at the top of the ballot. Adjust weight for future preferences.
ballotWeights[ballotit->first]=ballotWeights[ballotit->first]*gregorySurplusTransferValue;
}
}
eliminateCandidate(topOfThePoll,isLastCandidate);
}
void eliminateCandidate(string removeid,bool isLastCandidate){
std::map<std::string, int64_t> ballotsToRemove;
std::map<std::string, int64_t>::iterator btrit;
//Remove candidate from all ballots - note the candidate may be way down the preference list
for(ballotit=ballots.begin(); ballotit!=ballots.end(); ++ballotit){
int64_t markForRemoval = 0;
for(svpit2=ballotit->second.begin();svpit2!=ballotit->second.end();++svpit2){
if(svpit2->second==removeid){
markForRemoval = svpit2->first;
}
}
if(markForRemoval!=0){
ballotit->second.erase(markForRemoval);
}
//Make a note of ballot to remove
if(ballotit->second.size()==0){
if(!isLastCandidate){
wastedVotes[ballotit->first]=(ballotBalances[ballotit->first]*ballotWeights[ballotit->first]);
}
ballotsToRemove[ballotit->first]=1;
}
}
for(btrit=ballotsToRemove.begin(); btrit!=ballotsToRemove.end(); ++btrit){
ballots.erase(btrit->first);
}
}
void printBallots(){
LogPrintf("Current Ballot State\n");
int cutOff = 0;
for( ballotit = ballots.begin();ballotit != ballots.end();++ballotit){
LogPrintf("Voter: %s Balance: %ld Weight: %f Total: %f\n",ballotit->first.c_str(),ballotBalances[ ballotit->first ] / COIN,ballotWeights[ ballotit->first ],
(ballotBalances[ ballotit->first ] / COIN ) * ballotWeights[ ballotit->first ]);
int cutOff2 = 0;
for( svpit2 = ballotit->second.begin(); svpit2 != ballotit->second.end();++svpit2){
LogPrintf( "Preference: (%d) %ld %s \n",cutOff2,svpit2->first,svpit2->second.c_str());
}
cutOff2++;
cutOff++;
}
}
bool startsWith( const char *str, const char *pre ){
size_t lenpre = strlen( pre ),
lenstr = strlen( str );
return lenstr < lenpre ? false : strncmp( pre, str, lenpre ) == 0;
}
std::map<std::string,int64_t> getbalances(){
std::map<std::string,int64_t> addressvalue;
fstream myfile ((GetDataDir()/ "ratings/balances.dat").string().c_str());
char * pEnd;
std::string line;
if (myfile.is_open()){
while ( myfile.good() ){
getline (myfile,line);
if (line.empty()) continue;
std::vector<std::string> strs;
boost::split(strs, line, boost::is_any_of(","));
addressvalue[strs[0]]=strtoll(strs[1].c_str(),&pEnd,10);
}
myfile.close();
}
return addressvalue;
}
std::vector<std::string> getlast40miners(){
std::vector<std::string> last40miners;
fstream myfile ((GetDataDir()/ "ratings/minedblocks.dat").string().c_str());
std::string line;
int counter=0;
if (myfile.is_open()){
while ( myfile.good() && counter<40 ){
getline (myfile,line);
if (line.empty()) continue;
std::vector<std::string> strs;
boost::split(strs, line, boost::is_any_of(","));
last40miners.push_back(strs[0]);
counter++;
}
myfile.close();
}
return last40miners;
}
<file_sep>// Copyright (c) 2014 The Sapience AIFX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "ibtp.h"
#include "main.h"
#include "util.h"
#include "protocol.h"
#include "chainparams.h"
#include "net.h"
#include "utilstrencodings.h"
#include <map>
using namespace std;
void CIbtp::LoadMsgStart()
{
vChains.push_back(SChain("Litecoin ", "LTC", 0xfb, 0xc0, 0xb6, 0xdb));
vChains.push_back(SChain("Bitcoin", "BTC", 0xfa, 0xb2, 0xef, 0xf2));
vChains.push_back(SChain("Dash", "DSH", 0xbf, 0x0c, 0x6b, 0xbd));
vChains.push_back(SChain("Bitcredit", "BCR", 0xf9, 0xbe, 0xb4, 0xd9));
}
bool CIbtp::IsIbtpChain(const unsigned char msgStart[], std::string& chainName)
{
bool bFound = false;
CMessageHeader hdr;
BOOST_FOREACH(SChain p, vChains)
{
unsigned char pchMsg[4] = { p.pchMessageOne, p.pchMessageTwo, p.pchMessageThree, p.pchMessageFour };
//if(memcmp(hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE))
if(memcmp(msgStart, Params().MessageStart(), MESSAGE_START_SIZE !=0))
{
if(memcmp(msgStart, pchMsg, sizeof(pchMsg)) == 0)
{
bFound = true;
chainName = p.sChainName;
printf("Found IBTP chain: %s\n", p.sChainName.c_str());
}
}
}
return bFound;
}
<file_sep>#ifndef RECEIPTPAGE_H
#define RECEIPTPAGE_H
#include <QWidget>
namespace Ui {
class ReceiptPage;
}
class MessageModel;
class InvoiceTableModel;
class ReceiptTableModel;
QT_BEGIN_NAMESPACE
class QTableView;
class QItemSelection;
class QSortFilterProxyModel;
class QMenu;
class QModelIndex;
QT_END_NAMESPACE
/** Widget that shows a list of sending or receiving addresses.
*/
class ReceiptPage : public QWidget
{
Q_OBJECT
public:
explicit ReceiptPage(QWidget *parent = 0);
~ReceiptPage();
void setModel(MessageModel *model);
public slots:
void exportClicked();
private:
Ui::ReceiptPage *ui;
ReceiptTableModel *model;
MessageModel *messageModel;
QSortFilterProxyModel *proxyModel;
QMenu *contextMenu;
QAction *replyAction;
QAction *resendAction;
QAction *copyFromAddressAction;
QAction *copyToAddressAction;
QAction *deleteAction;
QAction *viewAction;
private slots:
void on_newButton_clicked();
void on_replyButton_clicked();
void on_copyFromAddressButton_clicked();
void on_copyToAddressButton_clicked();
void on_deleteButton_clicked();
void selectionChanged();
/** Spawn contextual menu (right mouse menu) for address book entry */
void contextualMenu(const QPoint &point);
signals:
};
#endif // RECEIPTPAGE_H
<file_sep>Colorcore
=========
Colorcore is an open source colored coin wallet compatible with the `Open Assets Protocol <https://github.com/OpenAssets/open-assets-protocol/blob/master/specification.mediawiki>`_. It supports two modes: a command line interface, and a JSON/RPC server. The command line interface is suitable for managing a local wallet without going through any third-party service. The JSON/RPC interface is suitable for server-side implementations of colored coins and programmatic colored coins wallet management.
Open Assets is a protocol for issuing and transferring custom digital tokens in a secure way on the Bitcoin blockchain (or any compatible blockchain).
Use `Coinprism <https://www.coinprism.com>`_ for a web-based and user-friendly colored coins wallet.
Requirements
============
The following items are required to run Colorcore in the default mode:
* `Python 3.4 <https://www.python.org/downloads/>`_
* The following Python packages: `openassets <https://github.com/openassets/openassets>`_, `python-bitcoinlib <https://github.com/petertodd/python-bitcoinlib>`_, `aiohttp <https://github.com/KeepSafe/aiohttp>`_
* An operational Bitcoin Core wallet with JSON/RPC enabled and full transaction index
Installation
============
Clone the source code from GitHub::
$ git clone https://github.com/OpenAssets/colorcore.git
Update the requirements::
$ cd colorcore
$ pip install --upgrade -r requirements.txt
Configuration
=============
Make sure your have a Bitcoin Core server running, with the following arguments: ``-txindex=1 -server=1``. You may need to have a username and password configured in the configuration file for Bitcoin Core (``bitcoin.conf``).
All the configuration for Colorcore is done though the ``config.ini`` file::
[general]
# Defines what provider to use to retrieve information from the Blockchain
blockchain-provider=bitcoind
[bitcoind]
# Replace username, password and port with the username, password and port for Bitcoin Core
# The default port is 8332 in MainNet and 18332 in TestNet
rpcurl=http://<username>:<password>@localhost:<port>
[environment]
dust-limit=600
default-fees=10000
[cache]
# Path of the cache file (use :memory: to disable)
path=cache.db
[rpc]
# The port on which to expose the Colorcore RPC interface
port=8080
Usage
=====
The general syntax for executing Colorcore is the following::
python colorcore.py <command> <arguments>
All the commands are documented. Use the following command to show the documentation::
python colorcore.py --help
The currently supported commands are the following:
* **getbalance**: Returns the balance in both bitcoin and colored coin assets for all of the addresses available in your Bitcoin Core wallet.
* **listunspent**: Returns an array of unspent transaction outputs, augmented with the asset ID and quantity of each output.
* **sendbitcoin**: Creates a transaction for sending bitcoins from an address to another.
* **sendasset**: Creates a transaction for sending an asset from an address to another.
* **issueasset**: Creates a transaction for issuing an asset.
* **distribute**: Creates a batch of transactions used for creating a token and distributing it to participants of a crowd sale.
RPC server
----------
Use the following command to start the RPC server::
python colorcore.py server
Colorcore will then start listening on the port specified in the configuration file.
To call the RPC server, issue a HTTP POST request to http://localhost:<port>/<operation>. The list of valid operations is the same as the list of commands available via command line.
The arguments must be passed to the server in the body of the request, using the ``application/x-www-form-urlencoded`` encoding. Argument names are the same as for the command line interface.
Issue an asset
--------------
Issuing an asset is done through a standard Bitcoin transaction. The following command can be used to issue one million units of an asset::
python colorcore.py issueasset <address> 1000000
The ``<address>`` placeholder represents the issuing address. You must own the private key for this address in your Bitcoin Core wallet, and you must have at least 0.000006 BTC on that address in order to successfully issue the asset. If the operation is successful, this command will return the transaction hash of the issuing transaction. You can then use a `color-aware block explorer <https://www.coinprism.info>`_ to see the details of the transaction.
Get your balance
----------------
Getting the balance of the wallet stored on the Bitcoin Core instance can be done by using the following command::
python colorcore.py getbalance
Send an asset
-------------
Use the ``sendasset`` operation to send an asset to another address::
python colorcore.py sendasset <from> <asset> <quantity> <to>
Crowdsales
----------
Crowdsales can be operated from Colorcore using the ``distribute`` command. It is not vulnerable to double spends, and allows the issuer to change the price of their tokens over time.
Remarks
-------
Fees can be specified through the ``--fees`` argument, and the default amount for fees can be changed through the ``config.ini`` file.
Once you have colored coins on one address, make sure you use the ``sendbitcoin`` operation to send uncolored bitcoins from that address. If you use Bitcoin Core to send bitcoins, Bitcoin Core might spend your colored outputs as it is not aware of colored coins.
If RPC is enabled, it is highly recommended to use a firewall to prevent access to Colorcore from an unauthorized remote machine.
Blockchain Providers
====================
Colorcore supports several modes. The mode can be defined using the ``blockchain-provider`` setting under ``[general]``. The following values are supported:
* ``bitcoind``: Colorcore connects only to a Bitcoin Core instance. For this to work, you need an operational Bitcoin Core wallet with JSON/RPC enabled and full transaction index.
The following setting must be configured: ``rpcurl`` under ``[bitcoind]``.
* ``chain.com``: This is the lightweight mode. Colorcore connects to the `chain.com <https://chain.com/>`_ API. You must have a valid API Key and API secret. Using this mode, you will only be able to perform read operations such as ``getbalance`` and ``listunspent``. Any operation requiring to sign a transaction will fail. Bitcoin Core is not required when using this mode.
The following settings must be configured: ``base-url``, ``api-key-id`` and ``secret`` under ``[chain.com]``.
* ``chain.com+bitcoind``: Colorcore connects to the chain.com API for obtaining blockchain data, but signs transactions using Bitcoin Core. All operations are supported.
The following settings must be configured: ``base-url``, ``api-key-id`` and ``secret`` under ``[chain.com]`` and ``rpcurl`` under ``[bitcoind]``.
License
=======
The MIT License (MIT)
Copyright (c) 2014 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<file_sep>// Copyright (c) 2014 The ShadowCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef COIN_STATE_H
#define COIN_STATE_H
#include <string>
#include "sync.h"
extern bool fReindexing;
#endif /* COIN_STATE_H */
<file_sep>#include "assetspage.h"
#include "ui_assetspage.h"
#include <QApplication>
#include <QDebug>
#include <QJsonArray>
#include <QComboBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
#include <QClipboard>
#include <QStringList>
#include "util.h"
#include "addresstablemodel.h"
#include "addressbookpage.h"
#include "guiutil.h"
#include "optionsmodel.h"
AssetsPage::AssetsPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::AssetsPage),
model(0)
{
ui->setupUi(this);
serverProc = new QProcess(this);
if (!runColorCore()) return;
getBalance();
// normal bitcredit address field
GUIUtil::setupAddressWidget(ui->chainID, this);
connect(ui->startButton, SIGNAL(pressed()), this, SLOT(update()));
connect(ui->transferButton, SIGNAL(pressed()), this, SLOT(sendassets()));
connect(ui->issueButton, SIGNAL(pressed()), this, SLOT(issueassets()));
connect(ui->tableWidget, SIGNAL(cellDoubleClicked (int, int) ), this, SLOT(cellSelected( int, int )));
}
void AssetsPage::update()
{
ui->tableWidget->clearContents();
getBalance();
}
void AssetsPage::on_pasteButton_clicked()
{
ui->chainID->setText(QApplication::clipboard()->text());
}
void AssetsPage::setModel(WalletModel *model)
{
this->model = model;
}
void AssetsPage::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->chainID->setText(dlg.getReturnValue());
ui->amount->setFocus();
}
}
void AssetsPage::clear()
{
// clear UI elements
ui->chainID->clear();
ui->amount->clear();
ui->metadata->clear();
}
void AssetsPage::listunspent()
{
QString response;
if (!sendRequest("listunspent", response)) {
//TODO print error
return;
}
QJsonParseError err;
QJsonDocument jsonDoc = QJsonDocument::fromJson(response.toUtf8(), &err);
QJsonArray jsonArray = jsonDoc.array();
for (int i = 0; i < jsonArray.size(); i++) {
ui->tableWidget->insertRow(0);
QVariant oaAddrElement = jsonArray.at(i).toVariant();
QVariantMap oaAddrMap = oaAddrElement.toMap();
QString oaAddress = oaAddrMap["oa_address"].toString();
QString address = oaAddrMap["address"].toString();
QString assetID = oaAddrMap["asset_id"].toString();
double amount = oaAddrMap["amount"].toDouble();
unsigned long int quantity = oaAddrMap["asset_quantity"].toULongLong();
ui->tableWidget->setItem(i, 0, new QTableWidgetItem(address));
ui->tableWidget->setItem(i, 1, new QTableWidgetItem(oaAddress));
ui->tableWidget->setItem(i, 2, new QTableWidgetItem(assetID));
ui->tableWidget->setItem(i, 3, new QTableWidgetItem(QString::number(quantity)));
ui->tableWidget->setItem(i, 4, new QTableWidgetItem(QString::number(amount)));
}
}
void AssetsPage::getBalance()
{
QString response;
if (!sendRequest("getbalance", response)) {
//TODO print error
return;
}
QString assetID;
QComboBox *assetids;
QComboBox *qtys;
unsigned long int quantity=0;
QJsonParseError err;
QJsonDocument jsonDoc = QJsonDocument::fromJson(response.toUtf8(), &err);
QJsonArray jsonArray = jsonDoc.array();
for (int i = 0; i < jsonArray.size(); i++) {
ui->tableWidget->setRowCount(jsonArray.size());
QVariant oaAddrElement = jsonArray.at(i).toVariant();
QVariantMap oaAddrMap = oaAddrElement.toMap();
QString oaAddress = oaAddrMap["oa_address"].toString();
QString address = oaAddrMap["address"].toString();
double balance = oaAddrMap["value"].toDouble();
QVariantList data = oaAddrMap["assets"].toList();
assetids = new QComboBox;
qtys = new QComboBox;
assetids->setEditable(true);
qtys->setEditable(true);
foreach(QVariant v, data) {
assetids->addItem(v.toMap().value("asset_id").toString());
qtys->addItem(v.toMap().value("quantity").toString());
//assetID = v.toMap().value("asset_id").toString();
//quantity = v.toMap().value("quantity").toULongLong();
}
ui->tableWidget->setItem(i, 0, new QTableWidgetItem(address));
ui->tableWidget->setItem(i, 1, new QTableWidgetItem(oaAddress));
ui->tableWidget->setCellWidget(i, 2, assetids );
ui->tableWidget->setCellWidget(i, 3, qtys );
//ui->tableWidget->setItem(i, 2, new QTableWidgetItem(assetID));
//ui->tableWidget->setItem(i, 3, new QTableWidgetItem(QString::number(quantity)));
ui->tableWidget->setItem(i, 4, new QTableWidgetItem(QString::number(balance)));
}
}
void AssetsPage::sendassets()
{
QProcess p;
QString sendCmd,data;
data=ui->chainID->text()+ " "+ ui->asset->text() + " " +ui->amount->text() +" " + ui->sendTo->text();
QMessageBox msgBox;
msgBox.setWindowTitle("Transfer Asset");
msgBox.setText("Please confirm you wish to send " + ui->amount->text() + "units of " + ui->asset->text() + "to "+ ui->sendTo->text());
msgBox.setStandardButtons(QMessageBox::Yes);
msgBox.addButton(QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Cancel);
if(msgBox.exec() == QMessageBox::Yes){
#ifdef WIN32
p.setWorkingDirectory(QCoreApplication::applicationDirPath());
sendCmd ="cmd.exe /c python.exe assets/colorcore.py sendasset" + data;
#else
sendCmd ="python3.4 "+ QCoreApplication::applicationDirPath() +"/assets/colorcore.py sendasset " + data;
#endif
p.start(sendCmd);
if (!p.waitForStarted()){
LogPrintf("Error: Could not send! \n");
}
p.waitForFinished();
}
ui->chainID->clear();
ui->asset->clear();
ui->amount->clear();
ui->sendTo->clear();
}
void AssetsPage::issueassets()
{
QProcess d,m;
QString sendCmd, data;
data =ui->chainID->text()+" "+ ui->amount->text();
#ifdef WIN32
d.setWorkingDirectory(QCoreApplication::applicationDirPath());
sendCmd = "cmd.exe /c python.exe assets/colorcore.py issueasset "+data ;
#else
sendCmd = "python3.4 "+ QCoreApplication::applicationDirPath() +"/assets/colorcore.py issueasset " + data;
#endif
d.start(sendCmd);
if (!d.waitForStarted()){
LogPrintf("Error: Could not issue! \n");
}
d.waitForFinished();
if (ui->distribute->isChecked()){
data =ui->chainID->text()+" "+ ui->sendTo->text()+" "+ ui->price->text();
#ifdef WIN32
m.setWorkingDirectory(QCoreApplication::applicationDirPath());
sendCmd ="cmd.exe /c python.exe assets/colorcore.py distribute "+ data;
#else
sendCmd ="python3.4 "+ QCoreApplication::applicationDirPath() +"/assets/colorcore.py distribute " + data;
#endif
m.start(sendCmd);
if (!m.waitForStarted()){
LogPrintf("Error: Could not distribute! \n");
}
m.waitForFinished();
}
ui->chainID->clear();
ui->amount->clear();
ui->sendTo->clear();
ui->price->clear();
}
bool AssetsPage::runColorCore()
{
QString startCmd;
QObject::connect(serverProc, SIGNAL(readyRead()), this, SLOT(readPyOut()));
#ifdef WIN32
serverProc->setWorkingDirectory(QCoreApplication::applicationDirPath());
startCmd = "cmd.exe /c python.exe assets/colorcore.py server";
#else
startCmd = "python3.4 " + QCoreApplication::applicationDirPath() + "/assets/colorcore.py server";
#endif
serverProc->start(startCmd);
if (!serverProc->waitForStarted()){
LogPrintf("Error: Could not start! \n");
return false;
}
return true;
}
void AssetsPage::readPyOut() {
QByteArray pyOut = serverProc->readAllStandardOutput();
if (pyOut.length() < 1) {
qDebug() << serverProc->errorString();
return;
}
qDebug() << pyOut;
}
bool AssetsPage::sendRequest(QString cmd, QString& result)
{
QNetworkAccessManager mgr;
QEventLoop eventLoop;
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
QNetworkRequest req(QUrl( QString("http://localhost:8080/"+cmd)));
QNetworkReply *reply = mgr.get(req);
eventLoop.exec();
if (reply->error() == QNetworkReply::NoError) {
result = (QString)reply->readAll();
delete reply;
return true;
}
result = (QString)reply->errorString();
delete reply;
return false;
}
void AssetsPage::cellSelected(int nRow, int nCol)
{
QAbstractItemModel* tmodel = ui->tableWidget->model();
QModelIndex index = tmodel->index(nRow, nCol);
if(nCol==0) ui->chainID->setText(ui->tableWidget->model()->data(index).toString());
if(nCol==1) ui->sendTo->setText(ui->tableWidget->model()->data(index).toString());
if(nCol==2) {
QComboBox *myCB = qobject_cast<QComboBox*>(ui->tableWidget->cellWidget(nRow,nCol));
ui->asset->setText(myCB->currentText());
}
if(nCol==3){
QComboBox *myCB = qobject_cast<QComboBox*>(ui->tableWidget->cellWidget(nRow,nCol));
ui->amount->setText(myCB->currentText());
}
}
AssetsPage::~AssetsPage()
{
serverProc->terminate();
if (serverProc->NotRunning) delete serverProc;
delete ui;
}
<file_sep>#ifndef SERVICESPAGE_H
#define SERVICESPAGE_H
#include <QWidget>
#include <string>
#include "walletmodel.h"
class WalletModel;
namespace Ui {
class ServicesPage;
}
class ServicesPage : public QWidget
{
Q_OBJECT
public:
explicit ServicesPage(QWidget *parent = 0);
~ServicesPage();
void setModel(WalletModel *model);
private slots:
void on_addressBookButton_clicked();
void on_pasteButton_clicked();
private:
Ui::ServicesPage *ui;
void gettrust();
WalletModel *model;
};
#endif // P2PSERVICES_H
<file_sep>// Copyright (c) 2014-2015 The Dash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BASENODEMAN_H
#define BASENODEMAN_H
//#include "bignum.h"
#include "sync.h"
#include "net.h"
#include "key.h"
#include "core.h"
#include "util.h"
#include "script/script.h"
#include "base58.h"
#include "main.h"
#include "basenode.h"
#define BASENODES_DUMP_SECONDS (15*60)
#define BASENODES_DSEG_SECONDS (3*60*60)
using namespace std;
class CBasenodeMan;
extern CBasenodeMan mnodeman;
void DumpBasenodes();
/** Access to the MN database (nodecache.dat)
*/
class CBasenodeDB
{
private:
boost::filesystem::path pathMN;
std::string strMagicMessage;
public:
enum ReadResult {
Ok,
FileError,
HashReadError,
IncorrectHash,
IncorrectMagicMessage,
IncorrectMagicNumber,
IncorrectFormat
};
CBasenodeDB();
bool Write(const CBasenodeMan &mnodemanToSave);
ReadResult Read(CBasenodeMan& mnodemanToLoad);
};
class CBasenodeMan
{
private:
// critical section to protect the inner data structures
mutable CCriticalSection cs;
// map to hold all MNs
// who's asked for the Basenode list and the last time
std::map<CNetAddr, int64_t> mAskedUsForBasenodeList;
// who we asked for the Basenode list and the last time
std::map<CNetAddr, int64_t> mWeAskedForBasenodeList;
// which Basenodes we've asked for
std::map<COutPoint, int64_t> mWeAskedForBasenodeListEntry;
public:
// keep track of dsq count to prevent basenodes from gaming darksend queue
int64_t nDsqCount;
std::vector<CBasenode> vBasenodes;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
// serialized format:
// * version byte (currently 0)
// * basenodes vector
{
LOCK(cs);
unsigned char nVersion = 0;
READWRITE(nVersion);
READWRITE(vBasenodes);
READWRITE(mAskedUsForBasenodeList);
READWRITE(mWeAskedForBasenodeList);
READWRITE(mWeAskedForBasenodeListEntry);
READWRITE(nDsqCount);
}
}
CBasenodeMan();
CBasenodeMan(CBasenodeMan& other);
/// Add an entry
bool Add(CBasenode &mn);
/// Check all Basenodes
void Check();
/// Check all Basenodes and remove inactive
void CheckAndRemove();
/// Clear Basenode vector
void Clear();
int CountEnabled();
int CountBasenodesAboveProtocol(int protocolVersion);
void DsegUpdate(CNode* pnode);
/// Find an entry
CBasenode* Find(const CTxIn& vin);
CBasenode* Find(const CPubKey& pubKeyBasenode);
/// Find an entry thta do not match every entry provided vector
CBasenode* FindOldestNotInVec(const std::vector<CTxIn> &vVins, int nMinimumAge, int nMinimumActiveSeconds);
/// Find a random entry
CBasenode* FindRandom();
/// Get the current winner for this block
CBasenode* GetCurrentBaseNode(int mod=1, int64_t nBlockHeight=0, int minProtocol=0);
std::vector<CBasenode> GetFullBasenodeVector() { Check(); return vBasenodes; }
std::vector<pair<int, CBasenode> > GetBasenodeRanks(int64_t nBlockHeight, int minProtocol=0);
int GetBasenodeRank(const CTxIn &vin, int64_t nBlockHeight, int minProtocol=0, bool fOnlyActive=true);
CBasenode* GetBasenodeByRank(int nRank, int64_t nBlockHeight, int minProtocol=0, bool fOnlyActive=true);
void ProcessBasenodeConnections();
void ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv);
/// Return the number of (unique) Basenodes
int size() { return vBasenodes.size(); }
std::string ToString() const;
//
// Relay Basenode Messages
//
void RelayBasenodeEntry(const CTxIn vin, const CService addr, const std::vector<unsigned char> vchSig, const int64_t nNow, const CPubKey pubkey, const CPubKey pubkey2, const int count, const int current, const int64_t lastUpdated, const int protocolVersion);
void RelayBasenodeEntryPing(const CTxIn vin, const std::vector<unsigned char> vchSig, const int64_t nNow, const bool stop);
void Remove(CTxIn vin);
};
#endif
<file_sep>// Copyright (c) 2014 The BCR developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef RPCWALLET_H
#define RPCWALLET_H
#include "wallet.h"
#include "walletdb.h"
#include "rpcserver.h"
#include "init.h"
#include "net.h"
#include "netbase.h"
#include "timedata.h"
#include "util.h"
#include "utilmoneystr.h"
void SendMoney(const CTxDestination &address, CAmount nValue, CWalletTx& wtxNew);
#endif
<file_sep># -*- coding: utf-8; -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2014 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import asyncio
import lib.bitcoin.base58
import lib.bitcoin.core
import lib.bitcoin.core.serialize
import lib.bitcoin.core.script
import lib.bitcoin.rpc
import lib.bitcoin.wallet
import colorcore.addresses
import colorcore.routing
import decimal
import itertools
import math
import openassets.protocol
import openassets.transactions
class Controller(object):
"""Contains all operations provided by Colorcore."""
def __init__(self, configuration, cache_factory, tx_parser, event_loop):
self.configuration = configuration
self.provider = configuration.create_blockchain_provider(event_loop)
self.tx_parser = tx_parser
self.cache_factory = cache_factory
self.event_loop = event_loop
self.convert = Convert(configuration.asset_byte)
@asyncio.coroutine
def getbalance(self,
address: "Obtain the balance of this address only, or all addresses if unspecified"=None,
minconf: "The minimum number of confirmations (inclusive)"='1',
maxconf: "The maximum number of confirmations (inclusive)"='9999999'
):
"""Obtains the balance of the wallet or an address."""
from_address = self._as_any_address(address) if address is not None else None
unspent_outputs = yield from self._get_unspent_outputs(
from_address, min_confirmations=self._as_int(minconf), max_confirmations=self._as_int(maxconf))
colored_outputs = [output.output for output in unspent_outputs]
sorted_outputs = sorted(colored_outputs, key=lambda output: output.script)
output_groups = [
(script, list(group)) for (script, group)
in itertools.groupby(sorted_outputs, lambda output: output.script)]
if not output_groups and address is not None:
output_groups.append((from_address.to_scriptPubKey(), []))
table = []
for script, script_outputs in output_groups:
total_value = self.convert.to_coin(sum([item.value for item in script_outputs]))
address = self.convert.script_to_address(script)
if address is not None:
oa_address = str(colorcore.addresses.Base58Address(
address, address.nVersion, self.configuration.namespace))
else:
oa_address = None
group_details = {
'address': self.convert.script_to_display_string(script),
'oa_address': oa_address,
'value': total_value,
'assets': []
}
table.append(group_details)
sorted_script_outputs = sorted(
[item for item in script_outputs if item.asset_id],
key=lambda output: output.asset_id)
for asset_id, outputs in itertools.groupby(sorted_script_outputs, lambda output: output.asset_id):
total_quantity = sum([item.asset_quantity for item in outputs])
group_details['assets'].append({
'asset_id': self.convert.asset_id_to_base58(asset_id),
'quantity': str(total_quantity)
})
return table
@asyncio.coroutine
def listunspent(self,
address: "Obtain the balance of this address only, or all addresses if unspecified"=None,
minconf: "The minimum number of confirmations (inclusive)"='1',
maxconf: "The maximum number of confirmations (inclusive)"='9999999'
):
"""Returns an array of unspent transaction outputs augmented with the asset ID and quantity of
each output."""
from_address = self._as_any_address(address) if address is not None else None
unspent_outputs = yield from self._get_unspent_outputs(
from_address, min_confirmations=self._as_int(minconf), max_confirmations=self._as_int(maxconf))
table = []
for output in unspent_outputs:
parsed_address = self.convert.script_to_address(output.output.script)
if parsed_address is not None:
oa_address = str(colorcore.addresses.Base58Address(
parsed_address, parsed_address.nVersion, self.configuration.namespace))
else:
oa_address = None
table.append({
'txid': lib.bitcoin.core.b2lx(output.out_point.hash),
'vout': output.out_point.n,
'address': self.convert.script_to_display_string(output.output.script),
'oa_address': oa_address,
'script': lib.bitcoin.core.b2x(output.output.script),
'amount': self.convert.to_coin(output.output.value),
'confirmations': output.confirmations,
'asset_id':
None if output.output.asset_id is None
else self.convert.asset_id_to_base58(output.output.asset_id),
'asset_quantity': str(output.output.asset_quantity)
})
return table
@asyncio.coroutine
def sendbitcoin(self,
address: "The address to send the bitcoins from",
amount: "The amount of satoshis to send",
to: "The address to send the bitcoins to",
fees: "The fess in satoshis for the transaction"=None,
mode: """'broadcast' (default) for signing and broadcasting the transaction,
'signed' for signing the transaction without broadcasting,
'unsigned' for getting the raw unsigned transaction without broadcasting"""='broadcast'
):
"""Creates a transaction for sending bitcoins from an address to another."""
from_address = self._as_any_address(address)
to_address = self._as_any_address(to)
builder = openassets.transactions.TransactionBuilder(self.configuration.dust_limit)
colored_outputs = yield from self._get_unspent_outputs(from_address)
transfer_parameters = openassets.transactions.TransferParameters(
colored_outputs, to_address.to_scriptPubKey(), from_address.to_scriptPubKey(),
self._as_int(amount))
transaction = builder.transfer_bitcoin(transfer_parameters, self._get_fees(fees))
return self.tx_parser((yield from self._process_transaction(transaction, mode)))
@asyncio.coroutine
def sendasset(self,
address: "The address to send the asset from",
asset: "The asset ID identifying the asset to send",
amount: "The amount of asset units to send",
to: "The address to send the asset to",
fees: "The fess in satoshis for the transaction"=None,
mode: """'broadcast' (default) for signing and broadcasting the transaction,
'signed' for signing the transaction without broadcasting,
'unsigned' for getting the raw unsigned transaction without broadcasting"""='broadcast'
):
"""Creates a transaction for sending an asset from an address to another."""
from_address = self._as_any_address(address)
to_address = self._as_openassets_address(to)
builder = openassets.transactions.TransactionBuilder(self.configuration.dust_limit)
colored_outputs = yield from self._get_unspent_outputs(from_address)
transfer_parameters = openassets.transactions.TransferParameters(
colored_outputs, to_address.to_scriptPubKey(), from_address.to_scriptPubKey(), self._as_int(amount))
transaction = builder.transfer_assets(
self.convert.base58_to_asset_id(asset), transfer_parameters, from_address.to_scriptPubKey(),
self._get_fees(fees))
return self.tx_parser((yield from self._process_transaction(transaction, mode)))
@asyncio.coroutine
def issueasset(self,
address: "The address to issue the asset from",
amount: "The amount of asset units to issue",
to: "The address to send the asset to; if unspecified, the assets are sent back to the issuing address"=None,
metadata: "The metadata to embed in the transaction"='',
fees: "The fess in satoshis for the transaction"=None,
mode: """'broadcast' (default) for signing and broadcasting the transaction,
'signed' for signing the transaction without broadcasting,
'unsigned' for getting the raw unsigned transaction without broadcasting"""='broadcast'
):
"""Creates a transaction for issuing an asset."""
from_address = self._as_any_address(address)
if to is None:
to_address = self._as_any_address(address)
else:
to_address = self._as_openassets_address(to)
builder = openassets.transactions.TransactionBuilder(self.configuration.dust_limit)
colored_outputs = yield from self._get_unspent_outputs(from_address)
issuance_parameters = openassets.transactions.TransferParameters(
colored_outputs, to_address.to_scriptPubKey(), from_address.to_scriptPubKey(), self._as_int(amount))
transaction = builder.issue(issuance_parameters, bytes(metadata, encoding='utf-8'), self._get_fees(fees))
return self.tx_parser((yield from self._process_transaction(transaction, mode)))
@asyncio.coroutine
def distribute(self,
address: "The address to distribute the asset from",
forward_address: "The address where to forward the collected bitcoin funds",
price: "Price of an asset unit in satoshis",
metadata: "The metadata to embed in the transaction"='',
fees: "The fess in satoshis for the transaction"=None,
mode: """'broadcast' for signing and broadcasting the transaction,
'signed' for signing the transaction without broadcasting,
'unsigned' for getting the raw unsigned transaction without broadcasting,
'preview' (default) for displaying a preview of the transactions"""='preview'
):
"""For every inbound transaction sending bitcoins to 'address', create an outbound transaction sending back
to the sender newly issued assets, and send the bitcoins to the forward address. The number of issued coins
sent back is proportional to the number of bitcoins sent, and configurable through the ratio argument.
Because the asset issuance transaction is chained from the inbound transaction, double spend is impossible."""
from_address = self._as_any_address(address)
to_address = self._as_any_address(forward_address)
decimal_price = self._as_decimal(price)
builder = openassets.transactions.TransactionBuilder(self.configuration.dust_limit)
colored_outputs = yield from self._get_unspent_outputs(from_address)
transactions = []
summary = []
for output in colored_outputs:
incoming_transaction = yield from self.provider.get_transaction(output.out_point.hash)
script = bytes(incoming_transaction.vout[0].scriptPubKey)
collected, amount_issued, change = self._calculate_distribution(
output.output.value, decimal_price, self._get_fees(fees), self.configuration.dust_limit)
if amount_issued > 0:
inputs = [lib.bitcoin.core.CTxIn(output.out_point, output.output.script)]
outputs = [
builder._get_colored_output(script),
builder._get_marker_output([amount_issued], bytes(metadata, encoding='utf-8')),
builder._get_uncolored_output(to_address.to_scriptPubKey(), collected)
]
if change > 0:
outputs.append(builder._get_uncolored_output(script, change))
transaction = lib.bitcoin.core.CTransaction(vin=inputs, vout=outputs)
transactions.append(transaction)
summary.append({
'from': self.convert.script_to_display_string(script),
'received': self.convert.to_coin(output.output.value) + " BCR",
'collected': self.convert.to_coin(collected) + " BCR",
'sent': str(amount_issued) + " Units",
'transaction': lib.bitcoin.core.b2lx(output.out_point.hash)
})
if mode == 'preview':
return summary
else:
result = []
for transaction in transactions:
result.append(self.tx_parser((yield from self._process_transaction(transaction, mode))))
return result
@staticmethod
def _calculate_distribution(output_value, price, fees, dust_limit):
effective_amount = output_value - fees - dust_limit
units_issued = int(effective_amount / price)
collected = int(math.ceil(units_issued * price))
change = effective_amount - collected
if change < dust_limit:
collected += change
return collected, units_issued, effective_amount - collected
# Private methods
@staticmethod
def _as_any_address(address):
try:
result = colorcore.addresses.Base58Address.from_string(address)
return result.address
except (lib.bitcoin.wallet.CBitcoinAddressError, lib.bitcoin.base58.Base58ChecksumError):
raise colorcore.routing.ControllerError("The address {} is an invalid address.".format(address))
def _as_openassets_address(self, address):
try:
result = colorcore.addresses.Base58Address.from_string(address)
if result.namespace != self.configuration.namespace:
raise colorcore.routing.ControllerError("The address {} is not an asset address.".format(address))
return result.address
except (lib.bitcoin.wallet.CBitcoinAddressError, lib.bitcoin.base58.Base58ChecksumError):
raise colorcore.routing.ControllerError("The address {} is an invalid address.".format(address))
@staticmethod
def _as_int(value):
try:
return int(value)
except ValueError:
raise colorcore.routing.ControllerError("Value '{}' is not a valid integer.".format(value))
@staticmethod
def _as_decimal(value):
try:
return decimal.Decimal(value)
except decimal.InvalidOperation:
raise colorcore.routing.ControllerError("Value '{}' is not a valid decimal number.".format(value))
def _get_fees(self, value):
if value is None:
return self.configuration.default_fees
else:
return self._as_int(value)
@asyncio.coroutine
def _get_unspent_outputs(self, address, **kwargs):
cache = self.cache_factory()
engine = openassets.protocol.ColoringEngine(self.provider.get_transaction, cache, self.event_loop)
unspent = yield from self.provider.list_unspent(None if address is None else [str(address)], **kwargs)
result = []
for item in unspent:
output_result = yield from engine.get_output(item['outpoint'].hash, item['outpoint'].n)
output = openassets.transactions.SpendableOutput(
lib.bitcoin.core.COutPoint(item['outpoint'].hash, item['outpoint'].n), output_result)
output.confirmations = item['confirmations']
result.append(output)
# Commit new outputs to cache
yield from cache.commit()
return result
@asyncio.coroutine
def _process_transaction(self, transaction, mode):
if mode == 'broadcast' or mode == 'signed':
# Sign the transaction
signed_transaction = yield from self.provider.sign_transaction(transaction)
if not signed_transaction['complete']:
raise colorcore.routing.ControllerError("Could not sign the transaction.")
if mode == 'broadcast':
result = yield from self.provider.send_transaction(signed_transaction['tx'])
return lib.bitcoin.core.b2lx(result)
else:
return signed_transaction['tx']
else:
# Return the transaction in raw format as a hex string
return transaction
class Convert(object):
"""Provides conversion helpers."""
def __init__(self, asset_byte):
self.asset_byte = asset_byte
@staticmethod
def to_coin(satoshis):
return '{0:.8f}'.format(decimal.Decimal(satoshis) / decimal.Decimal(lib.bitcoin.core.COIN))
def base58_to_asset_id(self, base58_asset_id):
"""
Parses a base58 asset ID into its bytes representation.
:param str base58_asset_id: The asset ID in base 58 representation.
:return: The byte representation of the asset ID.
:rtype: bytes
"""
try:
asset_id = lib.bitcoin.base58.CBase58Data(base58_asset_id)
except lib.bitcoin.base58.Base58ChecksumError:
raise colorcore.routing.ControllerError("Invalid asset ID.")
if asset_id.nVersion != self.asset_byte or len(asset_id) != 20:
raise colorcore.routing.ControllerError("Invalid asset ID.")
return bytes(asset_id)
def asset_id_to_base58(self, asset_id):
"""
Returns the base 58 representation of an asset ID.
:param bytes asset_id: The asset ID.
:return: The base58 representation of the asset ID.
:rtype: str
"""
return str(lib.bitcoin.base58.CBase58Data.from_bytes(asset_id, self.asset_byte))
@staticmethod
def script_to_address(script):
"""
Converts an output script to an address if possible, or None otherwise.
:param bytes script: The script to convert.
:return: The converted value.
:rtype: CBitcoinAddress | None
"""
try:
return lib.bitcoin.wallet.CBitcoinAddress.from_scriptPubKey(lib.bitcoin.core.CScript(script))
except lib.bitcoin.wallet.CBitcoinAddressError:
return None
@classmethod
def script_to_display_string(cls, script):
"""
Converts an output script to an address if possible, or a fallback string otherwise.
:param bytes script: The script to convert
:return: The converted value.
:rtype: str
"""
address = cls.script_to_address(script)
return str(address) if address is not None else "Unknown script"
<file_sep>#ifndef CONNECTIONWIDGET_H
#define CONNECTIONWIDGET_H
#include <QWidget>
#include <QTreeWidget>
#include <QSqlDatabase>
class ConnectionWidget: public QWidget
{
Q_OBJECT
public:
explicit ConnectionWidget(QWidget *parent = 0);
~ConnectionWidget();
QSqlDatabase currentDatabase() const;
signals:
void tableActivated(const QString &table);
void metaDataRequested(const QString &tableName);
public slots:
void refresh();
void showMetaData();
void on_tree_itemActivated(QTreeWidgetItem *item, int column);
void on_tree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous);
private:
void setActive(QTreeWidgetItem *);
QTreeWidget *tree;
QAction *metaDataAction;
QString activeDb;
};
#endif
<file_sep>
// Copyright (c) 2014-2015 The Dash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BASENODE_POS_H
#define BASENODE_POS_H
//#include "bignum.h"
#include "sync.h"
#include "net.h"
#include "key.h"
#include "core.h"
#include "util.h"
#include "script/script.h"
#include "base58.h"
#include "main.h"
using namespace std;
using namespace boost;
class CBasenodeScanning;
class CBasenodeScanningError;
extern map<uint256, CBasenodeScanningError> mapBasenodeScanningErrors;
extern CBasenodeScanning mnscan;
static const int MIN_BASENODE_POS_PROTO_VERSION = 70076;
/*
1% of the network is scanned every 2.5 minutes, making a full
round of scanning take about 4.16 hours. We're targeting about
a day of proof-of-service errors for complete removal from the
basenode system.
*/
static const int BASENODE_SCANNING_ERROR_THESHOLD = 6;
#define SCANNING_SUCCESS 1
#define SCANNING_ERROR_NO_RESPONSE 2
#define SCANNING_ERROR_IX_NO_RESPONSE 3
#define SCANNING_ERROR_MAX 3
void ProcessMessageBasenodePOS(CNode* pfrom, std::string& strCommand, CDataStream& vRecv);
class CBasenodeScanning
{
public:
void DoBasenodePOSChecks();
void CleanBasenodeScanningErrors();
};
// Returns how many basenodes are allowed to scan each block
int GetCountScanningPerBlock();
class CBasenodeScanningError
{
public:
CTxIn vinBasenodeA;
CTxIn vinBasenodeB;
int nErrorType;
int nExpiration;
int nBlockHeight;
std::vector<unsigned char> vchBaseNodeSignature;
CBasenodeScanningError ()
{
vinBasenodeA = CTxIn();
vinBasenodeB = CTxIn();
nErrorType = 0;
nExpiration = GetTime()+(60*60);
nBlockHeight = 0;
}
CBasenodeScanningError (CTxIn& vinBasenodeAIn, CTxIn& vinBasenodeBIn, int nErrorTypeIn, int nBlockHeightIn)
{
vinBasenodeA = vinBasenodeAIn;
vinBasenodeB = vinBasenodeBIn;
nErrorType = nErrorTypeIn;
nExpiration = GetTime()+(60*60);
nBlockHeight = nBlockHeightIn;
}
CBasenodeScanningError (CTxIn& vinBasenodeBIn, int nErrorTypeIn, int nBlockHeightIn)
{
//just used for IX, BasenodeA is any client
vinBasenodeA = CTxIn();
vinBasenodeB = vinBasenodeBIn;
nErrorType = nErrorTypeIn;
nExpiration = GetTime()+(60*60);
nBlockHeight = nBlockHeightIn;
}
uint256 GetHash() const {return SerializeHash(*this);}
bool SignatureValid();
bool Sign();
bool IsExpired() {return GetTime() > nExpiration;}
void Relay();
bool IsValid() {
return (nErrorType > 0 && nErrorType <= SCANNING_ERROR_MAX);
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(vinBasenodeA);
READWRITE(vinBasenodeB);
READWRITE(nErrorType);
READWRITE(nExpiration);
READWRITE(nBlockHeight);
READWRITE(vchBaseNodeSignature);
}
};
#endif
<file_sep>// Copyright (c) 2014 The ShadowCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
/*
Notes:
Running with -debug could leave to and from address hashes and public keys in the log.
parameters:
-nosmsg Disable secure messaging (fNoSmsg)
-debugsmsg Show extra debug messages (fDebugSmsg)
-smsgscanchain Scan the block chain for public key addresses on startup
Wallet Locked
A copy of each incoming message is stored in bucket files ending in _wl.dat
wl (wallet locked) bucket files are deleted if they expire, like normal buckets
When the wallet is unlocked all the messages in wl files are scanned.
Address Whitelist
Owned Addresses are stored in smsgAddresses vector
Saved to smsg.ini
Modify options using the smsglocalkeys rpc command or edit the smsg.ini file (with client closed)
*/
#include "smessage.h"
#include <stdint.h>
#include <time.h>
#include <map>
#include <stdexcept>
#include <sstream>
#include <errno.h>
#include <secp256k1.h>
#include <openssl/aes.h>
#include <openssl/evp.h>
#include "crypto/sha512.h"
#include "crypto/hmac_sha256.h"
#include <boost/atomic.hpp>
#include <boost/thread.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include "base58.h"
#include "crypter.h"
#include "db.h"
#include "init.h"
#include "rpcprotocol.h"
#include "dbwrapper.h"
#include "lz4/lz4.c"
#include "xxhash/xxhash.h"
#include "xxhash/xxhash.c"
//! anonymous namespace
namespace {
class CSecp256k1Init {
public:
CSecp256k1Init() {
secp256k1_start(SECP256K1_START_VERIFY);
}
~CSecp256k1Init() {
secp256k1_stop();
}
};
static CSecp256k1Init instance_of_csecp256k1;
}
static bool DeriveKey(secure_buffer &vchP, const CKey &keyR, const CPubKey &cpkDestK)
{
vchP.assign(cpkDestK.begin(), cpkDestK.end());
secure_buffer r(keyR.begin(), keyR.end());
return secp256k1_ec_pubkey_tweak_mul(&vchP[0], vchP.size(), &r[0]);
}
// TODO: For buckets older than current, only need to store no. messages and hash in memory
boost::signals2::signal<void (SecMsgStored& inboxHdr)> NotifySecMsgInboxChanged;
boost::signals2::signal<void (SecMsgStored& outboxHdr)> NotifySecMsgOutboxChanged;
boost::signals2::signal<void ()> NotifySecMsgWalletUnlocked;
bool fSecMsgEnabled = false;
boost::thread secureMsgThread;
std::map<int64_t, SecMsgBucket> smsgBuckets;
std::vector<SecMsgAddress> smsgAddresses;
SecMsgOptions smsgOptions;
uint32_t nPeerIdCounter = 1;
CCriticalSection cs_smsg;
CCriticalSection cs_smsgDB;
CCriticalSection cs_smsgThreads;
leveldb::DB *smsgDB = NULL;
namespace fs = boost::filesystem;
void SecMsgBucket::hashBucket()
{
if (fDebugSmsg)
LogPrintf("SecMsgBucket::hashBucket()\n");
timeChanged = GetTime();
std::set<SecMsgToken>::iterator it;
void* state = XXH32_init(1);
for (it = setTokens.begin(); it != setTokens.end(); ++it)
{
XXH32_update(state, it->sample, 8);
}
hash = XXH32_digest(state);
if (fDebugSmsg)
LogPrintf("Hashed %d messages, hash %u\n", (int) setTokens.size(), hash);
}
bool SecMsgDB::Open(const char* pszMode)
{
if (smsgDB)
{
pdb = smsgDB;
return true;
}
bool fCreate = strchr(pszMode, 'c');
fs::path fullpath = GetDataDir() / "smsgDB";
if (!fCreate
&& (!fs::exists(fullpath)
|| !fs::is_directory(fullpath)))
{
LogPrintf("SecMsgDB::open() - DB does not exist.\n");
return false;
}
leveldb::Options options;
options.create_if_missing = fCreate;
leveldb::Status s = leveldb::DB::Open(options, fullpath.string(), &smsgDB);
if (!s.ok())
{
LogPrintf("SecMsgDB::open() - Error opening db: %s.\n", s.ToString().c_str());
return false;
}
pdb = smsgDB;
return true;
}
class SecMsgBatchScanner : public leveldb::WriteBatch::Handler
{
public:
std::string needle;
bool* deleted;
std::string* foundValue;
bool foundEntry;
SecMsgBatchScanner() : foundEntry(false) {}
virtual void Put(const leveldb::Slice& key, const leveldb::Slice& value)
{
if (key.ToString() == needle)
{
foundEntry = true;
*deleted = false;
*foundValue = value.ToString();
}
}
virtual void Delete(const leveldb::Slice& key)
{
if (key.ToString() == needle)
{
foundEntry = true;
*deleted = true;
}
}
};
// When performing a read, if we have an active batch we need to check it first
// before reading from the database, as the rest of the code assumes that once
// a database transaction begins reads are consistent with it. It would be good
// to change that assumption in future and avoid the performance hit, though in
// practice it does not appear to be large.
bool SecMsgDB::ScanBatch(const CDataStream& key, std::string* value, bool* deleted) const
{
if (!activeBatch)
return false;
*deleted = false;
SecMsgBatchScanner scanner;
scanner.needle = key.str();
scanner.deleted = deleted;
scanner.foundValue = value;
leveldb::Status s = activeBatch->Iterate(&scanner);
if (!s.ok())
{
LogPrintf("SecMsgDB ScanBatch error: %s\n", s.ToString().c_str());
return false;
}
return scanner.foundEntry;
}
bool SecMsgDB::TxnBegin()
{
if (activeBatch)
return true;
activeBatch = new leveldb::WriteBatch();
return true;
}
bool SecMsgDB::TxnCommit()
{
if (!activeBatch)
return false;
leveldb::WriteOptions writeOptions;
writeOptions.sync = true;
leveldb::Status status = pdb->Write(writeOptions, activeBatch);
delete activeBatch;
activeBatch = NULL;
if (!status.ok())
{
LogPrintf("SecMsgDB batch commit failure: %s\n", status.ToString().c_str());
return false;
}
return true;
}
bool SecMsgDB::TxnAbort()
{
delete activeBatch;
activeBatch = NULL;
return true;
}
bool SecMsgDB::ReadPK(CKeyID& addr, CPubKey& pubkey)
{
if (!pdb)
return false;
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(sizeof(addr) + 2);
ssKey << 'p';
ssKey << 'k';
ssKey << addr;
std::string strValue;
bool readFromDb = true;
if (activeBatch)
{
// -- check activeBatch first
bool deleted = false;
readFromDb = ScanBatch(ssKey, &strValue, &deleted) == false;
if (deleted)
return false;
}
if (readFromDb)
{
leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &strValue);
if (!s.ok())
{
if (s.IsNotFound())
return false;
LogPrintf("LevelDB read failure: %s\n", s.ToString().c_str());
return false;
}
}
try {
CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION);
ssValue >> pubkey;
} catch (std::exception& e) {
LogPrintf("SecMsgDB::ReadPK() unserialize threw: %s.\n", e.what());
return false;
}
return true;
}
bool SecMsgDB::WritePK(CKeyID& addr, CPubKey& pubkey)
{
if (!pdb)
return false;
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(sizeof(addr) + 2);
ssKey << 'p';
ssKey << 'k';
ssKey << addr;
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.reserve(sizeof(pubkey));
ssValue << pubkey;
if (activeBatch)
{
activeBatch->Put(ssKey.str(), ssValue.str());
return true;
}
leveldb::WriteOptions writeOptions;
writeOptions.sync = true;
leveldb::Status s = pdb->Put(writeOptions, ssKey.str(), ssValue.str());
if (!s.ok())
{
LogPrintf("SecMsgDB write failure: %s\n", s.ToString().c_str());
return false;
}
return true;
}
bool SecMsgDB::ExistsPK(CKeyID& addr)
{
if (!pdb)
return false;
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(sizeof(addr)+2);
ssKey << 'p';
ssKey << 'k';
ssKey << addr;
std::string unused;
if (activeBatch)
{
bool deleted;
if (ScanBatch(ssKey, &unused, &deleted) && !deleted)
{
return true;
}
}
leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &unused);
return s.IsNotFound() == false;
}
bool SecMsgDB::NextSmesg(leveldb::Iterator* it, std::string& prefix, unsigned char* chKey, SecMsgStored& smsgStored)
{
if (!pdb)
return false;
if (!it->Valid()) // first run
it->Seek(prefix);
else
it->Next();
if (!(it->Valid()
&& it->key().size() == 18
&& memcmp(it->key().data(), prefix.data(), 2) == 0))
return false;
memcpy(chKey, it->key().data(), 18);
try {
CDataStream ssValue(it->value().data(), it->value().data() + it->value().size(), SER_DISK, CLIENT_VERSION);
ssValue >> smsgStored;
} catch (std::exception& e) {
LogPrintf("SecMsgDB::NextSmesg() unserialize threw: %s.\n", e.what());
return false;
}
return true;
}
bool SecMsgDB::NextSmesgKey(leveldb::Iterator* it, std::string& prefix, unsigned char* chKey)
{
if (!pdb)
return false;
if (!it->Valid()) // first run
it->Seek(prefix);
else
it->Next();
if (!(it->Valid()
&& it->key().size() == 18
&& memcmp(it->key().data(), prefix.data(), 2) == 0))
return false;
memcpy(chKey, it->key().data(), 18);
return true;
}
bool SecMsgDB::ReadSmesg(unsigned char* chKey, SecMsgStored& smsgStored)
{
if (!pdb)
return false;
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write((const char*)chKey, 18);
std::string strValue;
bool readFromDb = true;
if (activeBatch)
{
// -- check activeBatch first
bool deleted = false;
readFromDb = ScanBatch(ssKey, &strValue, &deleted) == false;
if (deleted)
return false;
}
if (readFromDb)
{
leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &strValue);
if (!s.ok())
{
if (s.IsNotFound())
return false;
LogPrintf("LevelDB read failure: %s\n", s.ToString().c_str());
return false;
}
}
try {
CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION);
ssValue >> smsgStored;
} catch (std::exception& e) {
LogPrintf("SecMsgDB::ReadSmesg() unserialize threw: %s.\n", e.what());
return false;
}
return true;
}
bool SecMsgDB::WriteSmesg(unsigned char* chKey, SecMsgStored& smsgStored)
{
if (!pdb)
return false;
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write((const char*)chKey, 18);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue << smsgStored;
if (activeBatch)
{
activeBatch->Put(ssKey.str(), ssValue.str());
return true;
}
leveldb::WriteOptions writeOptions;
writeOptions.sync = true;
leveldb::Status s = pdb->Put(writeOptions, ssKey.str(), ssValue.str());
if (!s.ok())
{
LogPrintf("SecMsgDB write failed: %s\n", s.ToString().c_str());
return false;
}
return true;
}
bool SecMsgDB::ExistsSmesg(unsigned char* chKey)
{
if (!pdb)
return false;
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write((const char*)chKey, 18);
std::string unused;
if (activeBatch)
{
bool deleted;
if (ScanBatch(ssKey, &unused, &deleted) && !deleted)
{
return true;
}
}
leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &unused);
return s.IsNotFound() == false;
return true;
}
bool SecMsgDB::EraseSmesg(unsigned char* chKey)
{
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write((const char*)chKey, 18);
if (activeBatch)
{
activeBatch->Delete(ssKey.str());
return true;
}
leveldb::WriteOptions writeOptions;
writeOptions.sync = true;
leveldb::Status s = pdb->Delete(writeOptions, ssKey.str());
if (s.ok() || s.IsNotFound())
return true;
LogPrintf("SecMsgDB erase failed: %s\n", s.ToString().c_str());
return false;
}
static boost::atomic_uint nThreadCount(0);
void ThreadSecureMsg(void* parg)
{
nThreadCount.fetch_add(1, boost::memory_order_relaxed);
// -- bucket management thread
RenameThread("bitcredit-smsg"); // Make this thread recognisable
std::vector<unsigned char> vchKey;
SecMsgStored smsgStored;
std::string sPrefix("qm");
unsigned char chKey[18];
while (fSecMsgEnabled) {
int64_t now = GetTime();
int64_t cutoffTime = now - SMSG_RETENTION;
{
LOCK(cs_smsg);
for (std::map<int64_t, SecMsgBucket>::iterator it(smsgBuckets.begin()); it != smsgBuckets.end(); it++) {
//if (fDebugSmsg)
// LogPrintf("Checking bucket %"PRId64", size %"PRIszu" \n", it->first, it->second.setTokens.size());
if (it->first < cutoffTime) {
if (fDebugSmsg)
LogPrintf("Removing bucket %d\n", (int) it->first);
std::string fileName = boost::lexical_cast<std::string>(it->first);
fs::path fullPath = GetDataDir() / "smsgStore" / (fileName + "_01.dat");
if (fs::exists(fullPath)) {
try {
fs::remove(fullPath);
}
catch (const fs::filesystem_error& ex) {
LogPrintf("Error removing bucket file %s.\n", ex.what());
}
}
else {
LogPrintf("Path %s does not exist\n", fullPath.string().c_str());
}
// -- look for a wl file, it stores incoming messages when wallet is locked
fullPath = GetDataDir() / "smsgStore" / (fileName + "_01_wl.dat");
if (fs::exists(fullPath)) {
try {
fs::remove(fullPath);
}
catch (const fs::filesystem_error& ex) {
LogPrintf("Error removing wallet locked file %s.\n", ex.what());
}
}
smsgBuckets.erase(it);
}
else if (it->second.nLockCount > 0) { // -- tick down nLockCount, so will eventually expire if peer never sends data
it->second.nLockCount--;
if (it->second.nLockCount == 0) { // lock timed out
uint32_t nPeerId = it->second.nLockPeerId;
int64_t ignoreUntil = GetTime() + SMSG_TIME_IGNORE;
if (fDebugSmsg)
LogPrintf("Lock on bucket %d for peer %u timed out.\n", (int) it->first, nPeerId);
// -- look through the nodes for the peer that locked this bucket
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (pnode->smsgData.nPeerId != nPeerId)
continue;
pnode->smsgData.ignoreUntil = ignoreUntil;
// -- alert peer that they are being ignored
std::vector<unsigned char> vchData;
vchData.resize(8);
memcpy(&vchData[0], &ignoreUntil, 8);
pnode->PushMessage("smsgIgnore", vchData);
if (fDebugSmsg)
LogPrintf("Lock on bucket %d for peer %u timed out.\n", (int) it->first, nPeerId);
break;
}
it->second.nLockPeerId = 0;
} // if (it->second.nLockCount == 0)
} // ! if (it->first < cutoffTime)
}
} // LOCK(cs_smsg);
SecMsgDB dbOutbox;
leveldb::Iterator* it;
{
LOCK(cs_smsgDB);
if (!dbOutbox.Open("cr+"))
continue;
// -- fifo (smallest key first)
it = dbOutbox.pdb->NewIterator(leveldb::ReadOptions());
}
// -- break up lock, SecureMsgSetHash will take long
for (;;)
{
{
LOCK(cs_smsgDB);
if (!dbOutbox.NextSmesg(it, sPrefix, chKey, smsgStored))
break;
}
SecureMessageHeader smsg(&smsgStored.vchMessage[0]);
const unsigned char* pPayload = &smsgStored.vchMessage[SMSG_HDR_LEN];
// -- message is removed here, no matter what
{
LOCK(cs_smsgDB);
dbOutbox.EraseSmesg(chKey);
}
// -- add to message store
{
LOCK(cs_smsg);
if (SecureMsgStore(smsg, pPayload, true) != 0) {
LogPrintf("SecMsgPow: Could not place message in buckets, message removed.\n");
continue;
}
}
// -- test if message was sent to self
if (SecureMsgScanMessage(smsg, pPayload, true) != 0) {
// message recipient is not this node (or failed)
}
}
{
LOCK(cs_smsg);
delete it;
}
try {
boost::this_thread::sleep_for(boost::chrono::seconds(SMSG_THREAD_DELAY)); // check every SMSG_THREAD_DELAY seconds
}
catch(boost::thread_interrupted &e) {
break;
}
}
LogPrintf("ThreadSecureMsg exited.\n");
nThreadCount.fetch_sub(1, boost::memory_order_relaxed);
}
int SecureMsgBuildBucketSet()
{
/*
Build the bucket set by scanning the files in the smsgStore dir.
smsgBuckets should be empty
*/
if (fDebugSmsg)
LogPrintf("SecureMsgBuildBucketSet()\n");
int64_t now = GetTime();
uint32_t nFiles = 0;
uint32_t nMessages = 0;
fs::path pathSmsgDir = GetDataDir() / "smsgStore";
fs::directory_iterator itend;
if (!fs::exists(pathSmsgDir)
|| !fs::is_directory(pathSmsgDir))
{
if (!fs::create_directory(pathSmsgDir)) {
LogPrintf("Message store directory does not exist and could not be created.\n");
return 1;
}
}
for (fs::directory_iterator itd(pathSmsgDir) ; itd != itend ; ++itd) {
if (!fs::is_regular_file(itd->status()))
continue;
std::string fileType = (*itd).path().extension().string();
if (fileType.compare(".dat") != 0)
continue;
std::string fileName = (*itd).path().filename().string();
if (fDebugSmsg)
LogPrintf("Processing file: %s.\n", fileName.c_str());
nFiles++;
// TODO files must be split if > 2GB
// time_noFile.dat
size_t sep = fileName.find_first_of("_");
if (sep == std::string::npos)
continue;
std::string stime = fileName.substr(0, sep);
int64_t fileTime = boost::lexical_cast<int64_t>(stime);
if (fileTime < now - SMSG_RETENTION) {
LogPrintf("Dropping file %s, expired.\n", fileName.c_str());
try {
fs::remove((*itd).path());
}
catch (const fs::filesystem_error& ex) {
LogPrintf("Error removing bucket file %s, %s.\n", fileName.c_str(), ex.what());
}
continue;
}
if (boost::algorithm::ends_with(fileName, "_wl.dat")) {
if (fDebugSmsg)
LogPrintf("Skipping wallet locked file: %s.\n", fileName.c_str());
continue;
}
SecureMessageHeader smsg;
std::set<SecMsgToken>& tokenSet = smsgBuckets[fileTime].setTokens;
{
LOCK(cs_smsg);
FILE *fp;
if (!(fp = fopen((*itd).path().string().c_str(), "rb"))) {
LogPrintf("Error opening file: %s (%d)\n", strerror(errno), __LINE__);
continue;
}
for (;;) {
long int ofs = ftell(fp);
SecMsgToken token;
token.offset = ofs;
if (fread(&smsg, sizeof(unsigned char), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN) {
if (!feof(fp)) {
LogPrintf("fread header failed\n");
}
break;
}
token.timestamp = smsg.timestamp;
if (smsg.nPayload < 8)
continue;
if (fread(token.sample, sizeof(unsigned char), 8, fp) != 8) {
LogPrintf("fread data failed: %s\n", strerror(errno));
break;
}
if (fseek(fp, smsg.nPayload-8, SEEK_CUR) != 0) {
LogPrintf("fseek, strerror: %s.\n", strerror(errno));
break;
}
tokenSet.insert(token);
}
fclose(fp);
}
smsgBuckets[fileTime].hashBucket();
nMessages += tokenSet.size();
if (fDebugSmsg)
LogPrintf("Bucket %d contains %d messages.\n", (int) fileTime, (int) tokenSet.size());
}
LogPrintf("Processed %u files, loaded %d buckets containing %u messages.\n", nFiles, (int) smsgBuckets.size(), nMessages);
return 0;
}
int SecureMsgAddWalletAddresses()
{
if (fDebugSmsg)
LogPrintf("SecureMsgAddWalletAddresses()\n");
std::string sAnonPrefix("ao");
uint32_t nAdded = 0;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook)
{
if (IsMine(*pwalletMain, entry.first) != ISMINE_SPENDABLE)
continue;
// -- skip addresses for anon outputs
if (entry.second.purpose.compare(0, sAnonPrefix.length(), sAnonPrefix) == 0)
continue;
// TODO: skip addresses for stealth transactions
CBitcreditAddress coinAddress(entry.first);
if (!coinAddress.IsValid())
continue;
std::string address;
std::string strPublicKey;
address = coinAddress.ToString();
bool fExists = 0;
for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)
{
if (address != it->sAddress)
continue;
fExists = 1;
break;
}
if (fExists)
continue;
bool recvEnabled = 1;
bool recvAnon = 1;
smsgAddresses.push_back(SecMsgAddress(address, recvEnabled, recvAnon));
nAdded++;
}
if (fDebugSmsg)
LogPrintf("Added %u addresses to whitelist.\n", nAdded);
return 0;
}
int SecureMsgReadIni()
{
if (!fSecMsgEnabled)
return false;
if (fDebugSmsg)
LogPrintf("SecureMsgReadIni()\n");
fs::path fullpath = GetDataDir() / "bitcredit.conf";
FILE *fp;
errno = 0;
if (!(fp = fopen(fullpath.string().c_str(), "r")))
{
LogPrintf("Error opening file: %s (%d)\n", strerror(errno), __LINE__);
return 1;
}
char cLine[512];
char *pName, *pValue;
char cAddress[64];
int addrRecv, addrRecvAnon;
while (fgets(cLine, 512, fp))
{
cLine[strcspn(cLine, "\n")] = '\0';
cLine[strcspn(cLine, "\r")] = '\0';
cLine[511] = '\0'; // for safety
// -- check that line contains a name value pair and is not a comment, or section header
if (cLine[0] == '#' || cLine[0] == '[' || strcspn(cLine, "=") < 1)
continue;
if (!(pName = strtok(cLine, "="))
|| !(pValue = strtok(NULL, "=")))
continue;
if (strcmp(pName, "newAddressRecv") == 0)
{
smsgOptions.fNewAddressRecv = (strcmp(pValue, "true") == 0) ? true : false;
} else
if (strcmp(pName, "newAddressAnon") == 0)
{
smsgOptions.fNewAddressAnon = (strcmp(pValue, "true") == 0) ? true : false;
} else
if (strcmp(pName, "key") == 0)
{
int rv = sscanf(pValue, "%64[^|]|%d|%d", cAddress, &addrRecv, &addrRecvAnon);
if (rv == 3)
{
smsgAddresses.push_back(SecMsgAddress(std::string(cAddress), addrRecv, addrRecvAnon));
} else
{
LogPrintf("Could not parse key line %s, rv %d.\n", pValue, rv);
}
} else
{
LogPrintf("Unknown setting name: '%s'.", pName);
}
}
LogPrintf("Loaded %d addresses.\n", (int) smsgAddresses.size());
fclose(fp);
return 0;
}
int SecureMsgWriteIni()
{
if (!fSecMsgEnabled)
return false;
if (fDebugSmsg)
LogPrintf("SecureMsgWriteIni()\n");
fs::path fullpath = GetDataDir() / "smsg.ini~";
FILE *fp;
errno = 0;
if (!(fp = fopen(fullpath.string().c_str(), "w")))
{
LogPrintf("Error opening file: %s (%d)\n", strerror(errno), __LINE__);
return 1;
}
if (fwrite("[Options]\n", sizeof(char), 10, fp) != 10)
{
LogPrintf("fwrite error: %s\n", strerror(errno));
fclose(fp);
return false;
}
if (fprintf(fp, "newAddressRecv=%s\n", smsgOptions.fNewAddressRecv ? "true" : "false") < 0
|| fprintf(fp, "newAddressAnon=%s\n", smsgOptions.fNewAddressAnon ? "true" : "false") < 0)
{
LogPrintf("fprintf error: %s\n", strerror(errno));
fclose(fp);
return false;
}
if (fwrite("\n[Keys]\n", sizeof(char), 8, fp) != 8)
{
LogPrintf("fwrite error: %s\n", strerror(errno));
fclose(fp);
return false;
}
for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)
{
errno = 0;
if (fprintf(fp, "key=%s|%d|%d\n", it->sAddress.c_str(), it->fReceiveEnabled, it->fReceiveAnon) < 0)
{
LogPrintf("fprintf error: %s\n", strerror(errno));
continue;
}
}
fclose(fp);
try {
fs::path finalpath = GetDataDir() / "smsg.ini";
fs::rename(fullpath, finalpath);
} catch (const fs::filesystem_error& ex)
{
LogPrintf("Error renaming file %s, %s.\n", fullpath.string().c_str(), ex.what());
}
return 0;
}
/** called from AppInit2() in init.cpp */
bool SecureMsgStart(bool fDontStart, bool fScanChain) {
if (fDontStart) {
LogPrintf("Secure messaging not started.\n");
return false;
}
LogPrintf("Secure messaging starting.\n");
SecureMsgEnable();
if (fScanChain) {
SecureMsgScanBlockChain();
}
return true;
}
bool SecureMsgEnable() {
// -- start secure messaging at runtime
if (fSecMsgEnabled) {
LogPrintf("SecureMsgEnable: secure messaging is already enabled.\n");
return false;
}
{
LOCK(cs_smsg);
fSecMsgEnabled = true;
smsgAddresses.clear(); // should be empty already
if (SecureMsgReadIni() != 0)
LogPrintf("Failed to read smsg.ini\n");
if (smsgAddresses.size() < 1) {
LogPrintf("No address keys loaded.\n");
if (SecureMsgAddWalletAddresses() != 0)
LogPrintf("Failed to load addresses from wallet.\n");
}
smsgBuckets.clear(); // should be empty already
if (SecureMsgBuildBucketSet() != 0) {
LogPrintf("SecureMsgEnable: could not load bucket sets, secure messaging disabled.\n");
fSecMsgEnabled = false;
return false;
}
} // LOCK(cs_smsg);
// -- start threads
secureMsgThread = boost::thread(&ThreadSecureMsg, (void*) NULL);
if (secureMsgThread.get_id() == boost::this_thread::get_id()) {
LogPrintf("SecureMsgEnable could not start threads, secure messaging disabled.\n");
fSecMsgEnabled = false;
return false;
}
// -- ping each peer, don't know which have messaging enabled
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
pnode->PushMessage("smsgPing");
pnode->PushMessage("smsgPong"); // Send pong as have missed initial ping sent by peer when it connected
}
}
LogPrintf("Secure messaging enabled.\n");
return true;
}
bool SecureMsgDisable() {
// -- stop secure messaging at runtime
if (!fSecMsgEnabled) {
LogPrintf("SecureMsgDisable: secure messaging is already disabled.\n");
return false;
}
{
LOCK(cs_smsg);
fSecMsgEnabled = false;
// -- clear smsgBuckets
std::map<int64_t, SecMsgBucket>::iterator it;
it = smsgBuckets.begin();
for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it) {
it->second.setTokens.clear();
}
smsgBuckets.clear();
// -- tell each smsg enabled peer that this node is disabling
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (!pnode->smsgData.fEnabled)
continue;
pnode->PushMessage("smsgDisabled");
pnode->smsgData.fEnabled = false;
}
}
if (SecureMsgWriteIni() != 0)
LogPrintf("Failed to save smsg.ini\n");
smsgAddresses.clear();
} // LOCK(cs_smsg);
secureMsgThread.interrupt();
if (secureMsgThread.joinable())
secureMsgThread.join();
if (smsgDB) {
LOCK(cs_smsgDB);
delete smsgDB;
smsgDB = NULL;
}
LogPrintf("Secure messaging disabled.\n");
return true;
}
bool SecureMsgReceiveData(CNode* pfrom, std::string strCommand, CDataStream& vRecv)
{
/*
Called from ProcessMessage
Runs in ThreadMessageHandler2
*/
if (fDebugSmsg)
LogPrintf("SecureMsgReceiveData() %s %s.\n", pfrom->addrName.c_str(), strCommand.c_str());
{
// break up?
LOCK(cs_smsg);
if (strCommand == "smsgInv")
{
std::vector<unsigned char> vchData;
vRecv >> vchData;
if (vchData.size() < 4)
{
Misbehaving(pfrom->GetId(), 1);
return false; // not enough data received to be a valid smsgInv
}
int64_t now = GetTime();
if (now < pfrom->smsgData.ignoreUntil)
{
if (fDebugSmsg)
LogPrintf("Node is ignoring peer %u until %d.\n", pfrom->smsgData.nPeerId, (int) pfrom->smsgData.ignoreUntil);
return false;
}
uint32_t nBuckets = smsgBuckets.size();
uint32_t nLocked = 0; // no. of locked buckets on this node
uint32_t nInvBuckets; // no. of bucket headers sent by peer in smsgInv
memcpy(&nInvBuckets, &vchData[0], 4);
if (fDebugSmsg)
LogPrintf("Remote node sent %d bucket headers, this has %d.\n", nInvBuckets, nBuckets);
// -- Check no of buckets:
if (nInvBuckets > (SMSG_RETENTION / SMSG_BUCKET_LEN) + 1) // +1 for some leeway
{
LogPrintf("Peer sent more bucket headers than possible %u, %u.\n", nInvBuckets, (SMSG_RETENTION / SMSG_BUCKET_LEN));
Misbehaving(pfrom->GetId(), 1);
return false;
}
if (vchData.size() < 4 + nInvBuckets*16)
{
LogPrintf("Remote node did not send enough data.\n");
Misbehaving(pfrom->GetId(), 1);
return false;
}
std::vector<unsigned char> vchDataOut;
vchDataOut.reserve(4 + 8 * nInvBuckets); // reserve max possible size
vchDataOut.resize(4);
uint32_t nShowBuckets = 0;
unsigned char *p = &vchData[4];
for (uint32_t i = 0; i < nInvBuckets; ++i)
{
int64_t time;
uint32_t ncontent, hash;
memcpy(&time, p, 8);
memcpy(&ncontent, p+8, 4);
memcpy(&hash, p+12, 4);
p += 16;
// Check time valid:
if (time < now - SMSG_RETENTION)
{
if (fDebugSmsg)
LogPrintf("Not interested in peer bucket %d, has expired.\n", (int) time);
if (time < now - SMSG_RETENTION - SMSG_TIME_LEEWAY){
Misbehaving(pfrom->GetId(), 1);
}
continue;
}
if (time > now + SMSG_TIME_LEEWAY)
{
if (fDebugSmsg)
LogPrintf("Not interested in peer bucket %d, in the future.\n", (int) time);
Misbehaving(pfrom->GetId(), 1);
continue;
}
if (ncontent < 1)
{
if (fDebugSmsg)
LogPrintf("Peer sent empty bucket, ignore %d %u %u.\n", (int32_t) time, ncontent, hash);
continue;
}
if (fDebugSmsg)
{
LogPrintf("peer bucket %d %u %u.\n", (int32_t) time, ncontent, hash);
//std::cout << "this bucket " << time << ", " << smsgBuckets[time].setTokens.size() << ", " << smsgBuckets[time].hash << std::endl;
}
if (smsgBuckets[time].nLockCount > 0)
{
if (fDebugSmsg)
//std::cout << "Bucket is locked " << smsgBuckets[time].nLockCount << " waiting for peer " << smsgBuckets[time].nLockPeerId << " to send data." << std::endl;
LogPrintf("Bucket is locked %d, waiting for peer %d to send data.\n", smsgBuckets[time].nLockCount, smsgBuckets[time].nLockPeerId);
nLocked++;
continue;
}
// -- if this node has more than the peer node, peer node will pull from this
// if then peer node has more this node will pull fom peer
if (smsgBuckets[time].setTokens.size() < ncontent
|| (smsgBuckets[time].setTokens.size() == ncontent
&& smsgBuckets[time].hash != hash)) // if same amount in buckets check hash
{
if (fDebugSmsg)
LogPrintf("Requesting contents of bucket %d.\n", (int32_t) time);
uint32_t sz = vchDataOut.size();
vchDataOut.resize(sz + 8);
memcpy(&vchDataOut[sz], &time, 8);
nShowBuckets++;
}
}
// TODO: should include hash?
memcpy(&vchDataOut[0], &nShowBuckets, 4);
if (vchDataOut.size() > 4)
{
pfrom->PushMessage("smsgShow", vchDataOut);
} else
if (nLocked < 1) // Don't report buckets as matched if any are locked
{
// -- peer has no buckets we want, don't send them again until something changes
// peer will still request buckets from this node if needed (< ncontent)
vchDataOut.resize(8);
memcpy(&vchDataOut[0], &now, 8);
pfrom->PushMessage("smsgMatch", vchDataOut);
if (fDebugSmsg)
LogPrintf("Sending smsgMatch, %d.\n", (int32_t) now);
}
} else
if (strCommand == "smsgShow")
{
std::vector<unsigned char> vchData;
vRecv >> vchData;
if (vchData.size() < 4)
return false;
uint32_t nBuckets;
memcpy(&nBuckets, &vchData[0], 4);
if (vchData.size() < 4 + nBuckets * 8)
return false;
if (fDebugSmsg)
LogPrintf("smsgShow: peer wants to see content of %u buckets.\n", nBuckets);
std::map<int64_t, SecMsgBucket>::iterator itb;
std::set<SecMsgToken>::iterator it;
std::vector<unsigned char> vchDataOut;
int64_t time;
unsigned char* pIn = &vchData[4];
for (uint32_t i = 0; i < nBuckets; ++i, pIn += 8)
{
memcpy(&time, pIn, 8);
itb = smsgBuckets.find(time);
if (itb == smsgBuckets.end())
{
if (fDebugSmsg)
LogPrintf("Don't have bucket %d.\n", (int32_t) time);
continue;
}
std::set<SecMsgToken>& tokenSet = (*itb).second.setTokens;
try { vchDataOut.resize(8 + 16 * tokenSet.size()); } catch (std::exception& e)
{
std::cout << "vchDataOut.resize " << (8 + 16 * tokenSet.size()) << " threw " << e.what() << std::endl;
continue;
}
memcpy(&vchDataOut[0], &time, 8);
unsigned char* p = &vchDataOut[8];
for (it = tokenSet.begin(); it != tokenSet.end(); ++it)
{
memcpy(p, &it->timestamp, 8);
memcpy(p+8, &it->sample, 8);
p += 16;
}
pfrom->PushMessage("smsgHave", vchDataOut);
}
} else
if (strCommand == "smsgHave")
{
// -- peer has these messages in bucket
std::vector<unsigned char> vchData;
vRecv >> vchData;
if (vchData.size() < 8)
return false;
int n = (vchData.size() - 8) / 16;
int64_t time;
memcpy(&time, &vchData[0], 8);
// -- Check time valid:
int64_t now = GetTime();
if (time < now - SMSG_RETENTION)
{
if (fDebugSmsg)
LogPrintf("Not interested in peer bucket %d, has expired.\n", (int32_t) time);
return false;
}
if (time > now + SMSG_TIME_LEEWAY)
{
if (fDebugSmsg)
LogPrintf("Not interested in peer bucket %d, in the future.\n", (int32_t) time);
Misbehaving(pfrom->GetId(), 1);
return false;
}
if (smsgBuckets[time].nLockCount > 0)
{
if (fDebugSmsg)
LogPrintf("Bucket %d lock count %u, waiting for message data from peer %u.\n", (int32_t) time, smsgBuckets[time].nLockCount, smsgBuckets[time].nLockPeerId);
return false;
}
if (fDebugSmsg)
LogPrintf("Sifting through bucket %d.\n", (int32_t) time);
std::vector<unsigned char> vchDataOut;
vchDataOut.resize(8);
memcpy(&vchDataOut[0], &vchData[0], 8);
std::set<SecMsgToken>& tokenSet = smsgBuckets[time].setTokens;
std::set<SecMsgToken>::iterator it;
SecMsgToken token;
unsigned char* p = &vchData[8];
for (int i = 0; i < n; ++i)
{
memcpy(&token.timestamp, p, 8);
memcpy(&token.sample, p+8, 8);
it = tokenSet.find(token);
if (it == tokenSet.end())
{
int nd = vchDataOut.size();
try {
vchDataOut.resize(nd + 16);
} catch (std::exception& e) {
LogPrintf("vchDataOut.resize %d threw: %s.\n", nd + 16, e.what());
continue;
}
memcpy(&vchDataOut[nd], p, 16);
}
p += 16;
}
if (vchDataOut.size() > 8)
{
if (fDebugSmsg)
{
LogPrintf("Asking peer for %d messages.\n", (int) (vchDataOut.size() - 8) / 16);
LogPrintf("Locking bucket %d for peer %u.\n", (int) time, pfrom->smsgData.nPeerId);
}
smsgBuckets[time].nLockCount = 3; // lock this bucket for at most 3 * SMSG_THREAD_DELAY seconds, unset when peer sends smsgMsg
smsgBuckets[time].nLockPeerId = pfrom->smsgData.nPeerId;
pfrom->PushMessage("smsgWant", vchDataOut);
}
} else
if (strCommand == "smsgWant")
{
std::vector<unsigned char> vchData;
vRecv >> vchData;
if (vchData.size() < 8)
return false;
std::vector<unsigned char> vchOne;
std::vector<unsigned char> vchBunch;
vchBunch.resize(4+8); // nmessages + bucketTime
int n = (vchData.size() - 8) / 16;
int64_t time;
uint32_t nBunch = 0;
memcpy(&time, &vchData[0], 8);
std::map<int64_t, SecMsgBucket>::iterator itb;
itb = smsgBuckets.find(time);
if (itb == smsgBuckets.end())
{
if (fDebugSmsg)
LogPrintf("Don't have bucket %d.\n", (int32_t) time);
return false;
}
std::set<SecMsgToken>& tokenSet = itb->second.setTokens;
std::set<SecMsgToken>::iterator it;
SecMsgToken token;
unsigned char* p = &vchData[8];
for (int i = 0; i < n; ++i)
{
memcpy(&token.timestamp, p, 8);
memcpy(&token.sample, p+8, 8);
it = tokenSet.find(token);
if (it == tokenSet.end())
{
if (fDebugSmsg)
LogPrintf("Don't have wanted message %d.\n", (int32_t) token.timestamp);
} else
{
//LogPrintf("Have message at %"PRId64".\n", it->offset); // DEBUG
token.offset = it->offset;
//LogPrintf("winb before SecureMsgRetrieve %"PRId64".\n", token.timestamp);
// -- place in vchOne so if SecureMsgRetrieve fails it won't corrupt vchBunch
SecureMessage smsg;
if (SecureMsgRetrieve(token, smsg) == 0)
{
nBunch++;
const size_t size = vchBunch.size();
vchBunch.resize(size + SMSG_HDR_LEN + smsg.nPayload);
memcpy(&vchBunch[size], &smsg, SMSG_HDR_LEN);
memcpy(&vchBunch[size+SMSG_HDR_LEN], &smsg.vchPayload[0], smsg.nPayload);
} else
{
LogPrintf("SecureMsgRetrieve failed %d.\n", (int32_t) token.timestamp);
}
if (nBunch >= 500
|| vchBunch.size() >= 96000)
{
if (fDebugSmsg)
LogPrintf("Break bunch %u, %d.\n", nBunch, (int) vchBunch.size());
break; // end here, peer will send more want messages if needed.
}
}
p += 16;
}
if (nBunch > 0)
{
if (fDebugSmsg)
LogPrintf("Sending block of %u messages for bucket %d.\n", nBunch, (int32_t) time);
memcpy(&vchBunch[0], &nBunch, 4);
memcpy(&vchBunch[4], &time, 8);
pfrom->PushMessage("smsgMsg", vchBunch);
}
} else
if (strCommand == "smsgMsg")
{
std::vector<unsigned char> vchData;
vRecv >> vchData;
if (fDebugSmsg)
LogPrintf("smsgMsg vchData.size() %d.\n", (int) vchData.size());
SecureMsgReceive(pfrom, vchData);
} else
if (strCommand == "smsgMatch")
{
std::vector<unsigned char> vchData;
vRecv >> vchData;
if (vchData.size() < 8)
{
LogPrintf("smsgMatch, not enough data %d.\n", (int) vchData.size());
Misbehaving(pfrom->GetId(), 1);
return false;
}
int64_t time;
memcpy(&time, &vchData[0], 8);
int64_t now = GetTime();
if (time > now + SMSG_TIME_LEEWAY)
{
LogPrintf("Warning: Peer buckets matched in the future: %d.\nEither this node or the peer node has the incorrect time set.\n", (int32_t) time);
if (fDebugSmsg)
LogPrintf("Peer match time set to now.\n");
time = now;
}
pfrom->smsgData.lastMatched = time;
if (fDebugSmsg)
LogPrintf("Peer buckets matched at %d.\n", (int32_t) time);
} else
if (strCommand == "smsgPing")
{
// -- smsgPing is the initial message, send reply
pfrom->PushMessage("smsgPong");
} else
if (strCommand == "smsgPong")
{
if (fDebugSmsg)
LogPrintf("Peer replied, secure messaging enabled.\n");
pfrom->smsgData.fEnabled = true;
} else
if (strCommand == "smsgDisabled")
{
// -- peer has disabled secure messaging.
pfrom->smsgData.fEnabled = false;
if (fDebugSmsg)
LogPrintf("Peer %u has disabled secure messaging.\n", pfrom->smsgData.nPeerId);
} else
if (strCommand == "smsgIgnore")
{
// -- peer is reporting that it will ignore this node until time.
// Ignore peer too
std::vector<unsigned char> vchData;
vRecv >> vchData;
if (vchData.size() < 8)
{
LogPrintf("smsgIgnore, not enough data %d.\n", (int) vchData.size());
Misbehaving(pfrom->GetId(), 1);
return false;
}
int64_t time;
memcpy(&time, &vchData[0], 8);
pfrom->smsgData.ignoreUntil = time;
if (fDebugSmsg)
LogPrintf("Peer %u is ignoring this node until %d, ignore peer too.\n", pfrom->smsgData.nPeerId, (int) time);
} else
{
// Unknown message
}
} // LOCK(cs_smsg);
return true;
}
bool SecureMsgSendData(CNode* pto, bool fSendTrickle)
{
/*
Called from ProcessMessage
Runs in ThreadMessageHandler2
*/
//LogPrintf("SecureMsgSendData() %s.\n", pto->addrName.c_str());
int64_t now = GetTime();
if (pto->smsgData.lastSeen == 0)
{
// -- first contact
pto->smsgData.nPeerId = nPeerIdCounter++;
if (fDebugSmsg)
LogPrintf("SecureMsgSendData() new node %s, peer id %u.\n", pto->addrName.c_str(), pto->smsgData.nPeerId);
// -- Send smsgPing once, do nothing until receive 1st smsgPong (then set fEnabled)
pto->PushMessage("smsgPing");
pto->smsgData.lastSeen = GetTime();
return true;
} else
if (!pto->smsgData.fEnabled
|| now - pto->smsgData.lastSeen < SMSG_SEND_DELAY
|| now < pto->smsgData.ignoreUntil)
{
return true;
}
// -- When nWakeCounter == 0, resend bucket inventory.
if (pto->smsgData.nWakeCounter < 1)
{
pto->smsgData.lastMatched = 0;
pto->smsgData.nWakeCounter = 10 + GetRandInt(300); // set to a random time between [10, 300] * SMSG_SEND_DELAY seconds
if (fDebugSmsg)
LogPrintf("SecureMsgSendData(): nWakeCounter expired, sending bucket inventory to %s.\n"
"Now %d next wake counter %u\n", pto->addrName.c_str(), (int32_t) now, pto->smsgData.nWakeCounter);
}
pto->smsgData.nWakeCounter--;
{
LOCK(cs_smsg);
std::map<int64_t, SecMsgBucket>::iterator it;
uint32_t nBuckets = smsgBuckets.size();
if (nBuckets > 0) // no need to send keep alive pkts, coin messages already do that
{
std::vector<unsigned char> vchData;
// should reserve?
vchData.reserve(4 + nBuckets*16); // timestamp + size + hash
uint32_t nBucketsShown = 0;
vchData.resize(4);
unsigned char* p = &vchData[4];
for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it)
{
SecMsgBucket &bkt = it->second;
uint32_t nMessages = bkt.setTokens.size();
if (bkt.timeChanged < pto->smsgData.lastMatched // peer has this bucket
|| nMessages < 1) // this bucket is empty
continue;
uint32_t hash = bkt.hash;
try { vchData.resize(vchData.size() + 16); } catch (std::exception& e)
{
LogPrintf("vchData.resize %d threw: %s.\n", (int) vchData.size() + 16, e.what());
continue;
}
memcpy(p, &it->first, 8);
memcpy(p+8, &nMessages, 4);
memcpy(p+12, &hash, 4);
p += 16;
nBucketsShown++;
//if (fDebug)
// LogPrintf("Sending bucket %"PRId64", size %d \n", it->first, it->second.size());
}
if (vchData.size() > 4)
{
memcpy(&vchData[0], &nBucketsShown, 4);
if (fDebugSmsg)
LogPrintf("Sending %d bucket headers.\n", nBucketsShown);
pto->PushMessage("smsgInv", vchData);
}
}
}
pto->smsgData.lastSeen = GetTime();
return true;
}
static int SecureMsgInsertAddress(CKeyID& hashKey, CPubKey& pubKey, SecMsgDB& addrpkdb)
{
/* insert key hash and public key to addressdb
should have LOCK(cs_smsg) where db is opened
returns
0 success
1 error
4 address is already in db
*/
if (addrpkdb.ExistsPK(hashKey))
{
//LogPrintf("DB already contains public key for address.\n");
CPubKey cpkCheck;
if (!addrpkdb.ReadPK(hashKey, cpkCheck))
{
LogPrintf("addrpkdb.Read failed.\n");
} else
{
if (cpkCheck != pubKey)
LogPrintf("DB already contains existing public key that does not match .\n");
}
return 4;
}
if (!addrpkdb.WritePK(hashKey, pubKey))
{
LogPrintf("Write pair failed.\n");
return 1;
}
CBitcreditAddress address;
address.Set(hashKey);
LogPrintf("Add public key of %s to database\n", address.ToString().c_str());
return 0;
}
int SecureMsgInsertAddress(CKeyID& hashKey, CPubKey& pubKey)
{
int rv;
{
LOCK(cs_smsgDB);
SecMsgDB addrpkdb;
if (!addrpkdb.Open("cr+"))
return 1;
rv = SecureMsgInsertAddress(hashKey, pubKey, addrpkdb);
}
return rv;
}
static bool ScanBlock(CBlock& block, SecMsgDB& addrpkdb, uint32_t& nTransactions, uint32_t& nInputs, uint32_t& nPubkeys, uint32_t& nDuplicates){
// -- should have LOCK(cs_smsg) where db is opened
BOOST_FOREACH(const CTransaction& tx, block.vtx){
if (tx.IsCoinBase())
continue; // leave out coinbase
/*
Look at the inputs of every tx.
If the inputs are standard, get the pubkey from scriptsig and
look for the corresponding output (the input(output of other tx) to the input of this tx)
get the address from scriptPubKey
add to db if address is unique.
Would make more sense to do this the other way around, get address first for early out.
*/
for (size_t i = 0; i < tx.vin.size(); i++){
/*
TODO ???
if (tx.nVersion == ANON_TXN_VERSION
&& tx.vin[i].IsAnonInput())
continue; // skip anon inputs
*/
const CScript &script = tx.vin[i].scriptSig;
opcodetype opcode;
std::vector<unsigned char> vch;
uint256 prevoutHash, blockHash;
// -- matching address is in scriptPubKey of previous tx output
for (CScript::const_iterator pc = script.begin(); script.GetOp(pc, opcode, vch); )
{
// -- opcode is the length of the following data, compressed public key is always 33
if (opcode == 33)
{
CPubKey pubKey(vch);
if (!pubKey.IsValid())
{
LogPrintf("Public key is invalid %s.\n", HexStr(vch).c_str());
continue;
}
prevoutHash = tx.vin[i].prevout.hash;
CTransaction txOfPrevOutput;
if (!GetTransaction(prevoutHash, txOfPrevOutput, blockHash, true))
{
LogPrintf("Could not get transaction %s (output %d) referenced by input #%d of transaction %s in block %s\n", prevoutHash.ToString().c_str(), tx.vin[i].prevout.n, (int) i, tx.GetHash().ToString().c_str(), block.GetHash().ToString().c_str());
continue;
}
unsigned int nOut = tx.vin[i].prevout.n;
if (nOut >= txOfPrevOutput.vout.size())
{
LogPrintf("Output %u, not in transaction: %s\n", nOut, prevoutHash.ToString().c_str());
continue;
}
const CTxOut &txOut = txOfPrevOutput.vout[nOut];
CTxDestination addressRet;
if (!ExtractDestination(txOut.scriptPubKey, addressRet))
{
LogPrintf("ExtractDestination failed: %s\n", prevoutHash.ToString().c_str());
continue;
}
CBitcreditAddress coinAddress(addressRet);
CKeyID hashKey;
if (!coinAddress.GetKeyID(hashKey))
{
LogPrintf("coinAddress.GetKeyID failed: %s\n", coinAddress.ToString().c_str());
continue;
}
if (hashKey != pubKey.GetID())
continue;
int rv = SecureMsgInsertAddress(hashKey, pubKey, addrpkdb);
nPubkeys += (rv == 0);
nDuplicates += (rv == 4);
}
//LogPrintf("opcode %d, %s, value %s.\n", opcode, GetOpName(opcode), HexStr(vch).c_str());
}
nInputs++;
}
nTransactions++;
if (nTransactions % 10000 == 0) // for ScanChainForPublicKeys
{
LogPrintf("Scanning transaction no. %u.\n", nTransactions);
}
}
return true;
}
bool SecureMsgScanBlock(CBlock& block)
{
/*
scan block for public key addresses
called from ProcessMessage() in main where strCommand == "block"
*/
if (fDebugSmsg)
LogPrintf("SecureMsgScanBlock().\n");
uint32_t nTransactions = 0;
uint32_t nInputs = 0;
uint32_t nPubkeys = 0;
uint32_t nDuplicates = 0;
{
LOCK(cs_smsgDB);
SecMsgDB addrpkdb;
if (!addrpkdb.Open("cw")
|| !addrpkdb.TxnBegin())
return false;
ScanBlock(block, addrpkdb,
nTransactions, nInputs, nPubkeys, nDuplicates);
addrpkdb.TxnCommit();
}
if (fDebugSmsg)
LogPrintf("Found %u transactions, %u inputs, %u new public keys, %u duplicates.\n", nTransactions, nInputs, nPubkeys, nDuplicates);
return true;
}
bool ScanChainForPublicKeys(CBlockIndex* pindexStart, size_t n)
{
LogPrintf("Scanning block chain for public keys.\n");
int64_t nStart = GetTimeMillis();
if (fDebugSmsg)
LogPrintf("From height %u.\n", pindexStart->nHeight);
// -- public keys are in txin.scriptSig
// matching addresses are in scriptPubKey of txin's referenced output
uint32_t nBlocks = 0;
uint32_t nTransactions = 0;
uint32_t nInputs = 0;
uint32_t nPubkeys = 0;
uint32_t nDuplicates = 0;
{
LOCK(cs_smsgDB);
SecMsgDB addrpkdb;
if (!addrpkdb.Open("cw")
|| !addrpkdb.TxnBegin())
return false;
CBlockIndex* pindex = pindexStart;
for (size_t i = 0; pindex != NULL && i < n; i++, pindex = pindex->pprev)
{
nBlocks++;
CBlock block;
ReadBlockFromDisk(block, pindex);
ScanBlock(block, addrpkdb,
nTransactions, nInputs, nPubkeys, nDuplicates);
}
addrpkdb.TxnCommit();
}
LogPrintf("Scanned %u blocks, %u transactions, %u inputs\n", nBlocks, nTransactions, nInputs);
LogPrintf("Found %u public keys, %u duplicates.\n", nPubkeys, nDuplicates);
LogPrintf("Took %d ms\n", (int32_t)(GetTimeMillis() - nStart));
return true;
}
bool SecureMsgScanBlockChain()
{
TRY_LOCK(cs_main, lockMain);
if (lockMain)
{
CBlockIndex *indexScan = chainActive.Tip();
try { // -- in try to catch errors opening db,
if (!ScanChainForPublicKeys(indexScan, indexScan->nHeight))
return false;
} catch (std::exception& e)
{
LogPrintf("ScanChainForPublicKeys() threw: %s.\n", e.what());
return false;
}
} else
{
LogPrintf("ScanChainForPublicKeys() Could not lock main.\n");
return false;
}
return true;
}
int SecureMsgScanBuckets(std::string &error, bool fDecrypt)
{
if (fDebugSmsg)
LogPrintf("SecureMsgScanBuckets()\n");
if (!fSecMsgEnabled) {
error = "Secure messaging is disabled.";
return fDecrypt ? 0 : RPC_METHOD_NOT_FOUND;
}
if (pwalletMain->IsLocked()) {
error = "Wallet is locked. Secure messaging needs an unlocked wallet.";
return RPC_WALLET_UNLOCK_NEEDED;
}
int64_t mStart = GetTimeMillis();
int64_t now = GetTime();
uint32_t nFiles = 0;
uint32_t nMessages = 0;
uint32_t nFoundMessages = 0;
fs::path pathSmsgDir = GetDataDir() / "smsgStore";
fs::directory_iterator itend;
if (!fs::exists(pathSmsgDir) || !fs::is_directory(pathSmsgDir)) {
if (!fs::create_directory(pathSmsgDir)) {
error = "Message store directory does not exist and could not be created.";
return 1;
}
}
SecureMessage smsg;
for (fs::directory_iterator itd(pathSmsgDir) ; itd != itend ; ++itd) {
if (!fs::is_regular_file(itd->status()))
continue;
std::string fileName = (*itd).path().filename().string();
if (!boost::algorithm::ends_with(fileName, fDecrypt ? "_wl.dat" : ".dat"))
continue;
if (fDebugSmsg)
LogPrintf("Processing file: %s.\n", fileName.c_str());
nFiles++;
// TODO files must be split if > 2GB
// time_noFile.dat
size_t sep = fileName.find_first_of("_");
if (sep == std::string::npos)
continue;
std::string stime = fileName.substr(0, sep);
int64_t fileTime = boost::lexical_cast<int64_t>(stime);
if (fileTime < now - SMSG_RETENTION) {
LogPrintf("Dropping file %s, expired.\n", fileName.c_str());
try {
fs::remove((*itd).path());
}
catch (const fs::filesystem_error& ex) {
LogPrintf("Error removing bucket file %s, %s.\n", fileName.c_str(), ex.what());
}
continue;
}
if (!fDecrypt && boost::algorithm::ends_with(fileName, "_wl.dat")) {
if (fDebugSmsg)
LogPrintf("Skipping wallet locked file: %s.\n", fileName.c_str());
continue;
}
{
LOCK(cs_smsg);
FILE *fp;
errno = 0;
if (!(fp = fopen((*itd).path().string().c_str(), "rb"))) {
LogPrintf("Error opening file: %s (%d)\n", strerror(errno), __LINE__);
continue;
}
for (;;) {
errno = 0;
if (fread(smsg.Header(), sizeof(unsigned char), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN) {
if (errno != 0) {
LogPrintf("fread header failed: %s\n", strerror(errno));
}
else {
//LogPrintf("End of file.\n");
}
break;
}
try {
smsg.vchPayload.resize(smsg.nPayload);
}
catch (std::exception& e) {
LogPrintf("SecureMsgWalletUnlocked(): Could not resize vchPayload, %u, %s\n", smsg.nPayload, e.what());
fclose(fp);
return 1;
}
if (fread(&smsg.vchPayload[0], 1, smsg.nPayload, fp) != smsg.nPayload) {
LogPrintf("fread data failed: %s\n", strerror(errno));
break;
}
// -- don't report to gui,
int rv = SecureMsgScanMessage(*smsg.Header(), &smsg.vchPayload[0], false);
if (rv == 0) {
nFoundMessages++;
}
else if (rv != 0) {
// SecureMsgScanMessage failed
}
nMessages ++;
}
fclose(fp);
// -- remove wl file when scanned
try {
fs::remove((*itd).path());
} catch (const boost::filesystem::filesystem_error& ex) {
LogPrintf("Error removing wl file %s - %s\n", fileName.c_str(), ex.what());
return 1;
}
}
}
LogPrintf("Processed %u files, scanned %u messages, received %u messages.\n", nFiles, nMessages, nFoundMessages);
LogPrintf("Took %d ms\n", (int)(GetTimeMillis() - mStart));
// -- notify gui
if (fDecrypt)
NotifySecMsgWalletUnlocked();
return 0;
}
int SecureMsgWalletKeyChanged(std::string sAddress, std::string sLabel, ChangeType mode)
{
if (!fSecMsgEnabled)
return 0;
LogPrintf("SecureMsgWalletKeyChanged()\n");
// TODO: default recv and recvAnon
{
LOCK(cs_smsg);
switch(mode)
{
case CT_NEW:
smsgAddresses.push_back(SecMsgAddress(sAddress, smsgOptions.fNewAddressRecv, smsgOptions.fNewAddressAnon));
break;
case CT_DELETED:
for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)
{
if (sAddress != it->sAddress)
continue;
smsgAddresses.erase(it);
break;
}
break;
default:
break;
}
} // LOCK(cs_smsg);
return 0;
}
int SecureMsgScanMessage(const SecureMessageHeader &smsg, const unsigned char *pPayload, bool reportToGui)
{
/*
Check if message belongs to this node.
If so add to inbox db.
if !reportToGui don't fire NotifySecMsgInboxChanged
- loads messages received when wallet locked in bulk.
returns
0 success,
1 error
2 no match
3 wallet is locked - message stored for scanning later.
*/
if (fDebugSmsg)
LogPrintf("SecureMsgScanMessage()\n");
if (pwalletMain->IsLocked())
{
if (fDebugSmsg)
LogPrintf("ScanMessage: Wallet is locked, storing message to scan later.\n");
int rv;
if ((rv = SecureMsgStoreUnscanned(smsg, pPayload)) != 0)
return 1;
return 3;
}
// -- Calculate hash of payload and enable verification of the HMAC
SecureMessageHeader header((const unsigned char*) smsg.begin());
memcpy(header.hash, Hash(&pPayload[0], &pPayload[smsg.nPayload]).begin(), 32);
std::string addressTo;
MessageData msg; // placeholder
bool fOwnMessage = false;
for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)
{
if (!it->fReceiveEnabled)
continue;
CBitcreditAddress coinAddress(it->sAddress);
addressTo = coinAddress.ToString();
if (!it->fReceiveAnon)
{
// -- have to do full decrypt to see address from
if (SecureMsgDecrypt(false, addressTo, header, pPayload, msg) == 0)
{
if (fDebugSmsg)
LogPrintf("%d: Decrypted message with %s.\n", __LINE__, addressTo.c_str());
if (msg.sFromAddress.compare("anon") != 0)
fOwnMessage = true;
break;
}
} else
{
if (SecureMsgDecrypt(true, addressTo, header, pPayload, msg) == 0)
{
if (fDebugSmsg)
LogPrintf("%d: Decrypted message with %s.\n", __LINE__, addressTo.c_str());
fOwnMessage = true;
break;
}
}
}
if (fOwnMessage)
{
// -- save to inbox
std::string sPrefix("im");
unsigned char chKey[18];
memcpy(&chKey[0], sPrefix.data(), 2);
memcpy(&chKey[2], &smsg.timestamp, 8);
memcpy(&chKey[10], pPayload, 8);
SecMsgStored smsgInbox;
smsgInbox.timeReceived = GetTime();
smsgInbox.status = (SMSG_MASK_UNREAD) & 0xFF;
smsgInbox.sAddrTo = addressTo;
// -- data may not be contiguous
try {
smsgInbox.vchMessage.resize(SMSG_HDR_LEN + smsg.nPayload);
} catch (std::exception& e) {
LogPrintf("SecureMsgScanMessage(): Could not resize vchData, %u, %s\n", SMSG_HDR_LEN + smsg.nPayload, e.what());
return 1;
}
memcpy(&smsgInbox.vchMessage[0], smsg.begin(), SMSG_HDR_LEN);
memcpy(&smsgInbox.vchMessage[SMSG_HDR_LEN], pPayload, smsg.nPayload);
{
LOCK(cs_smsgDB);
SecMsgDB dbInbox;
if (dbInbox.Open("cw"))
{
if (dbInbox.ExistsSmesg(chKey))
{
if (fDebugSmsg)
LogPrintf("Message already exists in inbox db.\n");
} else
{
dbInbox.WriteSmesg(chKey, smsgInbox);
if (reportToGui)
NotifySecMsgInboxChanged(smsgInbox);
LogPrintf("SecureMsg saved to inbox, received with %s.\n", addressTo.c_str());
}
}
}
}
return 0;
}
int SecureMsgGetLocalKey(CKeyID& ckid, CPubKey& cpkOut)
{
if (fDebugSmsg)
LogPrintf("SecureMsgGetLocalKey()\n");
CKey key;
if (!pwalletMain->GetKey(ckid, key))
return 4;
cpkOut = key.GetPubKey();
if (!cpkOut.IsValid()
|| !cpkOut.IsCompressed())
{
LogPrintf("Public key is invalid %s.\n", HexStr(std::vector<unsigned char>(cpkOut.begin(), cpkOut.end())).c_str());
return 1;
}
return 0;
}
int SecureMsgGetLocalPublicKey(std::string& strAddress, std::string& strPublicKey)
{
/* returns
0 success,
1 error
2 invalid address
3 address does not refer to a key
4 address not in wallet
*/
CBitcreditAddress address;
if (!address.SetString(strAddress))
return 2; // Invalid coin address
CKeyID keyID;
if (!address.GetKeyID(keyID))
return 3;
int rv;
CPubKey pubKey;
if ((rv = SecureMsgGetLocalKey(keyID, pubKey)) != 0)
return rv;
strPublicKey = EncodeBase58(pubKey.begin(), pubKey.end());
return 0;
}
int SecureMsgGetStoredKey(CKeyID& ckid, CPubKey& cpkOut)
{
/* returns
0 success,
1 error
2 public key not in database
*/
if (fDebugSmsg)
LogPrintf("SecureMsgGetStoredKey().\n");
{
LOCK(cs_smsgDB);
SecMsgDB addrpkdb;
if (!addrpkdb.Open("r")) {
LogPrintf("addrpkdb. Open() failed.\n");
return 1;
}
if (!addrpkdb.ReadPK(ckid, cpkOut))
{
CBitcreditAddress coinAddress;
coinAddress.Set(ckid);
LogPrintf("addrpkdb.Read failed: %s.\n", coinAddress.ToString().c_str());
return 2;
}
}
if (fDebugSmsg) {
CBitcreditAddress coinAddress;
coinAddress.Set(ckid);
LogPrintf("SecureMsgGetStoredKey(): found public key of %s\n", coinAddress.ToString().c_str());
}
return 0;
}
int SecureMsgAddAddress(std::string& address, std::string& publicKey)
{
/*
Add address and matching public key to the database
address and publicKey are in base58
returns
0 success
1 error
2 publicKey is invalid
3 publicKey != address
4 address is already in db
5 address is invalid
*/
CBitcreditAddress coinAddress(address);
if (!coinAddress.IsValid())
{
LogPrintf("Address is not valid: %s.\n", address.c_str());
return 5;
}
CKeyID hashKey;
if (!coinAddress.GetKeyID(hashKey))
{
LogPrintf("coinAddress.GetKeyID failed: %s.\n", coinAddress.ToString().c_str());
return 5;
}
std::vector<unsigned char> vchTest;
DecodeBase58(publicKey, vchTest);
CPubKey pubKey(vchTest);
// -- check that public key matches address hash
CKeyID id;
CBitcreditAddress(address).GetKeyID(id);
if (pubKey.GetID() != id)
{
LogPrintf("Public key does not hash to address, addressT %s.\n", pubKey.GetID().ToString().c_str());
return 3;
}
return SecureMsgInsertAddress(hashKey, pubKey);
}
int SecureMsgRetrieve(SecMsgToken &token, SecureMessage &smsg)
{
if (fDebugSmsg)
LogPrintf("SecureMsgRetrieve() %d.\n", (int32_t) token.timestamp);
// -- has cs_smsg lock from SecureMsgReceiveData
fs::path pathSmsgDir = GetDataDir() / "smsgStore";
int64_t bucket = token.timestamp - (token.timestamp % SMSG_BUCKET_LEN);
std::string fileName = boost::lexical_cast<std::string>(bucket) + "_01.dat";
fs::path fullpath = pathSmsgDir / fileName;
//LogPrintf("bucket %"PRId64".\n", bucket);
//LogPrintf("bucket lld %lld.\n", bucket);
//LogPrintf("fileName %s.\n", fileName.c_str());
FILE *fp;
if (!(fp = fopen(fullpath.string().c_str(), "rb"))) {
LogPrintf("Error opening file: %s\nPath %s\n", strerror(errno), fullpath.string().c_str());
return 1;
}
if (fseek(fp, token.offset, SEEK_SET) != 0) {
LogPrintf("fseek, strerror: %s.\n", strerror(errno));
fclose(fp);
return 1;
}
if (fread(smsg.Header(), sizeof(unsigned char), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN) {
LogPrintf("fread header failed: %s\n", strerror(errno));
fclose(fp);
return 1;
}
try {
smsg.vchPayload.resize(smsg.nPayload);
}
catch (std::exception& e) {
LogPrintf("SecureMsgRetrieve(): Could not resize vchPayload, %u, %s\n", smsg.nPayload, e.what());
return 1;
}
if (fread(&smsg.vchPayload[0], sizeof(unsigned char), smsg.nPayload, fp) != smsg.nPayload) {
LogPrintf("fread data failed: %s. Wanted %u bytes.\n", strerror(errno), smsg.nPayload);
fclose(fp);
return 1;
}
fclose(fp);
return 0;
}
int SecureMsgReceive(CNode* pfrom, std::vector<unsigned char>& vchData)
{
if (fDebugSmsg)
LogPrintf("SecureMsgReceive().\n");
if (vchData.size() < 12) { // nBunch4 + timestamp8
LogPrintf("Error: not enough data.\n");
return 1;
}
uint32_t nBunch;
int64_t bktTime;
memcpy(&nBunch, &vchData[0], 4);
memcpy(&bktTime, &vchData[4], 8);
// -- check bktTime ()
// bucket may not exist yet - will be created when messages are added
int64_t now = GetTime();
if (bktTime > now + SMSG_TIME_LEEWAY) {
if (fDebugSmsg)
LogPrintf("bktTime > now.\n");
// misbehave?
return 1;
}
else if (bktTime < now - SMSG_RETENTION) {
if (fDebugSmsg)
LogPrintf("bktTime < now - SMSG_RETENTION.\n");
// misbehave?
return 1;
}
std::map<int64_t, SecMsgBucket>::iterator itb;
if (nBunch == 0 || nBunch > 500) {
LogPrintf("Error: Invalid no. messages received in bunch %u, for bucket %d.\n", nBunch, (int32_t) bktTime);
Misbehaving(pfrom->GetId(), 1);
// -- release lock on bucket if it exists
itb = smsgBuckets.find(bktTime);
if (itb != smsgBuckets.end())
itb->second.nLockCount = 0;
return 1;
}
uint32_t n = 12;
for (uint32_t i = 0; i < nBunch; ++i) {
if (vchData.size() - n < SMSG_HDR_LEN) {
LogPrintf("Error: not enough data sent, n = %u.\n", n);
break;
}
SecureMessageHeader header(&vchData[n]);
int rv = SecureMsgValidate(header, vchData.size() - (n + SMSG_HDR_LEN));
string reason;
if (rv != 0) {
Misbehaving(pfrom->GetId(), 0);
if( rv==1 )
reason ="error";
if( rv==4 )
reason ="invalid version";
if( rv==5 )
reason ="payload too large";
if (fDebug) printf("SMSG Misbehave reason == %s .\n", reason.c_str());
continue;
}
// -- store message, but don't hash bucket
if (SecureMsgStore(header, &vchData[n + SMSG_HDR_LEN], false) != 0) {
// message dropped
break; // continue?
}
if (SecureMsgScanMessage(header, &vchData[n + SMSG_HDR_LEN], true) != 0) {
// message recipient is not this node (or failed)
}
n += SMSG_HDR_LEN + header.nPayload;
}
// -- if messages have been added, bucket must exist now
itb = smsgBuckets.find(bktTime);
if (itb == smsgBuckets.end()) {
if (fDebugSmsg)
LogPrintf("Don't have bucket %d.\n", (int32_t) bktTime);
return 1;
}
itb->second.nLockCount = 0; // this node has received data from peer, release lock
itb->second.nLockPeerId = 0;
itb->second.hashBucket();
return 0;
}
int SecureMsgStoreUnscanned(const SecureMessageHeader &header, const unsigned char *pPayload)
{
/*
When the wallet is locked a copy of each received message is stored to be scanned later if wallet is unlocked
*/
if (fDebugSmsg)
LogPrintf("SecureMsgStoreUnscanned()\n");
if (!pPayload) {
LogPrintf("Error: null pointer to payload.\n");
return 1;
}
fs::path pathSmsgDir;
try {
pathSmsgDir = GetDataDir() / "smsgStore";
fs::create_directory(pathSmsgDir);
}
catch (const boost::filesystem::filesystem_error& ex) {
LogPrintf("Error: Failed to create directory %s - %s\n", pathSmsgDir.string().c_str(), ex.what());
return 1;
}
int64_t now = GetTime();
if (header.timestamp > now + SMSG_TIME_LEEWAY) {
LogPrintf("Message > now.\n");
return 1;
}
else if (header.timestamp < now - SMSG_RETENTION) {
LogPrintf("Message < SMSG_RETENTION.\n");
return 1;
}
int64_t bucket = header.timestamp - (header.timestamp % SMSG_BUCKET_LEN);
std::string fileName = boost::lexical_cast<std::string>(bucket) + "_01_wl.dat";
fs::path fullpath = pathSmsgDir / fileName;
FILE *fp;
if (!(fp = fopen(fullpath.string().c_str(), "ab"))) {
LogPrintf("Error opening file: %s (%d)\n", strerror(errno), __LINE__);
return 1;
}
if (fwrite(&header, sizeof(unsigned char), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN
|| fwrite(pPayload, sizeof(unsigned char), header.nPayload, fp) != header.nPayload)
{
LogPrintf("fwrite failed: %s\n", strerror(errno));
fclose(fp);
return 1;
}
fclose(fp);
return 0;
}
int SecureMsgStore(const SecureMessageHeader &smsg, const unsigned char *pPayload, bool fUpdateBucket)
{
if (fDebugSmsg)
LogPrintf("SecureMsgStore()\n");
if (!pPayload) {
LogPrintf("Error: null pointer to payload.\n");
return 1;
}
long int ofs;
fs::path pathSmsgDir;
try {
pathSmsgDir = GetDataDir() / "smsgStore";
fs::create_directory(pathSmsgDir);
}
catch (const boost::filesystem::filesystem_error& ex) {
LogPrintf("Error: Failed to create directory %s - %s\n", pathSmsgDir.string().c_str(), ex.what());
return 1;
}
int64_t now = GetTime();
if (smsg.timestamp > now + SMSG_TIME_LEEWAY) {
LogPrintf("Message > now.\n");
return 1;
}
else if (smsg.timestamp < now - SMSG_RETENTION) {
LogPrintf("Message < SMSG_RETENTION.\n");
return 1;
}
int64_t bucket = smsg.timestamp - (smsg.timestamp % SMSG_BUCKET_LEN);
{
// -- must lock cs_smsg before calling
//LOCK(cs_smsg);
SecMsgToken token(smsg.timestamp, pPayload, smsg.nPayload, 0);
std::set<SecMsgToken>& tokenSet = smsgBuckets[bucket].setTokens;
std::set<SecMsgToken>::iterator it;
it = tokenSet.find(token);
if (it != tokenSet.end())
{
LogPrintf("Already have message.\n");
if (fDebugSmsg)
{
LogPrintf("nPayload: %u\n", smsg.nPayload);
LogPrintf("bucket: %d\n", (int) bucket);
LogPrintf("message ts: %d\n", (int) token.timestamp);
std::vector<unsigned char> vchShow;
vchShow.resize(8);
memcpy(&vchShow[0], token.sample, 8);
LogPrintf(" sample %s\n", HexStr(vchShow).c_str());
/*
LogPrintf("\nmessages in bucket:\n");
for (it = tokenSet.begin(); it != tokenSet.end(); ++it)
{
LogPrintf("message ts: %"PRId64, (*it).timestamp);
vchShow.resize(8);
memcpy(&vchShow[0], (*it).sample, 8);
LogPrintf(" sample %s\n", HexStr(vchShow).c_str());
}
*/
}
return 1;
}
std::string fileName = boost::lexical_cast<std::string>(bucket) + "_01.dat";
fs::path fullpath = pathSmsgDir / fileName;
FILE *fp;
if (!(fp = fopen(fullpath.string().c_str(), "ab")))
{
LogPrintf("Error opening file: %s (%d)\n", strerror(errno), __LINE__);
return 1;
}
// -- on windows ftell will always return 0 after fopen(ab), call fseek to set.
if (fseek(fp, 0, SEEK_END) != 0)
{
LogPrintf("Error fseek failed: %s\n", strerror(errno));
return 1;
}
ofs = ftell(fp);
if (fwrite(&smsg, sizeof(unsigned char), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN
|| fwrite(pPayload, sizeof(unsigned char), smsg.nPayload, fp) != smsg.nPayload)
{
LogPrintf("fwrite failed: %s\n", strerror(errno));
fclose(fp);
return 1;
}
fclose(fp);
token.offset = ofs;
//LogPrintf("token.offset: %"PRId64"\n", token.offset); // DEBUG
tokenSet.insert(token);
if (fUpdateBucket)
smsgBuckets[bucket].hashBucket();
}
//if (fDebugSmsg)
LogPrintf("SecureMsg added to bucket %d.\n", (int) bucket);
return 0;
}
int SecureMsgStore(const SecureMessage& smsg, bool fUpdateBucket)
{
return SecureMsgStore(smsg, &smsg.vchPayload[0], fUpdateBucket);
}
int SecureMsgValidate(const SecureMessageHeader &smsg_header, size_t nPayload)
{
/*
returns
0 success
1 error
4 invalid version
5 payload is too large
*/
if (smsg_header.nPayload != nPayload){
if (fDebug) printf("Message payload does not match got %d, expected %d .\n", smsg_header.nPayload, (int) nPayload);
return 1;
}
if (smsg_header.nVersion != 1)
return 4;
if (smsg_header.nPayload > SMSG_MAX_MSG_WORST){
if (fDebug) LogPrintf("Message payload larger than SMSG_MAX_MSG_WORST got %d, expected %d .\n", smsg_header.nPayload, SMSG_MAX_MSG_WORST);
return 5;
}
return 0;
}
int SecureMsgEncrypt(SecureMessage& smsg, std::string& addressFrom, std::string& addressTo, std::string& message)
{
/* Create a secure message
Using similar method to bitmessage.
If bitmessage is secure this should be too.
https://bitmessage.org/wiki/Encryption
Some differences:
bitmessage seems to use curve sect283r1
*coin addresses use secp256k1
returns
2 message is too long.
3 addressFrom is invalid.
4 addressTo is invalid.
5 Could not get public key for addressTo.
6 ECDH_compute_key failed
7 Could not get private key for addressFrom.
8 Could not allocate memory.
9 Could not compress message data.
10 Could not generate MAC.
11 Encrypt failed.
*/
if (fDebugSmsg)
LogPrintf("SecureMsgEncrypt(%s, %s, ...)\n", addressFrom.c_str(), addressTo.c_str());
if (message.size() > SMSG_MAX_MSG_BYTES) {
LogPrintf("Message is too long, %d.\n", (int) message.size());
return 2;
}
smsg.nVersion = 1;
smsg.timestamp = GetTime();
bool fSendAnonymous;
CBitcreditAddress coinAddrFrom;
CKeyID ckidFrom;
CKey keyFrom;
if (addressFrom.compare("anon") == 0) {
fSendAnonymous = true;
}
else {
fSendAnonymous = false;
if (!coinAddrFrom.SetString(addressFrom)) {
LogPrintf("addressFrom is not valid.\n");
return 3;
}
if (!coinAddrFrom.GetKeyID(ckidFrom)) {
LogPrintf("coinAddrFrom.GetKeyID failed: %s.\n", coinAddrFrom.ToString().c_str());
return 3;
}
}
CBitcreditAddress coinAddrDest;
CKeyID ckidDest;
if (!coinAddrDest.SetString(addressTo)) {
LogPrintf("addressTo is not valid.\n");
return 4;
}
if (!coinAddrDest.GetKeyID(ckidDest)) {
LogPrintf("%d: coinAddrDest.GetKeyID failed: %s.\n", __LINE__, coinAddrDest.ToString().c_str());
return 4;
}
// -- public key K is the destination address
CPubKey cpkDestK;
if (SecureMsgGetStoredKey(ckidDest, cpkDestK) != 0
&& SecureMsgGetLocalKey(ckidDest, cpkDestK) != 0) // maybe it's a local key (outbox?)
{
LogPrintf("Could not get public key for destination address.\n");
return 5;
}
// -- create save hash instances
secure_buffer sha_mem(sizeof(CSHA256) + sizeof(CSHA512) + sizeof(CHMAC_SHA256), 0);
CSHA256 &sha256 = *new (&sha_mem[0]) CSHA256();
CSHA512 &sha512 = *new (&sha256 + 1) CSHA512();
// -- make a key pair to which the receiver can respond
CKey keyS;
keyS.MakeNewKey(true); // make compressed key
CPubKey pubKeyS = keyS.GetPubKey();
// -- hash the timestamp and plaintext
uint256 msgHash;
sha256.Write((const unsigned char*) &smsg.timestamp, sizeof(smsg.timestamp)).
Write((const unsigned char*) &*message.begin(), message.size()).
Finalize(msgHash.begin());
// -- hash some entropy
secure_buffer vchKey(64+4, 0);
GetRandBytes(&vchKey[0], 16);
sha256.Write(&vchKey[0], 16);
sha256.Write(pubKeyS.begin(), 33);
sha256.Finalize(&vchKey[0]); // use this as key for hmac
// -- derive a new key pair, which is used for the encryption key computation
CKey keyR;
while (!keyR.IsValid()) {
CHMAC_SHA256 &hmac = *new (&sha512 + 1) CHMAC_SHA256(&vchKey[0], 32);
hmac.Write(&vchKey[64], 4); // prepend a counter
hmac.Write(keyS.begin(), 32);
hmac.Finalize(&vchKey[32]);
keyR.Set(&vchKey[32], &vchKey[64], true);
(*(uint32_t*) &vchKey[64])++;
}
// -- Compute a shared secret vchP derived from a new private key keyR and the public key of addressTo
secure_buffer vchP;
memcpy(smsg.cpkR, &keyR.GetPubKey()[0], sizeof(smsg.cpkR)); // copy public key
if (!DeriveKey(vchP, keyR, cpkDestK))
{
LogPrintf("ECDH key computation failed\n");
return 6;
}
// -- Use vchP and calculate the SHA512 hash H.
// The first 32 bytes of H are called key_e (encryption key) and the last 32 bytes are called key_m (key for HMAC).
secure_buffer vchHashed(64); // 512 bit
sha512.Write(&vchP[0], vchP.size());
sha512.Finalize(&vchHashed[0]);
secure_buffer vchPayload;
secure_buffer vchCompressed;
unsigned char* pMsgData;
uint32_t lenMsgData;
uint32_t lenMsg = message.size();
if (lenMsg > 128)
{
// -- only compress if over 128 bytes
int worstCase = LZ4_compressBound(message.size());
try {
vchCompressed.resize(worstCase);
} catch (std::exception& e) {
LogPrintf("vchCompressed.resize %u threw: %s.\n", worstCase, e.what());
return 8;
}
int lenComp = LZ4_compress((char*)message.c_str(), (char*)&vchCompressed[0], lenMsg);
if (lenComp < 1)
{
LogPrintf("Could not compress message data.\n");
return 9;
}
pMsgData = &vchCompressed[0];
lenMsgData = lenComp;
} else
{
// -- no compression
pMsgData = (unsigned char*)message.c_str();
lenMsgData = lenMsg;
}
const unsigned int size = SMSG_PL_HDR_LEN + lenMsgData;
try {
vchPayload.resize(size);
}
catch (std::exception& e) {
LogPrintf("vchPayload.resize %u threw: %s.\n", size, e.what());
return 8;
}
// -- create the payload header
PayloadHeader &header = *(PayloadHeader*) &vchPayload[0];
memcpy(header.lenPlain, &lenMsg, 4);
memcpy(&vchPayload[SMSG_PL_HDR_LEN], pMsgData, lenMsgData);
memcpy(header.cpkS, pubKeyS.begin(), sizeof(header.cpkS));
if (fSendAnonymous) {
memset(header.sigKeyVersion, 0, 66);
}
else {
// -- compact signature proves ownership of from address and allows the public key to be recovered, recipient can always reply.
if (!pwalletMain->GetKey(ckidFrom, keyFrom))
{
LogPrintf("Could not get private key for addressFrom.\n");
return 7;
}
LogPrintf("private key of %s obtained\n", CBitcreditAddress(ckidFrom).ToString().c_str());
// -- sign the the new public key of keyR with the private key of addressFrom
std::vector<unsigned char> vchSignature(65);
keyFrom.SignCompact(msgHash, vchSignature);
header.sigKeyVersion[0] = ((CBitcreditAddress_B*) &coinAddrFrom)->getVersion(); // vchPayload[0] = coinAddrDest.nVersion;
memcpy(header.signature, &vchSignature[0], vchSignature.size());
memset(&vchSignature[0], 0, vchSignature.size());
}
// -- use first 16 bytes of hash of cpkR as IV, fill up with zero
// less critical because the key shall be unique and the payload, too
std::vector<unsigned char> vchIV(WALLET_CRYPTO_KEY_SIZE, 0);
memcpy(&vchIV[0], Hash(smsg.cpkR, smsg.cpkR + sizeof(smsg.cpkR)).begin(), 16);
// -- Init crypter
CCrypter crypter;
crypter.SetKey(secure_buffer(vchHashed.begin(), vchHashed.begin()+32), vchIV);
// -- encrypt the plaintext
if (!crypter.Encrypt(vchPayload, smsg.vchPayload)) {
LogPrintf("crypter.Encrypt failed.\n");
return 11;
}
smsg.nPayload = smsg.vchPayload.size();
// -- calculate hash of encrypted payload
memcpy(smsg.hash, Hash(&smsg.vchPayload[0], &smsg.vchPayload[smsg.nPayload]).begin(), 32);
// -- Calculate a 32 byte MAC with HMACSHA256, using key_m as salt
// Message authentication code of the header
CHMAC_SHA256 hmac(&vchHashed[32], 32);
memcpy(smsg.mac, smsg.hash, 32);
hmac.Write(smsg.begin(), SMSG_HDR_LEN);
hmac.Finalize(smsg.mac);
//TODO save the private key keyS
return 0;
}
int SecureMsgSend(std::string& addressFrom, std::string& addressTo, std::string& message, std::string& sError)
{
/* Encrypt secure message, and place it on the network
Make a copy of the message to sender's first address and place in send queue db
proof of work thread will pick up messages from send queue db
*/
if (fDebugSmsg)
LogPrintf("SecureMsgSend(%s, %s, ...)\n", addressFrom.c_str(), addressTo.c_str());
if (pwalletMain->IsLocked()) {
sError = "Wallet is locked, wallet must be unlocked to send and receive messages.";
return RPC_WALLET_UNLOCK_NEEDED;
}
SecureMessage smsg;
int rv = SecureMsgEncrypt(smsg, addressFrom, addressTo, message);
if (rv != 0)
{
LogPrintf("SecureMsgSend(), encrypt for recipient failed.\n");
std::ostringstream oss;
switch(rv)
{
case 2:
oss << "Message size of " << message.size() << " bytes exceeds the maximum message length of " << SMSG_MAX_MSG_BYTES << " bytes.";
sError = oss.str();
return RPC_INVALID_PARAMS;
case 3:
sError = "Invalid addressFrom.";
return RPC_INVALID_ADDRESS_OR_KEY;
case 4:
sError = "Invalid addressTo.";
return RPC_INVALID_ADDRESS_OR_KEY;
case 5: sError = "Could not get public key for addressTo."; break;
case 6: sError = "ECDH key computation failed."; break;
case 7: sError = "Could not get private key for addressFrom."; break;
case 8:
sError = "Could not allocate memory.";
return RPC_OUT_OF_MEMORY;
case 9: sError = "Could not compress message data."; break;
case 11: sError = "Encrypt failed."; break;
default: sError = "Unspecified Error."; break;
}
return rv;
}
// -- Place message in send queue, proof of work will happen in a thread.
std::string sPrefix("qm");
unsigned char chKey[18];
memcpy(&chKey[0], sPrefix.data(), 2);
memcpy(&chKey[2], &smsg.timestamp, 8);
memcpy(&chKey[10], &smsg.vchPayload[0], 8);
SecMsgStored smsgSQ;
smsgSQ.timeReceived = GetTime();
smsgSQ.sAddrTo = addressTo;
try {
smsgSQ.vchMessage.resize(SMSG_HDR_LEN + smsg.nPayload);
} catch (std::exception& e) {
LogPrintf("smsgSQ.vchMessage.resize %u threw: %s.\n", SMSG_HDR_LEN + smsg.nPayload, e.what());
sError = "Could not allocate memory.";
return RPC_OUT_OF_MEMORY;
}
memcpy(&smsgSQ.vchMessage[0], smsg.begin(), SMSG_HDR_LEN);
memcpy(&smsgSQ.vchMessage[SMSG_HDR_LEN], &smsg.vchPayload[0], smsg.nPayload);
{
LOCK(cs_smsgDB);
SecMsgDB dbSendQueue;
if (dbSendQueue.Open("cw"))
{
dbSendQueue.WriteSmesg(chKey, smsgSQ);
//NotifySecMsgSendQueueChanged(smsgOutbox);
}
}
// -- for outbox create a copy encrypted for owned address
// if the wallet is encrypted private key needed to decrypt will be unavailable
if (fDebugSmsg)
LogPrintf("Encrypting message for outbox.\n");
std::string addressOutbox = "None";
CBitcreditAddress coinAddrOutbox;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook)
{
// -- get first owned address
if (IsMine(*pwalletMain, entry.first) != ISMINE_SPENDABLE)
continue;
coinAddrOutbox = entry.first;
addressOutbox = coinAddrOutbox.ToString();
break;
}
if (addressOutbox == "None")
{
LogPrintf("Warning: SecureMsgSend() could not find an address to encrypt outbox message with.\n");
} else
{
if (fDebugSmsg)
LogPrintf("Encrypting a copy for outbox, using address %s\n", addressOutbox.c_str());
SecureMessage smsgForOutbox;
if ((rv = SecureMsgEncrypt(smsgForOutbox, addressFrom, addressOutbox, message)) != 0)
{
LogPrintf("SecureMsgSend(), encrypt for outbox failed, %d.\n", rv);
} else
{
// -- save sent message to db
std::string sPrefix("sm");
unsigned char chKey[18];
memcpy(&chKey[0], sPrefix.data(), 2);
memcpy(&chKey[2], &smsgForOutbox.timestamp, 8);
memcpy(&chKey[10], &smsgForOutbox.vchPayload[0], 8); // sample
SecMsgStored smsgOutbox;
smsgOutbox.timeReceived = GetTime();
smsgOutbox.sAddrTo = addressTo;
smsgOutbox.sAddrOutbox = addressOutbox;
try {
smsgOutbox.vchMessage.resize(SMSG_HDR_LEN + smsgForOutbox.nPayload);
} catch (std::exception& e) {
LogPrintf("smsgOutbox.vchMessage.resize %u threw: %s.\n", SMSG_HDR_LEN + smsgForOutbox.nPayload, e.what());
sError = "Could not allocate memory.";
return RPC_OUT_OF_MEMORY;
}
memcpy(&smsgOutbox.vchMessage[0], smsgForOutbox.begin(), SMSG_HDR_LEN);
memcpy(&smsgOutbox.vchMessage[SMSG_HDR_LEN], &smsgForOutbox.vchPayload[0], smsgForOutbox.nPayload);
{
LOCK(cs_smsgDB);
SecMsgDB dbSent;
if (dbSent.Open("cw"))
{
dbSent.WriteSmesg(chKey, smsgOutbox);
NotifySecMsgOutboxChanged(smsgOutbox);
}
}
}
}
if (fDebugSmsg)
LogPrintf("Secure message queued for sending to %s.\n", addressTo.c_str());
return 0;
}
int SecureMsgDecrypt(bool fTestOnly, const std::string& address, const SecureMessageHeader &smsg, const unsigned char *pPayload, MessageData& msg) {
/* Decrypt secure message
address is the owned address to decrypt with.
validate first in SecureMsgValidate
returns
1 Error
2 Unknown version number
3 Decrypt address is not valid.
8 Could not allocate memory
*/
if (fDebugSmsg)
LogPrintf("SecureMsgDecrypt(), using %s, testonly %d.\n", address.c_str(), fTestOnly);
if (smsg.nVersion != 1) {
LogPrintf("Unknown version number.\n");
return 2;
}
// -- Fetch private key k, used to decrypt
CBitcreditAddress coinAddrDest;
CKeyID ckidDest;
CKey keyDest;
if (!coinAddrDest.SetString(address))
{
LogPrintf("Address is not valid.\n");
return RPC_INVALID_ADDRESS_OR_KEY;
}
if (!coinAddrDest.GetKeyID(ckidDest)) {
LogPrintf("%d: coinAddrDest.GetKeyID failed: %s, %s.\n", __LINE__, coinAddrDest.ToString().c_str(), address.c_str());
return RPC_INVALID_ADDRESS_OR_KEY;
}
if (!pwalletMain->GetKey(ckidDest, keyDest)) {
LogPrintf("Could not get private key for addressDest.\n");
return 3;
}
CPubKey keyR(smsg.cpkR, smsg.cpkR+33);
if (!keyR.IsValid()) {
LogPrintf("Could not get compressed public key for key R.\n");
return 1;
}
// -- Do an EC point multiply with private key k and public key R. This gives you public EC key P.
secure_buffer vchP;
if (!DeriveKey(vchP, keyDest, keyR)) {
LogPrintf("ECDH key derivation failed\n");
return 1;
}
// -- Use public key P to calculate the SHA512 hash H.
// The first 32 bytes of H are called key_e and the last 32 bytes are called key_m.
secure_buffer vchHashedDec(64); // 512 bits
secure_buffer sha512_mem(sizeof(CSHA512), 0);
CSHA512 &sha512 = *new (&sha512_mem[0]) CSHA512();
sha512.Write(&vchP[0], vchP.size());
sha512.Finalize(&vchHashedDec[0]);
sha512.~CSHA512();
// -- Message authentication code of header
SecureMessageHeader smsg_(smsg.begin());
memcpy(smsg_.mac, smsg.hash, 32);
unsigned char mac[32];
CHMAC_SHA256 hmac(&vchHashedDec[32], 32);
hmac.Write((const unsigned char*) smsg_.begin(), SMSG_HDR_LEN);
hmac.Finalize(mac);
if (memcmp(mac, smsg.mac, 32) != 0) {
if (fDebugSmsg)
LogPrintf("MAC does not match for address %s.\n", coinAddrDest.ToString().c_str()); // expected if message is not to address on node
return 1;
}
if (fTestOnly)
return 0;
std::vector<unsigned char> vchIV(WALLET_CRYPTO_KEY_SIZE, 0);
memcpy(&vchIV[0], Hash(smsg.cpkR, smsg.cpkR + sizeof(smsg.cpkR)).begin(), 16);
CCrypter crypter;
crypter.SetKey(secure_buffer(vchHashedDec.begin(), vchHashedDec.begin()+32), vchIV);
secure_buffer vchPayload;
if (!crypter.Decrypt(pPayload, smsg.nPayload, vchPayload)) {
LogPrintf("Decrypt failed.\n");
return 1;
}
PayloadHeader &header = *(PayloadHeader*) &vchPayload[0];
bool fFromAnonymous = (header.sigKeyVersion[0] == 0);
uint32_t lenData = vchPayload.size() - SMSG_PL_HDR_LEN;
uint32_t lenPlain;
memcpy(&lenPlain, header.lenPlain, 4);
unsigned char* pMsgData = &vchPayload[SMSG_PL_HDR_LEN];
try {
msg.sMessage.reserve(lenPlain + 1);
msg.sMessage.resize(lenPlain);
}
catch (std::exception& e) {
LogPrintf("msg.vchMessage.resize %u threw: %s.\n", lenPlain, e.what());
return 8;
}
char *message = &msg.sMessage[0];
if (lenPlain > 128) {
// -- decompress
if (LZ4_decompress_safe((char*) pMsgData, message, lenData, lenPlain) != (int) lenPlain) {
LogPrintf("Could not decompress message data.\n");
return 1;
}
}
else {
// -- plaintext
memcpy(message, pMsgData, lenPlain);
}
if (fFromAnonymous) {
// -- Anonymous sender
msg.sFromAddress = "anon";
LogPrintf("from anon\n");
}
else {
uint256 msgHash;
CSHA256().Write((const unsigned char*) &smsg.timestamp, 8).
Write((const unsigned char*) message, lenPlain).
Finalize(msgHash.begin());
CPubKey cpkFromSig;
std::vector<unsigned char> vchSig(65, 0);
memcpy(&vchSig[0], header.signature, vchSig.size());
bool valid = cpkFromSig.RecoverCompact(msgHash, vchSig);
if (!valid) {
LogPrintf("Signature validation failed.\n");
return 1;
}
if (!cpkFromSig.IsCompressed())
LogPrintf("key is not compressed\n");
// TODO check whether the public key is trusted
CKeyID ckidFrom(cpkFromSig.GetID());
int rv = 5;
try {
rv = SecureMsgInsertAddress(ckidFrom, cpkFromSig);
}
catch (std::exception& e) {
LogPrintf("SecureMsgInsertAddress(), exception: %s.\n", e.what());
//return 1;
}
switch(rv) {
case 0:
LogPrintf("Sender public key added to db.\n");
break;
case 4:
LogPrintf("Sender public key already in db.\n");
break;
default:
LogPrintf("Error adding sender public key to db.\n");
break;
}
msg.sFromAddress = secure_string(CBitcreditAddress(ckidFrom).ToString().c_str());
}
msg.sToAddress = secure_string(address.c_str());
msg.timestamp = smsg.timestamp;
// TODO insert new public key and link it with cpkFromSig
if (fDebugSmsg)
LogPrintf("Decrypted message for %s: %s.\n", address.c_str(), msg.sMessage.c_str());
return 0;
}
int SecureMsgDecrypt(const SecMsgStored& smsgStored, MessageData &msg, std::string &errorMsg)
{
SecureMessageHeader smsg(&smsgStored.vchMessage[0]);
const unsigned char* pPayload = &smsgStored.vchMessage[SMSG_HDR_LEN];
memcpy(smsg.hash, Hash(&pPayload[0], &pPayload[smsg.nPayload]).begin(), 32);
int error = SecureMsgDecrypt(false, smsgStored.sAddrTo, smsg, pPayload, msg);
errorMsg = "";
return error;
}
<file_sep>Sample configuration files for:
SystemD: bitcreditd.service
Upstart: bitcreditd.conf
OpenRC: bitcreditd.openrc
bitcreditd.openrcconf
have been made available to assist packagers in creating node packages here.
See doc/init.md for more information.
<file_sep>#ifndef ASSETSPAGE_H
#define ASSETSPAGE_H
#include <QWidget>
#include <QStringListModel>
#include <QFile>
#include <QProcess>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QTableWidget>
#include "walletmodel.h"
class WalletModel;
namespace Ui {
class AssetsPage;
}
class AssetsPage : public QWidget
{
Q_OBJECT
public:
explicit AssetsPage(QWidget *parent = 0);
~AssetsPage();
//bool colorQuery(QString cmd);
bool runColorCore();
bool sendRequest(QString cmd, QString &result);
void listunspent();
void getBalance();
void setModel(WalletModel *model);
private slots:
void readPyOut();
void on_addressBookButton_clicked();
void on_pasteButton_clicked();
void cellSelected(int nRow, int nCol);
public slots:
void update();
void clear();
void sendassets();
void issueassets();
private:
Ui::AssetsPage *ui;
WalletModel *model;
QProcess *serverProc;
};
#endif // MAINWINDOW_H
<file_sep>// Copyright (c) 2014-2015 The Darkcoin developers
// Copyright (c) 2009-2015 The Bitcoin developers
// Copyright (c) 2014-2016 Section-32 Financial Instruments
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "protocol.h"
#include "activebasenode.h"
#include "basenodeconfig.h"
#include "basenodeman.h"
#include <boost/lexical_cast.hpp>
#include "clientversion.h"
//
// Bootup the Basenode, look for a 50 000 BCR input and register on the network
//
void CActiveBasenode::ManageStatus()
{
std::string errorMessage;
if(!fBaseNode) return;
if (fDebug) LogPrintf("CActiveBasenode::ManageStatus() - Begin\n");
//need correct adjusted time to send ping
bool fIsInitialDownload = IsInitialBlockDownload();
if(fIsInitialDownload) {
status = BASENODE_SYNC_IN_PROCESS;
LogPrintf("CActiveBasenode::ManageStatus() - Sync in progress. Must wait until sync is complete to start Basenode.\n");
return;
}
if(status == BASENODE_INPUT_TOO_NEW || status == BASENODE_NOT_CAPABLE || status == BASENODE_SYNC_IN_PROCESS){
status = BASENODE_NOT_PROCESSED;
}
if(status == BASENODE_NOT_PROCESSED) {
if(strBaseNodeAddr.empty()) {
if(!GetLocal(service)) {
notCapableReason = "Can't detect external address. Please use the Basenodeaddr configuration option.";
status = BASENODE_NOT_CAPABLE;
LogPrintf("CActiveBasenode::ManageStatus() - not capable: %s\n", notCapableReason.c_str());
return;
}
} else {
service = CService(strBaseNodeAddr);
}
LogPrintf("CActiveBasenode::ManageStatus() - Checking inbound connection to '%s'\n", service.ToString().c_str());
if(!ConnectNode((CAddress)service, service.ToString().c_str())){
notCapableReason = "Could not connect to " + service.ToString();
status = BASENODE_NOT_CAPABLE;
LogPrintf("CActiveBasenode::ManageStatus() - not capable: %s\n", notCapableReason.c_str());
return;
}
if(pwalletMain->IsLocked()){
notCapableReason = "Wallet is locked.";
status = BASENODE_NOT_CAPABLE;
LogPrintf("CActiveBasenode::ManageStatus() - not capable: %s\n", notCapableReason.c_str());
return;
}
// Set defaults
status = BASENODE_NOT_CAPABLE;
notCapableReason = "Unknown. Check debug.log for more information.\n";
// Choose coins to use
CPubKey pubKeyCollateralAddress;
CKey keyCollateralAddress;
if(GetBaseNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress)) {
if(GetInputAge(vin) < BASENODE_MIN_CONFIRMATIONS){
notCapableReason = "Input must have least " + boost::lexical_cast<string>(BASENODE_MIN_CONFIRMATIONS) +
" confirmations - " + boost::lexical_cast<string>(GetInputAge(vin)) + " confirmations";
LogPrintf("CActiveBasenode::ManageStatus() - %s\n", notCapableReason.c_str());
status = BASENODE_INPUT_TOO_NEW;
return;
}
LogPrintf("CActiveBasenode::ManageStatus() - Is capable bank node!\n");
status = BASENODE_IS_CAPABLE;
notCapableReason = "";
pwalletMain->LockCoin(vin.prevout);
// send to all nodes
CPubKey pubKeyBasenode;
CKey keyBasenode;
if(!darkSendSigner.SetKey(strBaseNodePrivKey, errorMessage, keyBasenode, pubKeyBasenode))
{
LogPrintf("Register::ManageStatus() - Error upon calling SetKey: %s\n", errorMessage.c_str());
return;
}
if(!Register(vin, service, keyCollateralAddress, pubKeyCollateralAddress, keyBasenode, pubKeyBasenode, errorMessage)) {
LogPrintf("CActiveBasenode::ManageStatus() - Error on Register: %s\n", errorMessage.c_str());
}
return;
} else {
notCapableReason = "Could not find suitable coins!";
LogPrintf("CActiveBasenode::ManageStatus() - %s\n", notCapableReason.c_str());
}
}
//send to all peers
if(!Dseep(errorMessage)) {
LogPrintf("CActiveBasenode::ManageStatus() - Error on Ping: %s\n", errorMessage.c_str());
}
}
// Send stop dseep to network for remote Basenode
bool CActiveBasenode::StopBaseNode(std::string strService, std::string strKeyBasenode, std::string& errorMessage) {
CTxIn vin;
CKey keyBasenode;
CPubKey pubKeyBasenode;
if(!darkSendSigner.SetKey(strKeyBasenode, errorMessage, keyBasenode, pubKeyBasenode)) {
LogPrintf("CActiveBasenode::StopBaseNode() - Error: %s\n", errorMessage.c_str());
return false;
}
return StopBaseNode(vin, CService(strService), keyBasenode, pubKeyBasenode, errorMessage);
}
// Send stop dseep to network for main Basenode
bool CActiveBasenode::StopBaseNode(std::string& errorMessage) {
if(status != BASENODE_IS_CAPABLE && status != BASENODE_REMOTELY_ENABLED) {
errorMessage = "Basenode is not in a running status";
LogPrintf("CActiveBasenode::StopBaseNode() - Error: %s\n", errorMessage.c_str());
return false;
}
status = BASENODE_STOPPED;
CPubKey pubKeyBasenode;
CKey keyBasenode;
if(!darkSendSigner.SetKey(strBaseNodePrivKey, errorMessage, keyBasenode, pubKeyBasenode))
{
LogPrintf("Register::ManageStatus() - Error upon calling SetKey: %s\n", errorMessage.c_str());
return false;
}
return StopBaseNode(vin, service, keyBasenode, pubKeyBasenode, errorMessage);
}
// Send stop dseep to network for any Basenode
bool CActiveBasenode::StopBaseNode(CTxIn vin, CService service, CKey keyBasenode, CPubKey pubKeyBasenode, std::string& errorMessage) {
pwalletMain->UnlockCoin(vin.prevout);
return Dseep(vin, service, keyBasenode, pubKeyBasenode, errorMessage, true);
}
bool CActiveBasenode::Dseep(std::string& errorMessage) {
if(status != BASENODE_IS_CAPABLE && status != BASENODE_REMOTELY_ENABLED) {
errorMessage = "Basenode is not in a running status";
LogPrintf("CActiveBasenode::Dseep() - Error: %s\n", errorMessage.c_str());
return false;
}
CPubKey pubKeyBasenode;
CKey keyBasenode;
if(!darkSendSigner.SetKey(strBaseNodePrivKey, errorMessage, keyBasenode, pubKeyBasenode))
{
LogPrintf("CActiveBasenode::Dseep() - Error upon calling SetKey: %s\n", errorMessage.c_str());
return false;
}
return Dseep(vin, service, keyBasenode, pubKeyBasenode, errorMessage, false);
}
bool CActiveBasenode::Dseep(CTxIn vin, CService service, CKey keyBasenode, CPubKey pubKeyBasenode, std::string &retErrorMessage, bool stop) {
std::string errorMessage;
std::vector<unsigned char> vchBaseNodeSignature;
std::string strBaseNodeSignMessage;
int64_t baseNodeSignatureTime = GetAdjustedTime();
std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(baseNodeSignatureTime) + boost::lexical_cast<std::string>(stop);
if(!darkSendSigner.SignMessage(strMessage, errorMessage, vchBaseNodeSignature, keyBasenode)) {
retErrorMessage = "sign message failed: " + errorMessage;
LogPrintf("CActiveBasenode::Dseep() - Error: %s\n", retErrorMessage.c_str());
return false;
}
if(!darkSendSigner.VerifyMessage(pubKeyBasenode, vchBaseNodeSignature, strMessage, errorMessage)) {
retErrorMessage = "Verify message failed: " + errorMessage;
LogPrintf("CActiveBasenode::Dseep() - Error: %s\n", retErrorMessage.c_str());
return false;
}
// Update Last Seen timestamp in Basenode list
CBasenode* pmn = mnodeman.Find(vin);
if(pmn != NULL)
{
if(stop)
mnodeman.Remove(pmn->vin);
else
pmn->UpdateLastSeen();
}
else
{
// Seems like we are trying to send a ping while the Basenode is not registered in the network
retErrorMessage = "Darksend Basenode List doesn't include our Basenode, Shutting down Basenode pinging service! " + vin.ToString();
LogPrintf("CActiveBasenode::Dseep() - Error: %s\n", retErrorMessage.c_str());
status = BASENODE_NOT_CAPABLE;
notCapableReason = retErrorMessage;
return false;
}
//send to all peers
LogPrintf("CActiveBasenode::Dseep() - RelayBasenodeEntryPing vin = %s\n", vin.ToString().c_str());
mnodeman.RelayBasenodeEntryPing(vin, vchBaseNodeSignature, baseNodeSignatureTime, stop);
return true;
}
bool CActiveBasenode::Register(std::string strService, std::string strKeyBasenode, std::string txHash, std::string strOutputIndex, std::string& errorMessage) {
CTxIn vin;
CPubKey pubKeyCollateralAddress;
CKey keyCollateralAddress;
CPubKey pubKeyBasenode;
CKey keyBasenode;
if(!darkSendSigner.SetKey(strKeyBasenode, errorMessage, keyBasenode, pubKeyBasenode))
{
LogPrintf("CActiveBasenode::Register() - Error upon calling SetKey: %s\n", errorMessage.c_str());
return false;
}
if(!GetBaseNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress, txHash, strOutputIndex)) {
errorMessage = "could not allocate vin";
LogPrintf("CActiveBasenode::Register() - Error: %s\n", errorMessage.c_str());
return false;
}
return Register(vin, CService(strService), keyCollateralAddress, pubKeyCollateralAddress, keyBasenode, pubKeyBasenode, errorMessage);
}
bool CActiveBasenode::RegisterByPubKey(std::string strService, std::string strKeyBasenode, std::string collateralAddress, std::string& errorMessage) {
CTxIn vin;
CPubKey pubKeyCollateralAddress;
CKey keyCollateralAddress;
CPubKey pubKeyBasenode;
CKey keyBasenode;
if(!darkSendSigner.SetKey(strKeyBasenode, errorMessage, keyBasenode, pubKeyBasenode))
{
LogPrintf("CActiveBasenode::RegisterByPubKey() - Error upon calling SetKey: %s\n", errorMessage.c_str());
return false;
}
if(!GetBaseNodeVinForPubKey(collateralAddress, vin, pubKeyCollateralAddress, keyCollateralAddress)) {
errorMessage = "could not allocate vin for collateralAddress";
LogPrintf("Register::Register() - Error: %s\n", errorMessage.c_str());
return false;
}
return Register(vin, CService(strService), keyCollateralAddress, pubKeyCollateralAddress, keyBasenode, pubKeyBasenode, errorMessage);
}
bool CActiveBasenode::Register(CTxIn vin, CService service, CKey keyCollateralAddress, CPubKey pubKeyCollateralAddress, CKey keyBasenode, CPubKey pubKeyBasenode, std::string &retErrorMessage) {
std::string errorMessage;
std::vector<unsigned char> vchBaseNodeSignature;
std::string strBaseNodeSignMessage;
int64_t baseNodeSignatureTime = GetAdjustedTime();
std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end());
std::string vchPubKey2(pubKeyBasenode.begin(), pubKeyBasenode.end());
std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(baseNodeSignatureTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(PROTOCOL_VERSION);
if(!darkSendSigner.SignMessage(strMessage, errorMessage, vchBaseNodeSignature, keyCollateralAddress)) {
retErrorMessage = "sign message failed: " + errorMessage;
LogPrintf("CActiveBasenode::Register() - Error: %s\n", retErrorMessage.c_str());
return false;
}
if(!darkSendSigner.VerifyMessage(pubKeyCollateralAddress, vchBaseNodeSignature, strMessage, errorMessage)) {
retErrorMessage = "Verify message failed: " + errorMessage;
LogPrintf("CActiveBasenode::Register() - Error: %s\n", retErrorMessage.c_str());
return false;
}
CBasenode* pmn = mnodeman.Find(vin);
if(pmn == NULL)
{
LogPrintf("CActiveBasenode::Register() - Adding to Basenode list service: %s - vin: %s\n", service.ToString().c_str(), vin.ToString().c_str());
CBasenode mn(service, vin, pubKeyCollateralAddress, vchBaseNodeSignature, baseNodeSignatureTime, pubKeyBasenode, PROTOCOL_VERSION);
mn.UpdateLastSeen(baseNodeSignatureTime);
mnodeman.Add(mn);
}
//send to all peers
LogPrintf("CActiveBasenode::Register() - RelayElectionEntry vin = %s\n", vin.ToString().c_str());
mnodeman.RelayBasenodeEntry(vin, service, vchBaseNodeSignature, baseNodeSignatureTime, pubKeyCollateralAddress, pubKeyBasenode, -1, -1, baseNodeSignatureTime, PROTOCOL_VERSION);
return true;
}
bool CActiveBasenode::GetBaseNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey) {
return GetBaseNodeVin(vin, pubkey, secretKey, "", "");
}
bool CActiveBasenode::GetBaseNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex) {
// Find possible candidates
TRY_LOCK(pwalletMain->cs_wallet, fWallet);
if(!fWallet) return false;
vector<COutput> possibleCoins = SelectCoinsBasenode();
COutput *selectedOutput;
// Find the vin
if(!strTxHash.empty()) {
// Let's find it
uint256 txHash(strTxHash);
int outputIndex = atoi(strOutputIndex.c_str());
bool found = false;
BOOST_FOREACH(COutput& out, possibleCoins) {
if(out.tx->GetHash() == txHash && out.i == outputIndex)
{
selectedOutput = &out;
found = true;
break;
}
}
if(!found) {
LogPrintf("CActiveBasenode::GetBaseNodeVin - Could not locate valid vin\n");
return false;
}
} else {
// No output specified, Select the first one
if(possibleCoins.size() > 0) {
selectedOutput = &possibleCoins[0];
} else {
LogPrintf("CActiveBasenode::GetBaseNodeVin - Could not locate specified vin from possible list\n");
return false;
}
}
// At this point we have a selected output, retrieve the associated info
return GetVinFromOutput(*selectedOutput, vin, pubkey, secretKey);
}
// Extract Basenode vin information from output
bool CActiveBasenode::GetVinFromOutput(COutput out, CTxIn& vin, CPubKey& pubkey, CKey& secretKey) {
CScript pubScript;
vin = CTxIn(out.tx->GetHash(),out.i);
pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
CTxDestination address1;
ExtractDestination(pubScript, address1);
CBitcreditAddress address2(address1);
CKeyID keyID;
if (!address2.GetKeyID(keyID)) {
LogPrintf("CActiveBasenode::GetBaseNodeVin - Address does not refer to a key\n");
return false;
}
if (!pwalletMain->GetKey(keyID, secretKey)) {
LogPrintf ("CActiveBasenode::GetBaseNodeVin - Private key for address is not known\n");
return false;
}
pubkey = secretKey.GetPubKey();
return true;
}
bool CActiveBasenode::GetBaseNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey) {
return GetBaseNodeVinForPubKey(collateralAddress, vin, pubkey, secretKey, "", "");
}
bool CActiveBasenode::GetBaseNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex) {
CScript pubScript;
// Find possible candidates
vector<COutput> possibleCoins = SelectCoinsBasenodeForPubKey(collateralAddress);
COutput *selectedOutput;
// Find the vin
if(!strTxHash.empty()) {
// Let's find it
uint256 txHash(strTxHash);
int outputIndex = boost::lexical_cast<int>(strOutputIndex);
bool found = false;
BOOST_FOREACH(COutput& out, possibleCoins) {
if(out.tx->GetHash() == txHash && out.i == outputIndex)
{
selectedOutput = &out;
found = true;
break;
}
}
if(!found) {
LogPrintf("CActiveBasenode::GetBaseNodeVinForPubKey - Could not locate valid vin\n");
return false;
}
} else {
// No output specified, Select the first one
if(possibleCoins.size() > 0) {
selectedOutput = &possibleCoins[0];
} else {
LogPrintf("CActiveBasenode::GetBaseNodeVinForPubKey - Could not locate specified vin from possible list\n");
return false;
}
}
// At this point we have a selected output, retrieve the associated info
return GetVinFromOutput(*selectedOutput, vin, pubkey, secretKey);
}
// get all possible outputs for running basenode
vector<COutput> CActiveBasenode::SelectCoinsBasenode()
{
vector<COutput> vCoins;
vector<COutput> filteredCoins;
vector<COutPoint> confLockedCoins;
// Temporary unlock MN coins from basenode.conf
if(GetBoolArg("-bnconflock", true)) {
uint256 mnTxHash;
BOOST_FOREACH(CBasenodeConfig::CBasenodeEntry mne, basenodeConfig.getEntries()) {
mnTxHash.SetHex(mne.getTxHash());
COutPoint outpoint = COutPoint(mnTxHash, atoi(mne.getOutputIndex().c_str()));
confLockedCoins.push_back(outpoint);
pwalletMain->UnlockCoin(outpoint);
}
}
// Retrieve all possible outputs
pwalletMain->AvailableCoins(vCoins);
// Lock MN coins from basenode.conf back if they where temporary unlocked
if(!confLockedCoins.empty()) {
BOOST_FOREACH(COutPoint outpoint, confLockedCoins)
pwalletMain->LockCoin(outpoint);
}
// Filter
if (chainActive.Tip()->nHeight<145000) {
BOOST_FOREACH(const COutput& out, vCoins)
{
if(out.tx->vout[out.i].nValue == 250000*COIN) { //exactly
filteredCoins.push_back(out);
}
}
}
else {
BOOST_FOREACH(const COutput& out, vCoins)
{
if(out.tx->vout[out.i].nValue == 50000*COIN) { //exactly
filteredCoins.push_back(out);
}
}
}
return filteredCoins;
}
// get all possible outputs for running basenode for a specific pubkey
vector<COutput> CActiveBasenode::SelectCoinsBasenodeForPubKey(std::string collateralAddress)
{
CBitcreditAddress address(collateralAddress);
CScript scriptPubKey;
scriptPubKey= GetScriptForDestination(address.Get());
vector<COutput> vCoins;
vector<COutput> filteredCoins;
// Retrieve all possible outputs
pwalletMain->AvailableCoins(vCoins);
// Filter
if (chainActive.Tip()->nHeight<145000) {
BOOST_FOREACH(const COutput& out, vCoins)
{
if(out.tx->vout[out.i].nValue == 250000*COIN) { //exactly
filteredCoins.push_back(out);
}
}
}
else {
BOOST_FOREACH(const COutput& out, vCoins)
{
if(out.tx->vout[out.i].nValue == 50000*COIN) { //exactly
filteredCoins.push_back(out);
}
}
}
return filteredCoins;
}
// when starting a basenode, this can enable to run as a hot wallet with no funds
bool CActiveBasenode::EnableHotColdBaseNode(CTxIn& newVin, CService& newService)
{
if(!fBaseNode) return false;
status = BASENODE_REMOTELY_ENABLED;
//The values below are needed for signing dseep messages going forward
this->vin = newVin;
this->service = newService;
LogPrintf("CActiveBasenode::EnableHotColdBaseNode() - Enabled! You may shut down the cold daemon.\n");
return true;
}
<file_sep>#ifndef BIDPAGE_H
#define BIDPAGE_H
#include "clientmodel.h"
#include <QWidget>
namespace Ui
{
class BidPage;
}
class BidPage: public QWidget
{
Q_OBJECT
public:
BidPage(QWidget *parent = 0);
~BidPage();
QString str;
QString btctotal;
double btctot;
std::string theme;
void setClientModel(ClientModel *model);
private slots:
void SummonBTCWallet();
void SummonBTCExplorer();
void GetBids();
void setNumBlocks(int count);
int getNumBlocks();
void Estimate();
QString getDefaultDataDirectory();
QString pathAppend(const QString& path1, const QString& path2);
private:
Ui::BidPage *ui;
ClientModel *clientModel;
};
#endif // BIDPAGE_H
<file_sep>#!/usr/bin/env python2
# Copyright (c) 2014 The Bitcredit Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test REST interface
#
from test_framework import BitcreditTestFramework
from util import *
import base64
try:
import http.client as httplib
except ImportError:
import httplib
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
class HTTPBasicsTest (BitcreditTestFramework):
def run_test(self):
#################################################
# lowlevel check for http persistent connection #
#################################################
url = urlparse.urlparse(self.nodes[0].url)
authpair = url.username + ':' + url.password
headers = {"Authorization": "Basic " + base64.b64encode(authpair)}
conn = httplib.HTTPConnection(url.hostname, url.port)
conn.connect()
conn.request('GET', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read();
assert_equal('"error":null' in out1, True)
assert_equal(conn.sock!=None, True) #according to http/1.1 connection must still be open!
#send 2nd request without closing connection
conn.request('GET', '/', '{"method": "getchaintips"}', headers)
out2 = conn.getresponse().read();
assert_equal('"error":null' in out1, True) #must also response with a correct json-rpc message
assert_equal(conn.sock!=None, True) #according to http/1.1 connection must still be open!
conn.close()
#same should be if we add keep-alive because this should be the std. behaviour
headers = {"Authorization": "Basic " + base64.b64encode(authpair), "Connection": "keep-alive"}
conn = httplib.HTTPConnection(url.hostname, url.port)
conn.connect()
conn.request('GET', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read();
assert_equal('"error":null' in out1, True)
assert_equal(conn.sock!=None, True) #according to http/1.1 connection must still be open!
#send 2nd request without closing connection
conn.request('GET', '/', '{"method": "getchaintips"}', headers)
out2 = conn.getresponse().read();
assert_equal('"error":null' in out1, True) #must also response with a correct json-rpc message
assert_equal(conn.sock!=None, True) #according to http/1.1 connection must still be open!
conn.close()
#now do the same with "Connection: close"
headers = {"Authorization": "Basic " + base64.b64encode(authpair), "Connection":"close"}
conn = httplib.HTTPConnection(url.hostname, url.port)
conn.connect()
conn.request('GET', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read();
assert_equal('"error":null' in out1, True)
assert_equal(conn.sock!=None, False) #now the connection must be closed after the response
if __name__ == '__main__':
HTTPBasicsTest ().main ()
<file_sep>#include "optionsmodel.h"
#include "ircmodel.h"
#include "guiconstants.h"
#include "alert.h"
#include "main.h"
#include "ui_interface.h"
#include <QSet>
IRCModel::IRCModel(OptionsModel *optionsModel, QObject *parent) :
QObject(parent), optionsModel(optionsModel)
{
isConnected = false;
subscribeToCoreSignals();
}
IRCModel::~IRCModel()
{
unsubscribeFromCoreSignals();
}
void IRCModel::ircReceiveMessage(QString message)
{
isConnected = true;
emit ircMessageReceived(message);
}
OptionsModel *IRCModel::getOptionsModel()
{
return optionsModel;
}
static void NotifyIRCMessage(IRCModel *ircmodel, std::string message)
{
// Too noisy: OutputDebugStringF("NotifyIRCMessage %s\n", message);
QMetaObject::invokeMethod(ircmodel, "ircReceiveMessage", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(message)));
}
void IRCModel::subscribeToCoreSignals()
{
// Connect signals to irc
uiInterface.NotifyIRCMessage.connect(boost::bind(NotifyIRCMessage, this, _1));
}
void IRCModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from irc
uiInterface.NotifyIRCMessage.disconnect(boost::bind(NotifyIRCMessage, this, _1));
}
<file_sep># -*- coding: utf-8; -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2014 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Provides the infrastructure for calculating the asset ID and asset quantity of Bitcoin outputs,
according to the Open Assets Protocol.
"""
import asyncio
import lib.bitcoin.core
import lib.bitcoin.core.script
import enum
import hashlib
import io
class ColoringEngine(object):
"""The backtracking engine used to find the asset ID and asset quantity of any output."""
def __init__(self, transaction_provider, cache, event_loop):
"""
Constructs an instance of the ColorEngine class.
:param bytes -> Future[CTransaction] transaction_provider: A function returning a transaction given its hash.
:param OutputCache cache: The cache object to use.
:param BaseEventLoop | None event_loop: The event loop used to schedule asynchronous tasks.
"""
self._transaction_provider = transaction_provider
self._cache = cache
self._loop = event_loop
@asyncio.coroutine
def get_output(self, transaction_hash, output_index):
"""
Gets an output and information about its asset ID and asset quantity.
:param bytes transaction_hash: The hash of the transaction containing the output.
:param int output_index: The index of the output.
:return: An object containing the output as well as its asset ID and asset quantity.
:rtype: Future[TransactionOutput]
"""
cached_output = yield from self._cache.get(transaction_hash, output_index)
if cached_output is not None:
return cached_output
transaction = yield from self._transaction_provider(transaction_hash)
if transaction is None:
raise ValueError('Transaction {0} could not be retrieved'.format(lib.bitcoin.core.b2lx(transaction_hash)))
colored_outputs = yield from self.color_transaction(transaction)
for index, output in enumerate(colored_outputs):
yield from self._cache.put(transaction_hash, index, output)
return colored_outputs[output_index]
@asyncio.coroutine
def color_transaction(self, transaction):
"""
Computes the asset ID and asset quantity of every output in the transaction.
:param CTransaction transaction: The transaction to color.
:return: A list containing all the colored outputs of the transaction.
:rtype: Future[list[TransactionOutput]]
"""
# If the transaction is a coinbase transaction, the marker output is always invalid
if not transaction.is_coinbase():
for i, output in enumerate(transaction.vout):
# Parse the OP_RETURN script
marker_output_payload = MarkerOutput.parse_script(output.scriptPubKey)
if marker_output_payload is not None:
# Deserialize the payload as a marker output
marker_output = MarkerOutput.deserialize_payload(marker_output_payload)
if marker_output is not None:
# Fetch the colored outputs for previous transactions
inputs = []
for input in transaction.vin:
inputs.append((yield from asyncio.async(
self.get_output(input.prevout.hash, input.prevout.n), loop=self._loop)))
asset_ids = self._compute_asset_ids(
inputs,
i,
transaction.vout,
marker_output.asset_quantities)
if asset_ids is not None:
return asset_ids
# If no valid marker output was found in the transaction, all outputs are considered uncolored
return [
TransactionOutput(output.nValue, output.scriptPubKey, None, 0, OutputType.uncolored)
for output in transaction.vout]
@classmethod
def _compute_asset_ids(cls, inputs, marker_output_index, outputs, asset_quantities):
"""
Computes the asset IDs of every output in a transaction.
:param list[TransactionOutput] inputs: The outputs referenced by the inputs of the transaction.
:param int marker_output_index: The position of the marker output in the transaction.
:param list[CTxOut] outputs: The outputs of the transaction.
:param list[int] asset_quantities: The list of asset quantities of the outputs.
:return: A list of outputs with asset ID and asset quantity information.
:rtype: list[TransactionOutput]
"""
# If there are more items in the asset quantities list than outputs in the transaction (excluding the
# marker output), the marker output is deemed invalid
if len(asset_quantities) > len(outputs) - 1:
return None
# If there is no input in the transaction, the marker output is always invalid
if len(inputs) == 0:
return None
result = []
# Add the issuance outputs
issuance_asset_id = cls.hash_script(bytes(inputs[0].script))
for i in range(0, marker_output_index):
value, script = outputs[i].nValue, outputs[i].scriptPubKey
if i < len(asset_quantities) and asset_quantities[i] > 0:
output = TransactionOutput(value, script, issuance_asset_id, asset_quantities[i], OutputType.issuance)
else:
output = TransactionOutput(value, script, None, 0, OutputType.issuance)
result.append(output)
# Add the marker output
issuance_output = outputs[marker_output_index]
result.append(TransactionOutput(
issuance_output.nValue, issuance_output.scriptPubKey, None, 0, OutputType.marker_output))
# Add the transfer outputs
input_iterator = iter(inputs)
input_units_left = 0
for i in range(marker_output_index + 1, len(outputs)):
if i <= len(asset_quantities):
output_asset_quantity = asset_quantities[i - 1]
else:
output_asset_quantity = 0
output_units_left = output_asset_quantity
asset_id = None
while output_units_left > 0:
# Move to the next input if the current one is depleted
if input_units_left == 0:
current_input = next(input_iterator, None)
if current_input is None:
# There are less asset units available in the input than in the outputs:
# the marker output is considered invalid
return None
else:
input_units_left = current_input.asset_quantity
# If the current input is colored, assign its asset ID to the current output
if current_input.asset_id is not None:
progress = min(input_units_left, output_units_left)
output_units_left -= progress
input_units_left -= progress
if asset_id is None:
# This is the first input to map to this output
asset_id = current_input.asset_id
elif asset_id != current_input.asset_id:
# Another different asset ID has already been assigned to that output:
# the marker output is considered invalid
return None
result.append(TransactionOutput(
outputs[i].nValue, outputs[i].scriptPubKey, asset_id, output_asset_quantity, OutputType.transfer))
return result
@staticmethod
def hash_script(data):
"""
Hashes a script into an asset ID using SHA256 followed by RIPEMD160.
:param bytes data: The data to hash.
"""
sha256 = hashlib.sha256()
ripemd = hashlib.new('ripemd160')
sha256.update(data)
ripemd.update(sha256.digest())
return ripemd.digest()
class OutputType(enum.Enum):
uncolored = 0
marker_output = 1
issuance = 2
transfer = 3
class TransactionOutput(object):
"""Represents a transaction output and its asset ID and asset quantity."""
def __init__(
self,
value=-1,
script=lib.bitcoin.core.script.CScript(),
asset_id=None,
asset_quantity=0,
output_type=OutputType.uncolored):
"""
Initializes a new instance of the TransactionOutput class.
:param int value: The satoshi value of the output.
:param CScript script: The script controlling redemption of the output.
:param bytes | None asset_id: The asset ID of the output.
:param int asset_quantity: The asset quantity of the output.
:param OutputType output_type: The type of the output.
"""
assert 0 <= asset_quantity <= MarkerOutput.MAX_ASSET_QUANTITY
self._value = value
self._script = script
self._asset_id = asset_id
self._asset_quantity = asset_quantity
self._output_type = output_type
@property
def value(self):
"""
Gets the number of satoshis in the output.
:return: The value of the output in satoshis.
:rtype: int
"""
return self._value
@property
def script(self):
"""
Gets the script of the output.
:return: The output script.
:rtype: CScript
"""
return self._script
@property
def asset_id(self):
"""
Gets the asset ID of the output.
:return: The asset ID of the output, or None of the output is uncolored.
:rtype: bytes | None
"""
return self._asset_id
@property
def asset_quantity(self):
"""
Gets the asset quantity of the output.
:return: The asset quantity of the output (zero if the output is uncolored).
:rtype: int
"""
return self._asset_quantity
@property
def output_type(self):
"""
Gets the type of the output.
:return: The type of the output.
:rtype: OutputType
"""
return self._output_type
def __repr__(self):
return 'TransactionOutput(value=%r, script=%r, asset_id=%r, asset_quantity=%r, output_type=%r)' % \
(self.value, self.script, self.asset_id, self.asset_quantity, self.output_type)
class OutputCache(object):
"""Represents the interface for an object capable of storing the result of output coloring."""
@asyncio.coroutine
def get(self, transaction_hash, output_index):
"""
Returns a cached output.
:param bytes transaction_hash: The hash of the transaction the output belongs to.
:param int output_index: The index of the output in the transaction.
:return: The output for the transaction hash and output index provided if it is found in the cache, or None
otherwise.
:rtype: TransactionOutput
"""
return None
@asyncio.coroutine
def put(self, transaction_hash, output_index, output):
"""
Saves an output in cache.
:param bytes transaction_hash: The hash of the transaction the output belongs to.
:param int output_index: The index of the output in the transaction.
:param TransactionOutput output: The output to save.
"""
pass
class MarkerOutput(object):
"""Represents an Open Assets marker output."""
MAX_ASSET_QUANTITY = 2 ** 63 - 1
OPEN_ASSETS_TAG = b'OA\x01\x00'
def __init__(self, asset_quantities, metadata):
"""
Initializes a new instance of the MarkerOutput class.
:param list[int] asset_quantities: The list of asset quantities.
:param bytes metadata: The metadata in the marker output.
"""
self._asset_quantities = asset_quantities
self._metadata = metadata
@property
def asset_quantities(self):
"""
Gets the asset quantity list.
:return: The asset quantity list of the output.
:rtype: list[int]
"""
return self._asset_quantities
@property
def metadata(self):
"""
Gets the metadata contained in the marker output.
:return: The metadata contained in the marker output.
:rtype: bytes
"""
return self._metadata
@classmethod
def deserialize_payload(cls, payload):
"""
Deserializes the marker output payload.
:param bytes payload: A buffer containing the marker output payload.
:return: The marker output object.
:rtype: MarkerOutput
"""
with io.BytesIO(payload) as stream:
# The OAP marker and protocol version
oa_version = stream.read(4)
if oa_version != cls.OPEN_ASSETS_TAG:
return None
try:
# Deserialize the expected number of items in the asset quantity list
output_count = lib.bitcoin.core.VarIntSerializer.stream_deserialize(stream)
# LEB128-encoded unsigned integers representing the asset quantity of every output in order
asset_quantities = []
for i in range(0, output_count):
asset_quantity = cls.leb128_decode(stream)
# If the LEB128-encoded asset quantity of any output exceeds 9 bytes,
# the marker output is deemed invalid
if asset_quantity > cls.MAX_ASSET_QUANTITY:
return None
asset_quantities.append(asset_quantity)
# The var-integer encoded length of the metadata field.
metadata_length = lib.bitcoin.core.VarIntSerializer.stream_deserialize(stream)
# The actual metadata
metadata = stream.read(metadata_length)
# If the metadata string wasn't long enough, the marker output is malformed
if len(metadata) != metadata_length:
return None
# If there are bytes left to read, the marker output is malformed
last_byte = stream.read(1)
if len(last_byte) > 0:
return None
except lib.bitcoin.core.SerializationTruncationError:
return None
return MarkerOutput(asset_quantities, metadata)
def serialize_payload(self):
"""
Serializes the marker output data into a payload buffer.
:return: The serialized payload.
:rtype: bytes
"""
with io.BytesIO() as stream:
stream.write(self.OPEN_ASSETS_TAG)
lib.bitcoin.core.VarIntSerializer.stream_serialize(len(self.asset_quantities), stream)
for asset_quantity in self.asset_quantities:
stream.write(self.leb128_encode(asset_quantity))
lib.bitcoin.core.VarIntSerializer.stream_serialize(len(self.metadata), stream)
stream.write(self.metadata)
return stream.getvalue()
@staticmethod
def parse_script(output_script):
"""
Parses an output and returns the payload if the output matches the right pattern for a marker output,
or None otherwise.
:param CScript output_script: The output script to be parsed.
:return: The marker output payload if the output fits the pattern, None otherwise.
:rtype: bytes
"""
script_iterator = output_script.raw_iter()
try:
first_opcode, _, _ = next(script_iterator, (None, None, None))
_, data, _ = next(script_iterator, (None, None, None))
remainder = next(script_iterator, None)
except lib.bitcoin.core.script.CScriptTruncatedPushDataError:
return None
except lib.bitcoin.core.script.CScriptInvalidError:
return None
if first_opcode == lib.bitcoin.core.script.OP_RETURN and data is not None and remainder is None:
return data
else:
return None
@staticmethod
def build_script(data):
"""
Creates an output script containing an OP_RETURN and a PUSHDATA.
:param bytes data: The content of the PUSHDATA.
:return: The final script.
:rtype: CScript
"""
return lib.bitcoin.core.script.CScript(
bytes([lib.bitcoin.core.script.OP_RETURN]) + lib.bitcoin.core.script.CScriptOp.encode_op_pushdata(data))
@staticmethod
def leb128_decode(data):
"""
Decodes a LEB128-encoded unsigned integer.
:param BufferedIOBase data: The buffer containing the LEB128-encoded integer to decode.
:return: The decoded integer.
:rtype: int
"""
result = 0
shift = 0
while True:
character = data.read(1)
if len(character) == 0:
raise lib.bitcoin.core.SerializationTruncationError('Invalid LEB128 integer')
b = ord(character)
result |= (b & 0x7f) << shift
if b & 0x80 == 0:
break
shift += 7
return result
@staticmethod
def leb128_encode(value):
"""
Encodes an integer using LEB128.
:param int value: The value to encode.
:return: The LEB128-encoded integer.
:rtype: bytes
"""
if value == 0:
return b'\x00'
result = []
while value != 0:
byte = value & 0x7f
value >>= 7
if value != 0:
byte |= 0x80
result.append(byte)
return bytes(result)
def __repr__(self):
return 'MarkerOutput(asset_quantities=%r, metadata=%r)' % (self.asset_quantities, self.metadata)
<file_sep>#include "bidtracker.h"
#include "basenodeman.h"
#include "voting.h"
#include "wallet.h"
#include "base58.h"
#include "util.h"
#include <iostream>
#include <string>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <sstream>
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
//for (int i = 0; std::getline(f, line); ++i)
string remove(string input, char m)
{
input.erase(std::remove(input.begin(),input.end(), m),input.end());
return input;
}
std::string replacestring(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
double Bidtracker::getbalance(string url)
{
const char * c = url.c_str();
std::string readBuffer;
CAmount balance;
curl = curl_easy_init();
if(curl) {
curl_global_init(CURL_GLOBAL_ALL);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_URL, c);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Bitcredit/0.30");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
if(res != CURLE_OK) {
if (fDebug) LogPrintf("Curl Error on Bidtracker::getbalance() - %s - on URL:%s.\n", curl_easy_strerror(res), url);
}
else {
if (fDebug) LogPrintf("Curl Response on Bidtracker::getbalance() - Lenght %lu - Buffer - %s .\n", (long)readBuffer.size(), readBuffer);
}
std::string response = readBuffer;
if ( ! (istringstream(response) >> balance) ) balance = 0;
return balance;
}
void Bidtracker::btcsortunspent(){
ifstream myfile ((GetDataDir()/ "bidtracker/btcunspentraw.dat").string().c_str());
std::ofstream myfile2;
myfile2.open((GetDataDir()/ "bidtracker/btcbids.dat").string().c_str(),fstream::out);
std::string line, txid, url;
try
{
if (myfile.is_open()){
while ( myfile.good() ){
getline (myfile,line);
string temp = line;
std::string search;
std::string search2;
size_t pos;
size_t f = line.find("tx_hash_big_endian:");
size_t g = line.find("value:");
search = "tx_hash_big_endian";
pos = temp.find(search);
if (pos != std::string::npos){
std::string semp =line;
semp = semp.replace(f, std::string("tx_hash_big_endian:").length(), "");
semp = remove(semp, ',');
txid = semp;
url = "https://blockchain.info/rawtx/"+ txid ;
const char * d = url.c_str();
string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_global_init(CURL_GLOBAL_ALL);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_URL, d);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Bitcredit/0.30");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
if(res != CURLE_OK) {
if (fDebug) LogPrintf("Curl Error on Bidtracker::btcsortunspent() - %s - on URL:%s.\n", curl_easy_strerror(res), url);
}
else {
if (fDebug) LogPrintf("Curl Response on Bidtracker::btcsortunspent() - Lenght %lu - Buffer - %s .\n", (long)readBuffer.size(), readBuffer);
std::size_t pos1 = readBuffer.find("value");
readBuffer = readBuffer.substr(0,pos1);
readBuffer = remove(readBuffer, '"');
readBuffer = remove(readBuffer, '{');
readBuffer = remove(readBuffer,'}');
readBuffer = remove(readBuffer, '[');
readBuffer = remove(readBuffer, '\n');
std::string uemp =readBuffer;
std::size_t pos2 = uemp.find("addr:");
uemp = uemp.substr(pos2);
uemp = replacestring(uemp, "addr:", "");
erase_all(uemp, " ");
myfile2 << uemp;
}
}
search2 = "value:";
pos = temp.find(search2);
if (pos != std::string::npos){
std::string semp =line;
semp = semp.replace(g, std::string("value:").length(), "");
string value = semp;
value = remove(value, ',');
long double amount = atof(value.c_str());
myfile2 << std::fixed << amount << std::endl;
}
}
myfile.close();
myfile2.close();
}
}
catch (std::exception const &exc)
{
if (fDebug) LogPrintf("Bidtracker Error on Bidtracker::btcsortunspent() - %s .\n", exc.what());
}
catch (...)
{
if (fDebug) LogPrintf("Bidtracker Unknown Error on Bidtracker::btcsortunspent().\n");
}
}
void Bidtracker::btcsortunspentbackup(){
ifstream myfile ((GetDataDir()/ "bidtracker/btcunspentrawbackup.dat").string().c_str());
std::ofstream myfile2;
myfile2.open((GetDataDir()/ "bidtracker/btcbidsbackup.dat").string().c_str(),fstream::out);
try
{
std::string line, txid, url;
char * pEnd;
if (myfile.is_open()){
while (myfile.good()){
getline(myfile,line);
line = line.erase(line.find("txid:"), 5);
line = line.erase(line.find("amount:"), 7);
std::vector<std::string> strs;
boost::split(strs, line, boost::is_any_of(","));
long double amount = strtoll(strs[5].c_str(),&pEnd,10) *COIN;
txid = strs[1].c_str();
url = "https://blockchain.info/rawtx/"+ txid ;
const char * d = url.c_str();
string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_global_init(CURL_GLOBAL_ALL);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_URL, d);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Bitcredit/0.30");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
if(res != CURLE_OK) {
if (fDebug) LogPrintf("Curl Error on Bidtracker::btcsortunspentbackup() - %s - on URL:%s.\n", curl_easy_strerror(res), url);
}
else {
if (fDebug) LogPrintf("Curl Response on Bidtracker::btcsortunspentbackup() - Lenght %lu - Buffer - %s .\n", (long)readBuffer.size(), readBuffer);
std::size_t pos1 = readBuffer.find("value");
readBuffer = readBuffer.substr(0,pos1);
readBuffer = remove(readBuffer, '"');
readBuffer = remove(readBuffer, '{');
readBuffer = remove(readBuffer,'}');
readBuffer = remove(readBuffer, '[');
readBuffer = remove(readBuffer, '\n');
std::string uemp =readBuffer;
std::size_t pos2 = uemp.find("addr:");
uemp = uemp.substr(pos2);
uemp = replacestring(uemp, "addr:", "");
erase_all(uemp, " ");
myfile2 << uemp <<amount<< endl;
}
}
//myfile2 << strs[1].c_str() << "," << std::fixed << amount << std::endl;
myfile.close();
myfile2.close();
}
}
catch (std::exception const &exc)
{
if (fDebug) LogPrintf("Bidtracker Error on Bidtracker::btcsortunspentbackup() - %s .\n", exc.what());
}
catch (...)
{
if (fDebug) LogPrintf("Bidtracker Unknown Error on Bidtracker::btcsortunspentbackup().\n");
}
}
void Bidtracker::btcgetunspentbackup()
{
string address = "1BCRbid2i3wbgqrKtgLGem6ZchcfYbnhNu";
string url = "https://blockexplorer.com/api/addr/"+ address + "/utxo";
try
{
const char * c = url.c_str() ;
std::string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_global_init(CURL_GLOBAL_ALL);
curl_easy_setopt(curl, CURLOPT_URL, c);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Bitcredit/0.30");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
if(res != CURLE_OK) {
if (fDebug) LogPrintf("Curl Error on Bidtracker::btcgetunspentbackup() - %s - on URL:%s.\n", curl_easy_strerror(res), url);
}
else {
if (fDebug) LogPrintf("Curl Response on Bidtracker::btcgetunspentbackup() - Lenght %lu - Buffer - %s .\n", (long)readBuffer.size(), readBuffer);
readBuffer = remove(readBuffer, '[');
readBuffer = remove(readBuffer, ']');
readBuffer = replacestring(readBuffer, "},", "}\n");
readBuffer = remove(readBuffer, '{');
readBuffer = remove(readBuffer, '}');
readBuffer = remove(readBuffer, '"');
ofstream myfile((GetDataDir().string() + "/bidtracker/btcunspentrawbackup.dat").c_str(),fstream::out);
myfile << readBuffer<< std::endl;
myfile.close();
}
}
catch (std::exception const &exc)
{
if (fDebug) LogPrintf("Bidtracker Error on Bidtracker::btcgetunspentbackup() - %s .\n", exc.what());
}
catch (...)
{
if (fDebug) LogPrintf("Bidtracker Unknown Error on Bidtracker::btcgetunspentbackup().\n");
}
}
void Bidtracker::btcgetunspent()
{
std::string address = "1BCRbid2i3wbgqrKtgLGem6ZchcfYbnhNu";
std::string url;
url = "https://blockchain.info/unspent?active=" + address;
try
{
const char * c = url.c_str();
std::string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_global_init(CURL_GLOBAL_ALL);
curl_easy_setopt(curl, CURLOPT_URL, c);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Bitcredit/0.30");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
boost::filesystem::path biddir = GetDataDir() / "bidtracker";
if(!(boost::filesystem::exists(biddir))){
if(fDebug)LogPrintf("Biddir Doesn't Exists\n");
if (boost::filesystem::create_directory(biddir))
if(fDebug)LogPrintf("Biddir....Successfully Created !\n");
}
if(res != CURLE_OK) {
if (fDebug) LogPrintf("Curl Error on Bidtracker::btcgetunspent() - %s - on URL:%s.\n", curl_easy_strerror(res), url);
}
else {
if (fDebug) LogPrintf("Curl Response on Bidtracker::btcgetunspent() - Lenght %lu - Buffer - %s .\n", (long)readBuffer.size(), readBuffer);
ofstream myfile((GetDataDir().string() + "/bidtracker/btcunspentraw.dat").c_str(),fstream::out);
readBuffer = remove(readBuffer, ' ');
readBuffer = remove(readBuffer, '"');
myfile << readBuffer << std::endl;
myfile.close();
}
}
catch (std::exception const &exc)
{
if (fDebug) LogPrintf("Bidtracker Error on Bidtracker::btcgetunspent() - %s .\n", exc.what());
}
catch (...)
{
if (fDebug) LogPrintf("Bidtracker Unknown Error on Bidtracker::btcgetunspent().\n");
}
}
double Bidtracker::btcgetprice()
{
CAmount price;
std::string url;
url = "https://blockchain.info/q/24hrprice";
const char * c = url.c_str();
std::string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_global_init(CURL_GLOBAL_ALL);
curl_easy_setopt(curl, CURLOPT_URL, c);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Bitcredit/0.30");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
if(res != CURLE_OK) {
if (fDebug) LogPrintf("Curl Error on Bidtracker::btcgetprice() - %s - on URL:%s.\n", curl_easy_strerror(res), url);
}
else {
if (fDebug) LogPrintf("Curl Response on Bidtracker::btcgetprice() - Lenght %lu - Buffer - %s .\n", (long)readBuffer.size(), readBuffer);
price = atof(readBuffer.c_str());
}
return price;
}
double Bidtracker::bcrgetprice()
{
double price;
std::string url;
url = "https://bittrex.com/api/v1.1/public/getticker?market=BTC-BCR";
const char * c = url.c_str();
std::string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_global_init(CURL_GLOBAL_ALL);
curl_easy_setopt(curl, CURLOPT_URL, c);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Bitcredit/0.30");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
if(res != CURLE_OK) {
if (fDebug) LogPrintf("Curl Error on Bidtracker::bcrgetprice() - %s - on URL:%s.\n", curl_easy_strerror(res), url);
}
else {
if (fDebug) LogPrintf("Curl Response on Bidtracker::bcrgetprice() - Lenght %lu - Buffer - %s .\n", (long)readBuffer.size(), readBuffer);
std::size_t pos = readBuffer.find(",\"A");
readBuffer = readBuffer.substr(0,pos);
readBuffer = replacestring(readBuffer, ",", ",\n");
readBuffer = remove(readBuffer, ',');
readBuffer = remove(readBuffer, '"');
readBuffer = remove(readBuffer, ':');
readBuffer = remove(readBuffer, '{');
readBuffer = replacestring(readBuffer, "successtrue", "");
readBuffer = replacestring(readBuffer, "message", "");
readBuffer = replacestring(readBuffer, "resultBid", "");
readBuffer = remove(readBuffer, '\n');
}
if ( ! (istringstream(readBuffer) >> price) ) price = 0;
return price;
}
double Bidtracker::usdbtc(){
return btcgetprice();
}
long double Bidtracker::bcrbtc(){
return bcrgetprice();
}
void Bidtracker::combine()
{
std::ofstream myfile;
myfile.open((GetDataDir() /"bidtracker/prefinal.dat").string().c_str(),fstream::out);
ifstream myfile2((GetDataDir() /"bidtracker/btcbids.dat").string().c_str());
ifstream myfile3((GetDataDir() /"bidtracker/btcbidsbackup.dat").string().c_str());
if (myfile2.is_open()){
std::string line;
while ( myfile2.good() ){
getline (myfile2,line);
myfile<<line<<endl;
} }
if (myfile3.is_open()){
std::string line;
while ( myfile3.good() ){
getline (myfile3,line);
myfile<<line<<endl;
} }
myfile.close();
myfile2.close();
myfile3.close();
remove((GetDataDir() /"bidtracker/btcbids.dat").string().c_str());
remove((GetDataDir() /"bidtracker/btcbidsbackup.dat").string().c_str());
remove((GetDataDir() /"bidtracker/btcunspentraw.dat").string().c_str());
remove((GetDataDir() /"bidtracker/btcunspentrawbackup.dat").string().c_str());
}
int totalbid;
std::map<std::string,double>::iterator brit;
void sortbidtracker(){
std::map<std::string,double> finalbids;
fstream myfile2((GetDataDir() /"bidtracker/prefinal.dat").string().c_str());
totalbid=0;
char * pEnd;
std::string line;
while (getline(myfile2, line)){
if (!line.empty()) {
std::vector<std::string> strs;
boost::split(strs, line, boost::is_any_of(","));
totalbid+=strtoll(strs[1].c_str(),&pEnd,10);
finalbids[strs[0]]+=strtoll(strs[1].c_str(),&pEnd,10);
}
}
ofstream myfile;
myfile.open((GetDataDir() /"bidtracker/final.dat").string().c_str(), std::ofstream::trunc);
myfile << std::fixed << setprecision(8);
for(brit = finalbids.begin();brit != finalbids.end(); ++brit){
if (!(brit->second ==0 || totalbid == 0) )
myfile << brit->first << "," << (brit->second)/totalbid << endl;
}
myfile2.close();
myfile.close();
}
std::map<std::string,double> getbidtracker(){
std::map<std::string,double> finals;
fstream myfile((GetDataDir() /"bidtracker/final.dat").string().c_str());
char * pEnd;
std::string line;
while (getline(myfile, line)){
if (!line.empty()) {
std::vector<std::string> strs;
boost::split(strs, line, boost::is_any_of(","));
finals[strs[0]]=strtod(strs[1].c_str(),&pEnd);
}
}
return finals;
}
void getbids(){
int64_t nStart = GetTimeMillis();
Bidtracker h;
h.btcgetunspent();
h.btcgetunspentbackup();
h.btcsortunspent();
h.btcsortunspentbackup();
h.combine();
sortbidtracker();
if(fDebug)LogPrintf("Bids dump finished %dms\n", GetTimeMillis() - nStart);
}
<file_sep>#ifndef INVOICEPAGE_H
#define INVOICEPAGE_H
#include <QWidget>
namespace Ui {
class InvoicePage;
}
class MessageModel;
class InvoiceTableModel;
QT_BEGIN_NAMESPACE
class QTableView;
class QItemSelection;
class QSortFilterProxyModel;
class QMenu;
class QModelIndex;
QT_END_NAMESPACE
/** Widget that shows a list of sending or receiving addresses.
*/
class InvoicePage : public QWidget
{
Q_OBJECT
public:
explicit InvoicePage(QWidget *parent = 0);
~InvoicePage();
void setModel(MessageModel *model);
public slots:
void exportClicked();
private:
Ui::InvoicePage *ui;
InvoiceTableModel *model;
QSortFilterProxyModel *proxyModel;
QMenu *contextMenu;
QAction *replyAction;
QAction *payAction;
QAction *resendAction;
QAction *receiptAction;
QAction *copyFromAddressAction;
QAction *copyToAddressAction;
QAction *deleteAction;
QAction *viewAction;
private slots:
void on_newButton_clicked();
void on_payButton_clicked();
void on_replyButton_clicked();
void on_resendButton_clicked();
void on_receiptButton_clicked();
void on_copyFromAddressButton_clicked();
void on_copyToAddressButton_clicked();
void on_deleteButton_clicked();
void selectionChanged();
void viewInvoice(const QModelIndex & index);
/** Spawn contextual menu (right mouse menu) for address book entry */
void contextualMenu(const QPoint &point);
signals:
};
#endif // INVOICEPAGE_H
<file_sep>// Copyright (c) 2014 The Memorycoin developers
#include "sync.h"
#include "util.h"
#include "amount.h"
#include <algorithm>
#include <exception>
#include <map>
#include <set>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
#include <boost/unordered_map.hpp>
#include <list>
using namespace std;
extern CCriticalSection grantdb;
extern std::map<std::string,int64_t > grantAwards;
extern std::map<std::string,int64_t>::iterator gait;
extern std::map<std::string,int64_t> getbalances();
extern std::map<std::string,int64_t> gettxincount();
extern std::map<std::string,int64_t> gettxoutcount();
extern std::map<std::string,int64_t> gettotalin();
extern std::map<std::string,int64_t> gettotalout();
extern std::map<std::string,int64_t> getfirstseen();
extern std::map<std::string,int64_t> getcreditfinal();
extern std::map<std::string,int64_t> getminedblocks();
bool isGrantAwardBlock(int64_t nHeight);
bool getGrantAwards(int64_t nHeight);
static const int64_t GRANTBLOCKINTERVAL = 1;
int64_t getGrantDatabaseBlockHeight();
void processNextBlockIntoGrantDatabase();
bool getGrantAwardsFromDatabaseForBlock(int64_t nHeight);
bool ensureGrantDatabaseUptoDate(int64_t nHeight);
bool startsWith(const char *str, const char *pre);
void getWinnersFromBallots(int64_t nHeight,int officeNumber);
string electOrEliminate(int64_t droopQuota, unsigned int requiredCandidates);
void electCandidate(string topOfThePoll, double gregorySurplusTransferValue,bool isLastCandidate);
void eliminateCandidate(string topOfThePoll,bool isLastCandidate);
void printBallots();
bool deSerializeGrantDB(string filename);
<file_sep>#ifndef IRCMODEL_H
#define IRCMODEL_H
#include <QObject>
#include <vector>
#include "allocators.h" /* for SecureString */
#include <map>
class OptionsModel;
QT_BEGIN_NAMESPACE
class QTimer;
QT_END_NAMESPACE
/** Interface to NoirShares Secure Messaging from Qt view code. */
class IRCModel : public QObject
{
Q_OBJECT
public:
explicit IRCModel(OptionsModel *optionsModel, QObject *parent = 0);
~IRCModel();
OptionsModel *getOptionsModel();
bool getIRCConnected() {return isConnected;}
private:
OptionsModel *optionsModel;
void subscribeToCoreSignals();
void unsubscribeFromCoreSignals();
bool isConnected;
public slots:
void ircReceiveMessage(QString message);
signals:
// Receive IRC Message
void ircMessageReceived(QString message);
// Asynchronous error notification
void error(const QString &title, const QString &message, bool modal);
};
#endif // IRCMODEL_H
<file_sep># -*- coding: utf-8; -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2014 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import lib.bitcoin.base58
import lib.bitcoin.wallet
class Base58Address(bytes):
"""Represents a Base58-encoded address. It includes a version, checksum and namespace."""
def __init__(self, data, version, namespace):
"""
Initializes a Base58Address object from data, version and namespace.
:param bytes data: The base-58 payload.
:param int version: The version byte.
:param int | None namespace: The namespace byte.
:return: The Base58Address instance.
:rtype: Base58Address
"""
if not (0 <= version <= 255):
raise ValueError('version must be in range 0 to 255 inclusive; got %d' % version)
if namespace is not None and not (0 <= namespace <= 255):
raise ValueError('namespace must be None or in range 0 to 255 inclusive; got %d' % version)
if len(data) != 20:
raise ValueError('The payload must be 20 bytes long')
super().__init__()
self.address = lib.bitcoin.wallet.CBitcoinAddress.from_bytes(data, version)
self.namespace = namespace
def __new__(cls, data, version, namespace, *args, **kwargs):
return super().__new__(cls, data)
@classmethod
def from_string(cls, base58):
"""
Creates a new instance of the Base58Address class.
:param str base58: The Base-58 encoded address.
:return: The Base58Address instance.
:rtype: Base58Address
"""
decoded_bytes = lib.bitcoin.base58.decode(base58)
checksum = decoded_bytes[-4:]
calculated_checksum = lib.bitcoin.core.Hash(decoded_bytes[:-4])[:4]
if checksum != calculated_checksum:
raise lib.bitcoin.base58.Base58ChecksumError(
'Checksum mismatch: expected %r, calculated %r' % (checksum, calculated_checksum))
if len(decoded_bytes) == 26:
# The address has a namespace defined
namespace, version, data = decoded_bytes[0:1], decoded_bytes[1:2], decoded_bytes[2:-4]
return cls(data, version[0], namespace[0])
elif len(decoded_bytes) == 25:
# The namespace is undefined
version, data = decoded_bytes[0:1], decoded_bytes[1:-4]
return cls(data, version[0], None)
else:
raise ValueError('Invalid length')
def to_bytes(self):
"""Converts to a bytes instance.
Note that it's the data represented that is converted; the checksum, version and namespace are not included.
:return: The Base58Address instance.
:rtype: bytes
"""
return b'' + self
def __str__(self):
"""
Converts the address to a string.
:return: The base-58 encoded string.
:rtype: str
"""
if self.namespace is None:
full_payload = bytes([self.address.nVersion]) + self
else:
full_payload = bytes([self.namespace]) + bytes([self.address.nVersion]) + self
checksum = lib.bitcoin.core.Hash(full_payload)[0:4]
return lib.bitcoin.base58.encode(full_payload + checksum)
<file_sep>// Copyright (c) 2014 The ShadowCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "rpcserver.h"
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>
#include "smessage.h"
#include "init.h"
#include "util.h"
using namespace json_spirit;
using namespace std;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
static inline std::string GetTimeString(int64_t time) {
return DateTimeStrFormat("%Y-%m-%d %H:%M:%S", time);
}
Value smsgenable(const Array& params, bool fHelp) {
if (fHelp || params.size() != 0)
throw runtime_error(
"smsgenable \n"
"Enable secure messaging.");
if (fSecMsgEnabled)
throw runtime_error("Secure messaging is already enabled.");
Object result;
if (!SecureMsgEnable()) {
result.push_back(Pair("result", "Failed to enable secure messaging."));
}
else {
result.push_back(Pair("result", "Enabled secure messaging."));
}
return result;
}
Value smsgdisable(const Array& params, bool fHelp) {
if (fHelp || params.size() != 0)
throw runtime_error(
"smsgdisable \n"
"Disable secure messaging.");
if (!fSecMsgEnabled)
throw runtime_error("Secure messaging is already disabled.");
Object result;
if (!SecureMsgDisable()) {
result.push_back(Pair("result", "Failed to disable secure messaging."));
}
else {
result.push_back(Pair("result", "Disabled secure messaging."));
}
return result;
}
Value smsgoptions(const Array& params, bool fHelp) {
if (fHelp || params.size() > 3)
throw runtime_error(
"smsgoptions [list|set <optname> <value>]\n"
"List and manage options.");
std::string mode = "list";
if (params.size() > 0) {
mode = params[0].get_str();
}
Object result;
if (mode == "list") {
result.push_back(Pair("option", std::string("newAddressRecv = ") + (smsgOptions.fNewAddressRecv ? "true" : "false")));
result.push_back(Pair("option", std::string("newAddressAnon = ") + (smsgOptions.fNewAddressAnon ? "true" : "false")));
result.push_back(Pair("result", "Success."));
}
else if (mode == "set") {
if (params.size() < 3) {
result.push_back(Pair("result", "Too few parameters."));
result.push_back(Pair("expected", "set <optname> <value>"));
return result;
}
std::string optname = params[1].get_str();
bool is_bool = params[2].type() == bool_type;
bool value = is_bool && params[2].get_bool();
if (optname == "newAddressRecv") {
if (is_bool) {
smsgOptions.fNewAddressRecv = value;
}
else {
result.push_back(Pair("result", "Unknown value."));
return result;
}
result.push_back(Pair("set option", std::string("newAddressRecv = ") + (smsgOptions.fNewAddressRecv ? "true" : "false")));
}
else if (optname == "newAddressAnon") {
if (is_bool) {
smsgOptions.fNewAddressAnon = value;
}
else {
result.push_back(Pair("result", "Unknown value."));
return result;
}
result.push_back(Pair("set option", std::string("newAddressAnon = ") + (smsgOptions.fNewAddressAnon ? "true" : "false")));
}
else {
result.push_back(Pair("result", "Option not found."));
return result;
}
}
else {
result.push_back(Pair("result", "Unknown Mode."));
result.push_back(Pair("expected", "smsgoption [list|set <optname> <value>]"));
}
return result;
}
Value smsglocalkeys(const Array& params, bool fHelp) {
if (fHelp || params.size() > 3)
throw runtime_error(
"smsglocalkeys [whitelist|all|wallet|recv <+/-> <address>|anon <+/-> <address>]\n"
"List and manage keys.");
if (!fSecMsgEnabled)
throw runtime_error("Secure messaging is disabled.");
Object result;
std::string mode = "whitelist";
if (params.size() > 0) {
mode = params[0].get_str();
}
char cbuf[256];
if (mode == "whitelist" || mode == "all") {
uint32_t nKeys = 0;
int all = mode == "all" ? 1 : 0;
for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it) {
if (!all && !it->fReceiveEnabled)
continue;
CBitcreditAddress coinAddress(it->sAddress);
if (!coinAddress.IsValid())
continue;
std::string sPublicKey;
CKeyID keyID;
if (!coinAddress.GetKeyID(keyID))
continue;
CPubKey pubKey;
if (!pwalletMain->GetPubKey(keyID, pubKey))
continue;
if (!pubKey.IsValid() || !pubKey.IsCompressed()) {
continue;
};
sPublicKey = EncodeBase58(&pubKey[0], &pubKey[pubKey.size()]);
std::string sLabel = pwalletMain->mapAddressBook[keyID].name;
std::string sInfo;
if (all)
sInfo = std::string("Receive ") + (it->fReceiveEnabled ? "on, " : "off, ");
sInfo += std::string("Anon ") + (it->fReceiveAnon ? "on" : "off");
result.push_back(Pair("key", it->sAddress + " - " + sPublicKey + " " + sInfo + " - " + sLabel));
nKeys++;
}
snprintf(cbuf, sizeof(cbuf), "%u keys listed.", nKeys);
result.push_back(Pair("result", std::string(cbuf)));
}
else if (mode == "recv") {
if (params.size() < 3) {
result.push_back(Pair("result", "Too few parameters."));
result.push_back(Pair("expected", "recv <+/-> <address>"));
return result;
}
std::string op = params[1].get_str();
std::string addr = params[2].get_str();
std::vector<SecMsgAddress>::iterator it;
for (it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it) {
if (addr != it->sAddress)
continue;
break;
}
if (it == smsgAddresses.end()) {
result.push_back(Pair("result", "Address not found."));
return result;
}
if (op == "+" || op == "on" || op == "add" || op == "a") {
it->fReceiveEnabled = true;
}
else if (op == "-" || op == "off" || op == "rem" || op == "r") {
it->fReceiveEnabled = false;
}
else {
result.push_back(Pair("result", "Unknown operation."));
return result;
}
std::string sInfo;
sInfo = std::string("Receive ") + (it->fReceiveEnabled ? "on, " : "off,");
sInfo += std::string("Anon ") + (it->fReceiveAnon ? "on" : "off");
result.push_back(Pair("result", "Success."));
result.push_back(Pair("key", it->sAddress + " " + sInfo));
return result;
}
else if (mode == "anon") {
if (params.size() < 3) {
result.push_back(Pair("result", "Too few parameters."));
result.push_back(Pair("expected", "anon <+/-> <address>"));
return result;
}
std::string op = params[1].get_str();
std::string addr = params[2].get_str();
std::vector<SecMsgAddress>::iterator it;
for (it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it) {
if (addr != it->sAddress)
continue;
break;
}
if (it == smsgAddresses.end()) {
result.push_back(Pair("result", "Address not found."));
return result;
}
if (op == "+" || op == "on" || op == "add" || op == "a") {
it->fReceiveAnon = true;
}
else if (op == "-" || op == "off" || op == "rem" || op == "r") {
it->fReceiveAnon = false;
}
else {
result.push_back(Pair("result", "Unknown operation."));
return result;
}
std::string sInfo;
sInfo = std::string("Receive ") + (it->fReceiveEnabled ? "on, " : "off,");
sInfo += std::string("Anon ") + (it->fReceiveAnon ? "on" : "off");
result.push_back(Pair("result", "Success."));
result.push_back(Pair("key", it->sAddress + " " + sInfo));
return result;
}
else if (mode == "wallet") {
uint32_t nKeys = 0;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook) {
if (!IsMine(*pwalletMain, entry.first))
continue;
CBitcreditAddress coinAddress(entry.first);
if (!coinAddress.IsValid())
continue;
std::string address;
std::string sPublicKey;
address = coinAddress.ToString();
CKeyID keyID;
if (!coinAddress.GetKeyID(keyID))
continue;
CPubKey pubKey;
if (!pwalletMain->GetPubKey(keyID, pubKey))
continue;
if (!pubKey.IsValid()
|| !pubKey.IsCompressed()) {
continue;
}
sPublicKey = EncodeBase58(&pubKey[0], &pubKey[pubKey.size()]);
result.push_back(Pair("key", address + " - " + sPublicKey + " - " + entry.second.name));
nKeys++;
};
snprintf(cbuf, sizeof(cbuf), "%u keys listed from wallet.", nKeys);
result.push_back(Pair("result", std::string(cbuf)));
}
else {
result.push_back(Pair("result", "Unknown Mode."));
result.push_back(Pair("expected", "smsglocalkeys [whitelist|all|wallet|recv <+/-> <address>|anon <+/-> <address>]"));
}
return result;
}
Value smsgscanchain(const Array& params, bool fHelp) {
if (fHelp || params.size() != 0)
throw runtime_error(
"smsgscanchain \n"
"Look for public keys in the block chain.");
if (!fSecMsgEnabled)
throw runtime_error("Secure messaging is disabled.");
Object result;
if (!SecureMsgScanBlockChain()) {
result.push_back(Pair("result", "Scan Chain Failed."));
}
else {
result.push_back(Pair("result", "Scan Chain Completed."));
}
return result;
}
Value smsgscanbuckets(const Array& params, bool fHelp) {
if (fHelp || params.size() != 0)
throw runtime_error(
"smsgscanbuckets \n"
"Force rescan of all messages in the bucket store.");
if (!fSecMsgEnabled)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Secure messaging is disabled.");
Object result;
std::string error;
int ret = SecureMsgScanBuckets(error);
if (ret) {
throw JSONRPCError(ret, error);
}
return result;
}
Value smsgaddkey(const Array& params, bool fHelp) {
if (fHelp || params.size() != 2)
throw runtime_error(
"smsgaddkey <address> <pubkey>\n"
"Add address, pubkey pair to database.");
if (!fSecMsgEnabled)
throw runtime_error("Secure messaging is disabled.");
std::string addr = params[0].get_str();
std::string pubk = params[1].get_str();
Object result;
int rv = SecureMsgAddAddress(addr, pubk);
if (rv != 0) {
result.push_back(Pair("result", "Public key not added to db."));
switch (rv) {
case 2: result.push_back(Pair("reason", "publicKey is invalid.")); break;
case 3: result.push_back(Pair("reason", "publicKey does not match address.")); break;
case 4: result.push_back(Pair("reason", "address is already in db.")); break;
case 5: result.push_back(Pair("reason", "address is invalid.")); break;
default: result.push_back(Pair("reason", "error.")); break;
}
}
else {
result.push_back(Pair("result", "Added public key to db."));
}
return result;
}
Value smsggetpubkey(const Array& params, bool fHelp) {
if (fHelp || params.size() != 1)
throw runtime_error(
"smsggetpubkey <address>\n"
"Return the base58 encoded compressed public key for an address.\n"
"Tests localkeys first, then looks in public key db.\n");
if (!fSecMsgEnabled)
throw runtime_error("Secure messaging is disabled.");
std::string address = params[0].get_str();
std::string publicKey;
Object result;
int rv = SecureMsgGetLocalPublicKey(address, publicKey);
switch (rv) {
case 0:
result.push_back(Pair("result", "Success."));
result.push_back(Pair("address in wallet", address));
result.push_back(Pair("compressed public key", publicKey));
return result; // success, don't check db
case 2:
case 3:
result.push_back(Pair("result", "Failed."));
result.push_back(Pair("message", "Invalid address."));
return result;
case 4:
break; // check db
//case 1:
default:
result.push_back(Pair("result", "Failed."));
result.push_back(Pair("message", "Error."));
return result;
}
CBitcreditAddress coinAddress(address);
CKeyID keyID;
if (!coinAddress.GetKeyID(keyID)) {
result.push_back(Pair("result", "Failed."));
result.push_back(Pair("message", "Invalid address."));
return result;
}
CPubKey cpkFromDB;
rv = SecureMsgGetStoredKey(keyID, cpkFromDB);
switch (rv) {
case 0:
if (!cpkFromDB.IsValid() || !cpkFromDB.IsCompressed()) {
result.push_back(Pair("result", "Failed."));
result.push_back(Pair("message", "Invalid address."));
}
else {
//cpkFromDB.SetCompressedPubKey(); // make sure key is compressed
publicKey = EncodeBase58(&cpkFromDB[0], &cpkFromDB[cpkFromDB.size()]);
result.push_back(Pair("result", "Success."));
result.push_back(Pair("peer address in DB", address));
result.push_back(Pair("compressed public key", publicKey));
}
break;
case 2:
result.push_back(Pair("result", "Failed."));
result.push_back(Pair("message", "Address not found in wallet or db."));
return result;
//case 1:
default:
result.push_back(Pair("result", "Failed."));
result.push_back(Pair("message", "Error, GetStoredKey()."));
return result;
}
return result;
}
Value smsgsend(const Array& params, bool fHelp) {
if (fHelp || params.size() != 3)
throw runtime_error(
"smsgsend <addrFrom> <addrTo> <message>\n"
"Send an encrypted message from addrFrom to addrTo.");
if (!fSecMsgEnabled)
throw JSONRPCError(RPC_INVALID_REQUEST, "Secure messaging is disabled.");
std::string addrFrom = params[0].get_str();
std::string addrTo = params[1].get_str();
std::string msg = params[2].get_str();
Object result;
std::string sError;
int error = SecureMsgSend(addrFrom, addrTo, msg, sError);
sError = "Sending secure message failed - " + sError;
if (error > 0) {
throw runtime_error(sError);
}
else if (error < 0) {
throw JSONRPCError(error, sError);
}
return Value::null;
}
Value smsgsendanon(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"smsgsendanon <addrTo> <message>\n"
"Send an anonymous encrypted message to addrTo.");
if (!fSecMsgEnabled)
throw runtime_error("Secure messaging is disabled.");
std::string addrFrom = "anon";
std::string addrTo = params[0].get_str();
std::string msg = params[1].get_str();
Object result;
std::string sError;
int ret = SecureMsgSend(addrFrom, addrTo, msg, sError);
sError = "Sending anonymous massage failed - " + sError;
if (ret > 0) {
throw runtime_error(sError);
}
else if (ret < 0) {
throw JSONRPCError(ret, sError);
}
return Value::null;
}
Value smsginbox(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1) // defaults to read
throw runtime_error("smsginbox ( \"all|unread|clear\" )\n"
"\nDecrypt and display received secure messages in the inbox.\n"
"Warning: clear will delete all messages.");
if (!fSecMsgEnabled)
throw JSONRPCError(RPC_INVALID_REQUEST, "Secure messaging is disabled.");
if (pwalletMain->IsLocked())
throw runtime_error("Wallet is locked.");
std::string mode = "unread";
if (params.size() > 0)
{
mode = params[0].get_str();
}
Array result;
{
LOCK(cs_smsgDB);
SecMsgDB dbInbox;
if (!dbInbox.Open("cr+"))
throw runtime_error("Could not open DB.");
uint32_t nMessages = 0;
std::string sPrefix("im");
unsigned char chKey[18];
if (mode == "clear")
{
dbInbox.TxnBegin();
leveldb::Iterator* it = dbInbox.pdb->NewIterator(leveldb::ReadOptions());
while (dbInbox.NextSmesgKey(it, sPrefix, chKey))
{
dbInbox.EraseSmesg(chKey);
nMessages++;
};
delete it;
dbInbox.TxnCommit();
ostringstream oss;
oss << nMessages << " messages deleted";
return oss.str();
}
else if (mode == "all" || mode == "unread") {
int fCheckReadStatus = mode == "unread" ? 1 : 0;
SecMsgStored smsgStored;
MessageData msg;
dbInbox.TxnBegin();
leveldb::Iterator* it = dbInbox.pdb->NewIterator(leveldb::ReadOptions());
while (dbInbox.NextSmesg(it, sPrefix, chKey, smsgStored))
{
if (fCheckReadStatus
&& !(smsgStored.status & SMSG_MASK_UNREAD))
continue;
Object objM;
std::string errorMsg;
int error = SecureMsgDecrypt(smsgStored, msg, errorMsg);
if (!error) {
objM.push_back(Pair("received", GetTimeString(smsgStored.timeReceived)));
objM.push_back(Pair("sent", GetTimeString(msg.timestamp)));
objM.push_back(Pair("from", msg.sFromAddress.c_str()));
objM.push_back(Pair("to", msg.sToAddress.c_str()));
objM.push_back(Pair("text", msg.sMessage.c_str()));
}
else {
ostringstream oss;
oss << error;
objM.push_back(Pair("error", "Could not decrypt (" + oss.str() + ")"));
}
result.push_back(objM);
if (fCheckReadStatus) {
smsgStored.status &= ~SMSG_MASK_UNREAD;
dbInbox.WriteSmesg(chKey, smsgStored);
}
nMessages++;
}
delete it;
dbInbox.TxnCommit();
return result;
}
}
return smsginbox(params, true);
};
Value smsgoutbox(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1) // defaults to read
throw runtime_error(
"smsgoutbox ( \"all|clear\" )\n"
"Decrypt and display all sent messages.\n"
"Warning: clear will delete all sent messages.");
if (!fSecMsgEnabled)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Secure messaging is disabled.");
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is locked, but secure messaging needs an unlocked wallet.");
std::string mode = "all";
if (params.size() > 0) {
mode = params[0].get_str();
}
Array result;
std::string sPrefix("sm");
unsigned char chKey[18];
memset(&chKey[0], 0, 18);
{
LOCK(cs_smsgDB);
SecMsgDB dbOutbox;
if (!dbOutbox.Open("cr+"))
throw runtime_error("Could not open DB.");
uint32_t nMessages = 0;
if (mode == "clear") {
dbOutbox.TxnBegin();
leveldb::Iterator* it = dbOutbox.pdb->NewIterator(leveldb::ReadOptions());
while (dbOutbox.NextSmesgKey(it, sPrefix, chKey)) {
dbOutbox.EraseSmesg(chKey);
nMessages++;
}
delete it;
dbOutbox.TxnCommit();
return Value::null;
}
else if (mode == "all") {
SecMsgStored smsgStored;
MessageData msg;
leveldb::Iterator* it = dbOutbox.pdb->NewIterator(leveldb::ReadOptions());
while (dbOutbox.NextSmesg(it, sPrefix, chKey, smsgStored)) {
const unsigned char* pPayload = &smsgStored.vchMessage[SMSG_HDR_LEN];
SecureMessageHeader smsg(&smsgStored.vchMessage[0]);
memcpy(smsg.hash, Hash(&pPayload[0], &pPayload[smsg.nPayload]).begin(), 32);
int error = SecureMsgDecrypt(false, smsgStored.sAddrOutbox, smsg, pPayload, msg);
if (!error) {
Object objM;
objM.push_back(Pair("sent", GetTimeString(msg.timestamp)));
objM.push_back(Pair("from", msg.sFromAddress.c_str()));
objM.push_back(Pair("to", smsgStored.sAddrTo.c_str()));
objM.push_back(Pair("text", msg.sMessage.c_str()));
result.push_back(objM);
}
else if (error < 0) {
throw JSONRPCError(error, "Could not decrypt.");
}
else
throw runtime_error("Could not decrypt.");
nMessages++;
}
delete it;
return result;
}
}
return smsgoutbox(params, true);
};
Value smsgbuckets(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"smsgbuckets ( \"stats|dump\" )\n"
"Display some statistics.");
if (!fSecMsgEnabled)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Secure messaging is disabled.");
std::string mode = "stats";
if (params.size() > 0) {
mode = params[0].get_str();
}
Array result;
if (mode == "stats")
{
uint64_t nBuckets = 0;
uint64_t nMessages = 0;
uint64_t nBytes = 0;
{
LOCK(cs_smsg);
std::map<int64_t, SecMsgBucket>::iterator it;
it = smsgBuckets.begin();
for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it)
{
std::set<SecMsgToken>& tokenSet = it->second.setTokens;
std::string sBucket = boost::lexical_cast<std::string>(it->first);
std::string sFile = sBucket + "_01.dat";
nBuckets++;
nMessages += tokenSet.size();
Object objM;
objM.push_back(Pair("bucket", (uint64_t) it->first));
objM.push_back(Pair("time", GetTimeString(it->first)));
objM.push_back(Pair("no. messages", (uint64_t)tokenSet.size()));
objM.push_back(Pair("hash", (uint64_t) it->second.hash));
objM.push_back(Pair("last changed", GetTimeString(it->second.timeChanged)));
boost::filesystem::path fullPath = GetDataDir() / "smsgStore" / sFile;
if (!boost::filesystem::exists(fullPath))
{
// -- If there is a file for an empty bucket something is wrong.
if (tokenSet.size() == 0)
objM.push_back(Pair("file size", "Empty bucket."));
else
objM.push_back(Pair("file size, error", "File not found."));
} else
{
try {
uint64_t nFBytes = 0;
nFBytes = boost::filesystem::file_size(fullPath);
nBytes += nFBytes;
objM.push_back(Pair("file size", nFBytes));
} catch (const boost::filesystem::filesystem_error& ex)
{
objM.push_back(Pair("file size, error", ex.what()));
};
};
result.push_back(objM);
};
}; // LOCK(cs_smsg);
Object objM;
objM.push_back(Pair("buckets", result));
objM.push_back(Pair("no. buckets", nBuckets));
objM.push_back(Pair("no. messages", nMessages));
objM.push_back(Pair("size", nBytes));
return objM;
}
else if (mode == "dump") {
{
LOCK(cs_smsg);
std::map<int64_t, SecMsgBucket>::iterator it;
it = smsgBuckets.begin();
for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it) {
std::string sFile = boost::lexical_cast<std::string>(it->first) + "_01.dat";
try {
boost::filesystem::path fullPath = GetDataDir() / "smsgStore" / sFile;
boost::filesystem::remove(fullPath);
}
catch (const boost::filesystem::filesystem_error& ex) {
//objM.push_back(Pair("file size, error", ex.what()));
printf("Error removing bucket file %s.\n", ex.what());
}
}
smsgBuckets.clear();
} // LOCK(cs_smsg);
return Value::null;
}
return smsgbuckets(params, true);
};
<file_sep>#ifndef BROWSER_H
#define BROWSER_H
#include <QWidget>
#include <QSqlTableModel>
#include <QMessageBox>
#include <QWidget>
#include <QDir>
#include <QFile>
#include <QProcess>
#include <QTime>
#include <QTimer>
#include <QStringList>
#include <QMap>
#include <QSettings>
#include <QSlider>
#include "ui_databasebrowserwidget.h"
#include "walletmodel.h"
class WalletModel;
class ConnectionWidget;
class Browser: public QWidget, private Ui::Browser
{
Q_OBJECT
public:
Browser(QWidget *parent = 0);
virtual ~Browser();
QSqlError addConnection(const QString &driver, const QString &dbName, const QString &host,
const QString &user, const QString &passwd, int port = -1);
void insertRow();
void deleteRow();
void updateActions();
void setModel(WalletModel *model);
public slots:
void exec();
void showTable(const QString &table);
void showMetaData(const QString &table);
void addConnection();
void currentChanged();
void on_insertRowAction_triggered();
void on_deleteRowAction_triggered();
void on_fieldStrategyAction_triggered();
void on_rowStrategyAction_triggered();
void on_manualStrategyAction_triggered();
void on_submitAction_triggered();
void on_revertAction_triggered();
void on_selectAction_triggered();
void on_connectionWidget_tableActivated(const QString &table);
void on_connectionWidget_metaDataRequested(const QString &table);
void on_submitButton_clicked();
void on_clearButton_clicked();
void on_addressBookButton_clicked();
signals:
void statusMessage(const QString &message);
private:
WalletModel *model;
};
class CustomModel: public QSqlTableModel
{
Q_OBJECT
public:
explicit CustomModel(QObject *parent = 0, QSqlDatabase db = QSqlDatabase()):QSqlTableModel(parent, db) {}
QVariant data(const QModelIndex &idx, int role) const Q_DECL_OVERRIDE
{
if (role == Qt::BackgroundRole && isDirty(idx))
return QBrush(QColor(Qt::yellow));
return QSqlTableModel::data(idx, role);
}
};
#endif
<file_sep>#ifndef MESSAGEMODEL_H
#define MESSAGEMODEL_H
#include "uint256.h"
#include <vector>
#include "allocators.h" /* for SecureString */
#include "smessage.h"
#include <map>
#include <QAbstractTableModel>
#include <QStringList>
#include <QDateTime>
class MessageTablePriv;
class InvoiceTableModel;
class InvoiceItemTableModel;
class ReceiptTableModel;
class WalletModel;
class OptionsModel;
class SendMessagesRecipient
{
public:
QString address;
QString label;
QString pubkey;
QString message;
};
struct MessageTableEntry
{
enum Type {
Sent,
Received
};
std::vector<unsigned char> vchKey;
Type type;
QString label;
QString to_address;
QString from_address;
QDateTime sent_datetime;
QDateTime received_datetime;
bool read;
QString message;
MessageTableEntry() {}
MessageTableEntry(const std::vector<unsigned char> vchKey, Type type, const QString &label, const QString &to_address, const QString &from_address,
const QDateTime &sent_datetime, const QDateTime &received_datetime, const bool &read, const QString &message):
vchKey(vchKey), type(type), label(label), to_address(to_address), from_address(from_address), sent_datetime(sent_datetime), received_datetime(received_datetime),
read(read), message(message) {}
};
/** Interface to Secure Messaging from Qt view code. */
class MessageModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit MessageModel(/*CWallet *wallet,*/ WalletModel *walletModel, QObject *parent = 0);
~MessageModel();
enum StatusCode // Returned by sendMessages
{
OK,
InvalidAddress,
InvalidMessage,
DuplicateAddress,
MessageCreationFailed, // Error returned when DB is still locked
MessageCommitFailed,
Aborted,
FailedErrorShown
};
enum ColumnIndex {
Type = 0, /**< Sent/Received */
SentDateTime = 1, /**< Time Sent */
ReceivedDateTime = 2, /**< Time Received */
Label = 3, /**< User specified label */
ToAddress = 4, /**< To Bitcredit address */
FromAddress = 5, /**< From Bitcredit address */
Message = 6, /**< Plaintext */
Read = 7, /**< Plaintext */
TypeInt = 8, /**< Plaintext */
Key = 9, /**< chKey */
HTML = 10, /**< HTML Formatted Data */
};
/** Roles to get specific information from a message row.
These are independent of column.
*/
enum RoleIndex {
/** Type of message */
TypeRole = Qt::UserRole,
/** message key */
KeyRole,
/** Date and time this message was sent */
SentDateRole,
/** Date and time this message was received */
ReceivedDateRole,
/** From Address of message */
FromAddressRole,
/** To Address of message */
ToAddressRole,
/** Filter address related to message */
FilterAddressRole,
/** Label of address related to message */
LabelRole,
/** Full Message */
MessageRole,
/** Short Message */
ShortMessageRole,
/** Message Read */
ReadRole,
/** HTML Formatted */
HTMLRole,
/** Ambiguous bool */
Ambiguous
};
static const QString Sent; /**< Specifies sent message */
static const QString Received; /**< Specifies sent message */
/** @name Methods overridden from QAbstractTableModel
@{*/
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex & parent) const;
bool removeRows(int row, int count, const QModelIndex & parent = QModelIndex());
Qt::ItemFlags flags(const QModelIndex & index) const;
/*@}*/
/* Mark message as read
*/
bool markMessageAsRead(const QString &key) const;
/* Look up row index of a message in the model.
Return -1 if not found.
*/
int lookupMessage(const QString &message) const;
WalletModel *getWalletModel();
OptionsModel *getOptionsModel();
InvoiceTableModel *getInvoiceTableModel();
ReceiptTableModel *getReceiptTableModel();
bool getAddressOrPubkey( QString &Address, QString &Pubkey) const;
// Send messages to a list of recipients
StatusCode sendMessages(const QList<SendMessagesRecipient> &recipients);
StatusCode sendMessages(const QList<SendMessagesRecipient> &recipients, const QString &addressFrom);
private:
CWallet *wallet;
WalletModel *walletModel;
OptionsModel *optionsModel;
MessageTablePriv *priv;
InvoiceTableModel *invoiceTableModel;
ReceiptTableModel *receiptTableModel;
QStringList columns;
void subscribeToCoreSignals();
void unsubscribeFromCoreSignals();
public slots:
/* Check for new messages */
void newMessage(const SecMsgStored& smsg);
void newOutboxMessage(const SecMsgStored& smsg);
void walletUnlocked();
void setEncryptionStatus(int status);
friend class MessageTablePriv;
signals:
// Asynchronous error notification
void error(const QString &title, const QString &message, bool modal);
};
struct InvoiceItemTableEntry
{
std::vector<unsigned char> vchKey;
MessageTableEntry::Type type;
QString code;
QString description;
int quantity;
int64_t price;
//bool tax;
InvoiceItemTableEntry(){};
InvoiceItemTableEntry(const bool newInvoice):
vchKey(0), type(MessageTableEntry::Sent), code(""), description(""), quantity(0), price(0)
{
vchKey.resize(3);
memcpy(&vchKey[0], "new", 3);
};
InvoiceItemTableEntry(const std::vector<unsigned char> vchKey, MessageTableEntry::Type type, const QString &code, const QString &description, const int &quantity, const qint64 &price): //, const bool &tax):
vchKey(vchKey), type(type), code(code), description(description), quantity(quantity), price(price) {} //, tax(tax) {}
};
struct InvoiceTableEntry
{
std::vector<unsigned char> vchKey;
MessageTableEntry::Type type;
QString label;
QString to_address;
QString from_address;
QDateTime sent_datetime;
QDateTime received_datetime;
QString company_info_left;
QString company_info_right;
QString billing_info_left;
QString billing_info_right;
QString footer;
QString invoice_number;
QDate due_date;
InvoiceTableEntry() {}
InvoiceTableEntry(const bool newInvoice):
vchKey(0), type(MessageTableEntry::Sent), label(""), to_address(""), from_address(""), sent_datetime(), received_datetime(), company_info_left(""), company_info_right(""),
billing_info_left(""), billing_info_right(""), footer(""), invoice_number(""), due_date()
{
vchKey.resize(3);
memcpy(&vchKey[0], "new", 3);
};
InvoiceTableEntry(const std::vector<unsigned char> vchKey, MessageTableEntry::Type type, const QString &label, const QString &to_address, const QString &from_address,
const QDateTime &sent_datetime, const QDateTime &received_datetime, const QString &company_info_left, const QString &company_info_right,
const QString &billing_info_left, const QString &billing_info_right, const QString &footer, const QString &invoice_number, const QDate &due_date):
vchKey(vchKey), type(type), label(label), to_address(to_address), from_address(from_address), sent_datetime(sent_datetime), received_datetime(received_datetime),
company_info_left(company_info_left), company_info_right(company_info_right), billing_info_left(billing_info_left), billing_info_right(billing_info_right),
footer(footer), invoice_number(invoice_number), due_date(due_date)
{}
InvoiceTableEntry(const MessageTableEntry &messageTableEntry, const QString &company_info_left, const QString &company_info_right,
const QString &billing_info_left, const QString &billing_info_right, const QString &footer, const QString &invoice_number, const QDate &due_date):
vchKey(messageTableEntry.vchKey), type(messageTableEntry.type), label(messageTableEntry.label), to_address(messageTableEntry.to_address), from_address(messageTableEntry.from_address),
sent_datetime(messageTableEntry.sent_datetime), received_datetime(messageTableEntry.received_datetime),
company_info_left(company_info_left), company_info_right(company_info_right), billing_info_left(billing_info_left), billing_info_right(billing_info_right),
footer(footer), invoice_number(invoice_number), due_date(due_date)
{}
};
/** Interface to Secure Messaging Invoices from Qt view code. */
class InvoiceTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit InvoiceTableModel(MessageTablePriv *priv, QObject *parent = 0);
~InvoiceTableModel();
enum ColumnIndex {
Type = 0, /**< Sent/Received */
SentDateTime = 1, /**< Time Sent */
ReceivedDateTime = 2, /**< Time Received */
Label = 3, /**< User specified label */
ToAddress = 4, /**< To Bitcredit address */
FromAddress = 5, /**< From Bitcredit address */
InvoiceNumber = 6, /**< Plaintext */
DueDate = 7, /**< Plaintext */
//SubTotal = 8, /**< SubTotal */
Total = 8, /**< Total */
Paid = 9, /**< Amount Paid */
Outstanding = 10, /**< Amount Outstanding */
// Hidden fields
CompanyInfoLeft = 11, /**< Plaintext */
CompanyInfoRight = 12, /**< Plaintext */
BillingInfoLeft = 13, /**< Plaintext */
BillingInfoRight = 14, /**< Plaintext */
Footer = 15, /**< Plaintext */
};
/** @name Methods overridden from QAbstractTableModel
@{*/
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
//bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex & parent) const;
bool removeRows(int row, int count, const QModelIndex & parent = QModelIndex());
Qt::ItemFlags flags(const QModelIndex & index) const;
/*@}*/
MessageModel *getMessageModel();
InvoiceItemTableModel *getInvoiceItemTableModel();
void newInvoice(QString CompanyInfoLeft,
QString CompanyInfoRight,
QString BillingInfoLeft,
QString BillingInfoRight,
QString Footer,
QDate DueDate,
QString InvoiceNumber);
void newInvoiceItem();
void newReceipt(QString InvoiceNumber, CAmount ReceiptAmount);
//void setData(const int row, const int col, const QVariant & value);
QString getInvoiceJSON(const int row);
int lookupMessage(const QString &message) const;
private:
QStringList columns;
MessageTablePriv *priv;
InvoiceItemTableModel *invoiceItemTableModel;
public slots:
friend class MessageTablePriv;
};
/** Interface to Secure Messaging Invoice Items from Qt view code. */
class InvoiceItemTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit InvoiceItemTableModel(MessageTablePriv *priv, QObject *parent = 0);
~InvoiceItemTableModel();
enum ColumnIndex {
Type = 0, /**< Sent/Received */
Code = 1, /**< Item Code */
Description = 2, /**< Item Description */
Quantity = 3, /**< Item quantity */
Price = 4, /**< Item Price */
//Tax = 4, /**< Item Price */
Amount = 5, /**< Total for row */
};
/** @name Methods overridden from QAbstractTableModel
@{*/
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
bool setData(const QModelIndex & index, const QVariant & value, int role);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex & parent) const;
bool removeRows(int row, int count, const QModelIndex & parent = QModelIndex());
Qt::ItemFlags flags(const QModelIndex & index) const;
/*@}*/
private:
QStringList columns;
MessageTablePriv *priv;
/** Notify listeners that data changed. */
void emitDataChanged(const int idx);
public slots:
friend class MessageTablePriv;
};
struct ReceiptTableEntry
{
std::vector<unsigned char> vchKey;
MessageTableEntry::Type type;
QString label;
QString to_address;
QString from_address;
QDateTime sent_datetime;
QDateTime received_datetime;
QString invoice_number;
qint64 amount;
ReceiptTableEntry() {}
ReceiptTableEntry(const bool newReceipt):
vchKey(0), type(MessageTableEntry::Sent), label(""), to_address(""), from_address(""), sent_datetime(), received_datetime(), invoice_number(""), amount(0)
{
vchKey.resize(3);
memcpy(&vchKey[0], "new", 3);
};
ReceiptTableEntry(const std::vector<unsigned char> vchKey, MessageTableEntry::Type type, const QString &label, const QString &to_address, const QString &from_address,
const QDateTime &sent_datetime, const QDateTime &received_datetime, const QString &invoice_number, const qint64 &amount):
vchKey(vchKey), type(type), label(label), to_address(to_address), from_address(from_address), sent_datetime(sent_datetime), received_datetime(received_datetime),
invoice_number(invoice_number), amount(amount)
{}
ReceiptTableEntry(const MessageTableEntry &messageTableEntry, const QString &invoice_number, const qint64 &amount):
vchKey(messageTableEntry.vchKey), type(messageTableEntry.type), label(messageTableEntry.label), to_address(messageTableEntry.to_address), from_address(messageTableEntry.from_address),
sent_datetime(messageTableEntry.sent_datetime), received_datetime(messageTableEntry.received_datetime), invoice_number(invoice_number), amount(amount)
{}
ReceiptTableEntry(const InvoiceTableEntry &invoiceTableEntry, const qint64 &amount):
vchKey(invoiceTableEntry.vchKey), type(invoiceTableEntry.type), label(invoiceTableEntry.label), to_address(invoiceTableEntry.to_address), from_address(invoiceTableEntry.from_address),
sent_datetime(invoiceTableEntry.sent_datetime), received_datetime(invoiceTableEntry.received_datetime), invoice_number(invoiceTableEntry.invoice_number), amount(amount)
{}
};
/** Interface to Secure Messaging Receipts from Qt view code. */
class ReceiptTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit ReceiptTableModel(MessageTablePriv *priv, QObject *parent = 0);
~ReceiptTableModel();
enum ColumnIndex {
Type = 0, /**< Sent/Received */
SentDateTime = 1, /**< Time Sent */
ReceivedDateTime = 2, /**< Time Received */
Label = 3, /**< User specified label */
ToAddress = 4, /**< To Bitcredit address */
FromAddress = 5, /**< From Bitcredit address */
InvoiceNumber = 6, /**< Plaintext */
Amount = 7, /**< qint64 */
Outstanding = 8, /**< qint64 */
};
/** @name Methods overridden from QAbstractTableModel
@{*/
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
//bool setData(const QModelIndex & index, const QVariant & value, int role);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex & parent) const;
bool removeRows(int row, int count, const QModelIndex & parent = QModelIndex());
Qt::ItemFlags flags(const QModelIndex & index) const;
/*@}*/
QString getReceiptJSON(const int row);
private:
QStringList columns;
MessageTablePriv *priv;
public slots:
friend class MessageTablePriv;
};
#endif // MESSAGEMODEL_H
<file_sep>
//#include "bignum.h"
#include "sync.h"
#include "net.h"
#include "key.h"
#include "util.h"
#include "script/script.h"
#include "base58.h"
#include "protocol.h"
#include "activebasenode.h"
#include "basenodeman.h"
#include "spork.h"
#include <boost/lexical_cast.hpp>
#include "basenodeman.h"
using namespace std;
using namespace boost;
std::map<uint256, CBasenodeScanningError> mapBasenodeScanningErrors;
CBasenodeScanning mnscan;
/*
Basenode - Proof of Service
-- What it checks
1.) Making sure Basenodes have their ports open
2.) Are responding to requests made by the network
-- How it works
When a block comes in, DoBasenodePOS is executed if the client is a
basenode. Using the deterministic ranking algorithm up to 1% of the basenode
network is checked each block.
A port is opened from Basenode A to Basenode B, if successful then nothing happens.
If there is an error, a CBasenodeScanningError object is propagated with an error code.
Errors are applied to the Basenodes and a score is incremented within the basenode object,
after a threshold is met, the basenode goes into an error state. Each cycle the score is
decreased, so if the basenode comes back online it will return to the list.
Basenodes in a error state do not receive payment.
-- Future expansion
We want to be able to prove the nodes have many qualities such as a specific CPU speed, bandwidth,
and dedicated storage. E.g. We could require a full node be a computer running 2GHz with 10GB of space.
*/
void ProcessMessageBasenodePOS(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if(fLiteMode) return; //disable all darksend/basenode related functionality
if(IsInitialBlockDownload()) return;
if (strCommand == "mnse") //Basenode Scanning Error
{
CDataStream vMsg(vRecv);
CBasenodeScanningError mnse;
vRecv >> mnse;
CInv inv(MSG_BASENODE_SCANNING_ERROR, mnse.GetHash());
pfrom->AddInventoryKnown(inv);
if(mapBasenodeScanningErrors.count(mnse.GetHash())){
return;
}
mapBasenodeScanningErrors.insert(make_pair(mnse.GetHash(), mnse));
if(!mnse.IsValid())
{
LogPrintf("BasenodePOS::mnse - Invalid object\n");
return;
}
CBasenode* pmnA = mnodeman.Find(mnse.vinBasenodeA);
if(pmnA == NULL) return;
if(pmnA->protocolVersion < MIN_BASENODE_POS_PROTO_VERSION) return;
int nBlockHeight = chainActive.Tip()->nHeight;
if(nBlockHeight - mnse.nBlockHeight > 10){
LogPrintf("BasenodePOS::mnse - Too old\n");
return;
}
// Lowest basenodes in rank check the highest each block
int a = mnodeman.GetBasenodeRank(mnse.vinBasenodeA, mnse.nBlockHeight, MIN_BASENODE_POS_PROTO_VERSION);
if(a == -1 || a > GetCountScanningPerBlock())
{
if(a != -1) LogPrintf("BasenodePOS::mnse - BasenodeA ranking is too high\n");
return;
}
int b = mnodeman.GetBasenodeRank(mnse.vinBasenodeB, mnse.nBlockHeight, MIN_BASENODE_POS_PROTO_VERSION, false);
if(b == -1 || b < mnodeman.CountBasenodesAboveProtocol(MIN_BASENODE_POS_PROTO_VERSION)-GetCountScanningPerBlock())
{
if(b != -1) LogPrintf("BasenodePOS::mnse - BasenodeB ranking is too low\n");
return;
}
if(!mnse.SignatureValid()){
LogPrintf("BasenodePOS::mnse - Bad basenode message\n");
return;
}
CBasenode* pmnB = mnodeman.Find(mnse.vinBasenodeB);
if(pmnB == NULL) return;
if(fDebug) LogPrintf("ProcessMessageBasenodePOS::mnse - nHeight %d BasenodeA %s BasenodeB %s\n", mnse.nBlockHeight, pmnA->addr.ToString().c_str(), pmnB->addr.ToString().c_str());
pmnB->ApplyScanningError(mnse);
mnse.Relay();
}
}
// Returns how many basenodes are allowed to scan each block
int GetCountScanningPerBlock()
{
return std::max(1, mnodeman.CountBasenodesAboveProtocol(MIN_BASENODE_POS_PROTO_VERSION)/100);
}
void CBasenodeScanning::CleanBasenodeScanningErrors()
{
if(chainActive.Tip() == NULL) return;
std::map<uint256, CBasenodeScanningError>::iterator it = mapBasenodeScanningErrors.begin();
while(it != mapBasenodeScanningErrors.end()) {
if(GetTime() > it->second.nExpiration){ //keep them for an hour
LogPrintf("Removing old basenode scanning error %s\n", it->second.GetHash().ToString().c_str());
mapBasenodeScanningErrors.erase(it++);
} else {
it++;
}
}
}
// Check other basenodes to make sure they're running correctly
void CBasenodeScanning::DoBasenodePOSChecks()
{
if(!fBaseNode) return;
if(fLiteMode) return; //disable all darksend/basenode related functionality
if(IsInitialBlockDownload()) return;
int nBlockHeight = chainActive.Tip()->nHeight-5;
int a = mnodeman.GetBasenodeRank(activeBasenode.vin, nBlockHeight, MIN_BASENODE_POS_PROTO_VERSION);
if(a == -1 || a > GetCountScanningPerBlock()){
// we don't need to do anything this block
return;
}
// The lowest ranking nodes (Basenode A) check the highest ranking nodes (Basenode B)
CBasenode* pmn = mnodeman.GetBasenodeByRank(mnodeman.CountBasenodesAboveProtocol(MIN_BASENODE_POS_PROTO_VERSION)-a, nBlockHeight, MIN_BASENODE_POS_PROTO_VERSION, false);
if(pmn == NULL) return;
// -- first check : Port is open
if(!ConnectNode((CAddress)pmn->addr, NULL, true)){
// we couldn't connect to the node, let's send a scanning error
CBasenodeScanningError mnse(activeBasenode.vin, pmn->vin, SCANNING_ERROR_NO_RESPONSE, nBlockHeight);
mnse.Sign();
mapBasenodeScanningErrors.insert(make_pair(mnse.GetHash(), mnse));
mnse.Relay();
}
// success
CBasenodeScanningError mnse(activeBasenode.vin, pmn->vin, SCANNING_SUCCESS, nBlockHeight);
mnse.Sign();
mapBasenodeScanningErrors.insert(make_pair(mnse.GetHash(), mnse));
mnse.Relay();
}
bool CBasenodeScanningError::SignatureValid()
{
std::string errorMessage;
std::string strMessage = vinBasenodeA.ToString() + vinBasenodeB.ToString() +
boost::lexical_cast<std::string>(nBlockHeight) + boost::lexical_cast<std::string>(nErrorType);
CBasenode* pmn = mnodeman.Find(vinBasenodeA);
if(pmn == NULL)
{
LogPrintf("CBasenodeScanningError::SignatureValid() - Unknown Basenode\n");
return false;
}
CScript pubkey;
pubkey=GetScriptForDestination(pmn->pubkey2.GetID());
CTxDestination address1;
ExtractDestination(pubkey, address1);
CBitcreditAddress address2(address1);
if(!darkSendSigner.VerifyMessage(pmn->pubkey2, vchBaseNodeSignature, strMessage, errorMessage)) {
LogPrintf("CBasenodeScanningError::SignatureValid() - Verify message failed\n");
return false;
}
return true;
}
bool CBasenodeScanningError::Sign()
{
std::string errorMessage;
CKey key2;
CPubKey pubkey2;
std::string strMessage = vinBasenodeA.ToString() + vinBasenodeB.ToString() +
boost::lexical_cast<std::string>(nBlockHeight) + boost::lexical_cast<std::string>(nErrorType);
if(!darkSendSigner.SetKey(strBaseNodePrivKey, errorMessage, key2, pubkey2))
{
LogPrintf("CBasenodeScanningError::Sign() - ERROR: Invalid basenodeprivkey: '%s'\n", errorMessage.c_str());
return false;
}
CScript pubkey;
pubkey=GetScriptForDestination(pubkey2.GetID());
CTxDestination address1;
ExtractDestination(pubkey, address1);
CBitcreditAddress address2(address1);
//LogPrintf("signing pubkey2 %s \n", address2.ToString().c_str());
if(!darkSendSigner.SignMessage(strMessage, errorMessage, vchBaseNodeSignature, key2)) {
LogPrintf("CBasenodeScanningError::Sign() - Sign message failed");
return false;
}
if(!darkSendSigner.VerifyMessage(pubkey2, vchBaseNodeSignature, strMessage, errorMessage)) {
LogPrintf("CBasenodeScanningError::Sign() - Verify message failed");
return false;
}
return true;
}
void CBasenodeScanningError::Relay()
{
CInv inv(MSG_BASENODE_SCANNING_ERROR, GetHash());
vector<CInv> vInv;
vInv.push_back(inv);
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes){
pnode->PushMessage("inv", vInv);
}
}
<file_sep>// Copyright (c) 2014 The Sapience AIFX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef IBTP_H
#define IBTP_H
#include "netbase.h"
#include "serialize.h"
#include "uint256.h"
#include "version.h"
#include "util.h"
#include <map>
using namespace std;
struct SChain
{
public:
std::string sChainName;
std::string sCurrencyCode;
unsigned char pchMessageOne;
unsigned char pchMessageTwo;
unsigned char pchMessageThree;
unsigned char pchMessageFour;
SChain()
{
}
SChain(std::string sName, std::string sCode, unsigned char cOne, unsigned char cTwo, unsigned char cThree, unsigned char cFour)
{
sChainName = sName;
sCurrencyCode = sCode;
pchMessageOne = cOne;
pchMessageTwo = cTwo;
pchMessageThree = cThree;
pchMessageFour = cFour;
}
};
class CIbtp
{
public:
std::map<std::string, std::vector<unsigned char[4]> > mapBlockchainMessageStart;
std::vector<SChain> vChains;
CIbtp()
{
LoadMsgStart();
}
void LoadMsgStart();
bool IsIbtpChain(const unsigned char msgStart[], std::string& chainName);
};
#endif // IBTP_H
<file_sep># -*- coding: utf-8; -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2014 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Provides functions for constructing unsigned Open Assets transactions.
"""
import lib.bitcoin.core
import openassets.protocol
class TransactionBuilder(object):
"""Provides methods for constructing Open Assets transactions."""
def __init__(self, dust_amount):
"""
Initializes a new instance of the TransactionBuilder class.
:param int dust_amount: The minimum allowed output value.
"""
self._dust_amount = dust_amount
def issue(self, issuance_spec, metadata, fees):
"""
Creates a transaction for issuing an asset.
:param TransferParameters issuance_spec: The parameters of the issuance.
:param bytes metadata: The metadata to be embedded in the transaction.
:param int fees: The fees to include in the transaction.
:return: An unsigned transaction for issuing an asset.
:rtype: CTransaction
"""
inputs, total_amount = self._collect_uncolored_outputs(
issuance_spec.unspent_outputs, 2 * self._dust_amount + fees)
return lib.bitcoin.core.CTransaction(
vin=[lib.bitcoin.core.CTxIn(item.out_point, item.output.script) for item in inputs],
vout=[
self._get_colored_output(issuance_spec.to_script),
self._get_marker_output([issuance_spec.amount], metadata),
self._get_uncolored_output(issuance_spec.change_script, total_amount - self._dust_amount - fees)
]
)
def transfer(self, asset_transfer_specs, btc_transfer_spec, fees):
"""
Creates a transaction for sending assets and bitcoins.
:param list[(bytes, TransferParameters)] asset_transfer_specs: A list of tuples. In each tuple:
- The first element is the ID of an asset.
- The second element is the parameters of the transfer.
:param TransferParameters btc_transfer_spec: The parameters of the bitcoins being transferred.
:param int fees: The fees to include in the transaction.
:return: An unsigned transaction for sending assets and bitcoins.
:rtype: CTransaction
"""
inputs = []
outputs = []
asset_quantities = []
for asset_id, transfer_spec in asset_transfer_specs:
colored_outputs, collected_amount = self._collect_colored_outputs(
transfer_spec.unspent_outputs, asset_id, transfer_spec.amount)
inputs.extend(colored_outputs)
outputs.append(self._get_colored_output(transfer_spec.to_script))
asset_quantities.append(transfer_spec.amount)
if collected_amount > transfer_spec.amount:
outputs.append(self._get_colored_output(transfer_spec.change_script))
asset_quantities.append(collected_amount - transfer_spec.amount)
btc_excess = sum([input.output.value for input in inputs]) - sum([output.nValue for output in outputs])
if btc_excess < btc_transfer_spec.amount + fees:
# Not enough bitcoin inputs
uncolored_outputs, total_amount = self._collect_uncolored_outputs(
btc_transfer_spec.unspent_outputs, btc_transfer_spec.amount + fees - btc_excess)
inputs.extend(uncolored_outputs)
btc_excess += total_amount
change = btc_excess - btc_transfer_spec.amount - fees
if change > 0:
# Too much bitcoin in input, send it back as change
outputs.append(self._get_uncolored_output(btc_transfer_spec.change_script, change))
if btc_transfer_spec.amount > 0:
outputs.append(self._get_uncolored_output(btc_transfer_spec.to_script, btc_transfer_spec.amount))
if asset_quantities:
outputs.insert(0, self._get_marker_output(asset_quantities, b''))
return lib.bitcoin.core.CTransaction(
vin=[lib.bitcoin.core.CTxIn(item.out_point, item.output.script) for item in inputs],
vout=outputs
)
def transfer_bitcoin(self, transfer_spec, fees):
"""
Creates a transaction for sending bitcoins.
:param TransferParameters transfer_spec: The parameters of the bitcoins being transferred.
:param int fees: The fees to include in the transaction.
:return: The resulting unsigned transaction.
:rtype: CTransaction
"""
return self.transfer([], transfer_spec, fees)
def transfer_assets(self, asset_id, transfer_spec, btc_change_script, fees):
"""
Creates a transaction for sending an asset.
:param bytes asset_id: The ID of the asset being sent.
:param TransferParameters transfer_spec: The parameters of the asset being transferred.
:param bytes btc_change_script: The script where to send bitcoin change, if any.
:param int fees: The fees to include in the transaction.
:return: The resulting unsigned transaction.
:rtype: CTransaction
"""
return self.transfer(
[(asset_id, transfer_spec)],
TransferParameters(transfer_spec.unspent_outputs, None, btc_change_script, 0),
fees)
def btc_asset_swap(self, btc_transfer_spec, asset_id, asset_transfer_spec, fees):
"""
Creates a transaction for swapping assets for bitcoins.
:param TransferParameters btc_transfer_spec: The parameters of the bitcoins being transferred.
:param bytes asset_id: The ID of the asset being sent.
:param TransferParameters asset_transfer_spec: The parameters of the asset being transferred.
:param int fees: The fees to include in the transaction.
:return: The resulting unsigned transaction.
:rtype: CTransaction
"""
return self.transfer([(asset_id, asset_transfer_spec)], btc_transfer_spec, fees)
def asset_asset_swap(
self, asset1_id, asset1_transfer_spec, asset2_id, asset2_transfer_spec, fees):
"""
Creates a transaction for swapping an asset for another asset.
:param bytes asset1_id: The ID of the first asset.
:param TransferParameters asset1_transfer_spec: The parameters of the first asset being transferred.
It is also used for paying fees and/or receiving change if any.
:param bytes asset2_id: The ID of the second asset.
:param TransferDetails asset2_transfer_spec: The parameters of the second asset being transferred.
:param int fees: The fees to include in the transaction.
:return: The resulting unsigned transaction.
:rtype: CTransaction
"""
btc_transfer_spec = TransferParameters(
asset1_transfer_spec.unspent_outputs, asset1_transfer_spec.to_script, asset1_transfer_spec.change_script, 0)
return self.transfer(
[(asset1_id, asset1_transfer_spec), (asset2_id, asset2_transfer_spec)], btc_transfer_spec, fees)
@staticmethod
def _collect_uncolored_outputs(unspent_outputs, amount):
"""
Returns a list of uncolored outputs for the specified amount.
:param list[SpendableOutput] unspent_outputs: The list of available outputs.
:param int amount: The amount to collect.
:return: A list of outputs, and the total amount collected.
:rtype: (list[SpendableOutput], int)
"""
total_amount = 0
result = []
for output in unspent_outputs:
if output.output.asset_id is None:
result.append(output)
total_amount += output.output.value
if total_amount >= amount:
return result, total_amount
raise InsufficientFundsError
@staticmethod
def _collect_colored_outputs(unspent_outputs, asset_id, asset_quantity):
"""
Returns a list of colored outputs for the specified quantity.
:param list[SpendableOutput] unspent_outputs: The list of available outputs.
:param bytes asset_id: The ID of the asset to collect.
:param int asset_quantity: The asset quantity to collect.
:return: A list of outputs, and the total asset quantity collected.
:rtype: (list[SpendableOutput], int)
"""
total_amount = 0
result = []
for output in unspent_outputs:
if output.output.asset_id == asset_id:
result.append(output)
total_amount += output.output.asset_quantity
if total_amount >= asset_quantity:
return result, total_amount
raise InsufficientAssetQuantityError
def _get_uncolored_output(self, script, value):
"""
Creates an uncolored output.
:param bytes script: The output script.
:param int value: The satoshi value of the output.
:return: An object representing the uncolored output.
:rtype: TransactionOutput
"""
if value < self._dust_amount:
raise DustOutputError
return lib.bitcoin.core.CTxOut(value, lib.bitcoin.core.CScript(script))
def _get_colored_output(self, script):
"""
Creates a colored output.
:param bytes script: The output script.
:return: An object representing the colored output.
:rtype: TransactionOutput
"""
return lib.bitcoin.core.CTxOut(self._dust_amount, lib.bitcoin.core.CScript(script))
def _get_marker_output(self, asset_quantities, metadata):
"""
Creates a marker output.
:param list[int] asset_quantities: The asset quantity list.
:param bytes metadata: The metadata contained in the output.
:return: An object representing the marker output.
:rtype: TransactionOutput
"""
payload = openassets.protocol.MarkerOutput(asset_quantities, metadata).serialize_payload()
script = openassets.protocol.MarkerOutput.build_script(payload)
return lib.bitcoin.core.CTxOut(0, script)
class SpendableOutput(object):
"""Represents a transaction output with information about the asset ID and asset quantity associated to it."""
def __init__(self, out_point, output):
"""
Initializes a new instance of the TransactionOutput class.
:param COutPoint out_point: An object that can be used to locate the output.
:param TransactionOutput output: The actual output object.
"""
self._out_point = out_point
self._output = output
@property
def out_point(self):
"""
Gets an object that can be used to locate the output.
:return: An object that can be used to locate the output.
:rtype: COutPoint
"""
return self._out_point
@property
def output(self):
"""
Gets the output object.
:return: The actual output object.
:rtype: TransactionOutput
"""
return self._output
class TransferParameters(object):
"""Encapsulates the details of a bitcoin or asset transfer."""
def __init__(self, unspent_outputs, to_script, change_script, amount):
"""
Initializes an instance of the TransferParameters class.
:param list[SpendableOutput] unspent_outputs: The unspent outputs available for the transaction.
:param bytes to_script: The output script to which to send the assets or bitcoins.
:param bytes change_script: The output script to which to send any remaining change.
:param int amount: The asset quantity or amount of satoshis sent in the transaction.
"""
self._unspent_outputs = unspent_outputs
self._to_script = to_script
self._change_script = change_script
self._amount = amount
@property
def unspent_outputs(self):
"""
Gets the unspent outputs available for the transaction.
:return: The list of unspent outputs.
:rtype: list[SpendableOutput]
"""
return self._unspent_outputs
@property
def to_script(self):
"""
Gets the output script to which to send the assets or bitcoins.
:return: The output script.
:rtype: bytes
"""
return self._to_script
@property
def change_script(self):
"""
Gets the output script to which to send any remaining change.
:return: The output script.
:rtype: bytes
"""
return self._change_script
@property
def amount(self):
"""
Gets either the asset quantity or amount of satoshis sent in the transaction.
:return: The asset quantity or amount of satoshis.
:rtype: int
"""
return self._amount
class TransactionBuilderError(Exception):
"""The transaction could not be built."""
pass
class InsufficientFundsError(TransactionBuilderError):
"""An insufficient amount of bitcoins is available."""
pass
class InsufficientAssetQuantityError(TransactionBuilderError):
"""An insufficient amount of assets is available."""
pass
class DustOutputError(TransactionBuilderError):
"""The value of an output would be too small, and the output would be considered as dust."""
pass
<file_sep>#ifndef INVOICEMODEL_H
#define INVOICEMODEL_H
#endif // INVOICEMODEL_H
<file_sep>#ifndef STATISTICSPAGE_H
#define STATISTICSPAGE_H
#include "clientmodel.h"
#include "main.h"
#include "wallet.h"
#include "base58.h"
#include <QWidget>
#include <QDir>
#include <QFile>
#include <QProcess>
#include <QTime>
#include <QTimer>
#include <QStringList>
#include <QMap>
#include <QSettings>
#include <QSlider>
class Stats;
namespace Ui {
class StatisticsPage;
}
class ClientModel;
class StatisticsPage : public QWidget
{
Q_OBJECT
public:
explicit StatisticsPage(QWidget *parent = 0);
~StatisticsPage();
void setModel(ClientModel *model);
double trustr;
double mincreditscore;
double avecreditscore;
double bestcreditscore, mintrust, btcassets, gbltrust, besttrust, netinterestrate,
trust, inflationindex, consensusindex, globaldebt;
int64_t grantsaverage, gblmoneysupply, grantstotal, gblavailablecredit;
int totalnumtxPrevious;
QString bankstatus;
int64_t marketcap;
std::string theme;
public slots:
void updateStatistics();
void updatePrevious(double,double,double,double,double,double,double,double,double,double,int,int64_t,double,int64_t,double,int64_t,double,QString,double );
private slots:
private:
Ui::StatisticsPage *ui;
ClientModel *model;
};
#endif // STATISTICSPAGE_H
<file_sep>#!/bin/bash
# create multiresolution windows icon
ICON_SRC=../../src/qt/res/icons/bitcredit.png
ICON_DST=../../src/qt/res/icons/bitcredit.ico
convert ${ICON_SRC} -resize 16x16 bitcredit-16.png
convert ${ICON_SRC} -resize 32x32 bitcredit-32.png
convert ${ICON_SRC} -resize 48x48 bitcredit-48.png
convert bitcredit-16.png bitcredit-32.png bitcredit-48.png ${ICON_DST}
<file_sep>// Copyright (c) 2014 The ShadowCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef SDC_CORE_H
#define SDC_CORE_H
#include "util.h"
#include "serialize.h"
#include "primitives/transaction.h"
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <inttypes.h>
class CKeyImageSpent
{
// stored in txdb, key is keyimage
public:
CKeyImageSpent() {};
CKeyImageSpent(uint256& txnHash_, uint32_t inputNo_, int64_t nValue_)
{
txnHash = txnHash_;
inputNo = inputNo_;
nValue = nValue_;
};
uint256 txnHash; // hash of spending transaction
uint32_t inputNo; // keyimage is for inputNo of txnHash
int64_t nValue; // reporting only
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(txnHash);
READWRITE(inputNo);
READWRITE(nValue);
}
};
class CAnonOutput
{
// stored in txdb, key is pubkey
public:
CAnonOutput() {};
CAnonOutput(COutPoint& outpoint_, int64_t nValue_, int nBlockHeight_, uint8_t nCompromised_)
{
outpoint = outpoint_;
nValue = nValue_;
nBlockHeight = nBlockHeight_;
nCompromised = nCompromised_;
};
COutPoint outpoint;
int64_t nValue; // rather store 2 bytes, digit + power 10 ?
int nBlockHeight;
uint8_t nCompromised; // TODO: mark if output can be identified (spent with ringsig 1)
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(outpoint);
READWRITE(nValue);
READWRITE(nBlockHeight);
READWRITE(nCompromised);
}
};
class CAnonOutputCount
{ // CountAllAnonOutputs
public:
CAnonOutputCount()
{
nValue = 0;
nExists = 0;
nSpends = 0;
nOwned = 0;
nLeastDepth = 0;
}
CAnonOutputCount(int64_t nValue_, int nExists_, int nSpends_, int nOwned_, int nLeastDepth_)
{
nValue = nValue_;
nExists = nExists_;
nSpends = nSpends_;
nOwned = nOwned_;
nLeastDepth = nLeastDepth_;
}
void set(int64_t nValue_, int nExists_, int nSpends_, int nOwned_, int nLeastDepth_)
{
nValue = nValue_;
nExists = nExists_;
nSpends = nSpends_;
nOwned = nOwned_;
nLeastDepth = nLeastDepth_;
}
void addCoin(int nCoinDepth, int64_t nCoinValue)
{
nExists++;
nValue = nCoinValue;
if (nCoinDepth < nLeastDepth)
nLeastDepth = nCoinDepth;
}
void updateDepth(int nCoinDepth, int64_t nCoinValue)
{
nValue = nCoinValue;
if (nLeastDepth == 0
|| nCoinDepth < nLeastDepth)
nLeastDepth = nCoinDepth;
}
void incSpends(int64_t nCoinValue)
{
nSpends++;
nValue = nCoinValue;
}
void decSpends(int64_t nCoinValue)
{
nSpends--;
nValue = nCoinValue;
}
void incExists(int64_t nCoinValue)
{
nExists++;
nValue = nCoinValue;
}
void decExists(int64_t nCoinValue)
{
nExists--;
nValue = nCoinValue;
}
int64_t nValue;
int nExists;
int nSpends;
int nOwned; // todo
int nLeastDepth;
};
#endif // SDC_CORE_H
<file_sep>// Copyright (c) 2014-2015 The Bitcredit Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCREDIT_QT_RPCCONSOLE_H
#define BITCREDIT_QT_RPCCONSOLE_H
#include "guiutil.h"
#include "peertablemodel.h"
#include "net.h"
#include "walletmodel.h"
#include "vanitygenwork.h"
#include <QStandardItemModel>
#include <QWidget>
#include <QTimer>
#include <QStringList>
#include <QString>
#include <QFile>
#include <QDir>
#include <QItemSelection>
class ClientModel;
class WalletModel;
class CBasenodeMan;
namespace Ui {
class RPCConsole;
}
QT_BEGIN_NAMESPACE
class QItemSelection;
QT_END_NAMESPACE
/** Local Bitcredit RPC console. */
class RPCConsole: public QWidget
{
Q_OBJECT
public:
explicit RPCConsole(QWidget *parent);
~RPCConsole();
void setWalletModel(WalletModel *walletModel);
int ours;
void setClientModel(ClientModel *model);
void updatePlot();
QThread *threadVan;
VanityGenWork *van;
QStandardItemModel *model;
void updateUi();
int busyCounter = 1;
int getNewJobsCount();
void rebuildTableView();
enum MessageClass {
MC_ERROR,
MC_DEBUG,
CMD_REQUEST,
CMD_REPLY,
CMD_ERROR
};
protected:
virtual bool eventFilter(QObject* obj, QEvent *event);
void keyPressEvent(QKeyEvent *);
private slots:
void on_lineEdit_returnPressed();
void on_tabWidget_currentChanged(int index);
/** open the debug.log from the current datadir */
void on_openDebugLogfileButton_clicked();
/** change the time range of the network traffic graph */
void on_sldGraphRange_valueChanged(int value);
/** update traffic statistics */
void updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut);
void resizeEvent(QResizeEvent *event);
void showEvent(QShowEvent *event);
void hideEvent(QHideEvent *event);
void changeNumberOfCores(int i);
void switchMining();
QString getDefaultDataDirectory();
public slots:
void clear();
void message(int category, const QString &message, bool html = false);
/** Set number of connections shown in the UI */
void setNumConnections(int count);
/** Set number of blocks shown in the UI */
void setNumBlocks(int count);
void setBasenodeCount(const QString &strBasenodes);
/** Go forward or back in history */
void browseHistory(int offset);
/** Scroll console view to end */
void scrollToEnd();
/** Handle selection of peer in peers list */
void peerSelected(const QItemSelection &selected, const QItemSelection &deselected);
/** Handle updated peer information */
void peerLayoutChanged();
void updateNodeList();
void startThread();
void stopThread();
void addPatternClicked();
void changeAllowedText();
void checkAllowedText(int curpos);
void updateLabelNrThreads(int nThreads);
void updateVanityGenUI();
void tableViewClicked(QItemSelection sel1,QItemSelection sel2);
void deleteRows();
void changeMatchCase(bool state);
void customMenuRequested(QPoint pos);
void copyAddress();
void copyPrivateKey();
void importIntoWallet();
void deleteEntry();
void loadFile();
void saveFile();
signals:
// For RPC command executor
void stopExecutor();
void cmdRequest(const QString &command);
private:
static QString FormatBytes(quint64 bytes);
void startExecutor();
void setTrafficGraphRange(int mins);
/** show detailed information on ui about selected node */
void updateNodeDetail(const CNodeCombinedStats *stats);
enum ColumnWidths
{
ADDRESS_COLUMN_WIDTH = 200,
SUBVERSION_COLUMN_WIDTH = 100,
PING_COLUMN_WIDTH = 80
};
Ui::RPCConsole *ui;
ClientModel *clientModel;
QStringList history;
int historyPtr;
NodeId cachedNodeid;
QTimer *timer;
WalletModel *walletModel;
CCriticalSection cs_adrenaline;
void subscribeToCoreSignals();
void unsubscribeFromCoreSignals();
QStringList myStringList;
QString listitems;
QFile *myTextFile;
QString path;
QString dataDir;
std::string theme;
QString themestring;
QString ourcount;
std::auto_ptr<WalletModel::UnlockContext> unlockContext;
QVector<double> vX;
QVector<double> vY;
QVector<double> vX2;
QVector<double> vY2;
void restartMining(bool fGenerate);
void timerEvent(QTimerEvent *event);
QMenu *contextMenu;
QAction *copyAddressAction;
QAction *copyPrivateKeyAction;
QAction *importIntoWalletAction;
QAction *deleteAction;
int tableIndexClicked;
QFile file;
};
#endif // BITCREDIT_QT_RPCCONSOLE_H
<file_sep>[general]
# The following blockchain providers are supported:
# - bitcoind (default): Connects to Bitcoin Core
# - chain.com: Connects to the chain.com API
# - chain.com+bitcoind: Connects to the chain.com API, and uses Bitcoin Core for the local wallet
#
#blockchain-provider=bitcoind
coin=BitCredit
[environment]
# The default settings work for MainNet
# Change them to use with TestNet or an alt-coin
#
#version-byte=0
#p2sh-version-byte=5
#asset-version-byte=23
dust-limit=600
default-fees=10000
[cache]
# Path of the cache file (use :memory: to disable)
#
path=cache.db
[rpc]
# The port on which to expose the Colorcore RPC interface
#
port=8080
#[bitcoind]
# Replace username, password and port with the username, password and port for Bitcoin Core
#
rpcurl=http://1q2w3e:3e2w1q@localhost:8880
<file_sep>// Copyright (c) 2011-2013 The Bitcredit Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCREDIT_QT_OPTIONSDIALOG_H
#define BITCREDIT_QT_OPTIONSDIALOG_H
#include <QDialog>
#include <QTreeView>
#include <QPushButton>
#include <QFileSystemModel>
#include <QModelIndex>
#include <QLabel>
#include <QString>
#include <QFileInfo>
#include <QFile>
#include <QStringList>
#include <QTextStream>
#include <QRadioButton>
#include <QMessageBox>
#include <QSpinBox>
#include <QComboBox>
#include <QCheckBox>
class OptionsModel;
class QValidatedLineEdit;
QT_BEGIN_NAMESPACE
class QDataWidgetMapper;
QT_END_NAMESPACE
namespace Ui {
class OptionsDialog;
}
/** Preferences dialog. */
class OptionsDialog : public QDialog
{
Q_OBJECT
public:
explicit OptionsDialog(QWidget *parent, bool enableWallet);
~OptionsDialog();
void setModel(OptionsModel *model);
void setMapper();
QString driverName() const;
QString databaseName() const;
QString userName() const;
QString password() const;
QString hostName() const;
int port() const;
bool useDefaultDatabase();
protected:
bool eventFilter(QObject *object, QEvent *event);
private slots:
/* enable OK button */
void enableOkButton();
/* disable OK button */
void disableOkButton();
/* set OK button state (enabled / disabled) */
void setOkButtonState(bool fState);
void on_resetButton_clicked();
void on_okButton_clicked();
void on_cancelButton_clicked();
void setTheme();
//void getData(const QModelIndex &index);
void showRestartWarning(bool fPersistent = false);
void clearStatusLabel();
void doProxyIpChecks(QValidatedLineEdit *pUiProxyIp, int nProxyPort);
/* query the networks, for which the default proxy is used */
void updateDefaultProxyNets();
QString getDefaultDataDirectory();
signals:
void proxyIpChecks(QValidatedLineEdit *pUiProxyIp, int nProxyPort);
private:
Ui::OptionsDialog *ui;
OptionsModel *model;
QDataWidgetMapper *mapper;
bool fProxyIpsValid;
QTreeView *tree;
QPushButton *pushButton_apply_theme;
QFileSystemModel *model2;
QModelIndex *idx;
QModelIndex *index;
QLabel *test;
QString selected;
QString *homedir;
QFile *qss;
QString confFile;
QString themename;
QStringList *filters;
QRadioButton *checkOrange;
QRadioButton *checkDark;
QRadioButton *checkGreen;
QRadioButton *checkBlue;
QRadioButton *checkPink;
QRadioButton *checkPurple;
QRadioButton *checkTurq;
QString path;
QString dataDir;
QStringList confList;
QStringList themepath;
QString data;
QString tempfile;
QString tempstring;
};
#endif // BITCREDIT_QT_OPTIONSDIALOG_H
<file_sep>from PyQt4 import QtCore, QtGui
import requests,json,sys
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Form(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setupUi(self)
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(427, 338)
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.label = QtGui.QLabel(Form)
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout.addWidget(self.label, 10, 0, 1, 1)
self.issue_amnt = QtGui.QLineEdit(Form)
self.issue_amnt.setText(_fromUtf8(""))
self.issue_amnt.setObjectName(_fromUtf8("issue_amnt"))
self.gridLayout.addWidget(self.issue_amnt, 9, 2, 1, 1)
self.addressWidget = QtGui.QTreeWidget(Form)
self.addressWidget.setObjectName(_fromUtf8("addressWidget"))
self.gridLayout.addWidget(self.addressWidget, 0, 0, 1, 3)
self.label_2 = QtGui.QLabel(Form)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.gridLayout.addWidget(self.label_2, 7, 0, 1, 1)
self.snd_add = QtGui.QLineEdit(Form)
self.snd_add.setText(_fromUtf8(""))
self.snd_add.setObjectName(_fromUtf8("snd_add"))
self.gridLayout.addWidget(self.snd_add, 11, 0, 1, 1)
self.label_3 = QtGui.QLabel(Form)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.gridLayout.addWidget(self.label_3, 7, 2, 1, 1)
self.sa_btn = QtGui.QPushButton(Form)
self.sa_btn.setObjectName(_fromUtf8("sa_btn"))
self.gridLayout.addWidget(self.sa_btn, 13, 0, 1, 1)
self.ia_btn = QtGui.QPushButton(Form)
self.ia_btn.setObjectName(_fromUtf8("ia_btn"))
self.gridLayout.addWidget(self.ia_btn, 13, 2, 1, 1)
self.assetsWidget = QtGui.QTreeWidget(Form)
self.assetsWidget.setObjectName(_fromUtf8("assetsWidget"))
self.gridLayout.addWidget(self.assetsWidget, 2, 0, 1, 3)
self.label_4 = QtGui.QLabel(Form)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.gridLayout.addWidget(self.label_4, 10, 2, 1, 1)
self.issue_add = QtGui.QLineEdit(Form)
self.issue_add.setText(_fromUtf8(""))
self.issue_add.setObjectName(_fromUtf8("issue_add"))
self.gridLayout.addWidget(self.issue_add, 11, 2, 1, 1)
self.snd_amnt = QtGui.QLineEdit(Form)
self.snd_amnt.setText(_fromUtf8(""))
self.snd_amnt.setObjectName(_fromUtf8("snd_amnt"))
self.gridLayout.addWidget(self.snd_amnt, 9, 0, 1, 1)
self.rf_btn = QtGui.QPushButton(Form)
self.rf_btn.setObjectName(_fromUtf8("rf_btn"))
self.gridLayout.addWidget(self.rf_btn, 3, 2, 1, 1)
self.chw_btn = QtGui.QPushButton(Form)
self.chw_btn.setObjectName(_fromUtf8("chw_btn"))
self.gridLayout.addWidget(self.chw_btn, 3, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "ColorUI", None))
self.addressWidget.headerItem().setText(0, _translate("Form", "Addresses", None))
__sortingEnabled = self.addressWidget.isSortingEnabled()
self.addressWidget.setSortingEnabled(False)
getBalance()
for item in r:
qi = QtGui.QTreeWidgetItem()
qi.setText(0, _translate("Form", item['oa_address'], None))
qi_c = QtGui.QTreeWidgetItem()
qi_c.setText(0, _translate("Form", item['value'], None))
qi.addChild(qi_c)
self.addressWidget.addTopLevelItem(qi)
self.addressWidget.setSortingEnabled(__sortingEnabled)
self.assetsWidget.headerItem().setText(0, _translate("Form", "Assets", None))
__sortingEnabled = self.assetsWidget.isSortingEnabled()
self.assetsWidget.setSortingEnabled(False)
for item in r:
for a in item['assets']:
qi = QtGui.QTreeWidgetItem()
qi.setText(0, _translate("Form", a['asset_id'], None))
qi_c = QtGui.QTreeWidgetItem()
qi_c.setText(0, _translate("Form", a['quantity'], None))
qi.addChild(qi_c)
self.assetsWidget.addTopLevelItem(qi)
self.assetsWidget.setSortingEnabled(__sortingEnabled)
self.label_2.setText(_translate("Form", "Amount:", None))
self.label_3.setText(_translate("Form", "Amount:", None))
self.sa_btn.setText(_translate("Form", "Send Assets", None))
self.ia_btn.setText(_translate("Form", "Issue Assets", None))
self.assetsWidget.headerItem().setText(0, _translate("Form", "Assets", None))
__sortingEnabled = self.assetsWidget.isSortingEnabled()
self.assetsWidget.setSortingEnabled(False)
self.assetsWidget.setSortingEnabled(__sortingEnabled)
self.label_4.setText(_translate("Form", "Address:", None))
self.label.setText(_translate("Form", "Address:", None))
self.rf_btn.setText(_translate("Form", "Refresh", None))
self.chw_btn.setText(_translate("Form", "Change Wallet", None))
self.rf_btn.clicked.connect(self.rebuild)
self.chw_btn.clicked.connect(self.chWallet)
self.assetsWidget.currentItemChanged.connect(self.assetClick)
self.addressWidget.currentItemChanged.connect(self.addyClick)
self.sa_btn.clicked.connect(self.sendAsset)
self.sa_btn.clicked.connect(self.rebuild)
self.ia_btn.clicked.connect(self.issueAsset)
self.ia_btn.clicked.connect(self.rebuild)
def rebuild(form):
getBalance()
form.addressWidget.clear()
for item in r:
qi = QtGui.QTreeWidgetItem()
qi.setText(0, _translate("Form", item['oa_address'], None))
qi_c = QtGui.QTreeWidgetItem()
qi_c.setText(0, _translate("Form", item['value'], None))
qi.addChild(qi_c)
form.addressWidget.addTopLevelItem(qi)
form.assetsWidget.clear()
for item in r:
for a in item['assets']:
qi = QtGui.QTreeWidgetItem()
qi.setText(0, _translate("Form", a['asset_id'], None))
qi_c = QtGui.QTreeWidgetItem()
qi_c.setText(0, _translate("Form", a['quantity'], None))
qi.addChild(qi_c)
form.assetsWidget.addTopLevelItem(qi)
def sendAsset(form):
global r2
payload = {'address': "%s"%addy, 'asset': "%s"%asset, 'amount': "%s"%form.snd_amnt.text(), "to": "%s"%form.snd_add.text()}
r2 = requests.post(url + "sendasset", data=payload)
print r2.json(),asset,form.snd_add.text(),form.snd_amnt.text()
print(r2.url)
global stuff
stuff = r2.json()
ex3 = popupForm()
ex3.show()
def issueAsset(form):
global r3
payload = {'address': "%s"%addy, "to": "%s"%form.issue_add.text(), 'amount': "%s"%form.issue_amnt.text()}
r3 = requests.post(url + "issueasset", data=payload)
print r3.json(),addy,form.snd_add.text(),form.snd_amnt.text()
print(r3.url)
#global stuff
#stuff = r3.json()
#ex3 = popupForm()
#ex3.show()
def chWallet(self):
ex.hide()
ex2.show()
def assetClick(self, current, previous):
if (previous != None):
print "old: " + previous.text(0)
global asset
asset = current.text(0)
def addyClick(self, current, previous):
if (previous != None):
print "old: " + previous.text(0)
global addy
addy = current.text(0)
class Ui_Form2(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setupUi2(self)
def setupUi2(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(528, 227)
self.label = QtGui.QLabel(Form)
self.label.setGeometry(QtCore.QRect(190, -10, 141, 101))
self.label.setObjectName(_fromUtf8("label"))
self.address = QtGui.QLineEdit(Form)
self.address.setGeometry(QtCore.QRect(150, 140, 231, 16))
self.address.setObjectName(_fromUtf8("address"))
self.label_2 = QtGui.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(230, 110, 51, 16))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.pushButton = QtGui.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(220, 180, 81, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.retranslateUi2(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi2(self, Form):
Form.setWindowTitle(_translate("Form", "ColorUI", None))
self.label.setText(_translate("Form", "<html><head/><body><p><span style=\" font-size:28pt; font-weight:600;\">ColorUI</span></p></body></html>", None))
self.label_2.setText(_translate("Form", "Enter URL:", None))
self.pushButton.setText(_translate("Form", "Access Wallet", None))
self.pushButton.clicked.connect(self.screen2)
def screen2(form):
global url
url = form.address.text()
requests.post(url + "getbalance").json()
global ex
ex = Ui_Form()
ex2.hide()
ex.show()
def getBalance():
global r
r = requests.post(url + "getbalance").json()
class popupForm(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setupUi(self)
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(276, 88)
self.horizontalLayout = QtGui.QHBoxLayout(Form)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label = QtGui.QLabel(Form)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout.addWidget(self.label)
self.uiText(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def uiText(self, Form):
print stuff
Form.setWindowTitle(_translate("Form", "Result", None))
self.label.setText(_translate("Form", "<html><head/><body><p><span style=\" font-size:14pt;\">%s</span></p></body></html>"%stuff, None))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
global ex2
ex2 = Ui_Form2()
ex2.show()
sys.exit(app.exec_())
<file_sep>#!/bin/bash
# This is a thin wrapper around bitcredit-cli that strips the Windows-style EOLs
# from the output if present. It is necessary when using bitcredit-cli.exe on
# Linux since shells will interpret the line-endings as part of the result.
CURDIR=$(cd $(dirname "$0"); pwd)
# Get BUILDDIR and REAL_BITCREDITD
# Grab the value of $REAL_BITCREDITCLI which may be bitcredit-cli.exe.
. "${CURDIR}/tests-config.sh"
"${REAL_BITCREDITCLI}" "$@" | sed 's/\r//'
<file_sep>#include "guiutil.h"
#include "guiconstants.h"
#include "bitcreditunits.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "messagemodel.h"
#include "addresstablemodel.h"
#include "invoicepage.h"
#include "invoiceviewpage.h"
#include "receiptpage.h"
#include "addresstablemodel.h"
#include "pubkey.h"
#include "ui_interface.h"
#include "base58.h"
#include "init.h"
#include "util.h"
#include "json_spirit.h"
#include <QSet>
#include <QTimer>
#include <QDateTime>
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
#include <QFont>
#include <QColor>
Q_DECLARE_METATYPE(std::vector<unsigned char>);
QList<QString> ambiguous; /**< Specifies Ambiguous addresses */
const QString MessageModel::Sent = "Sent";
const QString MessageModel::Received = "Received";
struct MessageTableEntryLessThan
{
bool operator()(const MessageTableEntry &a, const MessageTableEntry &b) const {return a.received_datetime < b.received_datetime;};
bool operator()(const MessageTableEntry &a, const QDateTime &b) const {return a.received_datetime < b;}
bool operator()(const QDateTime &a, const MessageTableEntry &b) const {return a < b.received_datetime;}
};
struct InvoiceTableEntryLessThan
{
bool operator()(const InvoiceTableEntry &a, const InvoiceTableEntry &b) const {return a.received_datetime < b.received_datetime;};
bool operator()(const InvoiceTableEntry &a, const QDateTime &b) const {return a.received_datetime < b;}
bool operator()(const QDateTime &a, const InvoiceTableEntry &b) const {return a < b.received_datetime;}
};
struct ReceiptTableEntryLessThan
{
bool operator()(const ReceiptTableEntry &a, const ReceiptTableEntry &b) const {return a.received_datetime < b.received_datetime;};
bool operator()(const ReceiptTableEntry &a, const QDateTime &b) const {return a.received_datetime < b;}
bool operator()(const QDateTime &a, const ReceiptTableEntry &b) const {return a < b.received_datetime;}
};
// Private implementation
class MessageTablePriv
{
public:
QList<MessageTableEntry> cachedMessageTable;
QList<InvoiceTableEntry> cachedInvoiceTable;
QList<InvoiceItemTableEntry> cachedInvoiceItemTable;
QList<ReceiptTableEntry> cachedReceiptTable;
MessageModel *parent;
MessageTablePriv(MessageModel *parent):
parent(parent) {}
void refreshMessageTable()
{
cachedMessageTable.clear();
cachedInvoiceTable.clear();
cachedInvoiceItemTable.clear();
cachedReceiptTable.clear();
if (parent->getWalletModel()->getEncryptionStatus() == WalletModel::Locked)
{
// -- messages are stored encrypted, can't load them without the private keys
return;
};
Dbt datKey;
Dbt datValue;
datKey.set_flags(DB_DBT_USERMEM);
datValue.set_flags(DB_DBT_USERMEM);
std::vector<unsigned char> vchKeyData;
std::vector<unsigned char> vchValueData;
vchKeyData.resize(100);
vchValueData.resize(100);
datKey.set_ulen(vchKeyData.size());
datKey.set_data(&vchKeyData[0]);
datValue.set_ulen(vchValueData.size());
datValue.set_data(&vchValueData[0]);
std::vector<unsigned char> vchKey;
{
LOCK(cs_smsgDB);
SecMsgDB dbSmsg;
if (!dbSmsg.Open("cr+"))
//throw runtime_error("Could not open DB.");
return;
unsigned char chKey[18];
std::vector<unsigned char> vchKey;
vchKey.resize(18);
SecMsgStored smsgStored;
MessageData msg;
QString label;
QDateTime sent_datetime;
QDateTime received_datetime;
std::string sPrefix("im");
leveldb::Iterator* it = dbSmsg.pdb->NewIterator(leveldb::ReadOptions());
while (dbSmsg.NextSmesg(it, sPrefix, chKey, smsgStored))
{
std::string errorMsg;
if (SecureMsgDecrypt(smsgStored, msg, errorMsg) == 0)
{
label = parent->getWalletModel()->getAddressTableModel()->labelForAddress(QString(msg.sFromAddress.c_str()));
sent_datetime .setTime_t(msg.timestamp);
received_datetime.setTime_t(smsgStored.timeReceived);
memcpy(&vchKey[0], chKey, 18);
handleMessageEntry(MessageTableEntry(vchKey,
MessageTableEntry::Received,
label,
QString::fromStdString(smsgStored.sAddrTo),
QString(msg.sFromAddress.c_str()),
sent_datetime,
received_datetime,
!(smsgStored.status & SMSG_MASK_UNREAD),
msg.sMessage.c_str()),
true);
}
};
delete it;
sPrefix = "sm";
it = dbSmsg.pdb->NewIterator(leveldb::ReadOptions());
while (dbSmsg.NextSmesg(it, sPrefix, chKey, smsgStored))
{
const unsigned char* pPayload = &smsgStored.vchMessage[SMSG_HDR_LEN];
SecureMessageHeader smsg(&smsgStored.vchMessage[0]);
memcpy(smsg.hash, Hash(&pPayload[0], &pPayload[smsg.nPayload]).begin(), 32);
if (SecureMsgDecrypt(false, smsgStored.sAddrOutbox, smsg, pPayload, msg) == 0)
{
label = parent->getWalletModel()->getAddressTableModel()->labelForAddress(QString::fromStdString(smsgStored.sAddrTo));
sent_datetime.setTime_t(msg.timestamp);
received_datetime.setTime_t(smsgStored.timeReceived);
memcpy(&vchKey[0], chKey, 18);
handleMessageEntry(MessageTableEntry(vchKey,
MessageTableEntry::Sent,
label,
QString::fromStdString(smsgStored.sAddrTo),
QString(msg.sFromAddress.c_str()),
sent_datetime,
received_datetime,
!(smsgStored.status & SMSG_MASK_UNREAD),
msg.sMessage.c_str()),
true);
};
};
delete it;
}
}
void newMessage(const SecMsgStored& inboxHdr)
{
// we have to copy it, because it doesn't like constants going into Decrypt
SecMsgStored smsgStored = inboxHdr;
//SecMsgStored &smsgInbox = const_cast<SecMsgStored&>(inboxHdr); // un-const the reference
MessageData msg;
QString label;
QDateTime sent_datetime;
QDateTime received_datetime;
std::string errorMsg;
if (SecureMsgDecrypt(smsgStored, msg, errorMsg) == 0)
{
label = parent->getWalletModel()->getAddressTableModel()->labelForAddress(QString(msg.sFromAddress.c_str()));
sent_datetime .setTime_t(msg.timestamp);
received_datetime.setTime_t(smsgStored.timeReceived);
std::vector<unsigned char> vchKey;
std::string sPrefix("im");
vchKey.resize(18);
memcpy(&vchKey[0], sPrefix.data(), 2);
memcpy(&vchKey[2], &msg.timestamp, 8);
memcpy(&vchKey[10], &smsgStored.vchMessage[SMSG_HDR_LEN], 8); // sample
handleMessageEntry(MessageTableEntry(vchKey,
MessageTableEntry::Received,
label,
QString::fromStdString(smsgStored.sAddrTo),
msg.sFromAddress.c_str(),
sent_datetime,
received_datetime,
!(smsgStored.status & SMSG_MASK_UNREAD),
msg.sMessage.c_str()),
false);
}
}
void newOutboxMessage(const SecMsgStored& outboxHdr)
{
SecMsgStored &smsgStored = const_cast<SecMsgStored&>(outboxHdr); // un-const the reference
MessageData msg;
QString label;
QDateTime sent_datetime;
QDateTime received_datetime;
const unsigned char* pPayload = &smsgStored.vchMessage[SMSG_HDR_LEN];
SecureMessageHeader smsg(&smsgStored.vchMessage[0]);
memcpy(smsg.hash, Hash(&pPayload[0], &pPayload[smsg.nPayload]).begin(), 32);
if (SecureMsgDecrypt(false, smsgStored.sAddrOutbox, smsg, pPayload, msg) == 0)
{
label = parent->getWalletModel()->getAddressTableModel()->labelForAddress(smsgStored.sAddrTo.c_str());
sent_datetime .setTime_t(msg.timestamp);
received_datetime.setTime_t(smsgStored.timeReceived);
std::string sPrefix("sm");
std::vector<unsigned char> vchKey(18);
memcpy(&vchKey[0], sPrefix.data(), 2);
memcpy(&vchKey[2], &msg.timestamp, 8);
memcpy(&vchKey[10], &smsgStored.vchMessage[SMSG_HDR_LEN], 8); // sample
handleMessageEntry(MessageTableEntry(vchKey,
MessageTableEntry::Sent,
label,
QString::fromStdString(smsgStored.sAddrTo),
msg.sFromAddress.c_str(),
sent_datetime,
received_datetime,
!(smsgStored.status & SMSG_MASK_UNREAD),
msg.sMessage.c_str()),
false);
}
}
void setEncryptionStatus(int status)
{
if (status == WalletModel::Locked)
{
// -- Wallet is locked, clear secure message display.
cachedMessageTable.clear();
cachedInvoiceTable.clear();
cachedInvoiceItemTable.clear();
cachedReceiptTable.clear();
//parent->reset(); // reload table view
//parent->getInvoiceTableModel()->getInvoiceItemTableModel()->reset();
};
};
bool markAsRead(const int& idx)
{
MessageTableEntry *rec = index(idx);
if(!rec || rec->read)
// Can only mark one row at a time, and cannot mark rows not in model.
return false;
{
LOCK(cs_smsgDB);
SecMsgDB dbSmsg;
if (!dbSmsg.Open("cr+"))
//throw runtime_error("Could not open DB.");
return false;
SecMsgStored smsgStored;
dbSmsg.ReadSmesg(&rec->vchKey[0], smsgStored);
smsgStored.status &= ~SMSG_MASK_UNREAD;
dbSmsg.WriteSmesg(&rec->vchKey[0], smsgStored);
rec->read = !(smsgStored.status & SMSG_MASK_UNREAD);
}
return true;
};
void walletUnlocked()
{
// -- wallet is unlocked, can get at the private keys now
refreshMessageTable();
//parent->reset(); // reload table view
// parent->getInvoiceTableModel()->getInvoiceItemTableModel()->reset();
}
void newInvoice(InvoiceTableEntry invoice)
{
addInvoiceEntry(invoice, false);
}
void newReceipt(ReceiptTableEntry receipt)
{
addReceiptEntry(receipt, false);
}
void newInvoiceItem()
{
InvoiceItemTableEntry invoice(true);
addInvoiceItemEntry(invoice, false);
}
QString getInvoiceJSON(const int row)
{
QList<InvoiceTableEntry>::iterator inv;
json_spirit::Object invoice;
invoice.push_back(json_spirit::Pair("type", "invoice" ));
invoice.push_back(json_spirit::Pair("company_info_left", cachedInvoiceTable[row].company_info_left.toStdString()));
invoice.push_back(json_spirit::Pair("company_info_right", cachedInvoiceTable[row].company_info_right.toStdString()));
invoice.push_back(json_spirit::Pair("billing_info_left", cachedInvoiceTable[row].billing_info_left.toStdString()));
invoice.push_back(json_spirit::Pair("billing_info_right", cachedInvoiceTable[row].billing_info_right.toStdString()));
invoice.push_back(json_spirit::Pair("footer", cachedInvoiceTable[row].footer.toStdString()));
invoice.push_back(json_spirit::Pair("invoice_number", cachedInvoiceTable[row].invoice_number.toStdString()));
invoice.push_back(json_spirit::Pair("due_date", cachedInvoiceTable[row].due_date.toString().toStdString()));
json_spirit::Array items;
for(int i = 0;i<cachedInvoiceItemTable.size();i++)
if(cachedInvoiceItemTable[i].vchKey == cachedInvoiceTable[row].vchKey)
{
json_spirit::Object item;
item.push_back(json_spirit::Pair("code", cachedInvoiceItemTable[i].code.toStdString()));
item.push_back(json_spirit::Pair("description", cachedInvoiceItemTable[i].description.toStdString()));
item.push_back(json_spirit::Pair("price", int64_t(cachedInvoiceItemTable[i].price)));
//item.push_back(json_spirit::Pair("tax", i->tax));
item.push_back(json_spirit::Pair("quantity", cachedInvoiceItemTable[i].quantity));
items.push_back(item);
parent->getInvoiceTableModel()->getInvoiceItemTableModel()->beginRemoveRows(QModelIndex(), 0, 0);
cachedInvoiceItemTable.removeAt(i);
parent->getInvoiceTableModel()->getInvoiceItemTableModel()->endRemoveRows();
}
invoice.push_back(json_spirit::Pair("items", items));
if(row==0)
{
parent->getInvoiceTableModel()->beginRemoveRows(QModelIndex(), 0, 0);
cachedInvoiceTable.removeAt(row);
parent->getInvoiceTableModel()->endRemoveRows();
}
return QString::fromStdString(json_spirit::write(invoice));
}
QString getReceiptJSON(const int row)
{
QList<ReceiptTableEntry>::iterator inv;
json_spirit::Object receipt;
receipt.push_back(json_spirit::Pair("type", "receipt" ));
receipt.push_back(json_spirit::Pair("invoice_number", cachedReceiptTable[row].invoice_number.toStdString()));
receipt.push_back(json_spirit::Pair("amount", int64_t(cachedReceiptTable[row].amount)));
//receipt.push_back(json_spirit::Pair("outstanding", "0")); //TODO: Calculate outstanding. cachedReceiptTable[row].amount.toStdString()));
if(row==0)
{
parent->getReceiptTableModel()->beginRemoveRows(QModelIndex(), 0, 0);
cachedReceiptTable.removeAt(row);
parent->getReceiptTableModel()->endRemoveRows();
}
//qDebug() << QString::fromStdString(json_spirit::write(receipt));
return QString::fromStdString(json_spirit::write(receipt));
}
MessageTableEntry *index(int idx)
{
if(idx >= 0 && idx < cachedMessageTable.size())
return &cachedMessageTable[idx];
else
return 0;
}
int64_t getTotal(std::vector<unsigned char> & vchKey) {
int64_t total = 0;
QList<InvoiceItemTableEntry>::iterator i;
for (i = cachedInvoiceItemTable.begin(); i != cachedInvoiceItemTable.end(); ++i)
if(i->vchKey == vchKey)
total += (i->price * i->quantity);
return total;
}
private:
// Get the json value
const json_spirit::mValue & find_value(json_spirit::mObject & obj, const char * key)
{
std::string newKey = key;
json_spirit::mObject::const_iterator i = obj.find(newKey);
if(i != obj.end() && i->first == newKey)
return i->second;
else
return json_spirit::mValue::null;
}
const std::string get_value(json_spirit::mObject & obj, const char * key)
{
json_spirit::mValue val = find_value(obj, key);
if(val.is_null())
return "";
else
return val.get_str();
}
// Determine if it is a special message, i.e.: Invoice, Receipt, etc...
void handleMessageEntry(const MessageTableEntry & message, const bool append)
{
addMessageEntry(message, append);
json_spirit::mValue mVal;
json_spirit::read(message.message.toStdString(), mVal);
if(mVal.is_null())
{
addMessageEntry(message, append);
return;
}
json_spirit::mObject mObj(mVal.get_obj());
json_spirit::mValue mvType = find_value(mObj, "type");
if(!mvType.is_null())
{
std::string type = mvType.get_str();
if (type == "invoice")
{
json_spirit::mArray items(find_value(mObj, "items").get_array());
for(uint i = 0;i < items.size();i++)
{
json_spirit::mObject item_obj = items[i].get_obj();
addInvoiceItemEntry(InvoiceItemTableEntry(message.vchKey,
message.type,
QString::fromStdString(get_value(item_obj, "code")),
QString::fromStdString(get_value(item_obj, "description")),
find_value(item_obj, "quantity").get_int(),
find_value(item_obj, "price").get_int64()),
//find_value(item_obj, "tax").get_bool()),
append);
}
addInvoiceEntry(InvoiceTableEntry(message,
QString::fromStdString(get_value(mObj, "company_info_left" )),
QString::fromStdString(get_value(mObj, "company_info_right")),
QString::fromStdString(get_value(mObj, "billing_info_left" )),
QString::fromStdString(get_value(mObj, "billing_info_right")),
QString::fromStdString(get_value(mObj, "footer" )),
QString::fromStdString(get_value(mObj, "invoice_number" )),
QDate::fromString(QString::fromStdString(get_value(mObj, "due_date")))),
append);
// DEBUG std::string str = json_spirit::write(mVal);
// DEBUG qDebug() << "invoice" << str.c_str();
}
else if (type == "receipt")
{
addReceiptEntry(ReceiptTableEntry(message,
QString::fromStdString(get_value(mObj, "invoice_number")),
find_value(mObj, "amount").get_int64()),
append);
// DEBUG std::string str = json_spirit::write(mVal);
// DEBUG qDebug() << "receipt" << str.c_str();
}
else
addMessageEntry(message, append);
}
else
{
addMessageEntry(message, append);
// DEBUG std::string str = json_spirit::write(mVal);
// DEBUG qDebug() << "str" << str.c_str();
}
}
void addMessageEntry(const MessageTableEntry & message, const bool & append)
{
if(append)
{
cachedMessageTable.append(message);
} else
{
int index = qLowerBound(cachedMessageTable.begin(), cachedMessageTable.end(), message.received_datetime, MessageTableEntryLessThan()) - cachedMessageTable.begin();
parent->beginInsertRows(QModelIndex(), index, index);
cachedMessageTable.insert(
index,
message);
parent->endInsertRows();
}
}
void addInvoiceEntry(const InvoiceTableEntry & invoice, const bool append)
{
if(append) cachedInvoiceTable.append(invoice);
else
{
int index = qLowerBound(cachedInvoiceTable.begin(), cachedInvoiceTable.end(), invoice.received_datetime, InvoiceTableEntryLessThan()) - cachedInvoiceTable.begin();
parent->getInvoiceTableModel()->beginInsertRows(QModelIndex(), index, index);
cachedInvoiceTable.insert(
index,
invoice);
parent->getInvoiceTableModel()->endInsertRows();
}
}
void addInvoiceItemEntry(const InvoiceItemTableEntry & item, const bool append)
{
if(append) cachedInvoiceItemTable.append(item);
else
{
int index = cachedInvoiceItemTable.size();
parent->getInvoiceTableModel()->getInvoiceItemTableModel()->beginInsertRows(QModelIndex(), index, index);
cachedInvoiceItemTable.insert(index, item);
parent->getInvoiceTableModel()->getInvoiceItemTableModel()->endInsertRows();
}
}
void addReceiptEntry(const ReceiptTableEntry & receipt, const bool append)
{
if(append) cachedReceiptTable.append(receipt);
else
{
int index = qLowerBound(cachedReceiptTable.begin(), cachedReceiptTable.end(), receipt.received_datetime, ReceiptTableEntryLessThan()) - cachedReceiptTable.begin();
parent->getReceiptTableModel()->beginInsertRows(QModelIndex(), index, index);
cachedReceiptTable.insert(index, receipt);
parent->getReceiptTableModel()->endInsertRows();
}
}
};
MessageModel::MessageModel(WalletModel *walletModel, QObject *parent) :
QAbstractTableModel(parent), walletModel(walletModel), optionsModel(0), priv(0), invoiceTableModel(0)
{
columns << tr("Type") << tr("Sent Date Time") << tr("Received Date Time") << tr("Label") << tr("To Address") << tr("From Address") << tr("Message");
optionsModel = walletModel->getOptionsModel();
priv = new MessageTablePriv(this);
priv->refreshMessageTable();
invoiceTableModel = new InvoiceTableModel(priv, parent);
receiptTableModel = new ReceiptTableModel(priv, parent);
subscribeToCoreSignals();
}
MessageModel::~MessageModel()
{
delete priv;
delete invoiceTableModel;
delete receiptTableModel;
unsubscribeFromCoreSignals();
}
bool MessageModel::getAddressOrPubkey(QString &address, QString &pubkey) const
{
CBitcreditAddress addressParsed(address.toStdString());
if(addressParsed.IsValid()) {
CKeyID destinationAddress;
CPubKey destinationKey;
addressParsed.GetKeyID(destinationAddress);
if (SecureMsgGetStoredKey(destinationAddress, destinationKey) != 0
&& SecureMsgGetLocalKey(destinationAddress, destinationKey) != 0) // test if it's a local key
return false;
address = destinationAddress.ToString().c_str();
pubkey = QString::fromStdString(EncodeBase58(&destinationKey[0], destinationKey.end()));
return true;
}
return false;
}
WalletModel *MessageModel::getWalletModel()
{
return walletModel;
}
OptionsModel *MessageModel::getOptionsModel()
{
return optionsModel;
}
InvoiceTableModel *MessageModel::getInvoiceTableModel()
{
return invoiceTableModel;
}
ReceiptTableModel *MessageModel::getReceiptTableModel()
{
return receiptTableModel;
}
MessageModel::StatusCode MessageModel::sendMessages(const QList<SendMessagesRecipient> &recipients, const QString &addressFrom)
{
QSet<QString> setAddress;
if(recipients.empty())
return OK;
// Pre-check input data for validity
foreach(const SendMessagesRecipient &rcp, recipients)
{
if(!walletModel->validateAddress(rcp.address))
return InvalidAddress;
if(rcp.message == "")
return MessageCreationFailed;
std::string sendTo = rcp.address.toStdString();
std::string pubkey = rcp.pubkey.toStdString();
std::string message = rcp.message.toStdString();
std::string addFrom = addressFrom.toStdString();
SecureMsgAddAddress(sendTo, pubkey);
setAddress.insert(rcp.address);
std::string sError;
if (SecureMsgSend(addFrom, sendTo, message, sError) != 0)
{
QMessageBox::warning(NULL, tr("Send Secure Message"),
tr("Send failed: %1.").arg(sError.c_str()),
QMessageBox::Ok, QMessageBox::Ok);
return FailedErrorShown;
};
// Add addresses / update labels that we've sent to to the address book
std::string strAddress = rcp.address.toStdString();
CTxDestination dest = CBitcreditAddress(strAddress).Get();
std::string strLabel = rcp.label.toStdString();
{
/*
LOCK(wallet->cs_wallet);
std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest);
Check if we have a new address or an updated label
if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
{
wallet->SetAddressBookName(dest, strLabel);
}*/
}
}
if(recipients.size() > setAddress.size())
return DuplicateAddress;
return OK;
}
MessageModel::StatusCode MessageModel::sendMessages(const QList<SendMessagesRecipient> &recipients)
{
return sendMessages(recipients, "anon");
}
int MessageModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->cachedMessageTable.size();
}
int MessageModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant MessageModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
MessageTableEntry *rec = static_cast<MessageTableEntry*>(index.internalPointer());
switch(role)
{
case Qt::DisplayRole:
switch(index.column())
{
case Label: return (rec->label.isEmpty() ? tr("(no label)") : rec->label);
case ToAddress: return rec->to_address;
case FromAddress: return rec->from_address;
case SentDateTime: return rec->sent_datetime;
case ReceivedDateTime: return rec->received_datetime;
case Message: return rec->message;
case Read: return rec->read;
case TypeInt: return rec->type;
case HTML: return rec->received_datetime.toString() + "<br>" + (rec->label.isEmpty() ? rec->from_address : rec->label) + "<br>" + rec->message;
case Type:
switch(rec->type)
{
case MessageTableEntry::Sent: return Sent;
case MessageTableEntry::Received: return Received;
default: break;
}
case Key: return (rec->type == MessageTableEntry::Sent ? Sent : Received) + rec->from_address + QString::number(rec->sent_datetime.toTime_t());
}
break;
case Qt::EditRole:
if(index.column() == Key)
return (rec->type == MessageTableEntry::Sent ? Sent : Received) + rec->from_address + QString::number(rec->sent_datetime.toTime_t());
break;
case KeyRole: return QVariant::fromValue(rec->vchKey);
case TypeRole: return rec->type;
case SentDateRole: return rec->sent_datetime;
case ReceivedDateRole: return rec->received_datetime;
case FromAddressRole: return rec->from_address;
case ToAddressRole: return rec->to_address;
case FilterAddressRole: return (rec->type == MessageTableEntry::Sent ? rec->to_address + rec->from_address : rec->from_address + rec->to_address);
case LabelRole: return rec->label;
case MessageRole: return rec->message;
case ShortMessageRole: return rec->message; // TODO: Short message
case ReadRole: return rec->read;
case HTMLRole: return rec->received_datetime.toString() + "<br>" + (rec->label.isEmpty() ? rec->from_address : rec->label) + "<br>" + rec->message;
case Ambiguous:
int it;
for (it = 0; it<ambiguous.length(); it++) {
if(ambiguous[it] == (rec->type == MessageTableEntry::Sent ? rec->to_address + rec->from_address : rec->from_address + rec->to_address))
return false;
}
QString address = (rec->type == MessageTableEntry::Sent ? rec->to_address + rec->from_address : rec->from_address + rec->to_address);
ambiguous.append(address);
return "true";
break;
}
return QVariant();
}
QVariant MessageModel::headerData(int section, Qt::Orientation orientation, int role) const
{
return (orientation == Qt::Horizontal && role == Qt::DisplayRole ? columns[section] : QVariant());
}
Qt::ItemFlags MessageModel::flags(const QModelIndex & index) const
{
if(index.isValid())
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return 0;
}
QModelIndex MessageModel::index(int row, int column, const QModelIndex & parent) const
{
Q_UNUSED(parent);
MessageTableEntry *data = priv->index(row);
return (data ? createIndex(row, column, priv->index(row)) : QModelIndex());
}
bool MessageModel::removeRows(int row, int count, const QModelIndex & parent)
{
MessageTableEntry *rec = priv->index(row);
if(count != 1 || !rec)
// Can only remove one row at a time, and cannot remove rows not in model.
return false;
{
LOCK(cs_smsgDB);
SecMsgDB dbSmsg;
if (!dbSmsg.Open("cr+"))
//throw runtime_error("Could not open DB.");
return false;
dbSmsg.EraseSmesg(&rec->vchKey[0]);
}
beginRemoveRows(parent, row, row);
priv->cachedMessageTable.removeAt(row);
endRemoveRows();
return true;
}
void MessageModel::newMessage(const SecMsgStored &smsgInbox)
{
priv->newMessage(smsgInbox);
}
void MessageModel::newOutboxMessage(const SecMsgStored &smsgOutbox)
{
priv->newOutboxMessage(smsgOutbox);
}
void MessageModel::setEncryptionStatus(int status)
{
// We're only interested in NotifySecMsgWalletUnlocked when unlocked, as its called after new messagse are processed
if(status == WalletModel::Unlocked && QObject::sender()!=NULL)
return;
priv->refreshMessageTable();
//reset(); // reload table view
}
void MessageModel::walletUnlocked()
{
priv->walletUnlocked();
}
bool MessageModel::markMessageAsRead(const QString &key) const
{
return priv->markAsRead(lookupMessage(key));
}
int MessageModel::lookupMessage(const QString &key) const
{
QModelIndexList lst = match(index(0, Key, QModelIndex()), Qt::EditRole, key, 1, Qt::MatchExactly);
if(lst.isEmpty())
return -1;
else
return lst.at(0).row();
}
static void NotifySecMsgInbox(MessageModel *messageModel, SecMsgStored inboxHdr)
{
// Too noisy: OutputDebugStringF("NotifySecMsgInboxChanged %s\n", message);
QMetaObject::invokeMethod(messageModel, "newMessage", Qt::QueuedConnection,
Q_ARG(SecMsgStored, inboxHdr));
}
static void NotifySecMsgOutbox(MessageModel *messageModel, SecMsgStored outboxHdr)
{
QMetaObject::invokeMethod(messageModel, "newOutboxMessage", Qt::QueuedConnection,
Q_ARG(SecMsgStored, outboxHdr));
}
static void NotifySecMsgWallet(MessageModel *messageModel)
{
QMetaObject::invokeMethod(messageModel, "walletUnlocked", Qt::QueuedConnection);
}
void MessageModel::subscribeToCoreSignals()
{
qRegisterMetaType<SecMsgStored>("SecMsgStored");
// Connect signals
NotifySecMsgInboxChanged.connect(boost::bind(NotifySecMsgInbox, this, _1));
NotifySecMsgOutboxChanged.connect(boost::bind(NotifySecMsgOutbox, this, _1));
NotifySecMsgWalletUnlocked.connect(boost::bind(NotifySecMsgWallet, this));
connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int)));
}
void MessageModel::unsubscribeFromCoreSignals()
{
// Disconnect signals
NotifySecMsgInboxChanged.disconnect(boost::bind(NotifySecMsgInbox, this, _1));
NotifySecMsgOutboxChanged.disconnect(boost::bind(NotifySecMsgOutbox, this, _1));
NotifySecMsgWalletUnlocked.disconnect(boost::bind(NotifySecMsgWallet, this));
disconnect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int)));
}
// InvoiceTableModel
InvoiceTableModel::InvoiceTableModel(MessageTablePriv *priv, QObject *parent) :
QAbstractTableModel(parent), priv(priv), invoiceItemTableModel(0)
{
columns << tr("Type") << tr("Sent Date Time") << tr("Recieved Date Time") << tr("Label") << tr("To Address") << tr("From Address") << tr("Invoice No.") << tr("Due Date") << "Invoice Amount" << "Amount Paid" << "Amount Outstanding";
invoiceItemTableModel = new InvoiceItemTableModel(priv, parent);
}
InvoiceTableModel::~InvoiceTableModel()
{
delete invoiceItemTableModel;
}
MessageModel *InvoiceTableModel::getMessageModel()
{
return priv->parent;
}
InvoiceItemTableModel *InvoiceTableModel::getInvoiceItemTableModel()
{
return invoiceItemTableModel;
}
void InvoiceTableModel::newInvoice(QString CompanyInfoLeft,
QString CompanyInfoRight,
QString BillingInfoLeft,
QString BillingInfoRight,
QString Footer,
QDate DueDate,
QString InvoiceNumber)
{
InvoiceTableEntry invoice(true);
invoice.company_info_left = CompanyInfoLeft;
invoice.company_info_right = CompanyInfoRight;
invoice.billing_info_left = BillingInfoLeft;
invoice.billing_info_right = BillingInfoRight;
invoice.footer = Footer;
invoice.due_date = DueDate;
invoice.invoice_number = InvoiceNumber;
priv->newInvoice(invoice);
}
void InvoiceTableModel::newInvoiceItem()
{
priv->newInvoiceItem();
}
void InvoiceTableModel::newReceipt(QString InvoiceNumber, CAmount ReceiptAmount)
{
ReceiptTableEntry receipt(true);
receipt.invoice_number = InvoiceNumber;
receipt.amount = ReceiptAmount;
priv->newReceipt(receipt);
}
QString InvoiceTableModel::getInvoiceJSON(const int row)
{
return priv->getInvoiceJSON(row);
}
int InvoiceTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->cachedInvoiceTable.size();
}
int InvoiceTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant InvoiceTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
InvoiceTableEntry *rec;
int64_t total;
if(role != Qt::TextAlignmentRole)
rec = static_cast<InvoiceTableEntry*>(index.internalPointer());
switch(role)
{
case Qt::DisplayRole:
switch(index.column())
{
case Label: return (rec->label.isEmpty() ? tr("(no label)") : rec->label);
case ToAddress: return rec->to_address;
case FromAddress: return rec->from_address;
case SentDateTime: return rec->sent_datetime;
case ReceivedDateTime: return rec->received_datetime;
case CompanyInfoLeft: return rec->company_info_left;
case CompanyInfoRight: return rec->company_info_right;
case BillingInfoLeft: return rec->billing_info_left;
case BillingInfoRight: return rec->billing_info_right;
case Footer: return rec->footer;
case InvoiceNumber: return rec->invoice_number;
case DueDate: return rec->due_date;
case Paid: return 0; // TODO: Calculate Paid
case Outstanding: return 0; // TODO: Calculate Outstanding
case Type:
switch(rec->type)
{
case MessageTableEntry::Sent: return MessageModel::Sent;
case MessageTableEntry::Received: return MessageModel::Received;
}
case Total:
total = priv->getTotal(rec->vchKey);
return BitcreditUnits::formatWithUnit(priv->parent->getOptionsModel()->getDisplayUnit(), total);
break;
default: break;
}
break;
case Qt::TextAlignmentRole:
switch(index.column())
{
case InvoiceNumber:
case Total:
case Paid:
case Outstanding:
return Qt::AlignRight;
default: break;
}
break;
case Qt::UserRole:
switch(index.column())
{
case Type:
switch(rec->type)
{
case MessageTableEntry::Sent: return MessageModel::Sent;
case MessageTableEntry::Received: return MessageModel::Received;
}
default:
return QString((char*)&rec->vchKey[0]) + QString::number(rec->type);
}
}
return QVariant();
}
/*
bool InvoiceTableModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
if(!index.isValid())
return false;
qDebug() << value << index;
InvoiceTableEntry *rec = static_cast<InvoiceTableEntry*>(index.internalPointer());
//editStatus = OK;
if(role == Qt::EditRole)
{
qDebug() << value << index;
switch(index.column())
{
case InvoiceNumber: rec->invoice_number = value.toString(); break;
case DueDate: rec->due_date = value.toDate(); break;
case CompanyInfoLeft: rec->company_info_left = value.toString(); break;
case CompanyInfoRight: rec->company_info_right = value.toString(); break;
case BillingInfoLeft: rec->billing_info_left = value.toString(); break;
case BillingInfoRight: rec->billing_info_right = value.toString(); break;
case Footer: rec->footer = value.toString(); break;
}
return true;
}
return false;
}
void InvoiceTableModel::setData(const int row, const int col, const QVariant & value)
{
InvoiceTableEntry rec = priv->cachedInvoiceTable.at(row);
qDebug() << value << col;
switch(col)
{
case InvoiceNumber: rec.invoice_number = value.toString(); break;
case DueDate: rec.due_date = value.toDate(); break;
case CompanyInfoLeft: rec.company_info_left = value.toString(); break;
case CompanyInfoRight: rec.company_info_right = value.toString(); break;
case BillingInfoLeft: rec.billing_info_left = value.toString(); break;
case BillingInfoRight: rec.billing_info_right = value.toString(); break;
case Footer: rec.footer = value.toString(); break;
}
}
*/
QVariant InvoiceTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
return (orientation == Qt::Horizontal && role == Qt::DisplayRole ? columns[section] : QVariant());
}
Qt::ItemFlags InvoiceTableModel::flags(const QModelIndex & index) const
{
if(index.isValid())
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return 0;
}
QModelIndex InvoiceTableModel::index(int row, int column, const QModelIndex & parent) const
{
Q_UNUSED(parent);
return (row >= 0 && row < priv->cachedInvoiceTable.size() ? createIndex(row, column, &priv->cachedInvoiceTable[row]) : QModelIndex());
}
bool InvoiceTableModel::removeRows(int row, int count, const QModelIndex & parent)
{
if(count != 1 || !(row >= 0 && row < priv->cachedInvoiceTable.size()))
// Can only remove one row at a time, and cannot remove rows not in model.
// Also refuse to remove receiving addresses.
return false;
InvoiceTableEntry rec = priv->cachedInvoiceTable.at(row);
for (int i = 0; i < priv->cachedInvoiceItemTable.size(); i++)
if(priv->cachedInvoiceItemTable[i].vchKey == rec.vchKey && priv->cachedInvoiceItemTable[i].type == rec.type)
invoiceItemTableModel->removeRow(i);
if(rec.type == MessageTableEntry::Received)
{
LOCK(cs_smsgDB);
SecMsgDB dbSmsg;
dbSmsg.EraseSmesg(&rec.vchKey[0]);
} else
if(rec.type == MessageTableEntry::Sent)
{
LOCK(cs_smsgDB);
SecMsgDB dbSmsg;
dbSmsg.EraseSmesg(&rec.vchKey[0]);
}
beginRemoveRows(parent, row, row);
priv->cachedInvoiceTable.removeAt(row);
endRemoveRows();
return true;
}
// InvoiceItemTableModel
InvoiceItemTableModel::InvoiceItemTableModel(MessageTablePriv *priv, QObject *parent) :
QAbstractTableModel(parent), priv(priv)
{
columns << tr("Type") << tr("Code") << tr("Description") << tr("Quantity") << tr("Price") /*<< tr("Tax")*/ << tr("Amount");
}
InvoiceItemTableModel::~InvoiceItemTableModel()
{
}
int InvoiceItemTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->cachedInvoiceItemTable.size();
}
int InvoiceItemTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant InvoiceItemTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
InvoiceItemTableEntry *rec;
if(role != Qt::TextAlignmentRole)
rec = static_cast<InvoiceItemTableEntry*>(index.internalPointer());
switch(role)
{
case Qt::DisplayRole:
switch(index.column())
{
case Code:
return rec->code;
case Description:
return rec->description;
case Quantity:
return rec->quantity;
//case Tax:
// return rec->tax;
case Price:
return BitcreditUnits::formatWithUnit(priv->parent->getOptionsModel()->getDisplayUnit(), rec->price);
case Amount:
return BitcreditUnits::formatWithUnit(priv->parent->getOptionsModel()->getDisplayUnit(), (rec->quantity * rec->price));
case Type:
switch(rec->type)
{
case MessageTableEntry::Sent: return MessageModel::Sent;
case MessageTableEntry::Received: return MessageModel::Received;
}
}
break;
case Qt::EditRole:
switch(index.column())
{
case Code:
return rec->code;
case Description:
return rec->description;
case Quantity:
return rec->quantity;
//case Tax:
// return rec->tax;
case Price:
return BitcreditUnits::format(priv->parent->getOptionsModel()->getDisplayUnit(), rec->price);
case Amount:
return (qint64)rec->quantity * rec->price;
}
break;
case Qt::TextAlignmentRole:
switch(index.column())
{
case Quantity:
//case Tax:
case Price:
case Amount:
return Qt::AlignRight;
default: break;
}
break;
case Qt::UserRole:
return QString((char*)&rec->vchKey[0]) + QString::number(rec->type);
}
return QVariant();
}
bool InvoiceItemTableModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
if(!index.isValid())
return false;
InvoiceItemTableEntry *rec = static_cast<InvoiceItemTableEntry*>(index.internalPointer());
if(role == Qt::EditRole)
{
switch(index.column())
{
case Code: rec->code = value.toString(); break;
case Description: rec->description = value.toString(); break;
case Quantity:
rec->quantity = value.toInt();
emitDataChanged(index.row());
break;
case Price:
BitcreditUnits::parse(priv->parent->getOptionsModel()->getDisplayUnit(), value.toString(), &rec->price);
emitDataChanged(index.row());
break;
}
return true;
}
return false;
}
QVariant InvoiceItemTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
return (orientation == Qt::Horizontal && role == Qt::DisplayRole ? columns[section] : QVariant());
}
Qt::ItemFlags InvoiceItemTableModel::flags(const QModelIndex & index) const
{
if(index.isValid())
{
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
if(index.column() != Amount)
retval |= Qt::ItemIsEditable;
return retval;
}
return 0;
}
QModelIndex InvoiceItemTableModel::index(int row, int column, const QModelIndex & parent) const
{
Q_UNUSED(parent);
return (row >= 0 && row < priv->cachedInvoiceItemTable.size() ? createIndex(row, column, &priv->cachedInvoiceItemTable[row]) : QModelIndex());
}
bool InvoiceItemTableModel::removeRows(int row, int count, const QModelIndex & parent)
{
if(count != 1 || !(row >= 0 && row < priv->cachedInvoiceItemTable.size()))
// Can only remove one row at a time, and cannot remove rows not in model.
// Also refuse to remove receiving addresses.
return false;
beginRemoveRows(parent, row, row);
priv->cachedInvoiceItemTable.removeAt(row);
endRemoveRows();
return true;
}
void InvoiceItemTableModel::emitDataChanged(const int idx)
{
emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
}
// ReceiptTableModel
ReceiptTableModel::ReceiptTableModel(MessageTablePriv *priv, QObject *parent) :
QAbstractTableModel(parent), priv(priv)
{
columns << tr("Type") << tr("Sent Date Time") << tr("Recieved Date Time") << tr("Label") << tr("To Address") << tr("From Address") << tr("Invoice No.") << "Receipt Amount" << "Amount Outstanding";
}
ReceiptTableModel::~ReceiptTableModel()
{
}
QString ReceiptTableModel::getReceiptJSON(const int row)
{
return priv->getReceiptJSON(row);
}
int ReceiptTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->cachedReceiptTable.size();
}
int ReceiptTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant ReceiptTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
ReceiptTableEntry *rec;
if(role != Qt::TextAlignmentRole)
rec = static_cast<ReceiptTableEntry*>(index.internalPointer());
switch(role)
{
case Qt::DisplayRole:
switch(index.column())
{
case Label: return (rec->label.isEmpty() ? tr("(no label)") : rec->label);
case ToAddress: return rec->to_address;
case FromAddress: return rec->from_address;
case SentDateTime: return rec->sent_datetime;
case ReceivedDateTime: return rec->received_datetime;
case InvoiceNumber: return rec->invoice_number;
case Amount: return BitcreditUnits::formatWithUnit(priv->parent->getOptionsModel()->getDisplayUnit(), rec->amount);
case Type:
switch(rec->type)
{
case MessageTableEntry::Sent: return MessageModel::Sent;
case MessageTableEntry::Received: return MessageModel::Received;
}
default: break;
}
break;
case Qt::TextAlignmentRole:
switch(index.column())
{
case InvoiceNumber:
case Amount:
return Qt::AlignRight;
default: break;
}
break;
case Qt::UserRole:
switch(index.column())
{
case Type:
switch(rec->type)
{
case MessageTableEntry::Sent: return MessageModel::Sent;
case MessageTableEntry::Received: return MessageModel::Received;
}
default:
return QString((char*)&rec->vchKey[0]) + QString::number(rec->type);
}
}
return QVariant();
}
/*
bool ReceiptTableModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
if(!index.isValid())
return false;
qDebug() << value << index;
InvoiceTableEntry *rec = static_cast<InvoiceTableEntry*>(index.internalPointer());
//editStatus = OK;
if(role == Qt::EditRole)
{
qDebug() << value << index;
switch(index.column())
{
case InvoiceNumber: rec->invoice_number = value.toString(); break;
case DueDate: rec->due_date = value.toDate(); break;
case CompanyInfoLeft: rec->company_info_left = value.toString(); break;
case CompanyInfoRight: rec->company_info_right = value.toString(); break;
case BillingInfoLeft: rec->billing_info_left = value.toString(); break;
case BillingInfoRight: rec->billing_info_right = value.toString(); break;
case Footer: rec->footer = value.toString(); break;
}
return true;
}
return false;
}
void ReceiptTableModel::setData(const int row, const int col, const QVariant & value)
{
InvoiceTableEntry rec = priv->cachedInvoiceTable.at(row);
qDebug() << value << col;
switch(col)
{
case InvoiceNumber: rec.invoice_number = value.toString(); break;
case DueDate: rec.due_date = value.toDate(); break;
case CompanyInfoLeft: rec.company_info_left = value.toString(); break;
case CompanyInfoRight: rec.company_info_right = value.toString(); break;
case BillingInfoLeft: rec.billing_info_left = value.toString(); break;
case BillingInfoRight: rec.billing_info_right = value.toString(); break;
case Footer: rec.footer = value.toString(); break;
}
}
*/
QVariant ReceiptTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
return (orientation == Qt::Horizontal && role == Qt::DisplayRole ? columns[section] : QVariant());
}
Qt::ItemFlags ReceiptTableModel::flags(const QModelIndex & index) const
{
if(index.isValid())
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return 0;
}
QModelIndex ReceiptTableModel::index(int row, int column, const QModelIndex & parent) const
{
Q_UNUSED(parent);
return (row >= 0 && row < priv->cachedReceiptTable.size() ? createIndex(row, column, &priv->cachedReceiptTable[row]) : QModelIndex());
}
bool ReceiptTableModel::removeRows(int row, int count, const QModelIndex & parent)
{
if(count != 1 || !(row >= 0 && row < priv->cachedReceiptTable.size()))
// Can only remove one row at a time, and cannot remove rows not in model.
return false;
ReceiptTableEntry rec = priv->cachedReceiptTable.at(row);
if(rec.type == MessageTableEntry::Received)
{
LOCK(cs_smsgDB);
SecMsgDB dbSmsg;
dbSmsg.EraseSmesg(&rec.vchKey[0]);
} else
if(rec.type == MessageTableEntry::Sent)
{
LOCK(cs_smsgDB);
SecMsgDB dbSmsg;
dbSmsg.EraseSmesg(&rec.vchKey[0]);
}
beginRemoveRows(parent, row, row);
priv->cachedReceiptTable.removeAt(row);
endRemoveRows();
return true;
}
<file_sep>#include "rpcserver.h"
#include "trust.h"
#include "json/json_spirit_value.h"
#include "sync.h"
#include "util.h"
using namespace json_spirit;
Value gettrust(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettrust <ChainID>\n"
"Returns an object containing information about a ChainID's trust and credit scores\n"
"This should be used for debugging/confirmation purposes only; this is a resource intensive\n"
"operation and may slow down wallet operation, especially on smaller computers.\n"
"\nExamples:\n"
+ HelpExampleCli("gettrust", "61Xw5qzVvbvumfKMUDcRYpzq4ELzCPnP1N")
+ HelpExampleRpc("gettrust", "6<KEY>")
);
string search =params[0].get_str().c_str();
Object o;
sqlite3 *rawdb;
sqlite3_stmt *stmt;
char *zErrMsg = 0;
int rc;
const char *sql;
rc = sqlite3_open((GetDataDir() / "ratings/rawdata.db").string().c_str(), &rawdb);
if( rc ){
if (fDebug) LogPrintf("Can't open database: %s\n", sqlite3_errmsg(rawdb));
}else{
if (fDebug) LogPrintf("Opened database successfully\n");
}
sql="select * from RAWDATA where ADDRESS = ?";
rc = sqlite3_prepare(rawdb,sql, strlen(sql), &stmt, 0 );
sqlite3_bind_text(stmt, 1,search.data(), search.size(), 0);
int64_t balance, outgoingtx, firstuse, incomingtx, totalinputs, totaloutputs;
double avedailyincome;
double trust=0;
if (sqlite3_step(stmt) == SQLITE_ROW){
balance = (sqlite3_column_int(stmt, 1))/COIN;
firstuse = sqlite3_column_int(stmt, 2);
incomingtx = sqlite3_column_int(stmt, 3);
outgoingtx = sqlite3_column_int(stmt, 4);
totalinputs = sqlite3_column_int(stmt, 5);
totaloutputs = sqlite3_column_int(stmt, 6);
int64_t totaltx= incomingtx+outgoingtx;
double globallife = (GetTime()- 1418504572)/24*3600;
double lifetime = (GetTime() - firstuse)/24*3600;
int64_t totalnettx = chainActive.Tip()->nChainTx;
double txfreq = totaltx/lifetime;
double nettxfreq = totalnettx / globallife;
double spendfactor = balance/totaloutputs;
double savefactor;
if (totalinputs !=0)
savefactor =balance/totalinputs;
else
savefactor = 0;
double nettxpart = totaltx/ totalnettx;
double aveinput = totalinputs/ incomingtx;
double aveoutput = totaloutputs / outgoingtx;
avedailyincome = totalinputs / lifetime;
double avedailyexpenditure = totaloutputs / lifetime;
{
{
if (lifetime > 360 )
trust+= 20;
else if (lifetime > 30 && lifetime < 360 )
trust+= lifetime*0.055;
else
trust+= 0;
}
{
if (totaltx > 10000){
trust+= 10;
}
else if (totaltx>0 && totaltx< 10000){
trust+= totaltx*0.001;
}
else
trust+= 0;
}
{
if(balance > 1000000){
trust+= 25;
}
else if(balance > 0 && balance <= 1000000){
trust+= balance/50000;
}
else
trust+= 0;
}
{
if (txfreq > 5)
trust+=15;
else if (txfreq> 0.01 && txfreq< 5)
trust+= txfreq *3;
else
trust+= 0;
}
{
if (savefactor > 0.1)
trust+=20;
else if (savefactor> 0.001 && savefactor< 0.1)
trust+= savefactor *200;
else
trust+= 0;
}
{
if (avedailyincome > 100)
trust+=20;
else if (avedailyincome > 1 && avedailyincome< 100)
trust+= avedailyincome/5;
else
trust+= 0;
}
{
int count = 0;
char* minerquery = sqlite3_mprintf("select count(*) from BLOCKS where MINER = '%q'",search.c_str());
rc = sqlite3_exec(rawdb, minerquery, callback, &count, &zErrMsg);
double points = count/chainActive.Tip()->nHeight;
if (points > 0.01 )
trust+= 20;
else if (points > 0.0001 && points < 0.01)
trust+= points*190;
else
trust+= 0;
}
}
}
o.push_back(Pair("ChainID", search));
o.push_back(Pair("Trust Rating", trust));
o.push_back(Pair("Balance", balance));
o.push_back(Pair("Daily Income", avedailyincome));
//o.push_back(Pair("Credit Rating", credit));
//o.push_back(Pair("Votes", votes));
//o.push_back(Pair("Blacklisted", fBlacklisted));
return o;
}
<file_sep>// Copyright (c) 2010 <NAME>
// Copyright (c) 2009-2012 The Bitcredit developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Copyright (c) 2013-2014 Memorycoin Dev Team
#include "votecoinsdialog.h"
#include "ui_votecoinsdialog.h"
#include "walletmodel.h"
#include "bitcreditunits.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "votecoinsentry.h"
#include "guiutil.h"
#include "askpassphrasedialog.h"
#include "base58.h"
#include "clientmodel.h"
#include <QMessageBox>
#include <QTextDocument>
#include <QScrollBar>
VoteCoinsDialog::VoteCoinsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::VoteCoinsDialog),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
fNewRecipientAllowed = true;
//this->setStyleSheet("background-image:url(:/images/background);");
}
void VoteCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
for(int i = 0; i < ui->entries->count(); ++i)
{
VoteCoinsEntry *entry = qobject_cast<VoteCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(model);
}
}
if(model && model->getOptionsModel())
{
}
}
VoteCoinsDialog::~VoteCoinsDialog()
{
delete ui;
}
void VoteCoinsDialog::on_sendButton_clicked(){
QList<SendCoinsRecipient> recipients;
bool valid = true;
if(!model)
return;
for(int i = 0; i < ui->entries->count(); ++i)
{
VoteCoinsEntry *entry = qobject_cast<VoteCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
// Format confirmation message
QStringList formatted;
foreach(const SendCoinsRecipient &rcp, recipients)
{
#if QT_VERSION >= 0x050000
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcreditUnits::formatWithUnit(BitcreditUnits::BCR, rcp.amount), rcp.label.toHtmlEscaped(), rcp.address));
#else
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcreditUnits::formatWithUnit(BitcreditUnits::BCR, rcp.amount), Qt::escape(rcp.label), rcp.address));
#endif
}
fNewRecipientAllowed = false;
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
WalletModelTransaction currentTransaction(recipients);
WalletModel::SendCoinsReturn prepareStatus;
processSendCoinsReturn(prepareStatus,
BitcreditUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()));
WalletModel::SendCoinsReturn sendstatus = model->sendCoins(currentTransaction);
processSendCoinsReturn(sendstatus);
if (sendstatus.status == WalletModel::OK)
{
accept();
}
fNewRecipientAllowed = true;
}
void VoteCoinsDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
{
delete ui->entries->takeAt(0)->widget();
}
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void VoteCoinsDialog::reject()
{
clear();
}
void VoteCoinsDialog::accept()
{
clear();
}
VoteCoinsEntry *VoteCoinsDialog::addEntry()
{
VoteCoinsEntry *entry = new VoteCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(VoteCoinsEntry*)), this, SLOT(removeEntry(VoteCoinsEntry*)));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
qApp->processEvents();
return entry;
}
void VoteCoinsDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
VoteCoinsEntry *entry = qobject_cast<VoteCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setRemoveEnabled(enabled);
}
}
}
void VoteCoinsDialog::removeEntry(VoteCoinsEntry* entry)
{
delete entry;
updateRemoveEnabled();
}
void VoteCoinsDialog::setAddress(const QString &address)
{
VoteCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
VoteCoinsEntry *first = qobject_cast<VoteCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setAddress(address);
}
void VoteCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
VoteCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
VoteCoinsEntry *first = qobject_cast<VoteCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
}
void VoteCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn &sendCoinsReturn, const QString &msgArg)
{
QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams;
// Default to a warning message, override if error message is needed
msgParams.second = CClientUIInterface::MSG_WARNING;
// This comment is specific to SendCoinsDialog usage of WalletModel::SendCoinsReturn.
// WalletModel::TransactionCommitFailed is used only in WalletModel::sendCoins()
// all others are used only in WalletModel::prepareTransaction()
switch(sendCoinsReturn.status)
{
case WalletModel::InvalidAddress:
msgParams.first = tr("The recipient address is not valid, please recheck.");
break;
case WalletModel::InvalidAmount:
msgParams.first = tr("The amount to pay must be larger than 0.");
break;
case WalletModel::AmountExceedsBalance:
msgParams.first = tr("The amount exceeds your balance.");
break;
case WalletModel::AmountWithFeeExceedsBalance:
msgParams.first = tr("The total exceeds your balance when the %1 transaction fee is included.").arg(msgArg);
break;
case WalletModel::DuplicateAddress:
msgParams.first = tr("Duplicate address found, can only send to each address once per send operation.");
break;
case WalletModel::TransactionCreationFailed:
msgParams.first = tr("Transaction creation failed!");
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
case WalletModel::TransactionCommitFailed:
msgParams.first = tr("The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
case WalletModel::AnonymizeOnlyUnlocked:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The wallet was unlocked only to anonymize coins."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InsaneFee:
msgParams.first = tr("A fee higher than %1 is considered an insanely high fee.").arg(BitcreditUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), 1000000));
break;
// included to prevent a compiler warning.
case WalletModel::OK:
default:
return;
}
//emit message(tr("Send Coins"), msgParams.first, msgParams.second);
}
<file_sep>#ifndef TRUST_ENGINE_H
#define TRUST_ENGINE_H
#include <stdio.h>
#include <algorithm>
#include <exception>
#include <map>
#include <set>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
#include <boost/unordered_map.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/thread.hpp>
#include <sqlite3.h>
using namespace std;
extern int callback(void *NotUsed, int argc, char **argv, char **azColName);
class TrustEngine
{
public:
void createdb();
};
#endif
<file_sep>#ifndef INVOICEITEMMODEL_H
#define INVOICEITEMMODEL_H
#endif // INVOICEITEMMODEL_H
<file_sep># colorcore
all in one colorcore wallet functionality
<file_sep>// Copyright (c) 2014-2015 The Bitcredit Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcconsole.h"
#include "ui_rpcconsole.h"
#include "addeditadrenalinenode.h"
#include "adrenalinenodeconfigdialog.h"
#include "activebasenode.h"
#include "basenodeconfig.h"
#include "basenodeman.h"
#include "bignum.h"
#include "walletdb.h"
#include "wallet.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "peertablemodel.h"
#include "sync.h"
#include "init.h"
#include "stdio.h"
#include "util.h"
#include "guiutil.h"
#include "intro.h"
#include "bitcreditgui.h"
#include "main.h"
#include "chainparams.h"
#include "rpcserver.h"
#include "rpcclient.h"
#include "basenode.h"
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include <QAbstractItemDelegate>
#include <QPainter>
#include <QTimer>
#include <QDebug>
#include <QScrollArea>
#include <QScroller>
#include <QDateTime>
#include <QApplication>
#include <QClipboard>
#include <QMessageBox>
#include <QPushButton>
#include <QDebug>
#include <QTextStream>
#include <QDir>
#include <QFileInfo>
#include "json/json_spirit_value.h"
#include <openssl/crypto.h>
#ifdef ENABLE_WALLET
#include <db_cxx.h>
#endif
#include <QKeyEvent>
#include <QScrollBar>
#include <QThread>
#include <QTime>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
// TODO: add a scrollback limit, as there is currently none
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_HISTORY = 50;
const QSize ICON_SIZE(24, 24);
const int INITIAL_TRAFFIC_GRAPH_MINS = 30;
const struct {
const char *url;
const char *source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{NULL, NULL}
};
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor : public QObject
{
Q_OBJECT
public slots:
void request(const QString &command);
signals:
void reply(int category, const QString &command);
};
#include "rpcconsole.moc"
/**
* Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
*
* - Arguments are delimited with whitespace
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] args Parsed arguments will be appended to this list
* @param[in] strCommand Command line to split
*/
bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand)
{
enum CmdParseState
{
STATE_EATING_SPACES,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED
} state = STATE_EATING_SPACES;
std::string curarg;
foreach(char ch, strCommand)
{
switch(state)
{
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES: // Handle runs of whitespace
switch(ch)
{
case '"': state = STATE_DOUBLEQUOTED; break;
case '\'': state = STATE_SINGLEQUOTED; break;
case '\\': state = STATE_ESCAPE_OUTER; break;
case ' ': case '\n': case '\t':
if(state == STATE_ARGUMENT) // Space ends argument
{
args.push_back(curarg);
curarg.clear();
}
state = STATE_EATING_SPACES;
break;
default: curarg += ch; state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch(ch)
{
case '\'': state = STATE_ARGUMENT; break;
default: curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch(ch)
{
case '"': state = STATE_ARGUMENT; break;
case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
default: curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch; state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch; state = STATE_DOUBLEQUOTED;
break;
}
}
switch(state) // final state
{
case STATE_EATING_SPACES:
return true;
case STATE_ARGUMENT:
args.push_back(curarg);
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString &command)
{
std::vector<std::string> args;
if(!parseCommandLine(args, command.toStdString()))
{
emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
if(args.empty())
return; // Nothing to do
try
{
std::string strPrint;
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
json_spirit::Value result = tableRPC.execute(
args[0],
RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
// Format result reply
if (result.type() == json_spirit::null_type)
strPrint = "";
else if (result.type() == json_spirit::str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
}
catch (const json_spirit::Object& objError)
{
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
}
catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
}
}
catch (const std::exception& e)
{
emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
extern json_spirit::Value GetNetworkHashPS(int lookup, int height);
RPCConsole::RPCConsole(QWidget *parent) :
QWidget(parent),
ui(new Ui::RPCConsole),
clientModel(0),
historyPtr(0),
cachedNodeid(-1)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this);
#ifndef Q_OS_MAC
ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
#endif
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
ui->messagesWidget->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));
// set library version labels
ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
#ifdef ENABLE_WALLET
ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
#else
ui->label_berkeleyDBVersion->hide();
ui->berkeleyDBVersion->hide();
#endif
startExecutor();
setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);
ui->detailWidget->hide();
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
subscribeToCoreSignals();
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateNodeList()));
timer->start(30000);
int nThreads = boost::thread::hardware_concurrency();
int nUseThreads = GetArg("-genproclimit", -1);
if (nUseThreads < 0)
nUseThreads = nThreads;
ui->sliderCores->setMinimum(0);
ui->sliderCores->setMaximum(nThreads);
ui->sliderCores->setValue(nUseThreads);
ui->labelNCores->setText(QString("%1").arg(nUseThreads));
// setup Plot
// create graph
ui->diffplot_difficulty->addGraph();
// Use usual background
ui->diffplot_difficulty->setBackground(QBrush(QColor(255,255,255,255)));//QWidget::palette().color(this->backgroundRole())));
// give the axes some labels:
ui->diffplot_difficulty->xAxis->setLabel(tr("Blocks"));
ui->diffplot_difficulty->yAxis->setLabel(tr("Difficulty"));
// set the pens
//a13469
ui->diffplot_difficulty->graph(0)->setPen(QPen(QColor(161, 52, 105), 3, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin));//QPen(QColor(76, 76, 229)));
ui->diffplot_difficulty->graph(0)->setLineStyle(QCPGraph::lsLine);
// set axes label fonts:
QFont label = font();
ui->diffplot_difficulty->xAxis->setLabelFont(label);
ui->diffplot_difficulty->yAxis->setLabelFont(label);
// setup Plot
// create graph
ui->diffplot_hashrate->addGraph();
// Use usual background
ui->diffplot_hashrate->setBackground(QBrush(QColor(255,255,255,255)));//QWidget::palette().color(this->backgroundRole())));
// give the axes some labels:
ui->diffplot_hashrate->xAxis->setLabel(tr("Blocks"));
ui->diffplot_hashrate->yAxis->setLabel(tr("Hashrate H/s"));
// set the pens
//a13469, 6c3d94
ui->diffplot_hashrate->graph(0)->setPen(QPen(QColor(108, 61, 148), 3, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin));//QPen(QColor(76, 76, 229)));
ui->diffplot_hashrate->graph(0)->setLineStyle(QCPGraph::lsLine);
// set axes label fonts:
QFont label2 = font();
ui->diffplot_hashrate->xAxis->setLabelFont(label2);
ui->diffplot_hashrate->yAxis->setLabelFont(label2);
connect(ui->sliderCores, SIGNAL(valueChanged(int)), this, SLOT(changeNumberOfCores(int)));
connect(ui->pushSwitchMining, SIGNAL(clicked()), this, SLOT(switchMining()));
model = new QStandardItemModel(0,3,this);
QStringList headerLabels;
headerLabels << "Pattern" << "Privkey" << "Chance";
model->setHorizontalHeaderLabels(headerLabels);
ui->tableView->setModel(model);
ui->tableView->setAlternatingRowColors(true);
ui->tableView->verticalHeader()->setVisible(false);
ui->tableView->horizontalHeader()->setSectionResizeMode(1,QHeaderView::Stretch);
ui->tableView->horizontalHeader()->resizeSection(0,250);
ui->tableView->horizontalHeader()->resizeSection(2,150);
ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);//MultiSelection);
ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(tableViewClicked(QItemSelection,QItemSelection)));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customMenuRequested(QPoint)));
ui->tableView->setFocusPolicy(Qt::StrongFocus);
ui->tableView->installEventFilter(this);
VanityGenKeysChecked = 0;
VanityGenHashrate = 0;//"0.0";
VanityGenNThreads = 0;
VanityGenMatchCase = 0;
//Input field:
ui->vanitylineEdit->setValidator(new QRegExpValidator(QRegExp("(6BCR){1,1}[1-9A-HJ-NP-Za-km-z]{3,3}"), NULL));
ui->vanitylineEdit->setMaxLength(16);
connect(ui->vanitylineEdit, SIGNAL(textChanged(QString)), this, SLOT(changeAllowedText()));
connect(ui->vanitylineEdit, SIGNAL(returnPressed()), this, SLOT(addPatternClicked()));
checkAllowedText(0);
//"Add Pattern" - Buttton:
connect(ui->buttonPattern, SIGNAL(clicked()), this, SLOT(addPatternClicked()));
ui->horizontalSlider->setMaximum(nUseThreads);
ui->checkBoxAutoImport->setEnabled(false);
ui->buttonImport->setEnabled(false);
ui->buttonDelete->setEnabled(false);
connect(ui->checkBoxMatchCase, SIGNAL(clicked(bool)), this, SLOT(changeMatchCase(bool)));
connect(ui->buttonDelete, SIGNAL(clicked(bool)),this, SLOT(deleteRows()));
connect(ui->buttonImport, SIGNAL(clicked(bool)), this, SLOT(importIntoWallet()));
connect(ui->horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(updateLabelNrThreads(int)));
connect(ui->horizontalSlider, SIGNAL(sliderReleased()), this, SLOT(saveFile()));
connect(ui->checkBoxAutoImport, SIGNAL(released()), this, SLOT(saveFile()));
connect(ui->checkBoxShowPrivKeys, SIGNAL(released()), this, SLOT(saveFile()));
connect(ui->buttonStart,SIGNAL(clicked()), this, SLOT(startThread()));
copyAddressAction = new QAction("Copy Address", this);
copyPrivateKeyAction = new QAction("Copy PrivateKey", this);
importIntoWalletAction = new QAction("Import into Wallet", this);
deleteAction = new QAction("Delete", this);
contextMenu = new QMenu();
contextMenu->addAction(importIntoWalletAction);
contextMenu->addSeparator();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyPrivateKeyAction);
contextMenu->addSeparator();
contextMenu->addAction(deleteAction);
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyPrivateKeyAction, SIGNAL(triggered()), this, SLOT(copyPrivateKey()));
connect(importIntoWalletAction, SIGNAL(triggered()), this, SLOT(importIntoWallet()));
connect(deleteAction, SIGNAL(triggered()), this, SLOT(deleteEntry()));
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateVanityGenUI()));
timer->start(250);
updateUi();
loadFile();
startTimer(1500);
updateNodeList();
clear();
}
RPCConsole::~RPCConsole()
{
GUIUtil::saveWindowGeometry("nRPCConsoleWindow", this);
emit stopExecutor();
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
{
if(event->type() == QEvent::KeyPress) // Special key handling
{
QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
int key = keyevt->key();
Qt::KeyboardModifiers mod = keyevt->modifiers();
switch(key)
{
case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
case Qt::Key_PageUp: /* pass paging keys to messages widget */
case Qt::Key_PageDown:
if(obj == ui->lineEdit)
{
QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
return true;
}
break;
default:
// Typing in messages widget brings focus to line edit, and redirects key there
// Exclude most combinations and keys that emit no text, except paste shortcuts
if(obj == ui->messagesWidget && (
(!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
{
ui->lineEdit->setFocus();
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
}
}
return QWidget::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel *model)
{
clientModel = model;
ui->trafficGraph->setClientModel(model);
if(model)
{
// Keep up to date with client
setNumConnections(model->getNumConnections());
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(model->getNumBlocks());
connect(model, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
setBasenodeCount(model->getBasenodeCountString());
connect(model, SIGNAL(strBasenodesChanged(QString)), this, SLOT(setBasenodeCount(QString)));
updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64)));
// set up peer table
ui->peerWidget->setModel(model->getPeerTableModel());
ui->peerWidget->verticalHeader()->hide();
ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->peerWidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
// connect the peerWidget selection model to our peerSelected() handler
connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
this, SLOT(peerSelected(const QItemSelection &, const QItemSelection &)));
connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientName->setText(model->clientName());
ui->buildDate->setText(model->formatBuildDate());
ui->startupTime->setText(model->formatClientStartupTime());
ui->networkName->setText(QString::fromStdString(Params().NetworkIDString()));
}
}
static QString categoryClass(int category)
{
switch(category)
{
case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
case RPCConsole::CMD_ERROR: return "cmd-error"; break;
default: return "misc";
}
}
void RPCConsole::clear()
{
ui->messagesWidget->clear();
history.clear();
historyPtr = 0;
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for(int i=0; ICON_MAPPING[i].url; ++i)
{
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
ui->messagesWidget->document()->setDefaultStyleSheet(
"table { }"
"td.time { color: #808080; padding-top: 3px; } "
"td.message { font-family: monospace; font-size: 12px; } " // Todo: Remove fixed font-size
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
"b { color: #006060; } "
);
message(CMD_REPLY, (tr("Welcome to the Bitcredit Core RPC console.") + "<br>" +
tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")), true);
}
void RPCConsole::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_Return && ui->lineEdit->hasFocus()){
addPatternClicked();
}
if(event->key() == Qt::Key_Delete && !VanityGenRunning)
deleteRows();
if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape)
{
close();
}
}
void RPCConsole::message(int category, const QString &message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if(html)
out += message;
else
out += GUIUtil::HtmlEscape(message, true);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::setNumConnections(int count)
{
if (!clientModel)
return;
QString connections = QString::number(count) + " (";
connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
ui->numberOfConnections->setText(connections);
}
void RPCConsole::setNumBlocks(int count)
{
ui->numberOfBlocks->setText(QString::number(count));
if(clientModel)
ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
}
void RPCConsole::setBasenodeCount(const QString &strBasenodes)
{
ui->basenodeCount->setText(strBasenodes);
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
ui->lineEdit->clear();
if(!cmd.isEmpty())
{
message(CMD_REQUEST, cmd);
emit cmdRequest(cmd);
// Remove command, if already in history
history.removeOne(cmd);
// Append command to history
history.append(cmd);
// Enforce maximum history size
while(history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
historyPtr += offset;
if(historyPtr < 0)
historyPtr = 0;
if(historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if(historyPtr < history.size())
cmd = history.at(historyPtr);
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
QThread *thread = new QThread;
RPCExecutor *executor = new RPCExecutor();
executor->moveToThread(thread);
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - queue executor for deletion (in execution thread)
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
// Queue the thread for deletion (in this thread) when it is finished
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread->start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if(ui->tabWidget->widget(index) == ui->tab_console)
{
ui->lineEdit->setFocus();
}
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_sldGraphRange_valueChanged(int value)
{
const int multiplier = 5; // each position on the slider represents 5 min
int mins = value * multiplier;
setTrafficGraphRange(mins);
}
QString RPCConsole::FormatBytes(quint64 bytes)
{
if(bytes < 1024)
return QString(tr("%1 B")).arg(bytes);
if(bytes < 1024 * 1024)
return QString(tr("%1 KB")).arg(bytes / 1024);
if(bytes < 1024 * 1024 * 1024)
return QString(tr("%1 MB")).arg(bytes / 1024 / 1024);
return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
}
void RPCConsole::setTrafficGraphRange(int mins)
{
ui->trafficGraph->setGraphRangeMins(mins);
ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
}
void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
{
ui->lblBytesIn->setText(FormatBytes(totalBytesIn));
ui->lblBytesOut->setText(FormatBytes(totalBytesOut));
}
void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected)
{
Q_UNUSED(deselected);
if (!clientModel || selected.indexes().isEmpty())
return;
const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::peerLayoutChanged()
{
if (!clientModel)
return;
const CNodeCombinedStats *stats = NULL;
bool fUnselect = false;
bool fReselect = false;
if (cachedNodeid == -1) // no node selected yet
return;
// find the currently selected row
int selectedRow;
QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
if (selectedModelIndex.isEmpty())
selectedRow = -1;
else
selectedRow = selectedModelIndex.first().row();
// check if our detail node has a row in the table (it may not necessarily
// be at selectedRow since its position can change after a layout change)
int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeid);
if (detailNodeRow < 0)
{
// detail node dissapeared from table (node disconnected)
fUnselect = true;
cachedNodeid = -1;
ui->detailWidget->hide();
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
}
else
{
if (detailNodeRow != selectedRow)
{
// detail node moved position
fUnselect = true;
fReselect = true;
}
// get fresh stats on the detail node.
stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
}
if (fUnselect && selectedRow >= 0)
{
ui->peerWidget->selectionModel()->select(QItemSelection(selectedModelIndex.first(), selectedModelIndex.last()),
QItemSelectionModel::Deselect);
}
if (fReselect)
{
ui->peerWidget->selectRow(detailNodeRow);
}
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::updateNodeDetail(const CNodeCombinedStats *stats)
{
// Update cached nodeid
cachedNodeid = stats->nodeStats.nodeid;
// update the detail ui with latest node information
QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName));
if (!stats->nodeStats.addrLocal.empty())
peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
ui->peerHeading->setText(peerAddrDetails);
ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastSend) : tr("never"));
ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastRecv) : tr("never"));
ui->peerBytesSent->setText(FormatBytes(stats->nodeStats.nSendBytes));
ui->peerBytesRecv->setText(FormatBytes(stats->nodeStats.nRecvBytes));
ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nTimeConnected));
ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
ui->peerVersion->setText(QString("%1").arg(stats->nodeStats.nVersion));
ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
ui->peerHeight->setText(QString("%1").arg(stats->nodeStats.nStartingHeight));
// This check fails for example if the lock was busy and
// nodeStateStats couldn't be fetched.
if (stats->fNodeStateStatsAvailable) {
// Ban score is init to 0
ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));
// Sync height is init to -1
if (stats->nodeStateStats.nSyncHeight > -1)
ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
else
ui->peerSyncHeight->setText(tr("Unknown"));
} else {
ui->peerBanScore->setText(tr("Fetching..."));
ui->peerSyncHeight->setText(tr("Fetching..."));
}
ui->detailWidget->show();
}
void RPCConsole::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
}
void RPCConsole::showEvent(QShowEvent *event)
{
QWidget::showEvent(event);
if (!clientModel)
return;
// start PeerTableModel auto refresh
clientModel->getPeerTableModel()->startAutoRefresh();
}
void RPCConsole::hideEvent(QHideEvent *event)
{
QWidget::hideEvent(event);
if (!clientModel)
return;
// stop PeerTableModel auto refresh
clientModel->getPeerTableModel()->stopAutoRefresh();
}
static void NotifyAdrenalineNodeUpdated(RPCConsole *page, CAdrenalineNodeConfig nodeConfig)
{
// alias, address, privkey, collateral address
QString alias = QString::fromStdString(nodeConfig.sAlias);
QString addr = QString::fromStdString(nodeConfig.sAddress);
QString privkey = QString::fromStdString(nodeConfig.sBasenodePrivKey);
QString collateral = QString::fromStdString(nodeConfig.sCollateralAddress);
QMetaObject::invokeMethod(page, "updateAdrenalineNode", Qt::QueuedConnection,
Q_ARG(QString, alias),
Q_ARG(QString, addr),
Q_ARG(QString, privkey),
Q_ARG(QString, collateral)
);
}
void RPCConsole::subscribeToCoreSignals()
{
// Connect signals to core
uiInterface.NotifyAdrenalineNodeChanged.connect(boost::bind(&NotifyAdrenalineNodeUpdated, this, _1));
}
void RPCConsole::unsubscribeFromCoreSignals()
{
// Disconnect signals from core
uiInterface.NotifyAdrenalineNodeChanged.disconnect(boost::bind(&NotifyAdrenalineNodeUpdated, this, _1));
}
static QString seconds_to_DHMS(quint32 duration)
{
QString res;
int seconds = (int) (duration % 60);
duration /= 60;
int minutes = (int) (duration % 60);
duration /= 60;
int hours = (int) (duration % 24);
int days = (int) (duration / 24);
if((hours == 0)&&(days == 0))
return res.sprintf("%02dm:%02ds", minutes, seconds);
if (days == 0)
return res.sprintf("%02dh:%02dm:%02ds", hours, minutes, seconds);
return res.sprintf("%dd %02dh:%02dm:%02ds", days, hours, minutes, seconds);
}
void RPCConsole::updateNodeList()
{
TRY_LOCK(cs_basenodepayments, lockBasenodes);
if(!lockBasenodes)
return;
ui->countLabel->setText("Updating...");
ui->tableWidget->clearContents();
ui->tableWidget->setRowCount(0);
BOOST_FOREACH(CBasenode mn, mnodeman.vBasenodes)
{
int mnRow = 0;
ui->tableWidget->insertRow(0);
// populate list
// Address, Rank, Active, Active Seconds, Last Seen, Pub Key
QTableWidgetItem *activeItem = new QTableWidgetItem(QString::number(mn.IsEnabled()));
QTableWidgetItem *addressItem = new QTableWidgetItem(QString::fromStdString(mn.addr.ToString()));
QTableWidgetItem *rankItem = new QTableWidgetItem(QString::number(mnodeman.GetBasenodeRank(mn.vin, chainActive.Tip()->nHeight)));
QTableWidgetItem *activeSecondsItem = new QTableWidgetItem(seconds_to_DHMS((qint64)(mn.lastTimeSeen - mn.sigTime)));
QTableWidgetItem *lastSeenItem = new QTableWidgetItem(seconds_to_DHMS((qint64)(GetTime()-mn.lastTimeSeen)));
CScript pubkey;
pubkey =GetScriptForDestination(mn.pubkey.GetID());
CTxDestination address1;
ExtractDestination(pubkey, address1);
CBitcreditAddress address2(address1);
QTableWidgetItem *pubkeyItem = new QTableWidgetItem(QString::fromStdString(address2.ToString()));
ui->tableWidget->setItem(mnRow, 0, addressItem);
ui->tableWidget->setItem(mnRow, 1, rankItem);
ui->tableWidget->setItem(mnRow, 2, activeItem);
ui->tableWidget->setItem(mnRow, 3, activeSecondsItem);
ui->tableWidget->setItem(mnRow, 4, lastSeenItem);
ui->tableWidget->setItem(mnRow, 5, pubkeyItem);
}
// get default datadir and set path to mybasenodes.txt
QString dataDir = getDefaultDataDirectory();
QString path = QDir(dataDir).filePath("mybasenodes.txt");
theme = GetArg("-theme", "");
themestring = QString::fromUtf8(theme.c_str());
//check if file exists
QFileInfo checkFile(path);
if (checkFile.exists() && checkFile.isFile())
{
QFile myTextFile(path);
QStringList myStringList;
if (!myTextFile.open(QIODevice::ReadOnly))
{
QMessageBox::information(0, "Error opening file", myTextFile.errorString());
}
else
{
while(!myTextFile.atEnd())
{
myStringList.append(myTextFile.readLine());
}
myTextFile.close();
}
QString listitems = myStringList.join("");
//search for pubkeys that match those in our list
//ser our own count
ours = 0;
int rows = ui->tableWidget->rowCount();
if (rows >1)
for(int i = 0; i < rows; ++i)
{
QTableWidgetItem *temp = ui->tableWidget->item(i, 5);
QString str1 = temp->text();
//if showMineOnlychecked, hide everything else
if ((!listitems.contains(str1)) && ui->showMineOnly->isChecked())
{
ui->tableWidget->setRowHidden(i, true);
}
//else just change background colour
else if (listitems.contains(str1))
{
//highlight according to stylesheet
if (themestring.contains("orange"))
{
ui->tableWidget->item(i, 5)->setBackgroundColor("#ffa405");
}
else if (themestring.contains("dark"))
{
ui->tableWidget->item(i, 5)->setBackgroundColor("#ffa405");
}
else if (themestring.contains("green"))
{
ui->tableWidget->item(i, 5)->setBackgroundColor("#45f806");
}
else if (themestring.contains("blue"))
{
ui->tableWidget->item(i, 5)->setBackgroundColor("#088af8");
}
else if (themestring.contains("pink"))
{
ui->tableWidget->item(i, 5)->setBackgroundColor("#fb04db");
}
else if (themestring.contains("purple"))
{
ui->tableWidget->item(i, 5)->setBackgroundColor("#cb03d2");
}
else if (themestring.contains("turq"))
{
ui->tableWidget->item(i, 5)->setBackgroundColor("#0ab4dc");
}
//fallback on default
else
{
ui->tableWidget->item(i, 5)->setBackgroundColor("#ffa405");
}
ours += 1;
}
}
QString ourcount = QString::number(ours);
ui->countLabel->setText(QString::number(ui->tableWidget->rowCount()) + " (Mine: " + ourcount + ")");
}
else
{
ui->countLabel->setText(QString::number(ui->tableWidget->rowCount()));
}
}
QString RPCConsole::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
void RPCConsole::setWalletModel(WalletModel *model)
{
this->walletModel = model;
if(model && model->getOptionsModel())
{
}
if (walletModel->getEncryptionStatus() != WalletModel::Locked)
updateUi();
}
void RPCConsole::restartMining(bool fGenerate)
{
int nThreads = ui->sliderCores->value();
mapArgs["-genproclimit"] = QString("%1").arg(nThreads).toUtf8().data();
json_spirit::Array Args;
Args.push_back(fGenerate);
Args.push_back(nThreads);
setgenerate(Args, false);
updateUi();
}
void RPCConsole::changeNumberOfCores(int i)
{
restartMining(GetBoolArg("-gen", false));
}
void RPCConsole::switchMining()
{
restartMining(!GetBoolArg("-gen", false));
}
static QString formatTimeInterval(CBigNum t)
{
enum EUnit { YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NUM_UNITS };
const int SecondsPerUnit[NUM_UNITS] =
{
31556952, // average number of seconds in gregorian year
31556952/12, // average number of seconds in gregorian month
24*60*60, // number of seconds in a day
60*60, // number of seconds in an hour
60, // number of seconds in a minute
1
};
const char* UnitNames[NUM_UNITS] =
{
"year",
"month",
"day",
"hour",
"minute",
"second"
};
if (t > 0xFFFFFFFF)
{
t /= SecondsPerUnit[YEAR];
return QString("%1 years").arg(t.ToString(10).c_str());
}
else
{
unsigned int t32 = t.getuint();
int Values[NUM_UNITS];
for (int i = 0; i < NUM_UNITS; i++)
{
Values[i] = t32/SecondsPerUnit[i];
t32 %= SecondsPerUnit[i];
}
int FirstNonZero = 0;
while (FirstNonZero < NUM_UNITS && Values[FirstNonZero] == 0)
FirstNonZero++;
QString TimeStr;
for (int i = FirstNonZero; i < std::min(FirstNonZero + 3, (int)NUM_UNITS); i++)
{
int Value = Values[i];
TimeStr += QString("%1 %2%3 ").arg(Value).arg(UnitNames[i]).arg((Value == 1)? "" : "s"); // FIXME: this is English specific
}
return TimeStr;
}
}
void RPCConsole::timerEvent(QTimerEvent *)
{
double NetworkHashrate = GetNetworkHashPS(120, -1).get_real();
double Hashrate = GetBoolArg("-gen", false)? gethashespermin(json_spirit::Array(), false).get_real() : 0;
int m = int(Hashrate);
QString NextBlockTime;
if (Hashrate == 0)
NextBlockTime = QChar(L'∞');
else
{
CBigNum Target;
Target.SetCompact(chainActive.Tip()->nBits);
CBigNum ExpectedTime = (CBigNum(1) << 256)/(Target*m);
NextBlockTime = formatTimeInterval(ExpectedTime);
}
ui->labelNethashrate->setNum(NetworkHashrate);
ui->labelYourHashrate->setNum(Hashrate);
ui->labelNextBlock->setText(NextBlockTime);
}
void RPCConsole::updatePlot()
{
static int64_t lastUpdate = 0;
// Double Check to make sure we don't try to update the plot when it is disabled
if(!GetBoolArg("-chart", true)) { return; }
if (GetTime() - lastUpdate < 60) { return; } // This is just so it doesn't redraw rapidly during syncing
int numLookBack = 4320;
double diffMax = 0;
CBlockIndex* pindex = chainActive.Tip();
int height = pindex->nHeight;
int xStart = std::max<int>(height-numLookBack, 0) + 1;
int xEnd = height;
// Start at the end and walk backwards
int i = numLookBack-1;
int x = xEnd;
// This should be a noop if the size is already 2000
vX.resize(numLookBack);
vY.resize(numLookBack);
CBlockIndex* itr = pindex;
while(i >= 0 && itr != NULL)
{
vX[i] = itr->nHeight;
vY[i] = GetDifficulty(itr);
diffMax = std::max<double>(diffMax, vY[i]);
itr = itr->pprev;
i--;
x--;
}
ui->diffplot_difficulty->graph(0)->setData(vX, vY);
// set axes ranges, so we see all data:
ui->diffplot_difficulty->xAxis->setRange((double)xStart, (double)xEnd);
ui->diffplot_difficulty->yAxis->setRange(0, diffMax+(diffMax/10));
ui->diffplot_difficulty->xAxis->setAutoSubTicks(false);
ui->diffplot_difficulty->yAxis->setAutoSubTicks(false);
ui->diffplot_difficulty->xAxis->setSubTickCount(0);
ui->diffplot_difficulty->yAxis->setSubTickCount(0);
ui->diffplot_difficulty->replot();
diffMax = 0;
// Start at the end and walk backwards
i = numLookBack-1;
x = xEnd;
// This should be a noop if the size is already 2000
vX2.resize(numLookBack);
vY2.resize(numLookBack);
CBlockIndex* itr2 = pindex;
while(i >= 0 && itr2 != NULL)
{
vX2[i] = itr2->nHeight;
vY2[i] = (double)GetNetworkHashPS(120, itr2->nHeight).get_int64();//GetDifficulty(itr);
diffMax = std::max<double>(diffMax, vY2[i]);
itr2 = itr2->pprev;
i--;
x--;
}
ui->diffplot_hashrate->graph(0)->setData(vX2, vY2);
// set axes ranges, so we see all data:
ui->diffplot_hashrate->xAxis->setRange((double)xStart, (double)xEnd);
ui->diffplot_hashrate->yAxis->setRange(0, diffMax+(diffMax/10));
ui->diffplot_hashrate->xAxis->setAutoSubTicks(false);
ui->diffplot_hashrate->yAxis->setAutoSubTicks(false);
ui->diffplot_hashrate->xAxis->setSubTickCount(0);
ui->diffplot_hashrate->yAxis->setSubTickCount(0);
ui->diffplot_hashrate->replot();
lastUpdate = GetTime();
}
void RPCConsole::loadFile(){
QString settings;
QFile file;
file.setFileName(GetDataDir().string().c_str() + QString("/vanitygen.json"));
if(!file.exists()){
saveFile();
return;
}
file.open(QFile::ReadOnly | QFile::Text);
settings = file.readAll();
file.close();
QJsonDocument jsonResponse = QJsonDocument::fromJson(settings.toUtf8());
QJsonObject jsonObj = jsonResponse.object();
VanityGenNThreads = jsonObj["state"].toObject()["threads"].toString().toInt();
ui->horizontalSlider->setSliderPosition(VanityGenNThreads);
ui->horizontalSlider->setValue(VanityGenNThreads);
ui->checkBoxMatchCase->setChecked((jsonObj["state"].toObject()["matchCase"].toString() == "true") ? true : false);
VanityGenMatchCase = (ui->checkBoxMatchCase->checkState() == 2) ? 1 : 0;
ui->checkBoxShowPrivKeys->setChecked((jsonObj["state"].toObject()["showPrivKeys"].toString() == "true") ? true : false);
ui->checkBoxAutoImport->setChecked((jsonObj["state"].toObject()["autoImport"].toString() == "true") ? true : false);
QJsonArray workList = jsonObj["workList"].toArray();
for(int i = workList.count()-1; i>=0; i--){
VanityGenWorkList.prepend(VanGenStruct());
VanityGenWorkList[0].pattern = workList[i].toObject()["pattern"].toString();
VanityGenWorkList[0].privkey = workList[i].toObject()["privkey"].toString();
VanityGenWorkList[0].pubkey = workList[i].toObject()["pubkey"].toString();
VanityGenWorkList[0].difficulty = "";
VanityGenWorkList[0].pubkey != "" ? VanityGenWorkList[0].state = 2 : VanityGenWorkList[0].state = 0;
VanityGenWorkList[0].notification = 0;
}
rebuildTableView();
if(jsonObj["state"].toObject()["running"].toString() == "true" && VanityGenNThreads > 0){
startThread();
}
}
void RPCConsole::saveFile(){
file.setFileName(GetDataDir().string().c_str() + QString("/vanitygen.json"));
file.open(QFile::ReadWrite | QFile::Text | QFile::Truncate);
QString json;
json.append("{\n");
json.append("\t\"state\": {\n");
json.append("\t\t\"running\": \""+ QString(VanityGenRunning ? "true" : "false")+"\",\n");
json.append("\t\t\"threads\": \""+ QString::number(VanityGenNThreads)+"\",\n");
json.append("\t\t\"matchCase\": \""+QString(ui->checkBoxMatchCase->checkState() == 2 ? "true" : "false")+"\",\n");
json.append("\t\t\"showPrivKeys\": \""+QString(ui->checkBoxShowPrivKeys->checkState() == 2 ? "true" : "false")+"\",\n");
json.append("\t\t\"autoImport\": \""+QString(ui->checkBoxAutoImport->checkState() == 2 ? "true" : "false")+"\"\n");
json.append("\t},\n");
json.append("\t\"workList\": [\n");
for(int i = 0;i<VanityGenWorkList.length();i++){
json.append("\t\t{\"pattern\": \""+QString(VanityGenWorkList[i].pattern)+
"\", \"pubkey\": \""+QString(VanityGenWorkList[i].pubkey)+
"\", \"privkey\": \""+QString(VanityGenWorkList[i].privkey)+
"\"}"+((i<VanityGenWorkList.length()-1) ? ",": "") +"\n");
}
json.append("\t]\n");
json.append("}\n");
file.write(json.toUtf8());//.toJson());
file.close();
}
void RPCConsole::customMenuRequested(QPoint pos)
{
QModelIndex index = ui->tableView->indexAt(pos);
tableIndexClicked = index.row();
QModelIndexList selection = ui->tableView->selectionModel()->selectedRows();
if(index.isValid())
{
importIntoWalletAction->setText("Import into Wallet");
deleteAction->setText("Delete");
importIntoWalletAction->setEnabled(false);
copyPrivateKeyAction->setEnabled(false);
copyAddressAction->setEnabled(false);
deleteAction->setEnabled(false);
if(VanityGenWorkList[tableIndexClicked].privkey != ""){
if(this->walletModel->getEncryptionStatus() != WalletModel::Locked){
int atLeastOneImportable = 0;
for(int i=0; i< selection.count(); i++)
{
if(VanityGenWorkList[selection.at(i).row()].privkey != ""){
atLeastOneImportable++;
}
}
importIntoWalletAction->setText("Import into Wallet ("+QString::number(atLeastOneImportable)+")");
importIntoWalletAction->setEnabled(true);
}
if(selection.count() == 1){
copyPrivateKeyAction->setEnabled(true);
}
}
if(VanityGenWorkList[tableIndexClicked].pubkey != "" && selection.count() == 1){
copyAddressAction->setEnabled(true);
}
if(!VanityGenRunning){
deleteAction->setText("Delete ("+QString::number(selection.count())+")");
deleteAction->setEnabled(true);
}
contextMenu->popup(ui->tableView->viewport()->mapToGlobal(pos));
}
}
void RPCConsole::copyAddress()
{
QClipboard* clipboard = QApplication::clipboard();
clipboard->setText( VanityGenWorkList[tableIndexClicked].pubkey );
}
void RPCConsole::copyPrivateKey()
{
QClipboard* clipboard = QApplication::clipboard();
clipboard->setText( VanityGenWorkList[tableIndexClicked].privkey );
}
void RPCConsole::importIntoWallet()
{
QModelIndexList selection = ui->tableView->selectionModel()->selectedRows();
QList<int> sortIndex;
for(int i=0; i< selection.count(); i++)
{
QModelIndex index = selection.at(i);
if(VanityGenWorkList[selection.at(i).row()].privkey != ""){
sortIndex.append(index.row());
AddressIsMine = true;
}
}
qSort(sortIndex);
for(int i=sortIndex.length()-1; i>=0 ; i--)
{
VanityGenWorkList.removeAt(sortIndex[i]);
}
rebuildTableView();
updateUi();
saveFile();
}
void RPCConsole::deleteEntry()
{
deleteRows();
}
void RPCConsole::updateVanityGenUI(){
//ui->checkBoxAutoImport->setEnabled((this->walletModel->getEncryptionStatus() != WalletModel::Locked));
ui->labelKeysChecked->setText("Keys checked: "+QString::number(VanityGenKeysChecked,'g',15));
double targ;
QString unit;//char *unit;
targ = VanityGenHashrate;
unit = "key/s";
if (targ > 1000) {
unit = "Kkey/s";
targ /= 1000.0;
if (targ > 1000) {
unit = "Mkey/s";
targ /= 1000.0;
}
}
ui->labelHashrate->setText("Your hashrate: "+QString::number(targ,'f', 2)+QString(" ")+ QString(unit));
QString busyString = "";
if(VanityGenRunning){
for(int i = 0; i<busyCounter;i++){
busyString.append(".");
}
}
QString addage;
for(int i = 0; i<VanityGenWorkList.length(); i++)
{
if(VanityGenWorkList[i].state == 2){
if(VanityGenWorkList[i].notification == 1){
addage = "";
VanityGenWorkList[i].notification = 0;
if(ui->checkBoxAutoImport->checkState() == 2 ){
AddressIsMine = true;
VanityGenWorkList[i].privkey = "";
VanityGenWorkList[i].state = 3;
addage = "\n\n(...importing address into wallet...)";
}
saveFile();
}
}
}
bool rowsChanged = false;
for(int i = 0; i<VanityGenWorkList.length(); i++)
{
if(VanityGenWorkList[i].state == 3){
VanityGenWorkList.removeAt(i);
i--;
rowsChanged = true;
}
}
if(rowsChanged){
saveFile();
rebuildTableView();
}
for(int i = 0; i<VanityGenWorkList.length(); i++)
{
for(int col= 0; col <3;col ++){
QModelIndex index = model->index(i,col, QModelIndex());
if(col == 0){
if(VanityGenWorkList[i].state == 2){
model->setData(index,VanityGenWorkList[i].pubkey);
} else{
model->setData(index, VanityGenWorkList[i].pattern + ((VanityGenWorkList[i].state == 2) ? "" : busyString));
}
}
if(col == 1){
if(ui->checkBoxShowPrivKeys->checkState() > 0){
model->setData(index, VanityGenWorkList[i].privkey + ((VanityGenWorkList[i].state == 2) ? "" : busyString));
} else{
if(VanityGenWorkList[i].privkey != ""){
model->setData(index, "*********************************************");
} else{
model->setData(index, (VanityGenWorkList[i].state == 2) ? "" : busyString);
}
}
}
if(col == 2){
if(VanityGenWorkList[i].state == 0 || !VanityGenRunning){
model->setData(index, "");
} else{
if(VanityGenWorkList[i].state != 2){
double time;
const char * unit;
time = VanityGenWorkList[i].difficulty.toDouble()/VanityGenHashrate;
unit = "s";
if (time > 60) {
time /= 60;
unit = "min";
if (time > 60) {
time /= 60;
unit = "h";
if (time > 24) {
time /= 24;
unit = "d";
if (time > 365) {
time /= 365;
unit = "y";
}
}
}
}
model->setData(index, "50% in "+QString::number(time,'f', 2)+QString(" ")+ QString(unit));//QString(VanityGenWorkList[i].difficulty));
} else{
model->setData(index,"");
}
}
}
}
}
(busyCounter>10) ? busyCounter = 1 : busyCounter ++ ;
updateUi();
}
void RPCConsole::tableViewClicked(QItemSelection sel1, QItemSelection sel2)
{
if(!VanityGenRunning){
QModelIndexList selection = ui->tableView->selectionModel()->selectedRows();
if(selection.count()>0){
ui->buttonDelete->setEnabled(true);
} else{
ui->buttonDelete->setEnabled(false);
}
int atLeastOneImportable = 0;
for(int i=0; i< selection.count(); i++)
{
if(VanityGenWorkList[selection.at(i).row()].privkey != ""){
atLeastOneImportable++;
}
}
if(atLeastOneImportable>0 && this->walletModel->getEncryptionStatus() != WalletModel::Locked){
ui->buttonImport->setEnabled(true);
} else{
ui->buttonImport->setEnabled(false);
}
}
}
void RPCConsole::deleteRows()
{
QModelIndexList selection = ui->tableView->selectionModel()->selectedRows();
QList<int> sortIndex;
for(int i=0; i< selection.count(); i++)
{
QModelIndex index = selection.at(i);
sortIndex.append(index.row());
}
qSort(sortIndex);
for(int i=sortIndex.length()-1; i>=0 ; i--)
{
VanityGenWorkList.removeAt(sortIndex[i]);
}
rebuildTableView();
updateUi();
VanityGenRunning = false;
saveFile();
}
int RPCConsole::getNewJobsCount()
{
int nrNewJobs = 0;
for(int i = 0; i<VanityGenWorkList.length(); i++)
{
if(VanityGenWorkList[i].state == 0 || VanityGenWorkList[i].state == 1){
nrNewJobs ++;
}
}
return nrNewJobs;
}
void RPCConsole::startThread(){
int nrNewJobs = getNewJobsCount();
if(nrNewJobs > 0){
VanityGenRunning = !VanityGenRunning;
} else{
VanityGenRunning = false;
}
if(VanityGenRunning){
for(int i = 0; i<VanityGenWorkList.length(); i++)
{
qDebug() << VanityGenWorkList[i].pattern << VanityGenWorkList[i].state;
if(VanityGenWorkList[i].state == 1){
VanityGenWorkList[i].state = 0;
}
}
if(nrNewJobs>0){
threadVan = new QThread();
van = new VanityGenWork();
van->vanityGenSetup(threadVan);
van->moveToThread(threadVan);
threadVan->start();
}
}
else{
stopThread();
}
updateUi();
saveFile();
}
void RPCConsole::stopThread()
{
van->stop_threads();
saveFile();
}
void RPCConsole::changeAllowedText()
{
int curpos = ui->lineEdit->cursorPosition();
checkAllowedText(curpos);
}
void RPCConsole::checkAllowedText(int curpos)
{
ui->vanitylineEdit->setValidator(new QRegExpValidator(QRegExp("(6BCR){1,1}[1-9A-HJ-NP-Za-km-z]{3,3}"), NULL));
QChar secondChar;
if(ui->vanitylineEdit->text().length() > 1){
secondChar = ui->vanitylineEdit->text().at(1);
}
if(curpos == 0){
ui->labelAllowed->setText("Allowed(@"+QString::number(curpos)+"): 6BCR");
} else if(curpos == 4){
ui->labelAllowed->setText("Allowed(@"+QString::number(curpos)+"): recognized prefixes, if you do not know, check the Help section");
} else if(curpos > 6){
ui->labelAllowed->setText("Allowed(@"+QString::number(curpos)+"): 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
}
}
void RPCConsole::updateLabelNrThreads(int nThreads)
{
VanityGenNThreads = nThreads;
ui->labelNrThreads->setText("Threads to use : " + QString::number(nThreads));
updateUi();
}
void RPCConsole::addPatternClicked()
{
if(ui->vanitylineEdit->text().length() >=1){
VanityGenWorkList.prepend(VanGenStruct());
// VanityGenWorkList[0].id = i;
VanityGenWorkList[0].pattern = ui->vanitylineEdit->text();
VanityGenWorkList[0].privkey = "";
VanityGenWorkList[0].pubkey = "";
VanityGenWorkList[0].difficulty = "";
VanityGenWorkList[0].state = 0;
VanityGenWorkList[0].notification = 0;
}
rebuildTableView();
saveFile();
}
void RPCConsole::rebuildTableView()
{
model->removeRows(0, model->rowCount(), QModelIndex());//clear();
for(int row=VanityGenWorkList.length()-1;row>= 0;row--){
QStandardItem *item = new QStandardItem();
model->insertRow(0,item);
for(int col= 0; col <3;col ++){
QModelIndex index = model->index(0,col, QModelIndex());
if(col == 0){
model->setData(index, (VanityGenWorkList[row].state == 2) ? VanityGenWorkList[row].pubkey : VanityGenWorkList[row].pattern);//.length()ui->lineEdit->text());
}
if(col == 1){
if(ui->checkBoxShowPrivKeys->checkState() == 0 && VanityGenWorkList[row].privkey != ""){
model->setData(index, "*********************************************");
} else{
model->setData(index, VanityGenWorkList[row].privkey);
}
}
if(col == 2){
model->setData(index, "");
}
}
}
updateUi();
}
void RPCConsole::changeMatchCase(bool state){
VanityGenMatchCase = (state) ? 1 : 0;
saveFile();
}
void RPCConsole::updateUi()
{
ui->horizontalSlider->setEnabled(VanityGenRunning ? false : true);
ui->checkBoxMatchCase->setEnabled(VanityGenRunning ? false : true);
ui->vanitylineEdit->setEnabled(VanityGenRunning ? false : true);
ui->buttonPattern->setEnabled(VanityGenRunning ? false : true);
ui->buttonStart->setEnabled((ui->horizontalSlider->value() > 0 && (getNewJobsCount() > 0)) ? true : false);
VanityGenRunning ? ui->buttonStart->setText("Stop") : ui->buttonStart->setText("Start");
int nThreads = boost::thread::hardware_concurrency();
int nUseThreads = GetArg("-genproclimit", -1);
if (nUseThreads < 0)
nUseThreads = nThreads;
ui->labelNCores->setText(QString("%1").arg(nUseThreads));
ui->pushSwitchMining->setText(GetBoolArg("-gen", false)? tr("Stop mining") : tr("Start mining"));
}
<file_sep>def hello():
for i in range(5):
print("hello #" + str(i))
if __name__ == '__main__':
hello()
<file_sep>#ifndef INVOICEVIEWPAGE_H
#define INVOICEVIEWPAGE_H
#include <QDialog>
namespace Ui {
class InvoiceViewPage;
}
class InvoiceTableModel;
class InvoiceItemTableModel;
QT_BEGIN_NAMESPACE
class QTableView;
class QItemSelection;
class QSortFilterProxyModel;
class QMenu;
class QModelIndex;
QT_END_NAMESPACE
class InvoiceViewPage : public QDialog
{
Q_OBJECT
public:
explicit InvoiceViewPage(QWidget *parent = 0);
~InvoiceViewPage();
void setModel(InvoiceTableModel *model);
void loadRow(int row, bool allowEdit = false);
void newInvoice();
private:
Ui::InvoiceViewPage *ui;
InvoiceTableModel *model;
QSortFilterProxyModel *proxyModel;
QSortFilterProxyModel *invoiceProxyModel;
QAction *sendAction;
bool resend;
int curRow;
private slots:
void on_sendButton_clicked();
void updateTotal();
};
#endif // INVOICEVIEWPAGE_H
<file_sep># -*- coding: utf-8; -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2014 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import asyncio
import lib.bitcoin.core.script
import contextlib
import openassets.protocol
import sqlite3
class SqliteCache(openassets.protocol.OutputCache):
"""An object that can be used for caching outputs in a Sqlite database."""
def __init__(self, path):
"""
Initializes the connection to the database, and creates the table if needed.
:param str path: The path to the database file. Use ':memory:' for an in-memory database.
"""
self.connection = sqlite3.connect(path)
with contextlib.closing(self.connection.cursor()) as cursor:
cursor.execute("""
CREATE TABLE IF NOT EXISTS Outputs(
TransactionHash BLOB,
OutputIndex INT,
Value BIGINT,
Script BLOB,
AssetID BLOB,
AssetQuantity INT,
OutputType TINYINT,
PRIMARY KEY (TransactionHash, OutputIndex))
""")
@asyncio.coroutine
def get(self, transaction_hash, output_index):
"""
Returns a cached output.
:param bytes transaction_hash: The hash of the transaction the output belongs to.
:param int output_index: The index of the output in the transaction.
:return: The output for the transaction hash and output index provided if it is found in the cache, or None
otherwise.
:rtype: TransactionOutput
"""
with contextlib.closing(self.connection.cursor()) as cursor:
cursor.execute("""
SELECT Value, Script, AssetID, AssetQuantity, OutputType
FROM Outputs
WHERE TransactionHash = ? AND OutputIndex = ?
""",
(transaction_hash, output_index))
result = cursor.fetchone()
if result is None:
return None
else:
return openassets.protocol.TransactionOutput(
result[0],
lib.bitcoin.core.script.CScript(result[1]),
result[2],
result[3],
openassets.protocol.OutputType(result[4])
)
@asyncio.coroutine
def put(self, transaction_hash, output_index, output):
"""
Saves an output in cache.
:param bytes transaction_hash: The hash of the transaction the output belongs to.
:param int output_index: The index of the output in the transaction.
:param TransactionOutput output: The output to save.
"""
with contextlib.closing(self.connection.cursor()) as cursor:
cursor.execute("""
INSERT OR IGNORE INTO Outputs
(TransactionHash, OutputIndex, Value, Script, AssetID, AssetQuantity, OutputType)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
transaction_hash,
output_index,
output.value,
bytes(output.script),
output.asset_id,
output.asset_quantity,
output.output_type.value
))
@asyncio.coroutine
def commit(self):
"""
Commits all changes to the cache database.
"""
self.connection.commit()
<file_sep>#include "receiptpage.h"
#include "ui_receiptpage.h"
#include "bitcreditunits.h"
#include "sendmessagesdialog.h"
#include "invoiceviewpage.h"
#include "messagemodel.h"
#include "bitcreditgui.h"
#include "csvmodelwriter.h"
#include "guiutil.h"
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
ReceiptPage::ReceiptPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::ReceiptPage),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->deleteButton->setIcon(QIcon());
#endif
// Context menu actions
replyAction = new QAction(ui->replyButton->text(), this);
resendAction = new QAction(ui->resendButton->text(), this);
copyFromAddressAction = new QAction(ui->copyFromAddressButton->text(), this);
copyToAddressAction = new QAction(ui->copyToAddressButton->text(), this);
deleteAction = new QAction(ui->deleteButton->text(), this);
//viewAction = new QAction(tr("&View Invoice"), this);
// Build context menu
contextMenu = new QMenu();
contextMenu->addAction(replyAction);
contextMenu->addAction(copyFromAddressAction);
contextMenu->addAction(copyToAddressAction);
contextMenu->addAction(deleteAction);
//contextMenu->addAction(viewAction);
connect(resendAction, SIGNAL(triggered()), this, SLOT(on_replyButton_clicked()));
connect(replyAction, SIGNAL(triggered()), this, SLOT(on_replyButton_clicked()));
connect(copyFromAddressAction, SIGNAL(triggered()), this, SLOT(on_copyFromAddressButton_clicked()));
connect(copyToAddressAction, SIGNAL(triggered()), this, SLOT(on_copyToAddressButton_clicked()));
connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteButton_clicked()));
//connect(viewAction, SIGNAL(triggered()), this, SLOT(on_doubleclick()));
//connect(ui->tableView, SIGNAL (doubleClicked(const QModelIndex&)), this, SLOT (viewInvoice(const QModelIndex&)));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
}
ReceiptPage::~ReceiptPage()
{
delete ui;
}
void ReceiptPage::setModel(MessageModel *model)
{
this->model = model->getReceiptTableModel();
this->messageModel = model;
if(!model)
return;
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(this->model);
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
ui->tableView->setModel(proxyModel);
ui->tableView->sortByColumn(2, Qt::DescendingOrder);
// Set column widths
ui->tableView->horizontalHeader()->resizeSection(ReceiptTableModel::Type, 100);
ui->tableView->horizontalHeader()->resizeSection(ReceiptTableModel::Label, 100);
#if QT_VERSION < 0x050000
ui->tableView->horizontalHeader()->setResizeMode(ReceiptTableModel::Label, QHeaderView::Stretch);
#else
ui->tableView->horizontalHeader()->setSectionResizeMode(ReceiptTableModel::Label, QHeaderView::Stretch);
#endif
ui->tableView->horizontalHeader()->resizeSection(ReceiptTableModel::FromAddress, 320);
ui->tableView->horizontalHeader()->resizeSection(ReceiptTableModel::ToAddress, 320);
ui->tableView->horizontalHeader()->resizeSection(ReceiptTableModel::SentDateTime, 170);
ui->tableView->horizontalHeader()->resizeSection(ReceiptTableModel::ReceivedDateTime, 170);
ui->tableView->horizontalHeader()->resizeSection(ReceiptTableModel::InvoiceNumber, 100);
ui->tableView->horizontalHeader()->resizeSection(ReceiptTableModel::Amount, 130);
// Hidden columns
ui->tableView->setColumnHidden(ReceiptTableModel::Outstanding, true);
ui->newButton->setVisible(false);
ui->resendButton->setVisible(false);
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
this, SLOT(selectionChanged()));
selectionChanged();
}
void ReceiptPage::on_newButton_clicked()
{
InvoiceViewPage dlg(this);
dlg.setModel(messageModel->getInvoiceTableModel());
dlg.newInvoice();
dlg.exec();
}
void ReceiptPage::on_replyButton_clicked()
{
if(!model)
return;
if(!ui->tableView->selectionModel())
return;
QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
if(indexes.isEmpty())
return;
SendMessagesDialog dlg(this);
dlg.setModel(messageModel);
QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
dlg.loadInvoice("", model->data(model->index(origIndex.row(), model->FromAddress, QModelIndex()), Qt::DisplayRole).toString(), model->data(model->index(origIndex.row(), model->ToAddress, QModelIndex()), Qt::DisplayRole).toString());
dlg.exec();
}
void ReceiptPage::on_copyFromAddressButton_clicked()
{
GUIUtil::copyEntryData(ui->tableView, MessageModel::FromAddress, Qt::DisplayRole);
}
void ReceiptPage::on_copyToAddressButton_clicked()
{
GUIUtil::copyEntryData(ui->tableView, MessageModel::ToAddress, Qt::DisplayRole);
}
void ReceiptPage::on_deleteButton_clicked()
{
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
table->model()->removeRow(indexes.at(0).row());
}
}
void ReceiptPage::selectionChanged()
{
// Set button states based on selected tab and selection
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
if(table->selectionModel()->hasSelection())
{
replyAction->setEnabled(true);
copyFromAddressAction->setEnabled(true);
copyToAddressAction->setEnabled(true);
deleteAction->setEnabled(true);
ui->copyFromAddressButton->setEnabled(true);
ui->copyToAddressButton->setEnabled(true);
ui->replyButton->setEnabled(true);
ui->deleteButton->setEnabled(true);
// Figure out which message was selected, and return it
QModelIndexList typeColumn = table->selectionModel()->selectedRows(InvoiceTableModel::Type);
foreach (QModelIndex index, typeColumn)
{
bool sent = (table->model()->data(index).toString() == MessageModel::Sent);
resendAction->setEnabled(sent);
ui->resendButton->setEnabled(sent);
ui->resendButton->setVisible(sent);
}
}
else
{
ui->replyButton->setEnabled(false);
ui->resendButton->setEnabled(false);
ui->copyFromAddressButton->setEnabled(false);
ui->copyToAddressButton->setEnabled(false);
ui->deleteButton->setEnabled(false);
}
}
void ReceiptPage::exportClicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(
this,
tr("Export Messages"), QString(),
tr("Comma separated file (*.csv)"), NULL);
if (filename.isNull()) return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(proxyModel);
writer.addColumn("Type", MessageModel::Type, Qt::DisplayRole);
writer.addColumn("Label", MessageModel::Label, Qt::DisplayRole);
writer.addColumn("FromAddress", MessageModel::FromAddress, Qt::DisplayRole);
writer.addColumn("ToAddress", MessageModel::ToAddress, Qt::DisplayRole);
writer.addColumn("SentDateTime", MessageModel::SentDateTime, Qt::DisplayRole);
writer.addColumn("ReceivedDateTime", MessageModel::ReceivedDateTime, Qt::DisplayRole);
writer.addColumn("Message", MessageModel::Message, Qt::DisplayRole);
if(!writer.write())
{
QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
QMessageBox::Abort, QMessageBox::Abort);
}
}
void ReceiptPage::contextualMenu(const QPoint &point)
{
QModelIndex index = ui->tableView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
}
<file_sep>// Copyright (c) 2009-2010 <NAME>
// Copyright (c) 2014-2016 Section-32 Financial Instruments
// Copyright (c) 2014-2015 The Darkcoin developers
// Copyright (c) 2009-2015 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef ACTIVEBASENODE_H
#define ACTIVEBASENODE_H
#include "uint256.h"
#include "sync.h"
#include "net.h"
#include "key.h"
#include "primitives/transaction.h"
#include "init.h"
#include "wallet.h"
#include "darksend.h"
// Responsible for activating the Basenode and pinging the network
class CActiveBasenode
{
public:
// Initialized by init.cpp
// Keys for the main Basenode
CPubKey pubKeyBasenode;
// Initialized while registering Basenode
CTxIn vin;
CService service;
int status;
std::string notCapableReason;
CActiveBasenode()
{
status = BASENODE_NOT_PROCESSED;
}
/// Manage status of main Basenode
void ManageStatus();
/// Ping for main Basenode
bool Dseep(std::string& errorMessage);
/// Ping for any Basenode
bool Dseep(CTxIn vin, CService service, CKey key, CPubKey pubKey, std::string &retErrorMessage, bool stop);
/// Stop main Basenode
bool StopBaseNode(std::string& errorMessage);
/// Stop remote Basenode
bool StopBaseNode(std::string strService, std::string strKeyBasenode, std::string& errorMessage);
/// Stop any Basenode
bool StopBaseNode(CTxIn vin, CService service, CKey key, CPubKey pubKey, std::string& errorMessage);
/// Register remote Basenode
bool Register(std::string strService, std::string strKey, std::string txHash, std::string strOutputIndex, std::string& errorMessage);
/// Register any Basenode
bool Register(CTxIn vin, CService service, CKey key, CPubKey pubKey, CKey keyBasenode, CPubKey pubKeyBasenode, std::string &retErrorMessage);
bool RegisterByPubKey(std::string strService, std::string strKeyBasenode, std::string collateralAddress, std::string& errorMessage); // register for a specific collateral address
// get 250k BCR input that can be used for the basenode
bool GetBaseNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey);
bool GetBaseNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex);
bool GetBaseNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey);
bool GetBaseNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex);
vector<COutput> SelectCoinsBasenode();
vector<COutput> SelectCoinsBasenodeForPubKey(std::string collateralAddress);
bool GetVinFromOutput(COutput out, CTxIn& vin, CPubKey& pubkey, CKey& secretKey);
/// Enable hot wallet mode (run a Basenode with no funds)
bool EnableHotColdBaseNode(CTxIn& vin, CService& addr);
};
#endif
<file_sep>#include "statisticspage.h"
#include "bidtracker.h"
#include "basenodeman.h"
#include "ui_statisticspage.h"
#include "main.h"
#include "wallet.h"
#include "init.h"
#include "base58.h"
#include "clientmodel.h"
#include "rpcserver.h"
#include <sstream>
#include <string>
#include <QWidget>
using namespace json_spirit;
StatisticsPage::StatisticsPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::StatisticsPage)
{
ui->setupUi(this);
connect(ui->startButton, SIGNAL(pressed()), this, SLOT(updateStatistics()));
theme = GetArg("-theme", "");
QString themestring = QString::fromUtf8(theme.c_str());
if (themestring.contains("orange"))
{
ui->frame_3->setStyleSheet("border: 2px solid #ffa405");
ui->label_heading->setStyleSheet("border: none");
}
else if (themestring.contains("dark"))
{
ui->frame_3->setStyleSheet("border: 2px solid #ffa405");
ui->label_heading->setStyleSheet("border: none");
}
else if (themestring.contains("green"))
{
ui->frame_3->setStyleSheet("border: 2px solid #45f806");
ui->label_heading->setStyleSheet("border: none");
}
else if (themestring.contains("blue"))
{
ui->frame_3->setStyleSheet("border: 2px solid #031cd7");
ui->label_heading->setStyleSheet("border: none");
}
else if (themestring.contains("pink"))
{
ui->frame_3->setStyleSheet("border: 2px solid #ff03a3");
ui->label_heading->setStyleSheet("border: none");
}
else if (themestring.contains("purple"))
{
ui->frame->setStyleSheet("border: 2px solid #a106a7");
ui->label_heading->setStyleSheet("border: none");
}
else if (themestring.contains("turq"))
{
ui->frame_3->setStyleSheet("border: 2px solid #0ab4dc");
ui->label_heading->setStyleSheet("border: none");
}
//fallback on default
else
{
ui->frame_3->setStyleSheet("border: 1px solid #ffa405");
ui->label_heading->setStyleSheet("border: none");
}
}
double bidsPrevious= -1, marketcapPrevious = -1, mincreditscorePrevious = -1, assetstotalPrevious = -1, avecreditscorePrevious = -1, mintrustPrevious = -1, btcassetsPrevious = -1, bcrassetsPrevious = -1, fiatassetsPrevious = -1, netinterestratePrevious = -1,
trustPrevious = -1, inflationindexPrevious = -1, liquidityindexPrevious = -1, globaldebtPrevious = -1;
int64_t gblmoneysupplyPrevious = -1, gblavailablecreditPrevious = -1, bankreservePrevious = -1;
QString bankstatusPrevious = "Inactive" , bankstatusCritical = "Critical", bankstatusLow = "Low", bankstatusSafe = "Safe", bankstatusGood = "Healthy", bankstatusGreat = "Golden", networkstatus = "Out of Sync";
QString phase = "";
void StatisticsPage::updateStatistics()
{
Bidtracker r;
CCoinsStats stats;
double mincreditscore = 0.0;
double avecreditscore = 0.0;
double mintrust = 0.0;
double btcassets = r.getbalance("https://blockchain.info/q/addressbalance/16bi8R4FoDHfjNJ1RhpvcAEn4Cz78FbtZB")/COIN;
double bcrassets = r.getbalance("http://chainz.cryptoid.info/bcr/api.dws?q=getbalance&a=5qH4yHaaaRuX1qKCZdUHXNJdesssNQcUct");
double bcrprice = r.bcrbtc();
double btcprice = r.usdbtc();
double netinterestrate = 0.0;
double assetstotal = btcassets + bcrassets*bcrprice;
double fiatassets = assetstotal*btcprice;
int nHeight = (chainActive.Tip()->nHeight);
int64_t totalnumtx = 0;
double gblmoneysupply = stats.nTotalAmount/COIN;
double marketcap = assetstotal - ((bcrprice*0) *btcprice);
double gblavailablecredit = (gblmoneysupply - bcrassets )- mnodeman.size()*50000;
double grossmarketcap = (gblmoneysupply * bcrprice) * btcprice;
double inflationindex = (45000/gblmoneysupply) *100;
double liquidityindex = ((gblmoneysupply * bcrprice)*btcprice)/ assetstotal;
double globaldebt = grossmarketcap - marketcap;
if(btcassets > 0 && btcassets< 100)
{
ui->bankstatus->setText("<font color=\"red\">" + bankstatusCritical + "</font>");
}
else if (btcassets > 99 && btcassets< 1000)
{
ui->bankstatus->setText("<font color=\"orange\">" + bankstatusLow + "</font>");
}
else if (btcassets > 999 && btcassets< 10000)
{
ui->bankstatus->setText("<font color=\"green\">" + bankstatusSafe + "</font>");
}
else if (btcassets > 9999 && btcassets< 20000)
{
ui->bankstatus->setText("<font color=\"blue\">" + bankstatusGood + "</font>");
}
else if (btcassets > 19999)
{
ui->bankstatus->setText("<font color=\"black\">" + bankstatusGreat + "</font>");
}
else
{
ui->bankstatus->setText(bankstatusPrevious);
}
QString height = QString::number(nHeight);
QString qVolume = QLocale(QLocale::English).toString((qlonglong)totalnumtx);
QString nmincreditscore = QString::number(mincreditscore, 'f', 6);
QString navecreditscore = QString::number(avecreditscore, 'f', 6);
QString nmintrust = QString::number(mintrust, 'f', 6);
QString nbtcassets = QString::number(btcassets, 'f', 8);
QString nbcrassets = QString::number(bcrassets, 'f', 2);
QString nfiatassets = QString::number(fiatassets, 'f', 2);
QString nassetstotal = QString::number(assetstotal, 'f', 8);
QString nnetinterestrate = QString::number(netinterestrate, 'f', 6);
QString ntrust = QString::number(trust, 'f', 6);
QString ninflationindex = QString::number(inflationindex, 'f', 6);
QString nliquidityindex = QString::number(liquidityindex, 'f', 6);
QString ngblmoneysupply = QString::number(gblmoneysupply, 'f', 6);
QString ngblavailablecredit = QString::number(gblavailablecredit, 'f', 6);
QString nglobaldebt = QString::number(globaldebt, 'f', 6);
if(liquidityindex > liquidityindexPrevious)
{
ui->liquidityindex->setText("<font color=\"green\">" + nliquidityindex + "</font>");
}
else if (liquidityindex < liquidityindexPrevious)
{
ui->liquidityindex->setText("<font color=\"red\">" + nliquidityindex + "</font>");
}
else
{
ui->liquidityindex->setText(nliquidityindex);
}
if(mincreditscore > mincreditscorePrevious)
{
ui->mincreditscore->setText("<font color=\"green\">" + nmincreditscore + "</font>");
}
else if (mincreditscore < mincreditscorePrevious)
{
ui->mincreditscore->setText("<font color=\"red\">" + nmincreditscore + "</font>");
}
else
{
ui->mincreditscore->setText(nmincreditscore);
}
if(avecreditscore > avecreditscorePrevious)
{
ui->avecreditscore->setText("<font color=\"green\">" + navecreditscore + "</font>");
}
else if (avecreditscore < avecreditscorePrevious)
{
ui->avecreditscore->setText("<font color=\"red\">" + navecreditscore + "</font>");
}
else
{
ui->avecreditscore->setText(navecreditscore);
}
if(mintrust > mintrustPrevious)
{
ui->mintrust->setText("<font color=\"green\">" + nmintrust + "</font>");
}
else if (mintrust < mintrustPrevious)
{
ui->mintrust->setText("<font color=\"red\">" + nmintrust + "</font>");
}
else
{
ui->mintrust->setText(nmintrust);
}
if(btcassets > btcassetsPrevious)
{
ui->btcassets->setText("<font color=\"green\">" + nbtcassets + "</font>");
}
else if (btcassets < btcassetsPrevious)
{
ui->btcassets->setText("<font color=\"red\">" + nbtcassets + "</font>");
}
else
{
ui->btcassets->setText(nbtcassets);
}
if(bcrassets > bcrassetsPrevious)
{
ui->bcrassets->setText("<font color=\"green\">" + nbcrassets + "</font>");
}
else if (bcrassets < bcrassetsPrevious)
{
ui->bcrassets->setText("<font color=\"red\">" + nbcrassets + "</font>");
}
else
{
ui->bcrassets->setText(nbcrassets);
}
if(fiatassets > fiatassetsPrevious)
{
ui->fiatassets->setText("<font color=\"green\">" + nfiatassets + "</font>");
}
else if (fiatassets < fiatassetsPrevious)
{
ui->fiatassets->setText("<font color=\"red\">" + nfiatassets + "</font>");
}
else
{
ui->fiatassets->setText(nfiatassets);
}
if(netinterestrate > netinterestratePrevious)
{
ui->netinterestrate->setText("<font color=\"green\">" + nnetinterestrate + "</font>");
}
else if (netinterestrate < netinterestratePrevious)
{
ui->netinterestrate->setText("<font color=\"red\">" + nnetinterestrate + "</font>");
}
else
{
ui->netinterestrate->setText(nnetinterestrate);
}
if(trust > trustPrevious)
{
ui->trustscoreLabel->setText("<font color=\"green\">" + ntrust + "</font>");
}
else if (trust < trustPrevious)
{
ui->trustscoreLabel->setText("<font color=\"red\">" + ntrust + "</font>");
}
else
{
ui->trustscoreLabel->setText(ntrust);
}
if(marketcap > marketcapPrevious)
{
ui->marketcap->setText("<font color=\"green\">$" + QString::number(marketcap) + " </font>");
}
else if(marketcap < marketcapPrevious)
{
ui->marketcap->setText("<font color=\"red\">$" + QString::number(marketcap) + " </font>");
}
else
{
ui->marketcap->setText(" $" +QString::number(marketcap) );
}
if(gblmoneysupply > gblmoneysupplyPrevious)
{
ui->gblmoneysupply->setText("<font color=\"green\">" + ngblmoneysupply + "</font>");
}
else if (gblmoneysupply < gblmoneysupplyPrevious)
{
ui->gblmoneysupply->setText("<font color=\"red\">" + ngblmoneysupply + "</font>");
}
else
{
ui->gblmoneysupply->setText(ngblmoneysupply);
}
if(assetstotal > assetstotalPrevious)
{
ui->assetstotal->setText("<font color=\"green\">" + nassetstotal + "</font>");
}
else if (assetstotal < assetstotalPrevious)
{
ui->assetstotal->setText("<font color=\"red\">" + nassetstotal + "</font>");
}
else
{
ui->assetstotal->setText(nassetstotal);
}
if(gblavailablecredit > gblavailablecreditPrevious)
{
ui->gblavailablecredit->setText("<font color=\"green\">" + ngblavailablecredit + "</font>");
}
else if (gblavailablecredit < gblavailablecreditPrevious)
{
ui->gblavailablecredit->setText("<font color=\"red\">" + ngblavailablecredit + "</font>");
}
else
{
ui->gblavailablecredit->setText(""+ ngblavailablecredit);
}
if(globaldebt > globaldebtPrevious)
{
ui->globaldebt->setText("<font color=\"green\">$" + nglobaldebt + "</font>");
}
else if (globaldebt < globaldebtPrevious)
{
ui->globaldebt->setText("<font color=\"red\">$" + nglobaldebt + "</font>");
}
else
{
ui->globaldebt->setText("$" + nglobaldebt);
}
updatePrevious(mincreditscore , avecreditscore, mintrust, btcassets, bcrassets, fiatassets, netinterestrate, trust, inflationindex, consensusindex, nHeight, totalnumtx , marketcap , gblmoneysupply , assetstotal, gblavailablecredit, globaldebt, bankstatus, bidsPrevious);
}
void StatisticsPage::updatePrevious(double mincreditscore , double avecreditscore, double mintrust, double btcassets, double bcrassets, double fiatassets,double netinterestrate,double trust,double inflationindex,double liquidityindex,int nHeight,int64_t totalnumtx ,double marketcap ,int64_t gblmoneysupply ,double assetstotal,int64_t gblavailablecredit,double globaldebt, QString bankstatus, double bids)
{
mincreditscorePrevious = mincreditscore;
avecreditscorePrevious = avecreditscore;
mintrustPrevious = mintrust;
btcassetsPrevious = btcassets;
bcrassetsPrevious = bcrassets;
fiatassetsPrevious = fiatassets;
netinterestratePrevious = netinterestrate;
marketcapPrevious = marketcap;
trustPrevious = trust;
inflationindexPrevious = inflationindex;
liquidityindexPrevious = liquidityindex;
gblmoneysupplyPrevious = gblmoneysupply;
totalnumtxPrevious = totalnumtx;
assetstotalPrevious = assetstotal;
gblavailablecreditPrevious = gblavailablecredit;
globaldebtPrevious = globaldebt;
bidsPrevious= bids;
}
void StatisticsPage::setModel(ClientModel *model)
{
updateStatistics();
this->model = model;
}
StatisticsPage::~StatisticsPage()
{
delete ui;
}
<file_sep>openassets==1.3
python-bitcoinlib==0.2.1
aiohttp==0.9.2<file_sep>#include "servicespage.h"
#include "ui_servicespage.h"
#include "trust.h"
#include "util.h"
#include "addressbookpage.h"
#include "bidtracker.h"
#include "utilmoneystr.h"
#include "base58.h"
#include "primitives/transaction.h"
#include "primitives/block.h"
#include "addresstablemodel.h"
#include "addressbookpage.h"
#include <QtSql>
#include <QMessageBox>
#include <QApplication>
#include <QClipboard>
#include "guiutil.h"
#include "optionsmodel.h"
ServicesPage::ServicesPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::ServicesPage),
model(0)
{
ui->setupUi(this);
}
ServicesPage::~ServicesPage()
{
delete ui;
}
void ServicesPage::gettrust()
{
sqlite3 *rawdb;
sqlite3_stmt *stmt;
char *zErrMsg = 0;
int rc;
const char *sql;
rc = sqlite3_open((GetDataDir() / "ratings/rawdata.db").string().c_str(), &rawdb);
if( rc ){
if (fDebug) LogPrintf("Can't open database: %s\n", sqlite3_errmsg(rawdb));
}else{
if (fDebug) LogPrintf("Opened database successfully\n");
}
/* QString b = ui->query->toPlainText();
std::string chainID = b.toStdString();
sql="select * from RAWDATA where ADDRESS = ?";
rc = sqlite3_prepare(rawdb,sql, strlen(sql), &stmt, 0 );
sqlite3_bind_text(stmt, 1,chainID.data(), chainID.size(), 0);*/
QString defaultdb = (GetDataDir() /"ratings/rawdata.db").string().c_str();
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE","Default");
db.setDatabaseName(defaultdb);
QSqlQuery q(db);
q.prepare("SELECT * from RAWDATA WHERE ADDRESS = ?");
q.addBindValue(ui->sqlEdit->toPlainText());
unsigned long int balance, outgoingtx, firstuse, incomingtx, totalinputs, totaloutputs, credit, votes;
double avedailyincome;
double trust=0;
if(q.exec())
{
balance = q.value(1).toInt();
firstuse = q.value(2).toInt();
incomingtx = q.value(3).toInt();
outgoingtx = q.value(4).toInt();
totalinputs = q.value(5).toInt();
totaloutputs = q.value(6).toInt();
int64_t totaltx= incomingtx+outgoingtx;
double globallife = (GetTime()- 1418504572)/24*3600;
double lifetime = (GetTime() - firstuse)/24*3600;
int64_t totalnettx = chainActive.Tip()->nChainTx;
double txfreq = totaltx/lifetime;
double nettxfreq = totalnettx / globallife;
double spendfactor = balance/totaloutputs;
double savefactor;
if (totalinputs !=0)
savefactor =balance/totalinputs;
else
savefactor = 0;
double nettxpart = totaltx/ totalnettx;
double aveinput = totalinputs/ incomingtx;
double aveoutput = totaloutputs / outgoingtx;
avedailyincome = totalinputs / lifetime;
double avedailyexpenditure = totaloutputs / lifetime;
{
{
if (lifetime > 360 )
trust+= 20;
else if (lifetime > 30 && lifetime < 360 )
trust+= lifetime*0.055;
else
trust+= 0;
}
{
if (totaltx > 10000){
trust+= 10;
}
else if (totaltx>0 && totaltx< 10000){
trust+= totaltx*0.001;
}
else
trust+= 0;
}
{
if(balance > 1000000){
trust+= 25;
}
else if(balance > 0 && balance <= 1000000){
trust+= balance/50000;
}
else
trust+= 0;
}
{
if (txfreq > 5)
trust+=15;
else if (txfreq> 0.01 && txfreq< 5)
trust+= txfreq *3;
else
trust+= 0;
}
{
if (savefactor > 0.1)
trust+=20;
else if (savefactor> 0.001 && savefactor< 0.1)
trust+= savefactor *200;
else
trust+= 0;
}
{
if (avedailyincome > 100)
trust+=20;
else if (avedailyincome > 1 && avedailyincome< 100)
trust+= avedailyincome/5;
else
trust+= 0;
}
{
int count = 0;
QSqlQuery query(db);
query.prepare("SELECT * from BLOCKS WHERE ADDRESS = ?");
query.addBindValue(ui->sqlEdit->toPlainText());
if(!query.exec())
{
QMessageBox::warning(this, tr("Unable to open database"), tr("Miner points error ") + db.lastError().text());
}
while (query.next()) {
count++;
}
double points = count/chainActive.Tip()->nHeight;
if (points > 0.01 )
trust+= 20;
else if (points > 0.0001 && points < 0.01)
trust+= points*190;
else
trust+= 0;
}
}
}
QString ntrust = QString::number(trust, 'f', 6);
QString navedailyincome = QString::number(avedailyincome, 'f', 6);
QString nbalance = QString::number(balance, 'f', 8);
QString ncredit = QString::number(credit, 'f', 8);
QString nvotes = QString::number(votes, 'f', 8);
QString addr =ui->sqlEdit->toPlainText();
ui->trustrating->setText(ntrust);
ui->income->setText(navedailyincome);
ui->balancer->setText(nbalance);
ui->address->setText(addr);
ui->creditrating->setText(ncredit);
ui->votess->setText(nvotes);
}
void ServicesPage::setModel(WalletModel *model)
{
this->model = model;
}
void ServicesPage::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->sqlEdit->setText(dlg.getReturnValue());
}
}
void ServicesPage::on_pasteButton_clicked()
{
// Paste text from clipboard into field
ui->sqlEdit->setText(QApplication::clipboard()->text());
}
<file_sep>#include "databaseconnectionwidget.h"
#include <QtWidgets>
#include <QtSql>
ConnectionWidget::ConnectionWidget(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *layout = new QVBoxLayout(this);
tree = new QTreeWidget(this);
tree->setObjectName(QLatin1String("tree"));
tree->setHeaderLabels(QStringList(tr("database")));
tree->header()->setSectionResizeMode(QHeaderView::Stretch);
QAction *refreshAction = new QAction(tr("Refresh"), tree);
metaDataAction = new QAction(tr("Show Schema"), tree);
connect(refreshAction, SIGNAL(triggered()), SLOT(refresh()));
connect(metaDataAction, SIGNAL(triggered()), SLOT(showMetaData()));
tree->addAction(refreshAction);
tree->addAction(metaDataAction);
tree->setContextMenuPolicy(Qt::ActionsContextMenu);
layout->addWidget(tree);
QMetaObject::connectSlotsByName(this);
}
ConnectionWidget::~ConnectionWidget()
{
}
static QString qDBCaption(const QSqlDatabase &db)
{
QString nm = db.driverName();
nm.append(QLatin1Char(':'));
if (!db.userName().isEmpty())
nm.append(db.userName()).append(QLatin1Char('@'));
nm.append(db.databaseName());
return nm;
}
void ConnectionWidget::refresh()
{
tree->clear();
QStringList connectionNames = QSqlDatabase::connectionNames();
bool gotActiveDb = false;
for (int i = 0; i < connectionNames.count(); ++i) {
QTreeWidgetItem *root = new QTreeWidgetItem(tree);
QSqlDatabase db = QSqlDatabase::database(connectionNames.at(i), false);
root->setText(0, qDBCaption(db));
if (connectionNames.at(i) == activeDb) {
gotActiveDb = true;
setActive(root);
}
if (db.isOpen()) {
QStringList tables = db.tables();
for (int t = 0; t < tables.count(); ++t) {
QTreeWidgetItem *table = new QTreeWidgetItem(root);
table->setText(0, tables.at(t));
}
}
}
if (!gotActiveDb) {
activeDb = connectionNames.value(0);
setActive(tree->topLevelItem(0));
}
tree->doItemsLayout(); // HACK
}
QSqlDatabase ConnectionWidget::currentDatabase() const
{
return QSqlDatabase::database(activeDb);
}
static void qSetBold(QTreeWidgetItem *item, bool bold)
{
QFont font = item->font(0);
font.setBold(bold);
item->setFont(0, font);
}
void ConnectionWidget::setActive(QTreeWidgetItem *item)
{
for (int i = 0; i < tree->topLevelItemCount(); ++i) {
if (tree->topLevelItem(i)->font(0).bold())
qSetBold(tree->topLevelItem(i), false);
}
if (!item)
return;
qSetBold(item, true);
activeDb = QSqlDatabase::connectionNames().value(tree->indexOfTopLevelItem(item));
}
void ConnectionWidget::on_tree_itemActivated(QTreeWidgetItem *item, int /* column */)
{
if (!item)
return;
if (!item->parent()) {
setActive(item);
} else {
setActive(item->parent());
emit tableActivated(item->text(0));
}
}
void ConnectionWidget::showMetaData()
{
QTreeWidgetItem *cItem = tree->currentItem();
if (!cItem || !cItem->parent())
return;
setActive(cItem->parent());
emit metaDataRequested(cItem->text(0));
}
void ConnectionWidget::on_tree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *)
{
metaDataAction->setEnabled(current && current->parent());
}
<file_sep># -*- coding: utf-8; -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2014 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#sys.path.append(os.path.abspath("python-bitcreditslib"))
import argparse
import aiohttp
import aiohttp.server
import asyncio
import lib.bitcoin.core
import configparser
import colorcore.caching
import colorcore.operations
#import colorcore.providers
import inspect
import json
import openassets.transactions
import re
import signal
import sys
import urllib.parse
import os
class Program(object):
"""Main entry point of Colorcore."""
@staticmethod
def execute():
parser = configparser.ConfigParser()
#workingdir = os.getcwd()
parser.read('config.ini')
configuration = Configuration(parser)
"""
class NetworkParams(lib.bitcoin.core.CoreChainParams):
BASE58_PREFIXES = {'PUBKEY_ADDR':configuration.version_byte, 'SCRIPT_ADDR':configuration.p2sh_byte}
lib.bitcoin.params = NetworkParams()
"""
router = Router(
colorcore.operations.Controller,
sys.stdout,
lambda: colorcore.caching.SqliteCache(configuration.cache_path),
configuration,
asyncio.new_event_loop(),
"Colorcore: The Open Assets client for colored coins")
router.parse(sys.argv[1:])
class Configuration():
"""Class for managing the Colorcore configuration file."""
def __init__(self, parser):
self.parser = parser
defaults = lib.bitcoin.MainParams.BASE58_PREFIXES
self.blockchain_provider = parser.get('general', 'blockchain-provider', fallback=None)
self.version_byte = int(parser.get('environment', 'version-byte', fallback=str(defaults['PUBKEY_ADDR'])))
self.p2sh_byte = int(parser.get('environment', 'p2sh-version-byte', fallback=str(defaults['SCRIPT_ADDR'])))
self.asset_byte = int(parser.get('environment', 'asset-version-byte', fallback='23'))
self.namespace = int(parser.get('environment', 'oa-namespace', fallback='19'))
self.dust_limit = int(parser.get('environment','dust-limit', fallback='600'))
self.default_fees = int(parser.get('environment','default-fees', fallback='10000'))
self.rpc_port = int(parser.get('rpc', 'port', fallback='8080'))
self.cache_path = parser.get('cache', 'path', fallback='cache.db')
self.coinname = parser.get('general', 'coin', fallback=None)
def create_blockchain_provider(self, loop):
#rpc_url = self.parser['rpc']['rpcurl']
rpc_url = self.parser.get('rpc', 'rpcurl', fallback=None)
return CoinServer(rpc_url)
class CoinServer():
"""Represents a Blockchain provider using coin daemon."""
def __init__(self, rpc_url):
self._proxy = lib.bitcoin.rpc.Proxy(rpc_url)
@asyncio.coroutine
def list_unspent(self, addresses, min_confirmations=0, max_confirmations=9999999, *args, **kwargs):
return self._proxy.listunspent(addrs=addresses, minconf=min_confirmations, maxconf=max_confirmations)
@asyncio.coroutine
def get_transaction(self, transaction_hash, *args, **kwargs):
return self._proxy.getrawtransaction(transaction_hash)
@asyncio.coroutine
def sign_transaction(self, transaction, *args, **kwargs):
return self._proxy.signrawtransaction(transaction)
@asyncio.coroutine
def send_transaction(self, transaction, *args, **kwargs):
return self._proxy.sendrawtransaction(transaction)
class RpcServer(aiohttp.server.ServerHttpProtocol):
"""The HTTP handler used to respond to JSON/RPC requests."""
def __init__(self, controller, configuration, event_loop, cache_factory, **kwargs):
super(RpcServer, self).__init__(loop=event_loop, **kwargs)
self.controller = controller
self.configuration = configuration
self.cache_factory = cache_factory
self.event_loop = event_loop
@asyncio.coroutine
def handle_request(self, message, payload):
try:
url = re.search('^/(?P<operation>\w+)$', message.path)
if url is None:
return (yield from self.error(102, 'The request path is invalid', message))
# Get the operation function corresponding to the URL path
operation_name = url.group('operation')
operation = getattr(self.controller, operation_name, None)
if operation_name == '' or operation_name[0] == '_' or operation is None:
return (yield from self.error(
103, 'The operation name {name} is invalid'.format(name=operation_name), message))
# Read the POST body
post_data = yield from payload.read()
post_vars = {str(k, 'utf-8'): str(v[0], 'utf-8') for k, v in urllib.parse.parse_qs(post_data).items()}
tx_parser = Router.get_transaction_formatter(post_vars.pop('txformat', 'json'))
controller = self.controller(self.configuration, self.cache_factory, tx_parser, self.event_loop)
try:
result = yield from operation(controller, **post_vars)
except TypeError:
return (yield from self.error(104, 'Invalid parameters provided', message))
except ControllerError as error:
return (yield from self.error(201, str(error), message))
except openassets.transactions.TransactionBuilderError as error:
return (yield from self.error(301, type(error).__name__, message))
except NotImplementedError as error:
return (yield from self.error(202, str(error), message))
response = self.create_response(200, message)
yield from self.json_response(response, result)
if response.keep_alive():
self.keep_alive(True)
except Exception as exception:
response = self.create_response(500, message)
yield from self.json_response(
response, {'error': {'code': 0, 'message': 'Internal server error', 'details': str(exception)}})
def create_response(self, status, message):
response = aiohttp.Response(self.writer, status, http_version=message.version)
response.add_header('Content-Type', 'text/json')
return response
@asyncio.coroutine
def error(self, code, error, message):
response = self.create_response(400, message)
yield from self.json_response(response, {'error': {'code': code, 'message': error}})
@asyncio.coroutine
def json_response(self, response, data):
buffer = bytes(json.dumps(data, indent=4, separators=(',', ': ')), 'utf-8')
response.add_header('Content-Length', str(len(buffer)))
response.send_headers()
response.write(buffer)
yield from response.write_eof()
class Router:
"""Infrastructure for routing command line calls to the right function."""
extra_parameters = [
('txformat', "Format of transactions if a transaction is returned ('raw' or 'json')", 'json')
]
def __init__(self, controller, output, cache_factory, configuration, event_loop, description=None):
self.controller = controller
self.configuration = configuration
self.event_loop = event_loop
self.output = output
self.cache_factory = cache_factory
self._parser = argparse.ArgumentParser(description=description)
subparsers = self._parser.add_subparsers()
subparser = subparsers.add_parser('server', help="Starts the Colorcore JSON/RPC server.")
subparser.set_defaults(_func=self._run_rpc_server)
subparser = subparsers.add_parser('stop', help="Stop the Colorcore JSON/RPC server.")
subparser.set_defaults(_func=self._stop)
for name, function in inspect.getmembers(self.controller, predicate=inspect.isfunction):
# Skip non-public functions
if name[0] != '_':
subparser = subparsers.add_parser(name, help=function.__doc__)
self._create_subparser(subparser, configuration, function)
def _create_subparser(self, subparser, configuration, func):
subparser.set_defaults(_func=self._execute_operation(configuration, func))
func_signature = inspect.signature(func)
for name, arg in func_signature.parameters.items():
if name == 'self':
continue
if arg.kind != arg.POSITIONAL_OR_KEYWORD:
continue
arg_help = arg.annotation if arg.annotation is not arg.empty else None
if arg.default is arg.empty:
# a positional argument
subparser.add_argument(name, help=arg_help)
else:
# an optional argument
subparser.add_argument('--' + name, help=arg_help, nargs='?', default=arg.default)
for name, help, default in self.extra_parameters:
subparser.add_argument('--' + name, help=help, nargs='?', default=default)
def _execute_operation(self, configuration, function):
def decorator(*args, txformat, **kwargs):
# Instantiate the controller
controller = self.controller(
configuration, self.cache_factory, self.get_transaction_formatter(txformat), self.event_loop)
@asyncio.coroutine
def coroutine_wrapper():
try:
# Execute the operation on the controller
result = yield from function(controller, *args, **kwargs)
# Write the output of the operation onto the output stream
# sys.stdout.write("GETBALANCE")
self.output.write(json.dumps(result, indent=4, separators=(',', ': '), sort_keys=False) + '\n')
except ControllerError as error:
# The controller raised a known error
self.output.write("Error: {}\n".format(str(error)))
except openassets.transactions.TransactionBuilderError as error:
# A transaction could not be built
self.output.write("Error: {}\n".format(type(error).__name__))
except NotImplementedError as error:
# The transaction provider used is not capable of performing the operation
self.output.write("Error: {}\n".format(str(error)))
self.event_loop.run_until_complete(coroutine_wrapper())
return decorator
@staticmethod
def get_transaction_formatter(format):
"""
Returns a function for formatting output.
:param str format: Either 'json' for returning a JSON representation of the transaction, or 'raw' to return the
hex-encoded raw transaction. If the object is not a transaction, it is returned unmodified.
:return: The formatted response.
"""
if format == 'json':
def get_transaction_json(transaction):
if isinstance(transaction, lib.bitcoin.core.CTransaction):
return {
'version': transaction.nVersion,
'locktime': transaction.nLockTime,
'vin': [{
'txid': lib.bitcoin.core.b2lx(input.prevout.hash),
'vout': input.prevout.n,
'sequence': input.nSequence,
'scriptSig': {
'hex': lib.bitcoin.core.b2x(bytes(input.scriptSig))
}
}
for input in transaction.vin],
'vout': [{
'value': output.nValue,
'n': index,
'scriptPubKey': {
'hex': lib.bitcoin.core.b2x(bytes(output.scriptPubKey))
}
}
for index, output in enumerate(transaction.vout)]
}
else:
return transaction
else:
def get_transaction_json(transaction):
if isinstance(transaction, lib.bitcoin.core.CTransaction):
return lib.bitcoin.core.b2x(transaction.serialize())
else:
return transaction
return get_transaction_json
def _run_rpc_server(self):
"""
Starts the JSON/RPC server.
"""
# Instantiate the request handler
def create_server():
return RpcServer(
self.controller, self.configuration, self.event_loop, self.cache_factory,
keep_alive=60, debug=True, allowed_methods=('POST','GET'))
# Exit on SIGINT or SIGTERM
try:
for signal_name in ('SIGINT', 'SIGTERM'):
self.event_loop.add_signal_handler(getattr(signal, signal_name), self.event_loop.stop)
except NotImplementedError:
pass
aiohttp.HttpMessage.SERVER_SOFTWARE = 'Colorcore/{version}'.format(version=colorcore.__version__)
root_future = self.event_loop.create_server(create_server, '', self.configuration.rpc_port)
self.event_loop.run_until_complete(root_future)
self.output.write("Starting {name} Colorcore server on port {port}...\n".format(name=self.configuration.coinname, port=self.configuration.rpc_port))
self.event_loop.run_forever()
def parse(self, args):
"""
Parses the arguments and executes the corresponding operation.
:param list[str] args: The arguments to parse.
"""
args = vars(self._parser.parse_args(args))
func = args.pop('_func', self._parser.print_usage)
func(**args)
def _stop(self):
"""
Stops the JSON/RPC server.
"""
self.output.write("Stopping {name} Colorcore server on port {port}.\n".format(name=self.configuration.coinname, port=self.configuration.rpc_port))
self.event_loop.close()
class ControllerError(Exception):
"""A known error occurred while executing the operation."""
pass
<file_sep>#include "bidpage.h"
#include "ui_bidpage.h"
#include "util.h"
#include "guiutil.h"
#include "clientmodel.h"
#include "chainparams.h"
#include "main.h"
#include "net.h"
#include "basenodeman.h"
#include "bidtracker.h"
#include <fstream>
#include <QMessageBox>
#include <QDesktopServices>
#include <QUrl>
#include <QProcess>
#include <QStandardPaths>
#include <QDir>
#include <QFile>
#include <QTextStream>
BidPage::BidPage(QWidget *parent)
: QWidget(parent), ui(new Ui::BidPage)
{
ui->setupUi(this);
ui->lineEditBid->setEnabled(false); // cannot calc until update clicked and data fetched
ui->label_BTCassets->setStyleSheet("border: none");
connect(ui->pushButtonBTCExplorer, SIGNAL(clicked()), this, SLOT(SummonBTCExplorer()));
connect(ui->pushButtonBTC, SIGNAL(clicked()), this, SLOT(SummonBTCWallet()));
connect(ui->pushButtonRefresh, SIGNAL(clicked()), this, SLOT(GetBids()));
connect(ui->lineEditBid, SIGNAL(returnPressed()), this, SLOT(Estimate()));
theme = GetArg("-theme", "");
QString themestring = QString::fromUtf8(theme.c_str());
if (themestring.contains("orange"))
{
ui->pushButtonRefresh->setStyleSheet("border: 2px solid #ffa405");
ui->frame->setStyleSheet("border: 2px solid #ffa405");
ui->label_heading->setStyleSheet("border: none");
}
else if (themestring.contains("dark"))
{
ui->pushButtonRefresh->setStyleSheet("border: 2px solid #ffa405");
ui->frame->setStyleSheet("border: 2px solid #ffa405");
ui->label_heading->setStyleSheet("border: none");
}
else if (themestring.contains("green"))
{
ui->pushButtonRefresh->setStyleSheet("border: 2px solid #45f806");
ui->frame->setStyleSheet("border: 2px solid #45f806");
ui->label_heading->setStyleSheet("border: none");
}
else if (themestring.contains("blue"))
{
ui->pushButtonRefresh->setStyleSheet("border: 2px solid #031cd7");
ui->frame->setStyleSheet("border: 2px solid #031cd7");
ui->label_heading->setStyleSheet("border: none");
}
else if (themestring.contains("pink"))
{
ui->pushButtonRefresh->setStyleSheet("border: 2px solid #ff03a3");
ui->frame->setStyleSheet("border: 2px solid #ff03a3");
ui->label_heading->setStyleSheet("border: none");
}
else if (themestring.contains("purple"))
{
ui->pushButtonRefresh->setStyleSheet("border: 2px solid #a106a7");
ui->frame->setStyleSheet("border: 2px solid #a106a7");
ui->label_heading->setStyleSheet("border: none");
}
else if (themestring.contains("turq"))
{
ui->pushButtonRefresh->setStyleSheet("border: 2px solid #0ab4dc");
ui->frame->setStyleSheet("border: 2px solid #0ab4dc");
ui->label_heading->setStyleSheet("border: none");
}
//fallback on default
else
{
ui->pushButtonRefresh->setStyleSheet("border: 2px solid #ffa405");
ui->frame->setStyleSheet("border: 1px solid #ffa405");
ui->label_heading->setStyleSheet("border: none");
}
}
void BidPage::setClientModel(ClientModel *model)
{
clientModel = model;
if(model)
{
setNumBlocks(model->getNumBlocks());
//connect(model, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
}
}
int BidPage::getNumBlocks()
{
LOCK(cs_main);
return chainActive.Height();
}
void BidPage::setNumBlocks(int count)
{
ui->labelNumber->setText(QString::number(count));
}
void BidPage::Estimate()
{
QString bidtotal = ui->labelTotal_2->text();
float bidz = bidtotal.toFloat();
float mybid = ui->lineEditBid->text().toFloat();
float newtotal = bidz + mybid;
float mybcr = (mybid / newtotal) * 18000;
QString mybcrz = QString::number(mybcr);
float cost = mybid / mybcr;
QString coststr = QString::number(cost, 'f', 8);
ui->labelBCR->setText("<b>" + mybcrz + "</b> BCR @ " + "<b>" + coststr + "</b>");
}
void BidPage::GetBids()
{
// get current BTC assets
Bidtracker r;
double btcassets = r.getbalance("https://blockchain.info/q/addressbalance/16bi8R4FoDHfjNJ1RhpvcAEn4Cz78FbtZB");
QString reserves = QString::number(btcassets/COIN, 'f', 8);
ui->label_BTCassets->setText("Current BTC reserves: " + reserves);
// calc time until next 00:00 GMT
long int startdate = 1450396800; // 18 December 2015 00:00
long int current = GetTime();
long int diff = current - startdate;
int until = 86400 - (diff % 86400);
ui->labelNumber->setText(GUIUtil::formatDurationStr(until));
// get default datadir, tack on bidtracker
QString dataDir = getDefaultDataDirectory();
QString bidDir = "bidtracker";
QString datPath = pathAppend(dataDir, bidDir);
// get bids from /bidtracker/final.dat
QString bidspath = QDir(datPath).filePath("prefinal.dat");
double btctot = 0;
// for each line in file, get the float after the comma
QFile bidsFile(bidspath);
if (bidsFile.open(QIODevice::ReadOnly))
{
QTextStream btcin(&bidsFile);
while (!btcin.atEnd())
{
QString line = btcin.readLine();
if (line.isEmpty()){ continue; }
else if (line.startsWith("1")) // BTC
{
QString btcamount = line.remove(0, 35);
btctot = btctot + btcamount.toDouble();
}
else // we should never get here
{
QMessageBox::information(0, QString("Oops!"), QString("There is a problem with the file, please try again later!"), QMessageBox::Ok);
}
}
bidsFile.close();
}
// btctot, ltctot and dashtot are in satoshis, so divide by 10000000 to get right units
// to do - add radiobuttons or dropdown to select sats or not?
double btctotU = btctot / 100000000;
QString btctotal = QString::number(btctotU, 'f', 8);
//ui->labelBTC_2->setText(btctotal);
// add 'em up and display 'em
double alltot = btctotU;
QString alltotal = QString::number(alltot, 'f', 8);
ui->labelTotal_2->setText(alltotal);
// calc price per BCR based on total bids and display it
double bcrprice = alltot / 18000;
QString bcrPrice = QString::number(bcrprice, 'f', 8);
ui->labelEstprice_2->setText(bcrPrice);
ui->lineEditBid->setEnabled(true);
}
QString BidPage::pathAppend(const QString& path1, const QString& path2)
{
return QDir::cleanPath(path1 + QDir::separator() + path2);
}
QString BidPage::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
void BidPage::SummonBTCExplorer()
{
QDesktopServices::openUrl(QUrl("https://btc.blockr.io/address/info/1BCRbid2i3wbgqrKtgLGem6ZchcfYbnhNu", QUrl::TolerantMode));
}
void BidPage::SummonBTCWallet()
{
QProcess *proc = new QProcess(this);
#ifdef linux
proc->startDetached("bitcoin-qt");
#elif _WIN32
proc->startDetached("bitcoin-qt.exe");
#endif
}
BidPage::~BidPage()
{
delete ui;
}
<file_sep>// Copyright (c) 2014 The ShadowCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef SEC_MESSAGE_H
#define SEC_MESSAGE_H
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
#include "base58.h"
#include "net.h"
#include "db.h"
#include "pubkey.h"
#include "streams.h"
#include "ui_interface.h"
#include "wallet.h"
#include "lz4/lz4.h"
typedef std::vector<unsigned char, secure_allocator<unsigned char> > secure_buffer;
typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > secure_string;
const unsigned int SMSG_HDR_LEN = 84; // length of unencrypted header, 4 + 4 + 8 + 33 + 3 + 32
const unsigned int SMSG_PL_HDR_LEN = 4+33+1+65; // length of encrypted header in payload
const unsigned int SMSG_BUCKET_LEN = 60 * 10; // in seconds
const unsigned int SMSG_RETENTION = 60 * 60 * 24 * 90; // in seconds
const unsigned int SMSG_SEND_DELAY = 2; // in seconds, SecureMsgSendData will delay this long between firing
const unsigned int SMSG_THREAD_DELAY = 5;
const unsigned int SMSG_TIME_LEEWAY = 60;
const unsigned int SMSG_TIME_IGNORE = 90; // seconds that a peer is ignored for if they fail to deliver messages for a smsgWant
const unsigned int SMSG_MAX_MSG_BYTES = 4096; // the user input part
// max size of payload worst case compression
const unsigned int SMSG_MAX_MSG_WORST = LZ4_COMPRESSBOUND(SMSG_MAX_MSG_BYTES+SMSG_PL_HDR_LEN);
#define SMSG_MASK_UNREAD (1 << 0)
extern bool fSecMsgEnabled;
class SecMsgStored;
// Inbox db changed, called with lock cs_smsgDB held.
extern boost::signals2::signal<void (SecMsgStored& inboxHdr)> NotifySecMsgInboxChanged;
// Outbox db changed, called with lock cs_smsgDB held.
extern boost::signals2::signal<void (SecMsgStored& outboxHdr)> NotifySecMsgOutboxChanged;
// Wallet Unlocked, called after all messages received while locked have been processed.
extern boost::signals2::signal<void ()> NotifySecMsgWalletUnlocked;
class SecMsgBucket;
class SecMsgAddress;
class SecMsgOptions;
extern std::map<int64_t, SecMsgBucket> smsgBuckets;
extern std::vector<SecMsgAddress> smsgAddresses;
extern SecMsgOptions smsgOptions;
extern CCriticalSection cs_smsg; // all except inbox and outbox
extern CCriticalSection cs_smsgDB;
struct PayloadHeader {
unsigned char cpkS[33]; // public key for reply
unsigned char lenPlain[4];
unsigned char sigKeyVersion[1]; // version of public key hash derived form signature
unsigned char signature[65]; // provides authentication, signature[0] == 0 -> anon message
};
struct SecureMessageHeader {
uint32_t nVersion;
uint32_t nPayload;
int64_t timestamp;
unsigned char cpkR[33];
unsigned char reserved[3];
unsigned char mac[32];
unsigned char hash[32];
SecureMessageHeader() {}
SecureMessageHeader(const unsigned char *header) {
memcpy(this, header, SMSG_HDR_LEN);
}
unsigned char *begin() const {
return (unsigned char*) &nVersion;
}
unsigned char *end() const {
return (unsigned char*) (hash + sizeof(hash));
}
unsigned int GetSerializeSize(int, int=0) const
{
return (char*) hash - (char*) this;
}
template<typename Stream>
void Serialize(Stream& s, int, int=0) const
{
s.write((char*) this, (char*) hash - (char*) this);
}
template<typename Stream>
void Unserialize(Stream& s, int, int=0)
{
s.read((char*) this, (char*) hash - (char*) this);
}
};
class SecureMessage : public SecureMessageHeader {
public:
std::vector<unsigned char> vchPayload;
SecureMessageHeader *Header() {
return (SecureMessageHeader *) this;
}
SecureMessage() { }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(*this->Header());
READWRITE(this->vchPayload);
}
};
class MessageData
{
// -- Decrypted SecureMessage data
public:
int64_t timestamp;
secure_string sToAddress;
secure_string sFromAddress;
secure_string sMessage;
};
class SecMsgToken
{
public:
SecMsgToken(int64_t ts, const unsigned char* p, int np, long int o)
{
timestamp = ts;
if (np < 8) // payload will always be > 8, just make sure
memset(sample, 0, 8);
else
memcpy(sample, p, 8);
offset = o;
};
SecMsgToken() {};
~SecMsgToken() {};
bool operator <(const SecMsgToken& y) const
{
// pack and memcmp from timesent?
if (timestamp == y.timestamp)
return memcmp(sample, y.sample, 8) < 0;
return timestamp < y.timestamp;
}
int64_t timestamp;
unsigned char sample[8]; // a message hash
int64_t offset; // offset
};
class SecMsgBucket
{
public:
SecMsgBucket()
{
timeChanged = 0;
hash = 0;
nLockCount = 0;
nLockPeerId = 0;
};
~SecMsgBucket() {};
void hashBucket();
int64_t timeChanged;
uint32_t hash; // token set should get ordered the same on each node
uint32_t nLockCount; // set when smsgWant first sent, unset at end of smsgMsg, ticks down in ThreadSecureMsg()
uint32_t nLockPeerId; // id of peer that bucket is locked for
std::set<SecMsgToken> setTokens;
};
// -- get at the data
class CBitcreditAddress_B : public CBitcreditAddress
{
public:
unsigned char getVersion() const
{
assert(vchVersion.size() == sizeof(unsigned char));
return vchVersion[0];
}
};
class SecMsgAddress
{
public:
SecMsgAddress() {};
SecMsgAddress(std::string sAddr, bool receiveOn, bool receiveAnon)
{
sAddress = sAddr;
fReceiveEnabled = receiveOn;
fReceiveAnon = receiveAnon;
};
std::string sAddress;
bool fReceiveEnabled;
bool fReceiveAnon;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(this->sAddress);
READWRITE(this->fReceiveEnabled);
READWRITE(this->fReceiveAnon);
}
};
class SecMsgOptions
{
public:
SecMsgOptions()
{
// -- default options
fNewAddressRecv = true;
fNewAddressAnon = true;
}
bool fNewAddressRecv;
bool fNewAddressAnon;
};
class SecMsgStored
{
public:
int64_t timeReceived;
char status; // read etc
uint16_t folderId;
std::string sAddrTo; // when in owned addr, when sent remote addr
std::string sAddrOutbox; // owned address this copy was encrypted with
std::vector<unsigned char> vchMessage; // message header + encryped payload
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(this->timeReceived);
READWRITE(this->status);
READWRITE(this->folderId);
READWRITE(this->sAddrTo);
READWRITE(this->sAddrOutbox);
READWRITE(this->vchMessage);
}
};
class SecMsgDB
{
public:
SecMsgDB()
{
activeBatch = NULL;
};
~SecMsgDB()
{
// -- deletes only data scoped to this TxDB object.
if (activeBatch)
delete activeBatch;
};
bool Open(const char* pszMode="r+");
bool ScanBatch(const CDataStream& key, std::string* value, bool* deleted) const;
bool TxnBegin();
bool TxnCommit();
bool TxnAbort();
bool ReadPK(CKeyID& addr, CPubKey& pubkey);
bool WritePK(CKeyID& addr, CPubKey& pubkey);
bool ExistsPK(CKeyID& addr);
bool NextSmesg(leveldb::Iterator* it, std::string& prefix, unsigned char* vchKey, SecMsgStored& smsgStored);
bool NextSmesgKey(leveldb::Iterator* it, std::string& prefix, unsigned char* vchKey);
bool ReadSmesg(unsigned char* chKey, SecMsgStored& smsgStored);
bool WriteSmesg(unsigned char* chKey, SecMsgStored& smsgStored);
bool ExistsSmesg(unsigned char* chKey);
bool EraseSmesg(unsigned char* chKey);
leveldb::DB *pdb; // points to the global instance
leveldb::WriteBatch *activeBatch;
};
int SecureMsgBuildBucketSet();
int SecureMsgAddWalletAddresses();
int SecureMsgReadIni();
int SecureMsgWriteIni();
bool SecureMsgStart(bool fDontStart, bool fScanChain);
bool SecureMsgEnable();
bool SecureMsgDisable();
bool SecureMsgReceiveData(CNode* pfrom, std::string strCommand, CDataStream& vRecv);
bool SecureMsgSendData(CNode* pto, bool fSendTrickle);
bool SecureMsgScanBlock(CBlock& block);
bool ScanChainForPublicKeys(CBlockIndex* pindexStart, size_t n);
bool SecureMsgScanBlockChain();
int SecureMsgScanBuckets(std::string &, bool = false);
static inline int SecureMsgWalletUnlocked() {
std::string error;
return SecureMsgScanBuckets(error, true);
}
int SecureMsgWalletKeyChanged(std::string sAddress, std::string sLabel, ChangeType mode);
int SecureMsgScanMessage(const SecureMessageHeader &smsg, const unsigned char *pPayload, bool reportToGui);
int SecureMsgGetStoredKey(CKeyID& ckid, CPubKey& cpkOut);
int SecureMsgGetLocalKey(CKeyID& ckid, CPubKey& cpkOut);
int SecureMsgGetLocalPublicKey(std::string& strAddress, std::string& strPublicKey);
int SecureMsgAddAddress(std::string& address, std::string& publicKey);
int SecureMsgRetrieve(SecMsgToken &token, SecureMessage &smsg);
int SecureMsgReceive(CNode* pfrom, std::vector<unsigned char>& vchData);
int SecureMsgStoreUnscanned(const SecureMessageHeader &smsg, const unsigned char *pPayload);
int SecureMsgStore(const SecureMessageHeader &smsg, const unsigned char *pPayload, bool fUpdateBucket);
int SecureMsgStore(const SecureMessage &smsg, bool fUpdateBucket);
int SecureMsgSend(std::string& addressFrom, std::string& addressTo, std::string& message, std::string& sError);
int SecureMsgValidate(const SecureMessageHeader &smsg, size_t nPayload);
int SecureMsgEncrypt(SecureMessage& smsg, std::string& addressFrom, std::string& addressTo, std::string& message);
int SecureMsgDecrypt(bool fTestOnly, const std::string& address, const SecureMessageHeader& smsg, const unsigned char *pPayload, MessageData& msg);
int SecureMsgDecrypt(const SecMsgStored& smsgStored, MessageData &msg, std::string &errorMsg);
#endif // SEC_MESSAGE_H
<file_sep>#include "invoiceviewpage.h"
#include "ui_invoiceviewpage.h"
#include "messagemodel.h"
#include "optionsmodel.h"
#include "sendmessagesdialog.h"
#include "bitcreditunits.h"
#include "bitcreditgui.h"
#include "guiutil.h"
#include <QSortFilterProxyModel>
InvoiceViewPage::InvoiceViewPage(QWidget *parent) :
QDialog(parent),
ui(new Ui::InvoiceViewPage)
{
ui->setupUi(this);
}
InvoiceViewPage::~InvoiceViewPage()
{
delete ui;
}
void InvoiceViewPage::setModel(InvoiceTableModel *model)
{
this->model = model;
if(!model)
return;
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model->getInvoiceItemTableModel());
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
invoiceProxyModel = new QSortFilterProxyModel(this);
invoiceProxyModel->setSourceModel(model);
invoiceProxyModel->setDynamicSortFilter(true);
invoiceProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
invoiceProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
ui->invoiceItemTableView->setModel(proxyModel);
// Set column widths
ui->invoiceItemTableView->horizontalHeader()->resizeSection(InvoiceItemTableModel::Code, 100);
ui->invoiceItemTableView->horizontalHeader()->resizeSection(InvoiceItemTableModel::Description, 320);
#if QT_VERSION < 0x050000
ui->invoiceItemTableView->horizontalHeader()->setResizeMode(InvoiceItemTableModel::Description, QHeaderView::Stretch);
#else
ui->invoiceItemTableView->horizontalHeader()->setSectionResizeMode(InvoiceItemTableModel::Description, QHeaderView::Stretch);
#endif
ui->invoiceItemTableView->horizontalHeader()->resizeSection(InvoiceItemTableModel::Quantity, 100);
//ui->invoiceItemTableView->horizontalHeader()->resizeSection(InvoiceItemTableModel::Tax, 100);
ui->invoiceItemTableView->horizontalHeader()->resizeSection(InvoiceItemTableModel::Price, 100);
ui->invoiceItemTableView->horizontalHeader()->resizeSection(InvoiceItemTableModel::Amount, 100);
// Hidden columns
ui->invoiceItemTableView->setColumnHidden(InvoiceItemTableModel::Type, true);
ui->subtotalLabel->setVisible(false);
ui->taxLabel->setVisible(false);
ui->subtotal->setVisible(false);
ui->tax->setVisible(false);
connect(model->getInvoiceItemTableModel(), SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector<int>)), this, SLOT(updateTotal()));
//connect(ui->invoiceItemTableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(selectionChanged()));
//selectionChanged();
}
void InvoiceViewPage::loadRow(int row, bool allowEdit)
{
ui->companyInfoLeft ->setText(model->data(model->index(row, model->CompanyInfoLeft, QModelIndex()), Qt::DisplayRole).toString());
ui->companyInfoRight->setText(model->data(model->index(row, model->CompanyInfoRight, QModelIndex()), Qt::DisplayRole).toString());
ui->billingInfoLeft ->setText(model->data(model->index(row, model->BillingInfoLeft, QModelIndex()), Qt::DisplayRole).toString());
ui->billingInfoRight->setText(model->data(model->index(row, model->BillingInfoRight, QModelIndex()), Qt::DisplayRole).toString());
ui->footer ->setText(model->data(model->index(row, model->Footer, QModelIndex()), Qt::DisplayRole).toString());
ui->dueDate ->setDate(model->data(model->index(row, model->DueDate, QModelIndex()), Qt::DisplayRole).toDate());
ui->invoiceNumber ->setText(model->data(model->index(row, model->InvoiceNumber, QModelIndex()), Qt::DisplayRole).toString());
ui->total ->setText(model->data(model->index(row, model->Total, QModelIndex()), Qt::DisplayRole).toString());
proxyModel->setFilterRole(Qt::UserRole);
proxyModel->setFilterFixedString(model->data(model->index(row, 999, QModelIndex()), Qt::UserRole).toString());
ui->sendButton->setVisible(allowEdit);
resend = allowEdit;
curRow = row;
}
void InvoiceViewPage::newInvoice()
{
/* TODO: Pre-populate...
ui->companyInfoLeft ->setText(model->data(model->index(row, model->CompanyInfoLeft, QModelIndex()), Qt::DisplayRole).toString());
ui->companyInfoRight->setText(model->data(model->index(row, model->CompanyInfoRight, QModelIndex()), Qt::DisplayRole).toString());
ui->billingInfoLeft ->setText(model->data(model->index(row, model->BillingInfoLeft, QModelIndex()), Qt::DisplayRole).toString());
ui->billingInfoRight->setText(model->data(model->index(row, model->BillingInfoRight, QModelIndex()), Qt::DisplayRole).toString());
ui->footer ->setText(model->data(model->index(row, model->Footer, QModelIndex()), Qt::DisplayRole).toString());
ui->dueDate ->setDate(model->data(model->index(row, model->DueDate, QModelIndex()), Qt::DisplayRole).toDate());
ui->invoiceNumber ->setText(model->data(model->index(row, model->InvoiceNumber, QModelIndex()), Qt::DisplayRole).toString());
ui->total ->setText(model->data(model->index(row, model->Total, QModelIndex()), Qt::DisplayRole).toString());
*/
//proxyModel->setFilterRole(Qt::UserRole);
//proxyModel->setFilterFixedString("new");
//if(proxyModel->rowCount() == 0)
//{
model->newInvoiceItem();
//}
ui->sendButton->setVisible(true);
}
void InvoiceViewPage::on_sendButton_clicked()
{
if(!model)
return;
SendMessagesDialog dlg(this);
dlg.setModel(model->getMessageModel());
if(resend)
{
dlg.loadInvoice(model->getInvoiceJSON(curRow), model->data(model->index(curRow, model->FromAddress, QModelIndex()), Qt::DisplayRole).toString(), model->data(model->index(curRow, model->ToAddress, QModelIndex()), Qt::DisplayRole).toString());
}
else
{
model->newInvoice(ui->companyInfoLeft->document()->toPlainText(),
ui->companyInfoRight->document()->toPlainText(),
ui->billingInfoLeft->document()->toPlainText(),
ui->billingInfoRight->document()->toPlainText(),
ui->footer->document()->toPlainText(),
ui->dueDate->date(),
ui->invoiceNumber->text());
dlg.loadInvoice(model->getInvoiceJSON(0));
}
if(dlg.exec() == 0)
done(0);
}
void InvoiceViewPage::updateTotal()
{
if(!model)
return;
int64_t total = 0;
int rows = proxyModel->rowCount();
for(int i = 0; i < rows; i++)
{
total += proxyModel->data(proxyModel->index(i, InvoiceItemTableModel::Amount), Qt::EditRole).toLongLong();
if(i+1==rows && proxyModel->data(proxyModel->index(i, InvoiceItemTableModel::Code)).toString() != "")
model->newInvoiceItem();
}
ui->total->setText(BitcreditUnits::formatWithUnit(model->getMessageModel()->getOptionsModel()->getDisplayUnit(), total));
}
<file_sep>#ifndef BIDTRACKER_H
#define BIDTRACKER_H
#include "main.h"
#include <curl/curl.h>
#include <iostream>
#include <string>
#include "json/json_spirit.h"
using namespace json_spirit;
#ifndef BOOST_SPIRIT_THREADSAFE
#define BOOST_SPIRIT_THREADSAFE
#endif
void getbids();
extern int totalbid;
extern std::map<std::string,double> getbidtracker();
class Bidtracker
{
public:
CURLcode res;
CURL *curl;
void btcgetunspent();
void btcgetunspentbackup();
void btcsortunspent();
void btcsortunspentbackup();
double getbalance(string url);
double usdbtc();
long double bcrbtc();
double btcgetprice();
double bcrgetprice();
double credit();
double newcredit;
double totalcredit;
void combine();
};
#endif // BIDTRACKER_H
<file_sep>#include "trust.h"
#include "bidtracker.h"
#include "voting.h"
#include "util.h"
#include "utilmoneystr.h"
#include "base58.h"
#include "primitives/transaction.h"
#include "primitives/block.h"
int callback(void *NotUsed, int argc, char **argv, char **azColName){
int i;
for(i=0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
void TrustEngine::createdb()
{
sqlite3 *rawdb;
char *zErrMsg = 0;
int rc;
vector<const char*> sql;
rc = sqlite3_open((GetDataDir() /"ratings/rawdata.db").string().c_str(), &rawdb);
if( rc ){
if(fDebug)LogPrintf("Can't open database: %s\n", sqlite3_errmsg(rawdb));
exit(0);
}else{
if(fDebug)LogPrintf("Opened database successfully\n");
}
/* Create SQL statements */
sql.push_back("CREATE TABLE RAWDATA(" \
"ADDRESS TEXT PRIMARY KEY NOT NULL," \
"BALANCE INTEGER DEFAULT 0," \
"FIRSTSEEN INTEGER DEFAULT 0," \
"TXINCOUNT INTEGER DEFAULT 0," \
"TXOUTCOUNT INTEGER DEFAULT 0," \
"TOTALIN INTEGER DEFAULT 0," \
"TOTALOUT INTEGER DEFAULT 0);");
sql.push_back("CREATE TABLE BLOCKS(" \
" ID INTEGER PRIMARY KEY AUTOINCREMENT," \
" HASH TEXT," \
" TIME INTEGER," \
" MINER TEXT);");
/* Execute SQL statements */
for (unsigned int i =0;i < sql.size();i++){
rc = sqlite3_exec(rawdb, sql[i], callback, 0, &zErrMsg);
if( rc != SQLITE_OK ){
if (fDebug)LogPrintf("SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
else{
if (fDebug)LogPrintf( "Tables created successfully\n");
}
}
if(sqlite3_close(rawdb) != SQLITE_OK ){
if (fDebug)LogPrintf("SQL unable to close database %s\n", sqlite3_errmsg(rawdb));
sqlite3_free(zErrMsg);
}else{
if (fDebug)LogPrintf( "database closed successfully\n");
}
}
|
c6c6592c1a370d3e6990d2f45276860ffb73c8af
|
[
"Shell",
"C",
"INI",
"Markdown",
"Text",
"Python",
"C++"
] | 63 |
Shell
|
bitcreditscc/bicreditsnew
|
a9462c311ad4b7f21aec7a6dcf4d4f03d23ade15
|
113c8ef251052402887c1d7c49bf3d00b4e7dde9
|
refs/heads/master
|
<file_sep>#----------------------------------------------------------
# Load library
#----------------------------------------------------------
library(dplyr)
#----------------------------------------------------------
# Prepare dataset
#----------------------------------------------------------
# Load Data
filepath <- "household_power_consumption.txt"
data <- read.table(filepath, header=TRUE, sep=";", na.strings="?", stringsAsFactors=FALSE)
rm(filepath)
# Convert data$Date to data
data$Date <- as.Date(data$Date,"%d/%m/%Y")
tbl_data<-tbl_df(data)
rm(data)
# Create Dataset
dataset<-filter(tbl_data, Date >= "2007-02-01" & Date <="2007-02-02")
rm(tbl_data)
#Add column DateTime to dataset
dataset<-mutate(dataset, DateTime = as.POSIXct(paste(as.Date(Date), Time)))
# Build line chart, add legend and save it as png
png("plot3.png", width=480, height=480)
with(dataset, {
plot(Sub_metering_1 ~ DateTime, type="l", ylab="Energy Submetering", xlab="")
lines(Sub_metering_2 ~ DateTime,col="Red")
lines(Sub_metering_3 ~ DateTime,col="Blue")
})
# Legend
legend("topright", col=c("black", "red", "blue"), lty=1, lwd=2, legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
dev.off()
<file_sep>#----------------------------------------------------------
# Load library
#----------------------------------------------------------
library(dplyr)
#----------------------------------------------------------
# Prepare dataset
#----------------------------------------------------------
# Load Data
filepath <- "household_power_consumption.txt"
data <- read.table(filepath, header=TRUE, sep=";", na.strings="?", stringsAsFactors=FALSE)
rm(filepath)
# Convert data$Date to data
data$Date <- as.Date(data$Date,"%d/%m/%Y")
tbl_data<-tbl_df(data)
rm(data)
# Create Dataset
dataset<-filter(tbl_data, Date >= "2007-02-01" & Date <="2007-02-02")
rm(tbl_data)
# Build histogram and save it as png
png("plot1.png", width=480, height=480)
hist(dataset$Global_active_power, main="Global Active Power",xlab="Global Active Power (kilowatts)", ylab="Frequency", col="Red")
dev.off()
<file_sep>#----------------------------------------------------------
# Load library
#----------------------------------------------------------
library(dplyr)
#----------------------------------------------------------
# Prepare dataset
#----------------------------------------------------------
# Load Data
filepath <- "household_power_consumption.txt"
data <- read.table(filepath, header=TRUE, sep=";", na.strings="?", stringsAsFactors=FALSE)
rm(filepath)
# Convert data$Date to data
data$Date <- as.Date(data$Date,"%d/%m/%Y")
tbl_data<-tbl_df(data)
rm(data)
# Create Dataset
dataset<-filter(tbl_data, Date >= "2007-02-01" & Date <="2007-02-02")
rm(tbl_data)
#Add column DateTime to dataset
dataset<-mutate(dataset, DateTime = as.POSIXct(paste(as.Date(Date), Time)))
# Build line chart and save it as png
png("plot2.png", width=480, height=480)
with(dataset, {
plot(Global_active_power ~ DateTime, type="l", ylab="Global Active Power (kilowatts)", xlab="")
})
dev.off()
|
d16ffb78208dcaa7e580fa286bf9fd66e494b724
|
[
"R"
] | 3 |
R
|
djelattre/ExData_Plotting1
|
e747b73039ff610497feee7e1c80a2dc39abff6d
|
c95c63b4e45aa5ee95c36b6cba7bb48ab583da9b
|
refs/heads/master
|
<repo_name>micahsuomi/Word-Variety-Counter<file_sep>/main.js
const form = document.querySelector('.form');
const textArea = document.querySelector('.textarea');
const countWordsBtn = document.querySelector('.count-words-btn');
const totalWords = document.querySelector('.total-words-paragraph');
const longestWordsTitle = document.querySelector('.longest-words__title');
const longestWordsWrapper = document.querySelector('.longest-words__wrapper');
const palindromesWrapper = document.querySelector('.palindromes__wrapper');
const varietyWordsWrapper = document.querySelector('.words-variety__wrapper');
const mostFrequentWordsTitle = document.querySelector('.words-counted__title');
const wordsWrapper = document.querySelector('.words-counted__wrapper');
let testSentence = 'All yo#u n@eed is love. A?ll you &need is %lov$e. All you nee/d is love. All you need is lov@e. Lo%ve is a&ll you nee@d.'
const testRawText = '%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!?';
form.addEventListener('submit', (e) => {
e.preventDefault();
})
const createNode = (e) => {
return document.createElement(e);
}
const sortWordDiv = createNode('div');
const sortWordBtn = createNode('button');
sortWordBtn.setAttribute('class', 'sort-words');
sortWordBtn.textContent = 'Sort Words Length';
const sortCountDiv = createNode('div');
const checkWordsVariety = (paragraphToArr) => {
console.log(paragraphToArr)
let words = paragraphToArr;
let outputArr = [];
//we check the variety of text
for(const word of words) {
//we check if the word is not repeated, if it exists only one it will return an index of -1, //if it does exist after returning -1 it will return its own index
if(outputArr.indexOf(word.toLowerCase()) === -1) {
//we push the words without duplicates into a new array
outputArr.push(word.toLowerCase())
}
}
return outputArr
}
const findPalindromes = (paragraphToArr) => {
let palindromesArr = []
console.log(paragraphToArr)
for(const word of paragraphToArr) {
let reversedArr = []
let splittedWord = word.split('')
let reversedWord
while(splittedWord.length) {
reversedArr.push(splittedWord.pop())
reversedWord = reversedArr.join('')
}
if(reversedWord === word && reversedWord.length > 1) {
palindromesArr.push(word)
}
}
console.log(palindromesArr)
return palindromesArr;
}
const testWords = () => {
wordsWrapper.textContent = '';
totalWords.textContent = '';
varietyWordsWrapper.textContent = '';
longestWordsWrapper.textContent = '';
palindromesWrapper.textContent = '';
let contentLongestWords = '';
let varietyContent = '';
let contentWordsCounted = '';
let palindromesContent = '';
longestWordsTitle.textContent = 'Longest Words';
mostFrequentWordsTitle.textContent = 'Most Frequent Words';
wordsWrapper.append(sortWordDiv);
let regex = /[^A-Za-z ]/ig;
let regexUI = /[^A-Za-z,?!.' ]/ig
let sentence = textArea.value;
let newSentence = sentence.replace(regex,'');
let textAreaDisplay = sentence.replace(regexUI, '');
textArea.value = textAreaDisplay
console.log(newSentence)
let paragraphToArr = newSentence.split(' ');
const sentenceSet = new Set (paragraphToArr);
const sentenceCount = [];
const countArr = [];
for (const w of sentenceSet) {
if(w.length > 0) {
const filteredWords = paragraphToArr.filter((word) => word.toLowerCase() === w.toLowerCase());
sentenceCount.push({word: w, count: filteredWords.length});
countArr.push(w)
}
}
//calls the function to check variety of words and displays it
let result = checkWordsVariety(paragraphToArr);
let varietyPercentage = Math.round((result.length / paragraphToArr.length) * 100);
let palindromesArr = findPalindromes(paragraphToArr);
varietyContent +=
`<div class="variety-word__container">
<p>Words without duplicates: <span class="total">${result.length}</span></p>
<p>Variety: <span class="percentage"> ${varietyPercentage}%</span></p>
</div>`
palindromesContent +=
`<div class="palindromes__container">
<p>Number of Palindromes: <span class="total-palindromes">${palindromesArr.length}</span>: ${palindromesArr.join(', ')}</p>
</div>`
//sorts the longest words
//calls the check variety function to eliminate duplicate words
let sortCountWithVariety = checkWordsVariety(countArr)
sortCountWithVariety.sort((a, b) => {
if(a.length > b.length) return -1;
if(a.length < b.length) return 1;
return 0;
})
//we take the longest 3 words
let longestCounted = sortCountWithVariety.slice(0, 3);
console.log(longestCounted)
//we loop into the longest words and display them on the UI
for(let i = 0; i < longestCounted.length; i++) {
let word = longestCounted[i];
let len = word.length;
contentLongestWords +=
`<div class="longest-word-container">
<p class="longest-word">${word}</p>
<p class="longest-word__length"> ${len} characters</p>
</div>`
}
//we sort all the longest words from ascending
sentenceCount.sort((a, b) => {
if(a.count > b.count) return -1;
if(a.count < b.count) return 1;
return 0;
})
for(const w of sentenceCount) {
let{word, count} = w;
contentWordsCounted +=
`<div class="words-container">
<div class="word-container"><p class="wordCountedText">word: <span class="word"> ${word}</span></p></div>
<div class="count-container"><p>word count: <span class="count">${count}</span></p>
</div>
</div>`
}
longestWordsWrapper.innerHTML = contentLongestWords
varietyWordsWrapper.innerHTML = varietyContent;
palindromesWrapper.innerHTML = palindromesContent;
wordsWrapper.innerHTML = contentWordsCounted;
totalWords.innerHTML = `<p>Total words: <span class="total-words"> ${paragraphToArr.length}</span></p>`;
}
countWordsBtn.addEventListener('click', () => {
if(textArea.value.length < 1) {
wordsWrapper.textContent = "";
totalWords.textContent = `Please input some text`;
totalWords.style.color = `rgb(255, 81, 0)`;
totalWords.style.fontSize = '20px';
} else {
totalWords.style.color = `rgb(0, 0, 0)`;
testWords();
}
})
|
39db616a739d0210f46f6e42b8557a7c4b7c6ff2
|
[
"JavaScript"
] | 1 |
JavaScript
|
micahsuomi/Word-Variety-Counter
|
81e48446926ecf6abcb3aa03c859cfa7c489a445
|
ffb229bbd0e38d580a06f9a311b0d85cf753e1e4
|
refs/heads/master
|
<repo_name>sakjacob/Pomeranian-Game<file_sep>/Step2/Pomeranian.cpp
#include "pch.h"
#include "Pomeranian.h"
#include <string>
using namespace std;
/// Animal filename
const wstring AnimalBetaImageName = L"images/pomeranian.png";
/**
* Constructor
* \param yard Yard this animal is a member of
*/
CPomeranian::CPomeranian(CYard* yard) : CAnimal(yard, AnimalBetaImageName)
{
CAnimal::SetSpeed(minSpeedX, minSpeedY, maxSpeedX, maxSpeedY);
}
/**
* Save this item to an XML node
* \param node The node we are going to be a child of
* \return ptr to a XmlNode object
*/
std::shared_ptr<xmlnode::CXmlNode>
CPomeranian::XmlSave(const std::shared_ptr<xmlnode::CXmlNode>& node)
{
auto itemNode = CAnimal::XmlSave(node);
itemNode->SetAttribute(L"type", L"pomeranian");
return itemNode;
}
<file_sep>/Step2/Yard.h
/**
* \file Yard.h
*
* \author <NAME>
*
* This is the main class responsible for representing
* an yard
*/
#pragma once
#include <memory>
#include <vector>
#include "Item.h"
/**
* Initializes an Yard
*/
class CYard
{
public:
CYard();
virtual ~CYard();
void Add(std::shared_ptr<CItem> item);
/** Draw the yard
* \param graphics The GDI+ graphics context to draw on
*/
void OnDraw(Gdiplus::Graphics* graphics);
std::shared_ptr<CItem> HitTest(int x, int y);
void ToFront(std::shared_ptr<CItem> item);
void Save(const std::wstring& filename);
void Load(const std::wstring& filename);
void Clear();
void virtual XmlItem(const std::shared_ptr<xmlnode::CXmlNode>& node);
void Update(double elapsed);
/// Get the width of the yard
/// \returns Yard width
int GetWidth() const { return mBackground->GetWidth(); }
/// Get the height of the yard
/// \returns Yard height
int GetHeight() const { return mBackground->GetHeight(); }
private:
std::unique_ptr<Gdiplus::Bitmap> mBackground; ///< Background image
/// All of the items to populate our yard
std::vector<std::shared_ptr<CItem> > mItems;
};
<file_sep>/Step2/DecorCastle.h
/**
* \file DecorCastle.h
*
* \author <NAME>
*
* This class defines a beta animal
*/
#pragma once
#include "Item.h"
/**
* Creates a singe beta animal
*/
class CDecorCastle : public CItem
{
public:
/// Default constructor (disabled)
CDecorCastle() = delete;
/// Copy constructor (disabled)
CDecorCastle(const CDecorCastle&) = delete;
CDecorCastle(CYard* yard);
virtual std::shared_ptr<xmlnode::CXmlNode>
XmlSave(const std::shared_ptr<xmlnode::CXmlNode>& node) override;
};
<file_sep>/Step2/Animal.cpp
#include "pch.h"
#include "Animal.h"
#include "Yard.h"
/// Maximum speed in the X direction in
/// in pixels per second
const double MaxSpeedX = 50;
/// Maximum speed in the Y direction in
/// in pixels per second
const double MaxSpeedY = 35;
/**
* Constructor
* \param yard The yard we are in
* \param filename Filename for the image we use
*/
CAnimal::CAnimal(CYard* yard, const std::wstring& filename) :
CItem(yard, filename)
{
mSpeedX = ((double)rand() / RAND_MAX) * MaxSpeedX;
mSpeedY = ((double)rand() / RAND_MAX) * MaxSpeedY;
}
/**
* Determines speed and direction of animal
* \param minSpeedX minimum speed in x direction in pixels per second
* \param minSpeedY minimum speed in y direction in pixels per second
* \param maxSpeedX maximum speed in y direction in pixels per second
* \param maxSpeedY maximum speed in y direction in pixels per second
*/
void CAnimal::SetSpeed(double minSpeedX, double minSpeedY, double maxSpeedX, double maxSpeedY)
{
mSpeedX = minSpeedX + ((double)rand() / RAND_MAX) * (maxSpeedX - minSpeedX);
mSpeedY = minSpeedY + ((double)rand() / RAND_MAX) * (maxSpeedY - minSpeedY);
}
/**
* Handle updates in time of our animal
*
* This is called before we draw and allows us to
* move our animal. We add our speed times the amount
* of time that has elapsed.
* \param elapsed Time elapsed since the class call
*/
void CAnimal::Update(double elapsed)
{
SetLocation(GetX() + mSpeedX * elapsed,
GetY() + mSpeedY * elapsed);
double rightTurn = GetYard()->GetWidth() - 10 - GetImageWidth() / 2;
double leftTurn = GetYard()->GetWidth() - rightTurn;
double bottomTurn = GetYard()->GetHeight() - 10 - GetImageHeight() / 2;
double topTurn = GetYard()->GetHeight() - bottomTurn;
/// Changes direction when animal hits right border of screen
if (mSpeedX > 0 && GetX() >= rightTurn)
{
mSpeedX = -mSpeedX;
SetMirror(mSpeedX < 0);
}
/// Changes diretion when animal hits left border of screen
if (mSpeedX < 0 && GetX() <= leftTurn)
{
mSpeedX = -mSpeedX;
SetMirror(mSpeedX < 0);
}
/// Changes direction when animal hits the bottom border of screen
if (mSpeedY > 0 && GetY() >= bottomTurn)
{
mSpeedY = -mSpeedY;
}
/// Changes direction when animal hits the top border of screen
if (mSpeedY < 0 && GetY() <= topTurn)
{
mSpeedY = -mSpeedY;
}
}
/**
* Save this item to an XML node
* \param node The node we are going to be a child of
* \return ptr to a XmlNode object
*/
std::shared_ptr<xmlnode::CXmlNode>
CAnimal::XmlSave(const std::shared_ptr<xmlnode::CXmlNode>& node)
{
auto itemNode = CItem::XmlSave(node); //save values stored in CItem class
// Save Speed values
itemNode->SetAttribute(L"speedx", mSpeedX);
itemNode->SetAttribute(L"speedy", mSpeedY);
return itemNode;
}
/**
* Load the attributes for an animal node.
*
* This is the base class version that loads the attributes
* common to all animal.
*
* \param node The Xml node we are loading the item from
*/
void CAnimal::XmlLoad(const std::shared_ptr<xmlnode::CXmlNode>& node)
{
CItem::XmlLoad(node);
mSpeedX = node->GetAttributeDoubleValue(L"speedx", 0);
mSpeedY = node->GetAttributeDoubleValue(L"speedy", 0);
SetMirror(mSpeedX < 0);
}
<file_sep>/Step2/Yard.cpp
/**
* \file Yard.cpp
*
* \author <NAME>
*/
#include "pch.h"
#include "Yard.h"
#include "DecorCastle.h"
#include "Pomeranian.h"
#include "Animal.h"
#include "XmlNode.h"
#include <algorithm>
using namespace Gdiplus;
using namespace xmlnode;
using namespace std;
/**
* Yard constructor
*/
CYard::CYard()
{
mBackground = unique_ptr<Gdiplus::Bitmap>(
Bitmap::FromFile(L"images/backyard1.png"));
if (mBackground->GetLastStatus() != Ok)
{
AfxMessageBox(L"Failed to open images/background1.png");
}
}
/**
* Destructor
*/
CYard::~CYard()
{
}
/** Draw the yard
* \param graphics The GDI+ graphics context to draw on
*/
void CYard::OnDraw(Gdiplus::Graphics* graphics)
{
//RectF rc;
//graphics->GetClip(&rc);
//graphics->DrawImage(mBackground.get(), &rc);
graphics->DrawImage(mBackground.get(), 0, 0,
mBackground->GetWidth()*3, mBackground->GetHeight()*3);
FontFamily fontFamily(L"Arial");
Gdiplus::Font font(&fontFamily, 16);
SolidBrush green(Color(0, 64, 0));
graphics->DrawString(L"Under the Sea!", -1, &font, PointF(2, 2), &green);
/// Populates yard
for (auto item : mItems)
{
item->Draw(graphics);
}
}
/**
* Add an item to the yard
* \param item New item to add
*/
void CYard::Add(std::shared_ptr<CItem> item)
{
mItems.push_back(item);
}
/** Test an x,y click location to see if it clicked
* on some item in the yard.
* \param x X location
* \param y Y location
* \returns Pointer to item we clicked on or nullptr if none.
*/
std::shared_ptr<CItem> CYard::HitTest(int x, int y)
{
for (auto i = mItems.rbegin(); i != mItems.rend(); i++)
{
if ((*i)->HitTest(x, y))
{
return *i;
}
}
return nullptr;
}
/**
* If item exists and vector, moves it to the "top" (the end)
* of the vector
* \param item an object derived from CItem
*/
void CYard::ToFront(std::shared_ptr<CItem> item)
{
// finds and erases item from vector
auto loc = find(begin(mItems), end(mItems), item);
if (loc != end(mItems))
{
mItems.erase(loc);
mItems.push_back(item);
}
}
/**
* Save the yard as a .aqua XML file.
*
* Open an XML file and stream the yard data to it.
*
* \param filename The filename of the file to save the yard to
*/
void CYard::Save(const std::wstring& filename)
{
//
// Create an XML document
//
auto root = CXmlNode::CreateDocument(L"aqua");
// Iterate over all items and save them
for (auto item : mItems)
{
item->XmlSave(root);
}
try
{
root->Save(filename);
}
catch (CXmlNode::Exception ex)
{
AfxMessageBox(ex.Message().c_str());
}
}
/**
* Handle an item node.
* \param node Pointer to XML node we are handling
*/
void CYard::XmlItem(const std::shared_ptr<xmlnode::CXmlNode>& node)
{
// A pointer for the item we are loading
shared_ptr<CItem> item;
// We have an item. What type?
wstring type = node->GetAttributeValue(L"type", L"");
if (type == L"castle")
{
item = make_shared<CDecorCastle>(this);
}
if (type == L"pomeranian")
{
item = make_shared<CPomeranian>(this);
}
if (item != nullptr)
{
item->XmlLoad(node);
Add(item);
}
}
/**
* Load the yard from a .aqua XML file.
*
* Opens the XML file and reads the nodes, creating items as appropriate.
*
* \param filename The filename of the file to load the yard from.
*/
void CYard::Load(const std::wstring& filename)
{
// We surround with a try/catch to handle errors
try
{
// Open the document to read
shared_ptr<CXmlNode> root = CXmlNode::OpenDocument(filename);
// Once we know it is open, clear the existing data
Clear();
//
// Traverse the children of the root
// node of the XML document in memory!!!!
//
for (auto node : root->GetChildren())
{
if (node->GetType() == NODE_ELEMENT && node->GetName() == L"item")
{
XmlItem(node);
}
}
}
catch (CXmlNode::Exception ex)
{
AfxMessageBox(ex.Message().c_str());
}
}
/**
* Clear the yard data.
*
* Deletes all known items in the yard.
*/
void CYard::Clear()
{
mItems.clear(); // Clear and destroy the items in the yard
}
/** Handle updates for animation
* \param elapsed The time since the last update
*/
void CYard::Update(double elapsed)
{
for (auto item : mItems)
{
item->Update(elapsed);
}
}<file_sep>/Step2/Pomeranian.h
/**
* \file pomeranian.h
*
* \author <NAME>
*
* This class defines a Pomeranian
*/
#pragma once
#include "Animal.h"
/**
* Creates a singe pomeranian
*/
class CPomeranian : public CAnimal
{
public:
/// Default constructor (disabled)
CPomeranian() = delete;
/// Copy constructor (disabled)
CPomeranian(const CPomeranian&) = delete;
CPomeranian(CYard* yard);
virtual std::shared_ptr<xmlnode::CXmlNode>
XmlSave(const std::shared_ptr<xmlnode::CXmlNode>& node) override;
private:
/// min speed in x direction
double minSpeedX = 5;
/// min speed in y direction
double minSpeedY = 40;
/// possible speed above min x direction
double maxSpeedX = 20;
/// possible speed above min y direction
double maxSpeedY = 60;
};
<file_sep>/Step2/Item.h
/**
* \file Item.h
*
* \author <NAME>
*
* This file does something I am not sure of yet
*/
#pragma once
#include <memory>
#include <string>
#include "XmlNode.h"
using namespace Gdiplus;
/**
* Forward reference
*/
class CYard;
/**
* Represents an Item
*/
class CItem
{
protected:
CItem(CYard* yard, const std::wstring &filename);
public:
virtual ~CItem();
/// Default constructor (disabled)
CItem() = delete;
/// Copy constructor (disabled)
CItem(const CItem&) = delete;
/** The X location of the item
* \returns X location in pixels */
double GetX() const { return mX; }
/** The Y location of the item
* \returns Y location in pixels */
double GetY() const { return mY; }
/** The width of the item
* \returns width in pixels */
double GetImageWidth() const { return mItemImage->GetWidth(); }
/** The height of the item
* \returns height in pixels */
double GetImageHeight() const { return mItemImage->GetHeight(); }
/// Get the yard this item is in
/// \returns Yard pointer
CYard* GetYard() { return mYard; }
void virtual SetLocation(double x, double y, bool nudge = false);
/// Draw this item
/// \param graphics Graphics device to draw on
void Draw(Gdiplus::Graphics* graphics);
bool HitTest(int x, int y);
virtual std::shared_ptr<xmlnode::CXmlNode>
XmlSave(const std::shared_ptr<xmlnode::CXmlNode>& node);
virtual void XmlLoad(const std::shared_ptr<xmlnode::CXmlNode>& node);
/// Handle updates for animation
/// \param elapsed The time since the last update
virtual void Update(double elapsed) {}
/// Set the mirror status
/// \param m New mirror flag
void SetMirror(bool m) { mMirror = m; }
private:
// Item location in the yard
double mX = 0; ///< X location for the center of the item
double mY = 0; ///< Y location for the center of the item
bool mMirror = false; ///< True mirrors the item image
/// The yard this item is contained in
CYard* mYard;
/// The image of this item
std::unique_ptr<Gdiplus::Bitmap> mItemImage;
};
<file_sep>/Step2/DecorCastle.cpp
#include "pch.h"
#include "DecorCastle.h"
#include <string>
using namespace std;
/// Animal filename
const wstring DecorCastleImageName = L"images/castle.png";
/**
* Constructor
* \param yard Yard this animal is a member of
*/
CDecorCastle::CDecorCastle(CYard* yard) : CItem(yard, DecorCastleImageName)
{
}
/**
* Save this item to an XML node
* \param node The node we are going to be a child of
* \return ptr to a XmlNode object
*/
std::shared_ptr<xmlnode::CXmlNode>
CDecorCastle::XmlSave(const std::shared_ptr<xmlnode::CXmlNode>& node)
{
auto itemNode = CItem::XmlSave(node);
itemNode->SetAttribute(L"type", L"castle");
return itemNode;
}
<file_sep>/Step2/Animal.h
/**
* \file Animal.h
*
* \author <NAME>
*
* Base Class for animales in the yard
*
* Derives from CItem class. Note that
* decorative objects are not CAnimal objects
*/
#pragma once
#include "Item.h"
/**
* Base class for a animal
* This applies to all of the animal, but not the decor
* items in the yard.
*/
class CAnimal : public CItem
{
public:
/// Default constructor (disabled)
CAnimal() = delete;
/// Copy constructor (disabled)
CAnimal(const CAnimal&) = delete;
void Update(double elapsed);
virtual std::shared_ptr<xmlnode::CXmlNode>
XmlSave(const std::shared_ptr<xmlnode::CXmlNode>& node);
void XmlLoad(const std::shared_ptr<xmlnode::CXmlNode>& node);
private:
/// Animal speed in the X direction
double mSpeedX;
/// Animal speed in the Y direction
double mSpeedY;
protected:
CAnimal(CYard* yard, const std::wstring& filename);
void SetSpeed(double minX, double minY, double rangeX, double rangeY);
};
|
d7b95b1467f8d2e152338af6dc077b9f8c4db242
|
[
"C++"
] | 9 |
C++
|
sakjacob/Pomeranian-Game
|
405a42c40d43d9e956a803ac0e2710e5391d7ded
|
bcfbf63cd68aff8061cfecefcfa5e80ab6c38d14
|
refs/heads/master
|
<file_sep># jsStudy
## 계산기 구현
### 스펙
- 사용자가계산을할수있는Web App 구현
- 덧셈,뺄셈,나눗셈,곱셈연산을구현
- 계산과정을Text 창부분에표시
- 사용자는0~9까지의버튼을클릭하여숫자를입력
- 입력숫자는계산결과창에출력하여입력된수를보여준다
- 1000단위마다‘,’ 을찍어준다
- 입력은10자리까지만가능
- 소수점은5자리까지계산(5자리이하버림)
- “=“버튼을누를경우이전연산을중복수행
- 초기상태는항상0으로시작-R 키를누를경우초기화
- 구현된계산기는추후공학용계산기등으로확장가능성이있음
- 한화면에여러개의계산기가있을수있음
|
6be29dce5ed3fee19a153a0a790147ebc5a7f952
|
[
"Markdown"
] | 1 |
Markdown
|
ppyeonam/calculator
|
2ea429c2fc50a6b4f1105ebe6952e479c13c531f
|
2ba929df87c6e58547bad80a3ed031ecb1b5555c
|
refs/heads/master
|
<repo_name>goodoldlameme/lections<file_sep>/мет опт/metopt.md
> 15.02.2019
*Опр:* Задача оптимизации - найти экстремум (min/max) некоторой критериальной (целевой) функции F(x), где $x \in X$ (допустимое множество)
**Задача безусловной оптимизации (минимизации)**
min f(x) (при этом X=$\mathbb{R^n}$)
**Задача условной оптимизации (минимизации)**
min f(x) (при этом X - собственное подмножество $\mathbb{R^n}) [X \sub \mathbb{R^n}, X \neq \mathbb{R^n}]$
**Задача классической оптимизации (минимизации на условный экстремум)**
$min\ \phi_0(x) , \phi_i(x)=0, i=\overline{1,m}, m<n, x \in R^n$
**Общая задача математического программирование**
$min f_0(x), f_i(x) \le 0, i=\overline{1,k}, f_i(x)=0, i=\overline{k+1,m}, x \in X_0 \sub \mathbb{R^n}$
**Задача линейного программирования**
$min (c,x), (a_i,x) \le b_i, i=\overline{1,m_1}, (a_i,x)=b_i, i=\overline{m_1+1,m}, x \ge 0$
**Задача нелинейного программирования**
Задача программирования, которая не является задачей линейного программирования (хотя бы одна функция не линейная)
**Задача вариационного исчисления**
$min[I(x)=\int_{t_0}^TL(t,x(t),\hat{x}(t))dt]$
$x(t_0)=x_0$
$x(T)=x_1$
**Задача оптимального управления**
$min[\Phi(x_0,x,u)=\int_{t_0}^Tf_0(t,x(t),u(t))dt+g_0(x_0,x(T))]$
$\hat{x}=f(t,x(t),u(t)), x(t_0)=x_0, g_i(x,x(T)) \le 0$
u(t) - кусочно-непрерывная функция, $t \in [t_0,T]$
**Задача теории приближения функции**
$y=f(x), x \in [a,b], p(x,a)=\sum_{i=1}^m\alpha_i\phi_i(x)$
Найти $p^*:||f-p^*||=inf||f-p(x,a)||$
**Задача планирования производства**
Имеем производство, которое заключается в переработке некоторых ингредиентов (ресурсов)
Дано:
m - виды ресурсов
$b_i$ - известный объем i ресурса
n - технологии, с помощью которых перерабатываются ресурсы.
Каждая технология определяется вектором[](http://api.gmath.guru/cgi-bin/gmath?A%3D%20%5Cleft(%20%5Cbegin%7Barray%7D%7Bccc%7Da_1_j%20%20%5C%5Ca_2_j%20%5C%5C...%5C%5Ca_m_j%20%5Cend%7Barray%7D%20%5Cright)), где $a_{ij}$ - норма затрат i при использовании j технологии с единичной интенсивностью.
Единичная интенсивность - за единицу может браться интенсивность каждого ресурса, либо по затраченным ресурсам, либо количеством продукции за единицу времени.
Затраты ресурса при использовании j технологии в единицу времени - будем ее использовать как интенсивность
$c_j$ - ценность, заключенная в конечном продукции, произведенной j технологии за единицу времени
Задача: требуется так спланировать производство, чтобы не выйти за рамки отпущенных ресурсов и суммарная ценность произведенной продукции была максимальна.
Пусть $x_j$ - искомая интенсивность j технологического способа. $X=(x_1,...,x_n)$ - план производства.
$max\sum_{j=1}^n(c_j,x_j) $- максимальная суммарная ценность
$\sum_{j=1}^na_{ij}x_jb_i, i=\overline{1,m}$ - фактические затраты i ресурса
$x_j \ge 0, j=\overline{1,n}$ - условие неотрицательности, иначе j технология не используется
Второй вариант задачи планирования производства
m - виды ресурсов
$b_i$ - известный объем i ресурса
n - продуктов
[](http://api.gmath.guru/cgi-bin/gmath?A%3D%20%5Cleft(%20%5Cbegin%7Barray%7D%7Bccc%7Da_1_j%20%20%5C%5Ca_2_j%20%5C%5C...%5C%5Ca_m_j%20%5Cend%7Barray%7D%20%5Cright)), где $a_{ij}$ - норма затрат i при производстве одной единицы j продуктов.
Единичная интенсивность - за единицу может браться интенсивность каждого ресурса, либо по затраченным ресурсам, либо количеством продукции за единицу времени.
$c_j$ - ценность, заключенная в конечном продукции, произведенной j технологии за единицу времени
$x_j$ искомое количество произведенного j продукта, чтобы суммарная прибыль была максимальна.
**Задача о диете [определение оптимального рациона].**
m - полезных веществ
$b_i$- норма потребления i вещества за планируемый период
n - продуктов питания
$a_{ij}$- содержание i вещества в единице веса j продукта
$c_j$ - цена единицы веса j продукта
$x_j$- количество купленного j продукта.
Количество потребления продуктов, чтобы человек, потребляющий их, обеспечил необходимую норму потребление веществ.
$min \sum_{j=1}^nc_jx_j, \sum_{j=1}^na_{ij}x_j \ge b_i, i=\overline{1,m}, x_j \ge 0, j=\overline{1,n}$
**Транспортная задача**
m - грузообразующих пунктов одного продукта
$a_i$ - объем производства в i пункте
n - потребителей
$b_j$ - потребность j покупателя
$c_{ij}$ - удельный транспортные затраты (стоимость перевозки единицы груза из i пункта производства в j пункт потребления)
Требуется так спланировать перевозки чтобы:
1. был полностью вывезен продукт из каждого пункта производства
2. полностью удовлетворены потребности потребителей
3. суммарные транспортные затраты на перевозки были минимальны
$x_{ij}$ (перевозки) - количество продукции, перевезенные из i в j
Модель
$min\sum_{i=1}^m\sum_{j=1}^nc_{ij}x_{ij}, \sum_{j=1}^nx_{ij}=a_i, j=\overline{1,m}, \sum_{i=1}^mx_{ij}=b_i, i=\overline{1,n}, x_{ij} \ge 0, j=\overline{1,m}, i=\overline{1,n}$
**Общая задача ЛП**
$min (max) \sum_{j=1}^nc_jx_j$, [](http://api.gmath.guru/cgi-bin/gmath?%5Csum%5Climits_%7Bi%3D1%7D%5En%20a_i_j%20x_j%20%20%5Cleft(%20%5Cbegin%7Barray%7D%7Bccc%7D%5Cle%20%20%5C%5C%3D%20%5C%5C%5Cge%20%5Cend%7Barray%7D%20%5Cright)%20b_i), $x_j \ge 0, j=\overline{1,m} \le n$(может быть и m<n)
**Определения**
$\sum_{j=1}^nc_jx_j$ - целевая функция - функция, которая максимизируется или минимизируется
$(c_1,...,c_n)$ - вектор цели
Ограничения 3-х типов: неравенства(тут 2) и равенства
$A=(a_{ij})_{mn}$[](http://api.gmath.guru/cgi-bin/gmath?A%3D%20%5Cleft(%20%5Cbegin%7Barray%7D%7Bccc%7Da_1%20%5C%5C..%20%5C%5Ca_m%20%5C%5C%20%5Cend%7Barray%7D%20%5Cright)%3D(A_1%2C...%2CA_n)) - матрица (условий) задачи
$(b_1,...,b_m)$ - вектор (правых частей) ограничений
$(x_1,...,x_n)$ - план задачи ЛП, если удовлетворяет всем условиям задачи.
Вектор допустим, если удовл-т всем ограничениям
Допустимая область задач X - совокупность всех планов задачи
Оптимальный план - план, если $\forall x \in X:(c,\bar{x}) \ge (c,x)$ для max, или $\forall x \in X:(c,\bar{x}) \le (c,x)$ для min[оптимизирующий целевую функцию $x^*=arg min\sum_{j=1}^nc_jx_j$]
$X^*$ - множество оптимальных планов решений задачи ЛП
$z^*=\sum_{j=1}^nc_jx_j$ - оптимальное значение задачи
Решить задачу ЛП, значит найти хотя бы один оптимальный план и посчитать для него значение целевой функции
> 22.03.2019
### Частные формы ЛП
1) Планирование пр-ва $\sum_{j=1}^nc_jx_j$
(2) $\sum_{j=1}^n a_{ij}x_j \le b_i, i=1,...,m$ <u>стандартная симметрия задача ЛП</u>
$x_j \ge 0, j=1,...,n $
2) задача на min
(3) канонич-я задача ЛП(равенства) $min\sum_{j=1}^nc_jx_j$;
$\sum_{j=1}^na_{ij}x_j = b_i, i=1,...,m; x_j \ge 0; j=1,...,n$
(Решение методом Гаусса)
3) <u>Основная</u> задача (рассмотрим в теории)
$min \sum_{j=1}^nc_jx_j; \sum_{j=1}^na_{ij}x_j \le b_i; i=1,...,m$
(4) (подразумевается $x_j \ge 0$) (нет условий отрицания на переменную)
Сущ-т однозначные правила для перехода от одной задачи к другой, т.е. задачи эквивалентны.
Каждая форма имеет преимущество с т.з. ЛП
Симплекс метод - модификация метода Гаусса.
Для решения (3) в $L_p$, ее нужно привести к канонич. виду.
Можно упростить через матричный и векторный вид.
A = $(a_{ij})_{n \times n}; c = (c_1, ..., c_n) -вектор цели; b = (b_1, ..., b_n) - вект. правых частей; x = (x_1, ..., x_n)$
<u>Стандартная задача</u> вектор - столбец
(2') max $C^{T}$x; Ax $\le$ b; x $\ge$ 0
Можно записать A = [$A_1, ..., A_n$] = тут вертикально = $[a_1, ..., a_n]$
(2'') = max(c, x); $(a_i, x) \le b_i, i=1,...,m; x\ge0;$
(2''') max(c, x) $\sum_{j=1}^nA_jk_j \le b; x \ge 0$
<u>Правила перехода</u>
1) $max_{x \in S}f(x) = - min_{x \in S}(-f(x))$
$x^* - т. max$
$f(x^*) \ge f(x);\forall x \in S$
$-f(x^*) \le - f(x);\forall x \in S$
$min_{x \in S}f(x) = - max_{x \in S}(-f(x))$
2) $f_i(x) \ge 0 ~ -f_i(x) \le 0$
3) $(a_i, x) \le b_i$ ~ дополнительная переменная
$x_{n+i} = b_i - (a_i, x) \ge 0$
~$(a_i, x) + x_{n+i} = b_i; x_{n+i} \ge 0;$
4) $(a_i, x) = b_i $ ~ $(a_i, x) \le b_i\ и\ -(a_i, x) \le - b_i$ - пара неравенств
5) Исключения переменных
$a_{i_1}x_1 + a_{i_2}x_2 + ... + a_{in}x_n = b_i|: a_i; a_{i_1} \ge 0; x_i \ge 0$
$x_1 \frac{1}{a_{i_1}}(b_i - a_{i_2}x_2 - ... - a_{i_n}x_n)$
$x_1 \ge 0; a_{i_2}x_2 + ... + a_{i_n}x_n \le b_i$
### Метод Жордана-Гаусса
n переменных, m - ограничений
m перем-х через n-m перем-х
6) $x_j \ge 0$ ~ $-x_j \le 0$ ~ $(a_{ij}) \le b_j; b_j = 0; a_{ij} = -1$
7) $x_j$ - свободная перем-я
Правило: x = x'' - x'', x'$\ge$ 0, x'' > 0
$x_j = x_j' - x_j''$, где $x_j' \ge 0$ и $x_j'' \ge 0$
### Геометрическая интеграция задачи
#### $l_p$ на пл-ти и графический метод решения
(5) $max(z=c_1x_1 + c_2x_2)$ при
$a_{11}x_1 + a_{12}x_2 \le b_1$
.
.
.
$a_{21}x_1 + a_{22}x_2 \le b_2$
$a_{m1}x_1 + a_{m2}x_2 \le b_m$
Построим X - допустимое множество

$x - \bar{x} = k\cdot a_1$
$(a_1, x) = (a, \bar{x}) + k(a_1, a_1) = a_{11}x_1 + a_{12}x_2 \le b_1$
= $b_1 + k||a_1||^2 > b_1$ (часть решения неравенства )
$l_1: a_{11}x_1 + a_{12}x_2 = b_1$
$(a_1, x) = b_1; a_1 = (a_{11}, a_{12}) - вектор\ нормали$
$x_1 \ge 0; x_1 = 0 => 0x_2$
$x_2 \ge 0; x_2 = 0 => 0x_1$
X - общая часть всех полуплоскостей
1) многоугольник (1 вариант из всех)
2) или неограниченное многоугольное мн-во
3) или пустое мн-во => решений не имеет => нет планов

$x^* = \{_{l_3}^{l_2}$
Ответ: $x^* = (x_1^*, x_2^*), f^* = +\infin$
Целевая ф-я неогранич сверху на x
Реш-е задачи зависит от вектора $\vec{c}.$
Для нахождения нужно выбрать - $\vec{c}$
max($\vec{c}, x$) = -min(c, x);
$f^* = - \infin для min целевая функция не ограничена снизу$
### Геометрические свойства задачи $l_p$ в $\mathbb{R^n}$
(6) <u>Основная</u> min(c, x); $(a_i, x) \le b_i; i=1,...,m$
X = {x|$(a_i, x_i \le b_i), i \in \overline{1, m}$}
Мн-во решений системы лин-х неравенств.
$x - x_1 = \alpha(x_2 - x_1); 0\le \alpha \le 1$
$x = (1 - \alpha)x_1 + \alpha x_2 пробегает\ точки\ от\ x_1\ до\ x_2$
$x = \alpha_1 x_1 + \alpha_2 x_2$, где $\alpha_1 \ge 0, \alpha_2 \ge 0; \alpha_1 + \alpha_2 = 1$
x - выпуклая комбинация $x_1\ и\ x_2$
_Опр:_
S - выпуклые, если вместе с любыми своими 2-мя точками
> 01.03.2019
$X: \{x|(a_i,x) \le b_i, i=1...m\}$
X - множество решений, $X \in ℝ^n$.
Берем $\forall x \in [x^1,x^2], x^1,x^2 \in ℝ^n.$
$Произвольная\ точка\ отрезка\ x_{\alpha}=(1-\alpha)x^1+\alpha x^2, 0 \le \alpha \le 1$
Опр. S - выпукло, если с любыми своими двумя точками оно содержит отрезок, их соединяющий (сюда же попадают пустые и одноэлементные множества).
$\forall\ x^1, x^2 \in S, \alpha \in [0, 1]: x_{\alpha} = (1-\alpha)x_1 + \alpha_2x_2\in S$
*Утв*. Пересечение выпуклых множеств выпукло.
$\forall x^1, x^2 \in S_i => x^1, x^2 \in (\forall\ i) => [x^1, x^2] \in S_i (\forall\ i) => [x^1, x^2] \in S$
$Hi={x | (a_i,x)=b_i}, a \neq 0 - гиперплоскость $
*Утв*. Гиперплоскость есть выпуклое множество
$\forall\ x^1, x^2 \in H, \alpha \in [0,1] x_{\alpha} \in H(?)$
$(\alpha, x_{\alpha}) = (1-\alpha)(a, x^1) + \alpha(a, x^2) =(1-\alpha)b + 2b$ #
Гиперплоскость делит пространство на 2 полупространства
$H_i^-=\{x | (a_i,x) \le b_i\}$
$H_i^+=\{x | (a_i,x) \ge b_i\}$
Утв. $H_i^+,H_i^-$ есть выпуклые множества
$X= \cap _{i=1}^mH_i^-$ - многогранник решения системы (1)
*Свойство*: Множество X - выпукло
*Свойство*: Множество X - замкнуто
*Свойство*: Множество X - может быть ограниченным | неограниченным
*Опр*: Точка предельная, если $\overline{x} \in X {x_k} \in X, x_k \rightarrow \overline{x} (k \rightarrow \infin), x_k \neq \overline{x}$
Предельная точка принадлежит множеству Х => мн-во X - замкнутое.
*Опр*. Точка называется внутренней, если $\forall e\ \exists\ O_e(x \in X)$
*Опр*. Точка называется граничной, если в любой окрестности могут быть как точки из X, так и точки не из X. Совокупность таких точек образует <u>границу множества.</u>
*Опр*. k-грань - множество ограничений-равенств размерностью k, т.е.4
(2)
$(a_{i_l},x)=b_{i_l} i_l \in 1...m, l=1...k, \{a_{i_l}\}$ - линейно независимы
$(a_i,x) \le b_i; i \neq il$
Ребра - 2 грани, остальные неравенства
Вершина - 3 равенства, остальные - неравенства
*Теорема*: X $\neq \empty.$Пусть r(A) = r. Тогда $\forall k=1...r$ существует k-грань.
Максимальное r - ранг, а максимальный ранг - размерность пространства.
*Опр.* Вершина множества X - n-грань (пересечение линейно независимых гиперплоскостей)
(3)
$(a_{i_l},x)=b_{i_l} i_l \in 1...m, l=1...n, \{a_{i_l}\}$ - линейно независимы
$(a_i,x) \le b_i; i \neq il$
Точки k граней явл граничными точками
$\overline{x} \in X(i_k, ..., i_k) x = \overline{x}+\lambda a_{i_l}$
$(a_{i_l}, x) = (a_{i_l}, \overline{x}) + \lambda ||a_{i_l}||^2 = b_{i_l} + \lambda||a_{i_l}||^2 > b_{i_l}$
*Опр.* Выпуклая комбинация точек $x^1...x^k\ есть\ x=\sum_{i=1}^k a_i x^i, a_i \ge 0, \sum_{i=1}^k a_i=1$
*Утв.* Выпуклое множество содержит все выпуклые комбинации своих точек
> Д-во: S - выпуклое мн-во, $x^1, ..., x^m \in S, x_{\alpha} = \sum_{i=1}^m\alpha_i x^i, \alpha_i \ge 0, \sum_{i=1}^m \alpha_i =1$
>
> 1) k =2 $x_{\alpha} \in S$ - по опр выпукое мн-во
>
> 2) k =m - 1 предположение
>
> 3) $0 \le \alpha_m \le 1$
>
> $\alpha_m = 0$ вып для всех предыдущ
>
> $\alpha_m = 1 x = x_m. а x_m \in S$
>
> $0 < \alpha_m < 1 => 0 < 1- \alpha_m = \sum_{i-1}^{m-1}\alpha_i$
>
> $x_{\alpha} = (1 - \alpha_m)\sum_{i=1}^{m-1} \frac{\alpha_i}{1-\alpha_m}x^i + \alpha_m x^m$
>
> $x_{\alpha} = (1 - \alpha_m)y + \alpha_m x^m \in S$
>
> $y = \sum_{i=1}^{m-1} \frac{\alpha_i}{1-\alpha_m} = \frac{1}{1-\alpha_m}\sum_{i=1}^m \alpha_i = 1$
*Опр*. Множество всех выпуклых комбинаций точек из M называется выпуклой оболочкой M (обозначается coM)
*Свойства*:
1. coM - выпуклое мн-во
> $x^1, x^2 \in coM$
>
> $x^1 = \sum_{i=1}^m\alpha_i x^i, \alpha_i \ge 0, \sum_{i=1}^m \alpha_i =1$
>
> $x^2 = \sum_{i=1}^m\beta_i x^i, \beta_i \ge 0, \sum_{i=1}^m \beta_i =1$
2. $M \sub coM$
3. $S_i$ - выпуклое мн-во, которое содержит M =>
$coM \sub \cap_i S_i$ и $\cap_i S_i \sub coM $ => $\cap_i S_i = coM $

$\alpha + (1-\alpha)\beta + (1-\alpha)(1-\beta) = (1-\alpha)(\beta + 1 - \beta) = 1-\alpha; \alpha + (1-\alpha) = 1$
*Пример:* шестиугольник, разбиваем на треугольники. Точка x попадает в один из треугольников.

*Опр*. $\overline{x} \in M$ - крайняя (угловая) точка, если она не может быть представлена как нетривиальная выпуклая комбинация двух разных точек из M.
Нетривиальная, когда $\forall i\ \alpha_i > 0$
*Теорема:* Любое выпуклое замкнутое ограниченное множество в $ℝ^n$ может быть представлено как выпуклая оболочка своих крайних точек.
> Д-во: $x^0 - вершина\ и\ x^0$ явл решением системы (3)
>
> r(A) = n
>
> От противного: $x^0$ не явл крайней точкой Х.
>
> $\exists x^1, x^2 \in X; x^1 \neq x^2; 0 \le \alpha \le 1;\ x^0 = \alpha x^1 + (1-\alpha)$
>
> $b_{i_l} = (a_{i_l}, x^0) = \alpha(a_{i_l}, x^1) + (1-\alpha)(a_{i_l}, x^2) \ge (a{1_l}, x^1) и \ge (a_{i_l},x^2) $
>
> $(1-\alpha)(a_{i_l}, x^1 - x^2) \le 0\ и\ \alpha(a_{i_l}, x^1, x^2) \ge 0 => (a_{i_l}, x^1 - x^2) = 0, i_l = 1 $
> 15.03.19.
$\bar{x}$ - кр.т. X
Показать, что она вершина
$\bar{x} $ не может быть внутренней точкой мн-ва X
$(a_{i_l}, \bar{x}) - b_{i_l}=0, l= 1, ..., L; (a_i, \bar{x}) - b_i \le 0, i \neq i_l$
$\{a_{i_l}\}$ - лин независ.
$\mathbb{I}$ = $\overline{1, m} = \{\mathbb{I_1} \cup \mathbb{I_2} \cup \mathbb{I_3}\}$,
$\mathbb{I_1}$ = $\{i_{l_1}, ... i_{l_L}\}$, $\mathbb{I_2} = \{i| (a_i, \bar{x}) = b_i\}$, $\mathbb{I_3} = \{i|(a_i), \bar{x} < b_i\}$
L = n , L < n
о\п
$(a_{i_l}, x) = 0$
l = $\overline{1, L} $
уравнений меньше чем неизвестных след система имеет ненул решение
=>$ \exists x^* \neq 0$
$x_1 = \bar{x} + \epsilon x^*$
$x_2 = \bar{x} - \epsilon x^*$
$\epsilon $> 0
$i_l \in \mathbb{I_1}$: $I(a_{i_l}, x_1) = (a_{i_l}, \bar{x}) + \epsilon(a_{i_l}, x^*) = b_i$
$i \in \mathbb{I_2}: I(a_i, x_1) = (a_i, \bar{x}) + \epsilon(a_{i_l}, x^*) = b_i + \epsilon(\sum\limits_{l=1}^L \beta_l a_{i_l}, x^*) = b_i$
$i \in \mathbb{I_3}: I(a_i, x_1) = (a_i, \bar{x}) + \epsilon(a_{i_l}, x^*) < b_i$
$x_1 \in X, x_2 \in X, x_1 \neq x_2$
$\bar{x} = 0.5x_1 + 0.5x_2$ (противоречие с тем что x - крайнаяя точка)
_Опр_: Выпуклая оболочка конечного числа точек - выпуклый многогранник
$x^1, .., x^m$
многогранник ограниченное мн-во
x =$ \sum\limits_{i=1}^m \alpha_i x^i$,
$\alpha_i \ge 0,$
$ \sum\limits_{i=1}^m \alpha_i =1$
Замкнутое мн-во - мн-во, содержащее все свои предельные точки
$\{x_k\} \in M\ \lim\limits_{n \rightarrow \infin} x_k = \bar{x}$ => $\bar{x} \in M$
$x_k = \sum\limits_{i=1}^m\alpha_i^k x^i,\ \alpha_i^k \ge 0(\forall \in \overline{1, m}, \forall k \sum\limits_{i=1}^m \alpha_i^k =1)$
$\{\alpha_i^k\} \rightarrow \bar{\alpha_i}, i=1, m(k \rightarrow \infin)$
$0 \le \alpha_i^k \le 1$
m - огр=х числ-х посл-й
i = 1: {$k_j^1$}: $\alpha_1^{k^1_j} \rightarrow \bar{\alpha_1}$ $\sub$ {k}
i = 2: {$k_j^2$}: $\alpha_2^{k^2_j} \rightarrow \bar{\alpha_2}$ $\sub$ {$k_j^1$}
i = m: {$k_j^{m-1}$}: $\alpha_m^{k^m_j} \rightarrow \bar{\alpha_m}$ $\sub$ {$k_j^m$}
$k_j^m$ - по всем $\alpha$ будут сходиться
$x_{k_j^m} \rightarrow \bar{x}$
$x_{k_j^m} = \sum\limits_{i=1}^m \alpha_i^{k_j^m} x \rightarrow \sum\limits_{i=1}^m \bar{\alpha_i}x^i$
Получаем, что M - замкнутое мн-во
X = {x|Ax $\le b$}
1) X - огр.
крайняя точка - вершина => вершин $\le C^n_m$
2) X - неогр мн-во
ТУТ РИСУНОЧЕК
r(A) = n - ранг
$p_1, .., p$ - вершины X
$s_1, ..s_q$ - непр тут дописать
### Разрешимость задач ЛП
Мн-во огр - теорема Вейерштрасса
Мнво не огр - решение м.б, а м.ю не быть
Чтобы задача на max была разрешима, достаточно, чтобы усл. ф-я была огр сверху на допуст мн-ве Х
Чтобы задача на min была разрешима, достаточно, чтобы усл. ф-я была огр снизу на допуст мн-ве Х
**Задача линейного программирования**
max(c, x)
(2) ($a_i, x$) - $b_1\le 0 $
x $\ge 0$ i = 1,...m
$x^*$ - решение (2): $f^* = (c, x^*) \ge (c, x) \forall x \in X$
Доказываем, что $x^*$ совпадает с одной из вершин
если предположим, что x - ограниченное множество, то оно будет многогранником и выпуклой оболочкой своих вершин
$p_1, .. p_N$ - вершины N
$x^* = \sum\limits_{i=1}^N\alpha_ip_i, \alpha_i \ge 0; \sum\limits_{i=1}^N \alpha_i = 1$
$\bar{p_i}: (c, \bar{p_1}) \ge (c, p_i), i =1,..,N$
$f^* = (c, x^*) = \sum\limits_{i=1}^N \alpha_i (c, p_i) \le \sum\limits_{i=1}^N \alpha_i (c, \bar{p_i}) = (c, \bar{p_i})\sum\limits_{i=1}^N \alpha_i$
$(c, x^*) \le (c, \bar{p_i})\ и\ (с, x^*) \ge (c, \bar{p_i})$ => $(c, x^*) = (c, \bar{p_i})$
$\bar{p_1}, ...\bar{p_k}$ - решение (1)
$\bar{p} = \sum\limits_{i=1}^k \alpha_i\bar{p_i}$
$(c, \bar{p}) = \sum\limits_{i=1}^k\alpha_i(c, \bar{p}) = \sum\limits_{i}^k \alpha_if^* =f^*$
ТУТ РИСУНОЧЕК
проводим дополнительное ограничение
$x_1 + x_2 + .. + x_n = Q$
$Q > x^*_1 + x^*_2 + .. + x^*_n$ - отсекает на каждой оси отрезок величиной Q
$X_Q$ - получается дополнительное множетсво
Рассматриваем
$X \cap X_Q$
$x^*$- решение и там и там, а теперь станет станет решением на ограниенном мн-ве
Значит, по предыдущ, решение задачи будет совпадать с вершиной этого множества
Причем оно не может совпадать с решениями, которые были в граничной гиперплоскости, т.е. точка будет лежать внутри пространства
**Опорные планы для канонической**
(3) min(c,x)
$(a_i, x) - b_i = 0, x\ge 0, i=\overline{1,m}$
min(c, x)
$\sum\limits_{j=1}^nA_jx_j=b, x\ge 0$
$\bar{x} - план (3), \bar{x} = (\bar{x_1},\bar{x_n}), \bar{x_j} \ge 0$
$\{A_j\}_{j: x_j > 0}$ - лин. нез $\le$ m
_Утв:_ Любой опорный план задачи L явл. крайней точкой мн-ва Х
> Д-во:
>
> $\bar{x} $ - опорный план
>
> $\bar{x}$= $(\bar{x_1}, \bar{x_2},0,..., 0)$
>
> о/п: $\bar{x} - не явл. кр. точкой X, тогда \bar{x}$ - лежит на отр
>
> $\exists x^1, x^2 \in X, x^1 \neq x^2: \bar{x} = \alpha_1x^1 + \alpha_2 x^2$
>
> $\alpha_1 \alpha_2 > 0 $
>
> $\alpha_1 + \alpha_2 =1$
>
> Пусть $ x^1 = (x^1_1,...x_n^1$)
>
> $ x^2 = (x^2_1,...x_n^2$)
>
> Тогда $\bar{x} = (\alpha_1x_1^1 + \alpha_2x_1^2 + .. + \alpha_1x_n^1 + \alpha_2x_1^2)$
<file_sep>/lfocs/lfocs.md
# Лингвистические основы информатики
***
> *12.02.2019*
## Организационные вопросы
* <NAME> [<EMAIL>](mailto:<EMAIL>)
* Консультации: понедельник 16:10 КАДМ
## Рекомендуемая литература
- [Языки, грамматики, распознаватели](http://kadm.imkn.urfu.ru/files/shurzam.pdf) (Шур, Замятин) - основной учебник (много багов!)
- <NAME> "Компиляторы. Принципы, технологии, инструменты" (Dragon book)
- Ахо, Ульман "Теория синтаксического анализа, перевода и компиляции"
- Cooper K. Engineering a Compiler.
> [репозиторий с .djvu книгами](https://github.com/afrolovskiy/compilers_labs/tree/master/literature)
– Чем будем заниматься? – Теорий компиляции.
Узнаем:
- Что такое язык;
- Что такое компилятор;
- Что делает компилятор с языком;
Будем в теории знать, как написать компилятор.
Немножко комментарием и истории:
>Даже разбор формулы в экселе использует какие-то приёмы компиляции!
>
>В 50-х годах людям надоело писать на ассемблере, и они начали думать.
>
>К 60-м придумали. Дейкстра - двигатель прогресса, потому что придумал теорию, а не какое-то специфичное для задачи решение.
## Что такое компилятор?
По-простому – переводчик с языка на язык. Можно рассматривать как чёрный ящик с каким-то входом, выходом и магией внутри.
Принято разделять его работу на 2 фазы:
***
↓ исходный текст
фронтенд: __анализ__ исходного текста. Если есть ошибки, то останавливаемся.
↓ промежуточное представление
бэкенд: __синтез__ – генерация программы, которая нам нужна вместе с какими-то оптимизациями.
↓ целевой код
***
Заниматься будем фронтендом!
**Блок анализа**
***
↓ исходный текст
лексический анализ: разбиваем текст на токены – знаки, переменные, идентификаторы.
↓ токены
синтаксический анализ(парсер)
↓ промежуточное представление
***
## Язык
1. Лексика ~ слова
2. Синтаксис - правила построение предложений
3. Семантика
__Таблица символов__ – информация о переменных, константах, функциях. Используется на всех шагах анализа.
_Заполнение_:
- лексика(?): встречаем новый символ – записываем имя переменной и записываем место первого появления.
- семантика: тип, место хранения, время объявления.
Написанию компилятора предшествует описание языка.
_Рассмотрим язык с условным оператором_:
Что есть условный оператор с точки зрения синтаксиса? Опишем это с помощью __форм Бэкуса–Нуара__:
```
<условный оператор>::== if <логическое выражение> <список операторов> | else <список операторов>
<список операторов>::== <оператор>|<оператор>;<список операторов>
...
<идентификатор>::== [a-zA-Z]\w*
```
> **Обозначения**
>
> | {} — альтернатива
>
> <> — синтаксическая категория
>
> ::== — выводимость
**[Порождающая] грамматика** - объект математический. Основной способ описания синтаксиса и лексики (частный случай синтаксиса).
_**Опр:**_ __Грамматика__ – $G =:<\Sigma, \Gamma, P, S>$, где
- $\Sigma$ – терминальный алфавит (выходной);
- $\Gamma$ – нетерминальный алфавит (вспомогательный);
- $P$ – множество правил вывода;
- $S \in \Gamma$ – выделенный нетерминал – аксиома (одна).
_**Соглашения**_
- $a, b, c, :…$ – терминальные состояния (if - терминал);
- $x, y, z, :…$ – цепочки (слова) терминалов;
- $A, B, C, :…$ – нетерминалы;
- $X, Y, Z, :…$ – что угодно;
- $\alpha, \beta, \gamma, :...$ – произвольные цепочки (терминальные или нетерминальные);
- $\lambda$ – пустое слово.
_**Выводимость**_
**Правило вывода:** $(\alpha \rightarrow \beta)$ $\alpha;\beta \in (\Sigma \cup\Gamma)^*$, более конкретно $\alpha \in (\Sigma\cup\Gamma)^*\Gamma(\Sigma\cup\Gamma)^*$ - т.е в $\alpha$ должен быть хотя бы один элемент из не терминального состояния.
Основная функция этого правила – порождение языка.
_**Опр:**_ Цепочка $\gamma$ **непосредственно выводима** из цепочки $\sigma$, если $\gamma = \delta_1\beta \delta _2$, $\sigma = \delta _1 \alpha \delta _2$ и $(\alpha \rightarrow \beta) \in P$.
Обозначается как $\sigma \Rightarrow \gamma$.
> В цепочке сигма есть подпоследовательность альфа, которую можно заменить на бету. Выводимость - отношение на множестве цепочек. Рефлексивно-транзитивное замыкание $\sigma \Rightarrow \gamma.$ Возможность вывести одну цепочку из другой за некоторое число шагов.
_**Опр**:_ $\gamma$ **выводима** из $\sigma$ если существует последовательность цепочек $\eta_0, ..., \eta_n, n \ge 0$ такая, что $\eta _0 = \sigma, \eta _n = \gamma, \eta _{i-1} \Rightarrow \eta _i$ $ (\sigma \Rightarrow ^*\gamma)$.
Последовательность $\eta_0, ..., \eta_n$ – **вывод**.
Получается, что грамматика для нас — просто набор правил вывода. Потому что всё остальное мы зафиксировали в обозначениях.
_**Опр:**_ **Язык**, порождённый грамматикой $G = :<\Sigma, \Gamma, P, S>$ : ${w \in \Sigma^*|S \Rightarrow ^*w}$ — множество терминальных цепочек таких, что их можно вывести из аксиомы.
_Опр:_ $\eta_0, ..., \eta_n: \eta_0=s, \eta_n=w, \eta _{i-1} \Rightarrow \eta _i$, $\eta_i$ – форма (шаг).
_**Пример**_:
${a^n b^n | n \in \N_0}$ — Что это? Язык?
_Правила:_
- $S \rightarrow aSb$
- $S \rightarrow \lambda$
Рассмотрим вывод терминальной цепочки:
$S \Rightarrow aSb \Rightarrow aaSbb \Rightarrow aabb$
> $ab$ - терминалы (см. соглашения)
_**Ещё пример**_
$S \rightarrow ABS|\lambda$ $S \rightarrow SS|a|b|\lambda$
$AB \rightarrow BA$
$A \rightarrow a$
$B \rightarrow b$
$S \Rightarrow ABS \Rightarrow ABABS \Rightarrow ^* (AB)^nS \Rightarrow (AB)^n$
Можем перейти к терминалам
$S \Rightarrow ^*ABABAB \Rightarrow ABBAAB \Rightarrow abbaab$
Хотим загнать буквы А в конец, а B в начало. Будем менять местами буквы по второму правилу.
$ABABAB \Rightarrow BAABAB \Rightarrow BABAAB \Rightarrow BBAAAB \Rightarrow :...$
#
> *19.02.2019*
```
pos = init + rate * 60;
// после лескического анализа превращается в...
id,15 <=> <id,2><+><id,3><*><const><;>
// cинтаксическому анализу всё равно, как называется переменная
// после ситанксического анализа превращается в...
=
/ \
id,1 +
/ \
id,2 *
/ \
id,3 const
//после семантического добавятся какие-то атрибуты
```
На каждой стадии – новый язык. Значит, нужны новые способы порождения\описания. А этот способ порождает распознаватель.
## Иерархия Хомского-Шютценберже
| | Вид грамматики | Распознаватель | Класс языков |
| ---- | ---------------------- | ------------------------------------------------------ | ----------------------- |
| 0 | Грамматика общего вида | МТ | Рекурсивно перечислимые |
| 1 | Контекстно-зависимые | МТ с линейно ограниченной памятью (LBA) | КЗЯ |
| 2 | Контекстно-свободные | Недетерминированный автомат с магазинной памятью (PDA) | КСЯ |
| 3 | Праволинейные | ДКА | Регулярные языки |
Опр. Контекстно-зависимая грамматика — все правила имеют вид $\alpha A\gamma \rightarrow \alpha \beta\gamma$ (у терминала имеется контекст, который сохраняется при его раскрытии) .
***Опр.*** Язык обладает свойством $P$, если $\exists$ грамматика со свойством $P$, его порождающая.
***Опр.*** Контекстно-свободная грамматика — все правила имеют вид $A \rightarrow \beta$ (частный случай КЗГ, когда оба контекста пусты)
***Опр.*** Праволинейные грамматики — все правила имеют вид $A \rightarrow aB$ или $A \rightarrow\lambda $ справа либо лямбда, либо терминал+нетерминал
Вспомним пример. Кажется, что это грамматика обычного вида.
$S \rightarrow ABS|\lambda$ $S \rightarrow SS|a|b|\lambda$
$AB \rightarrow BA$
$A \rightarrow a$
$B \rightarrow b$
Построим КСГ, которая породит язык выше. Порождаем цепочки, где букв B на одну больше, чем a/
Из А должны выводиться строчки, где на одну a больше
$S \rightarrow aB|bA$
$A \rightarrow aS|bAA$
$B\rightarrow bS|aBB$
$A \rightarrow a$
$B \rightarrow b$
$abba : :S \rightarrow aB \rightarrow abS \rightarrow abbA \rightarrow abba $
Иерархия: регулярные $\subset$ КСЯ $\subset$ КЗЯ $\subset$ Rec $\subset$ RecEn[^2].
## Контекстно-свободные грамматики и языки
***Опр.*** Упорядоченное дерево — дерево с заданным линейным порядком со следующими свойствами:
1. Если $x$ - сын узла $y$, то $x \ge y$
2. Если $x \le y$ и они братья, то для всех сыновей $z$ узла $x$: $z\le y$
> Порядок, возникающий при обходе в глубину слева направо
**Пример**:
$S \rightarrow SS|(s)|\lambda$
$(( ))$
$S \rightarrow SS \rightarrow (s) \rightarrow ((s)) \rightarrow (())$
```
S₁
/ \
S₂ S₄
| / | \
λ₃ (₅ s₆ )₁₁
/ | \
(₇ s₈ )₁₀
|
λ₉
```
***Опр***. Дерево вывода цепочки $\omega$ в $G =:<\Sigma, \Gamma, P, S>$ — упорядоченное дерево со следующими свойствами:
1. Узлы – нетерминалы, корень – аксиома, листья – терминалы или $\lambda$, причём у листьев, помеченных пустым словом нет братьев.
> Если есть братья, то $\lambda a == a$
2. Если у узла $x$ все сыновья это некоторый набор $y_1, : … : y_n$, таких, что $y_1 \le : ...: \le y_n$, и узлы $x$, $y_1, : … : y_n$ помечены символами $X, Y_1, : … : Y_n$, то $(X \rightarrow Y_1, : … : Y_n) \in P$.
> Применили правило, в дереве появился куст вывода
3. Если все листья дерева имеют метки $a_1 \le a_2 \le : … \le : a_n$, то $\omega = a_1…a_n$
***Опр.*** Вывод цепочки $\omega (S \Rightarrow \alpha_1 \Rightarrow : … : \Rightarrow \alpha_n=\omega)$ в $G =:<\Sigma, \Gamma, P, S>$ представлен деревом вывода $T$, если $\exists$ набор стандартных поддеревьев $T_1, … T_n$ таких, что на упорядоченных листьях дерева $T_i $ написана форма $\alpha_i$.
***Опр.*** Стандартное поддерево $T' $дерева $T$, если:
1. корень $T'$ - корень $T$
2. Если узел $x$ дерева $T$$ \in T'$, то либо $x$ - лист, либо все сыновья $x$ в $T$ $\in T'$
> Если с узлом лежит хотя бы один его сын, то и все его сыновья тоже лежат.
**Пример по последнему языку:**

Наша любимая грамматика, которая порождает арифметику:
$E \rightarrow E+E|E*E|(E)|x$
$x+x*x$
```
E
/|\
E + E - этот куст можно передвинуть влево, получится два разных дерева
| /|\ для одного и того же. Плохо.
x E * E
| |
x x
```
***Опр.*** Грамматика однозначна, если $\forall \omega$, выводимой в грамматике, $\exists!$ дерево вывода.
Следующая грамматика однозначна и эквивалентна предыдущей
$E \rightarrow E + T|T$
$T \rightarrow T*F|F$
$F \rightarrow (E) |x$
1. Правосторонний вывод и r-формы:$E \rightarrow E + T \rightarrow E+T*F \rightarrow E+T*x \rightarrow E+F*x \rightarrow E+x*x\rightarrow T+x*x \rightarrow F+x*x \rightarrow x+x*x$
2. Левосторонний вывод и l-формы:$E \rightarrow E+T\rightarrow T+T \rightarrow F+T \rightarrow x+T \rightarrow x+T*F \rightarrow x+F*F \rightarrow x+x*F\rightarrow x+x*x $
Плата за однозначность - увеличение длины вывода
> 26.02.2019
## Праволинейная грамматика
| A $\rightarrow \alpha B$ | A $\rightarrow \alpha B$ |
| ------------------------ | :----------------------- |
| A $\rightarrow \lambda$ | A $\rightarrow$ $\alpha$ |
_**Теорема**_
Праволинейная грамматика порождает регулярный язык
_Д-во:_
$G = (\Sigma, \Gamma, P, S)$
$KA = (\Sigma, \Gamma, \delta, S, F)$
$F = {A \in \Gamma | (A \rightarrow \lambda) \in P}$
$\delta(A, a) = B <=> (A \rightarrow aB) \in P$
A <-a-> B
$w = a_1... a_n$
$S \rightarrow a_1A_1 \rightarrow a_1a_2A_2 \rightarrow ...\rightarrow a_1...a_nA_, \rightarrow a_1...a_n$
_Строим автомат по рег. выр-ю_
a(b+cc)*
<svg width="400" height="150" version="1.1" xmlns="http://www.w3.org/2000/svg">
<ellipse stroke="black" stroke-width="1" fill="none" cx="118.5" cy="88.5" rx="30" ry="30"/>
<text x="112.5" y="94.5" font-family="Times New Roman" font-size="20">S</text>
<ellipse stroke="black" stroke-width="1" fill="none" cx="223.5" cy="100.5" rx="30" ry="30"/>
<text x="216.5" y="106.5" font-family="Times New Roman" font-size="20">A</text>
<ellipse stroke="black" stroke-width="1" fill="none" cx="337.5" cy="88.5" rx="30" ry="30"/>
<text x="330.5" y="94.5" font-family="Times New Roman" font-size="20">B</text>
<path stroke="black" stroke-width="1" fill="none" d="M 213.439,72.362 A 22.5,22.5 0 1 1 239.714,75.398"/>
<text x="228.5" y="23.5" font-family="Times New Roman" font-size="20">b</text>
<polygon fill="black" stroke-width="1" points="239.714,75.398 248.809,72.893 241.448,66.125"/>
<polygon stroke="black" stroke-width="1" points="148.306,91.906 193.694,97.094"/>
<polygon fill="black" stroke-width="1" points="193.694,97.094 186.313,91.218 185.178,101.153"/>
<text x="164.5" y="116.5" font-family="Times New Roman" font-size="20">a</text>
<polygon stroke="black" stroke-width="1" points="253.335,97.359 307.665,91.641"/>
<polygon fill="black" stroke-width="1" points="307.665,91.641 299.185,87.505 300.232,97.451"/>
<text x="278.5" y="116.5" font-family="Times New Roman" font-size="20">c</text>
<polygon stroke="black" stroke-width="1" points="307.665,91.641 253.335,97.359"/>
<polygon fill="black" stroke-width="1" points="253.335,97.359 261.815,101.495 260.768,91.549"/>
<text x="274.5" y="84.5" font-family="Times New Roman" font-size="20">c</text>
</svg>
$S \rightarrow aA$
$A \rightarrow bA|cB|\lambda$
$B \rightarrow cA$
### Преобразования грамматик
Грамматики эквивалентные, если они порождают один и тот же язык.
#### Приведенные грамматики
_**Опр**:_ Нетерминал A $\in \Gamma$ - производящий, если из него можно получить производящую цепочку $A \Rightarrow _G^* u^- $
_**Опр**:_ A $\in \Gamma$ - достижимый, если $A \Rightarrow _G^* \alpha A\beta $
_**Опр:**_ Грамматика приведенная, если все ее нетерминалы достижимые и производящие
***Примеры***
$S \rightarrow bAc | AcB$
$A \rightarrow abC$
$B \rightarrow Ea$
$C \rightarrow BD$
$D \rightarrow CCa$
$E \rightarrow Fbb$
$F \rightarrow a$
$\Gamma_p$ = {F, E, B} - производящие
$\Gamma_r$ = {S, A, B, C, E, D, F} - достижимые
Нахождение $\Gamma_r: \Gamma_r \rightarrow S$ -> ~~S~~, A, B -> ~~S~~, ~~A~~, B, C, E -> ~~S~~, ~~A~~, ~~B~~, C, E, D -> ~~S~~, ~~A~~, ~~B~~, ~~C~~, E, D, F
$\Gamma_r^n = \Gamma_r^{n-1} \cup \{A | (B \rightarrow \alpha A\beta) \in P, B \in \Gamma_r^{n-1}\}$ - n-й шаг
добавляем нетерминалы из правой части
$\Gamma_p: $ все нетерминалы, из которых вывод цепочки за 1 шаг
$\Gamma_p^{n} = \Gamma_p^{n-1} \cup \{A | (A \rightarrow \gamma) \in P, \gamma \in (\Sigma \cup \Gamma_p^{n-1})\}$
**Теорема**
Для любой КСГ G существует эквивалентная ей приведенная грамматика
_**Д-во**:_
КСГ G = ($\Sigma, \Gamma, P, S$)
Находим $\Gamma_p$
Если S $\notin \Gamma_p, то G' = (\Sigma, \emptyset, \emptyset, \emptyset)$
Иначе $\widetilde{G} = (\Sigma, \Gamma_p, \widetilde{P}, S)$
$\widetilde{P} = \{(A \rightarrow \gamma) \in P |A,\gamma \in (\Sigma \cup \Gamma_p)^*\}$
Находим $(\Gamma_p)_r$
$G' = (\Sigma, (\Gamma_p)_r, P', S)$
P' = {$(A \rightarrow \gamma) \in \widetilde{P}| A, \gamma \in (\Sigma \cup (\Gamma_p)|r)^*$}
$(\Gamma_p)_p - достижимы\ в\ \widetilde{G}, G', производящие\ в\ \widetilde{G}, G'$
$A \in (\Gamma_p)_r$
$S {\Rightarrow}_{\widetilde{G}}^* \lambda AB \Rightarrow_{\widetilde{G'}}^* uwv $
**_Пример_**
S $\rightarrow$ ab|bAC
A $\rightarrow$ CB
B $\rightarrow$ aSA
C $\rightarrow$ bC|d
1) производящие $\rightarrow$ достижимые
$\Gamma_p = \{C, S\}; (\Gamma_p)_r = \{S\}; [G': S \rightarrow ab]$
2) достижимые $\rightarrow$ производящие
$\Gamma_p = \{S, A, B, C\}; (\Gamma_p)_r = \{C, S\}; [G': S \rightarrow ab; C \rightarrow d ]$
#### $\lambda$ - свободные грамматики
_**Опр:**_ $A \in \Gamma - аннулирующий, если A => ^* \lambda$
_**Опр:**_ $Ann(G)$ - мн-во аннулирующих нетерминалов.
Нахождение аннулирующий символов
$Ann^1(G) = \{A \in \Gamma | (A \rightarrow \lambda) \in P\}$
$Ann^n(G) = Ann^{n-1}(G) \cup \{A \in \Gamma | (A \rightarrow \gamma ) \in P, \gamma \in (Ann^{n-1}(G))^*\}$
_**Пример**_
S $\rightarrow$ aBC|AE
A $\rightarrow$ bC| $\lambda$
B $\rightarrow$ ACA
C $\rightarrow \lambda$
E $\rightarrow$ CA
D $\rightarrow$ bE|c
$Ann(G)$:
1. {A,C}
2. {A,C, B, E}
3. {A, B, C, E, S}
_**Опр**:_ $\lambda$ - свободная грамматика - грамматика, которая либо не содержит аннулирующих правил вида $(A \rightarrow \lambda)$, либо содержит единств. такое правило S $\rightarrow \lambda$ и S не встреч-ся в правых частях правил вывода.
__Теорема__ Любая грамматика эквивалентна некоторой $\lambda$ -свободной грамматике
_**Д-во:**_
$G = (\Sigma, \Gamma, P, S) - исх., G' = (\Sigma, \Gamma', P', S') - \lambda\ свободная $
0. Если $\lambda \in L(G), то\ \Gamma' = \Gamma \cup S', P' = P \cup \{(S' \rightarrow \lambda), (S' \rightarrow S)\}$
Иначе $\Gamma = \Gamma'$, S = S', P = P'
1. Построить Ann(G)
1.5 в $\Gamma'$ = \{A | ($A \rightarrow \gamma) \in P, \gamma \neq \lambda$\}
2. $\beta \preccurlyeq \gamma$, если $\beta$ - подпосл-ть $\gamma$ и все символы $\gamma$, которых нет в $\beta$, аннулирующие.
P' = $\{(A \rightarrow \beta) | (A \rightarrow \gamma) \in P, \beta \preccurlyeq \gamma, \beta \neq \lambda\}$
> Взяли все исходные правила. В новую грамматику положили их "части"-подстроки, в которых либо присутствует, либо удалён каждый из аннулирующих нетерминалов.
3. L(G) = L(G')
1. w $\in$ L(G')
$S \Rightarrow_{G'} \alpha_i \Rightarrow_{G'}... \Rightarrow_{G'} \alpha_n = w$
$\alpha_{i} \Rightarrow_{G'} \alpha_{i+1}(A \rightarrow \beta) \in P' $, значит, в $G$ $\exists (A \rightarrow \gamma) \in P, \beta \preceq \gamma$.
Тогда $\gamma \Rightarrow^*_G \beta$, следовательно, $A \Rightarrow^*_G \beta$, и это верно для любых цепочек.
2. $w \in L(G)$
**_Пример_**
Отрезаем поддеревья с $\lambda$ на конце. Предок этого поддерева имеет сыновей с непустыми на конце цепочками.

**_Пример_**
$S \rightarrow ~~abc~~|aB|~~aC~~|a|A|E|AE$
$S' \rightarrow S|\lambda$
$A \rightarrow \cancel{bc}|b; B \rightarrow \cancel{ACA}|\cancel{AC}|AA|\cancel{CA}|A|\cancel{C}$
$E \rightarrow A; D \rightarrow bE|b|c$
> 05.03.2019
### Нормальная форма Хомского(ХНФ)
($\lambda$-свободная)Грамматика находится в сокращенной форме Хомского, если все ее не аннулирующие правила вывода имеют вид:
A $\rightarrow$ BC
A $\rightarrow$ a
_**Теорема:**_
Любая грамматика эквивалентна некоторой грамматике в ХНФ.
_**Д-во:**_
$G = (\Sigma, \Gamma, P, S) - \lambda-свободна$
1. $\forall A \rightarrow X_1, ... ,X_n, n \ge 2$(хотя бы 2 символа)
если $X_i \in \Sigma$, то добавить новый нетерминал $X'_i$, новое правило $X'_i \rightarrow X_i$ и все вхождения $X_i$ в правые части правил, длина которых $\ge 2$ заменить на $X'_i$
_Пример_
$A \rightarrow aBc$
$A' \rightarrow a$
$A \rightarrow A'Bc$
$C' \rightarrow c$
$A \rightarrow A'BC'$
2. $A \rightarrow B$ что с ним делать? (выводится нетерминал из нетерминала)
Заменим правую часть на всё, что выводится из $B$. Но что, если есть цепочка $A \rightarrow B \rightarrow … \rightarrow A$ (цикл)? Сначала нужно от них избавиться.
_**Опр**_: Грамматика циклическая если $\exists A \in \Gamma: A =>^+ A.$
Ацикличная в противном случае.
_**Лемма**_:
Любая грамматика эквивалентна некоторой цикличной грамматике.
***Д-во:***
Пусть $A_1 \Rightarrow A_2 \Rightarrow … \Rightarrow A_n \Rightarrow A_1$
> Мы рассматриваем только цепные правила, так как грамматика $\lambda$-свободная, то есть не возникнет ситуации $A \rightarrow BC \rightarrow AC \rightarrow A$ (если из $C$ выводится $\lambda$)
заменим все $A_i$ на A и удалим правила вида A $\Rightarrow$ A
Почему это работает?
$G = (\Sigma, \Gamma, P, S)$ - цикличная
$G' = (\Sigma, \Gamma, P, S)$ которая получилась
Почему они эквивалентны?
$\Rightarrow$ одна выводится из другой, потому что вывод в G' получается стиранием индексов у $A_i$
$\Leftarrow$ Есть вывод в G', как получить в G
Возьмем какой-то вывод G'
пусть A участвовал в выводе $\Rightarrow$ такое вот выполнялось
B → $\alpha A \beta$ - применялось в выводе w
значит применялось обязательно A → $\gamma$
$\Downarrow$
Чтобы в G $(B \rightarrow \alpha A_i \beta), (A_j \rightarrow \gamma) \in$ P надо $A_i \Rightarrow _G^* A_j$
Если ациклическая, то заменять пока не дойдем до терминальных цепочек
заменять на правые, пока не примут вид A → $\alpha$ или A → $B_1...B_n$
Теперь берем получившиеся нетерминалы.
Eсли их там больше 2, то нас это не устраивает.
3. $\forall A → B_1B_2 ... B_n , n\ge 3$
замена
$A → B_1B'_2$
$B'_2 → B_2.. B_n => B'_2 → B_2 B'_3$
$B'_3 → b_3.. B_n$
...
$B'_{n-1}$
После этого правила примут нужный нам вид
***Пример***
S → AB|aAB
A → bB|aBC|$\lambda$
B → AS|bA|a
C → b
Приводим в $\lambda$-свободную грамматику.
> Ann(G) = {A}
S → AB|B|<u>aAB</u>|<u>ab</u>
A → <u>bB|aBC</u>
B → AS|S|<u>bA</u>|b|a
C → b
Приведем к ХНФ.
> A' → a
>
> B' → b
S → AB|B|<u>A'AB</u>|<u>A'B'</u>
A → <u>B'B|A'BC</u>
B → AS|S|<u>B'A</u>|b|a
C → b
Ищем циклы
> S → B
>
> B → S
***
S → AS|<u>A'AB</u>|A'B'|B'A|b|a
A → B'S|<u>A'SC</u>
C → b
A' → a
B' → b
***
S → AS|<u>A'D</u>|A'B'|B'A|b|a
A → B'S|<u>A'E</u>
E → SC
D → AB'
C → b
A' → a
B' → b
***
### Свойства КСЯ
Помеченная позиция - от балды выбираем позиции, но они должны быть разные
_**<NAME>**_
(прокачанная лемма о накачке :D)
Пусть L - КСЯ. Тогда $\exists m \in \mathbb{N}: \forall w \in L$, в которых помечено не менее m позиций, представимо в виде произведения слов $w = uxzyv:$
1) $xy$ содержит хотя бы одну помеченную позицию
2) $xzy$ содержит не более $m$ помеченных позиций
3) $u x^n z y^n v \in L\ \forall n \in \mathbb{N_0}$
_Д-во:_
> Пусть L порождается грамматикой в ХНФ.
>
> G = ($\Sigma, \Gamma$, P, S) ; L = L(G)
>
> m = $2^{|\Gamma| + 1}$
>
> Расcсмотрим w слово из L |w| $\ge$ m и пометим не менее m позиций.
>
> Рассм его дерево вывода
>
> 
>
> *<u>b - точки ветвления</u>*
>
> Построим путь $p_w$ в дереве вывода слова w в G.
>
> корень S $\in p_w$
>
> из двух потомков (потому что в ХНФ) узла, который уже $\in p_w$ выбираем того, из которого выводится больше помеченных позиций.
_**Опр:**_ Точки ветвления - узел, у которого из обоих потомков выводятся подслова w с помеченными позициями.
> (*) Каждая точка ветвления порождает не менее половины помеченных позиций от тех, что порождает предыдущая точка ветвления.
>
> В $p_w$ не менее |$\Gamma$| + 1 т.в.
>
> Среди всех точек ветвления в $p_w$ рассмотрим последние |$\Gamma$| + 1 точки =>
>
> => хотя бы 2 узла имеют одинаковую метку.
>
> Пусть это будет A
>
> 
>
> $v_1$ и $v_2$ точки ветвления
>
> A =>^+^ z
>
> A =>^+^ xzy
>
> A =>^+^ xAy
>
> Почему вып. лемма:
>
> 1) v_1 - точка ветвления => x или y содержат хотя бы одну помеченную позицию
>
> 2) В xzy не более m помеченных позиций по (*)
>
> 3) S =>^+^ uAv =>^+ uxAyv => ux^2^ A y^2^v => ...
Используется, чтобы опровергнуть КС
_**Пример**_
Грамматика в ХНФ
S -> AB
A -> AB|a
B -> BS|b

> 12.03.19.
### Лемма о накачке (Следствие теоремы Огдена)
L - КСЯ $\Rightarrow \exists n, m \in \mathbb{N}: \forall w \in L: |w| \ge n$ w представимо как uxzyv
причем:
1) xy $\neq \lambda$
2) |xzy| $\le$ m
3) $ux^k zy^kv \in L\ \forall k \in \mathbb{N_0}$
Вариант леммы Огдена, когда все позиции являются выделенными.
#### Следствия леммы о накачке
На экзамене на этот вопрос не надо доказывать лемму о накачке
и следствия не как в книжке
1. Язык {$a^n b^n c^n| n \in \mathbb{N}$} - не КСЯ
(лемма - проверка на то, что язык контекстно свободный)
_Д-во:_
> о/п
>
> L - КСЯ $\Rightarrow$ вып-ся лемма о накачке
>
> $a^l b^l c^l , l \ge m 3l \ge n$
>
> a..a..ab...b...bc...c..c
>
> блок - подслово из одинаковых букв
>
> xzy расп-но в одном блоке, либо на границе двух
>
> 1) б.о.о. xyz в аааааа
>
> будет ''накачиваться'' одна буква
>
> получится слово не из языка $(a^{l+r} b^l c^)$
>
> 2) б.о.о. xyz на границе $a^l b^l$
>
> если на границе x или y - чередование нарушается
>
> а если на границе z, то a и b накачиваются, а с нет
>
> противоречие
2. Язык L = {$ww|w \in \Sigma^*, |\Sigma| \ge$ 2} - не КСЯ
_Д-во_
> $\Sigma = \{a_1, ..., a_{n'}\}$
>
> для любого слова должно накачиваться => и для такого должно
>
> $a_1^l a_2^l ... a_k^l a_1^l a_2^l ... a_k^l , k \le n'$
>
> $l \ge m;\ 2|w| \ge n$
>
> Накачка может происходить двумя способами: одну из половин и когда границу
>
> 1) накачиваем вторую половину
>
> По предположению представимо $w^2 = uxzyv$
>
> $ux^2 zy^2 v$
>
> накачали один раз => длина слова увеличилась по крайней мере на m
>
> граница на блоке $a_1$, а вторая заканчивается на $a_k$, они не могут быть одинаковы
>
> [ w \][ $a_1$ \][ $a_k$ ]
>
> ww' = $ux^2 zy^2 v$ противоречие
>
> 2) [ \][$a_k$\][$a_1$\][]
>
> xzy - посередине $a_k$ и $a_1$
>
> $ux^2 y^2 v$
>
> $a_1^l a_k^{l+r} a_1^{l+s} a_k^l$
>
> r+s $\le$ m
>
> б.о.о. r $\ge$ s
>
> r = s => в новом слове первая половина кончается на большее количество $a_k$ -х
>
> r > s
>
> [$a_1$\][(середина)$a_k^{l+r}$\][]
>
> первая половина нач на $a_1$
>
> вторая - на а_k
>
> $a^n b^n c^k , k \ge n$ - не противоречит лемме о накачке, а в Лемме Огдена из-за того, что мы можем что-то выделить нам придется накачать что-то еще
**Теорема об унарных языках**
Для языка L $\subseteq$ = {a*} след усл эквивалентны
1) L - регулярный
2) L - КСЯ
3) мн-во длин слов из L - периодическое
$(M \subseteq \mathbb{N}, если \exists\ n_o, d \in \mathbb{N}:\forall n> n_0 (n\in M) => (n+d \in M))$
1 => 2 => 3 => 1
_Д-во_
> 2) => 3)
>
> $\exists n, m\ \forall a^n\ a^{n+r} \in L, r \le m$
>
> По лемме о накачке: $a^n = uxzyv = uvzxy$
>
> $uvz(xy)^k \in L$
>
> Положим $n_o$ = n из леммы о накачке, а d = m!
>
> m! делится на все r $\in$ \{1, ..., m\}
>
> $a^{n+lm!} \in L$ - накачать можно сколько угодно раз
>
> $\frac{m!}{r}$
>
> 3 => 1
>
> Докажем с помощью построение автомата
>
> $\forall i: 0 \le i \le d$ найдем минимальное $k_i \in$ M, $k_i \equiv $ i mod d; k_i > n_0
>
> Если для какого-то i $k_i$ не существует, положим его равным 0
>
> M - бесконечное => $\exists i: k_i > 0 $
>
> k = $\max\limits_i$$\{k_i\}$
>
> Строим автомат
>
> 
>
> Ручка имеет длину k
>
> Обод длины d
>
> $\forall$j $\in$ {0,..,k} сост-е $q_j$ закл <=> $a^j \in$ L
>
> для остальных $q_s$ - заключительное <=> $a^{s+rd} \in$ L
##### Подстановки
_Опр_ Подстановка $\tau$ : $2^{\Sigma^*}$ -> $2^{\Delta^*}$ ($\Sigma, \Delta$ - алфавиты)
1) $\tau(\lambda) = \lambda$
2) $\tau(a) \subseteq \Delta*, a \in \Sigma$
3) $\tau(a_1, ..., a_n) = \tau(a_1)\tau(a_2)..\tau(a_n)$
4) $\tau(L_1) = \bigcup\limits_{w \in L_1}\tau(w)$
!! Гомоморфизм - частный случай подстановки ($\forall a \in \Sigma, \tau(a) = w \in \Delta^*$)
\# _Пример_
Пусть $\Sigma = \{a_1, a_2\}$
$\tau(a_1) = L_1 \subseteq \Delta^*$
$\tau(a_2) = L_2 \subseteq \Delta^*$
$L = \{a_1,a_2\}$ - язык
$\tau(L) = \tau(a_1) \cup \tau(a_2) = L_1 \cup L_2$
L = {a_1a_2}
$\tau(L) = \tau(a_1)\cdot \tau(a_2) = L_1L_2$
L = {a_1}*
$\tau(L) = \tau({a_1}*) = \tau(\bigcup\limits_{i=0}a_1^i) = \bigcup\limits_{i=0}\tau (a_1^i) = \bigcup\limits_{i=0}\tau (a_1)^i = \bigcup\limits_{i=0}L_1^i = L_1^* $
**Теорема о подстановке**
Пусть $L \subseteq \Sigma^*$ - КСЯ $\tau: 2^{\Sigma^*} -> 2^{\Delta^*} $- подстановка: $\forall a \in \Sigma \tau(a) $- КСЯ
Тогда $\tau(L)$ - КСЯ
_Д-во_
>L - порожд G = $(\Sigma, \Gamma, P, S)$
>
>$\Sigma = \{a_1, ...,a_n\}$
>
>$G_i = (\Delta, \Gamma_i, P_i, S_i)\ L(G_i) = \tau(a_i)\ \forall i = \overline{1, n}\ (\Gamma_i \cap \Gamma_j = \empty, j \neq i; \Gamma \cap \Gamma_i = \empty\ \forall i)$в результате применения подстановки к одному символу получили
>
>Гр-ка H =$ (\Delta, \bar{\Gamma}, \bar{P}, S) $(аксиомы из грамматики G )
>
>$\bar{\Gamma} =\Gamma \cup \bigcup\limits_{i=1}^n \Gamma_i$
>
>$\bar{P} = \bigcup\limits_{i=1}^n P_i \cup P'$
>
>P' - из P заменой всех терминалов $a_i$ на соотв. $S_i$
>
>Нужно предъявить грамматику и доказать, что она порождает
>
>Мы предъявили теперь доказываем
>
>L(H) = $\tau(L)$
>
>1) w $\in$ L(H)
>
>
>
>Дерево вывода для w
>
>T' - станд. поддерево: все внутр. узлы из $\Gamma$, листья из $\bigcup\limits_{i=1}^n\Gamma_i \cup \Delta$
>
>если $\exists(A \rightarrow \alpha B\beta) \in \bar{P}$
>
>$A \in \Gamma; B \notin \Gamma, то\ \alpha, \beta = \lambda$
>
>$т.е. S =>^* S_i, ..., S_{i_k} =>_H^* w_{i_1}...w_{i_k} = w;
>w_{i_j} \in \tau(a_{i_j})$
>
>$w = \tau(a_{i_1}) \tau(a_{i_2}) ... \tau(a_{i_k}) = \tau(a_{i_1}...a_{i_k}), a_{i_1}...a_{i_k} \in L (т.к.S =>_G^* a_{i_1}...a_{i_k})$
>
>$w \in \tau(L)$
>
>19.03.19
>
>2) $w \in \tau(L)$
>
>$\exists u \in L: w \in \tau(u)$
>
>$u = a_{i_1}...a_{i_k} => w \in \tau(a_{i_1}...a_{i_k}) = \tau(a_{i_1})...\tau(a_{i_k})$
>
>из первой строчки
>
>$S =>_G^+ u = a_{i_1}...a_{i_k} <=> S =>H^+ S_{i_1}...S_{i_k} =>^* w_{i_1}...w_{i_k}; w_{i_j} \in \tau(a_{i_j})$
>
>$w \in L(H)$
> 19.03.19.
**Следствие 1**
Класс КСЯ замкнут относительно регулярных операций(*, $\cdot$, +)
$\{a_1, a_2\}$
$L_1 = \tau(a_1) $- КСЯ
$L_2 = \tau(a_2) $- КСЯ
по теореме подстановки $\tau(\{a_1, a_2\}) = L_1 \cup L_2$
**Следствие 2**
Класс КСЯ замкнут относительно перехода к гомоморфным образам
(гомоморфизм - частный случай подстановки)
$\tau(a) \subseteq \Sigma^*$ - подстановка
$\phi(a) \in \Sigma^*$, т.е. $\phi(a) = L, |L|=1$ - гомоморфизм
**Приложение**
Класс КСЯ не замкнут относительно пересечения и дополнения
_Д-во_
> возьмем 2 кся и докажем, что их пересеч не кся
>
> $L_1 = \{a^n b^n a^m| n, m \in \mathbb{N_0}\}$
>
> $L_2 = \{a^m b^n a^n| n, m \in \mathbb{N_0}\}$
>
> $L_1 = \{a^n b^n| n \in \mathbb{N_0}\} \cdot \{a^*\}$ - КСЯ по сл 1
>
> $L_2 =\{a^*\} \cdot \{b^n a^n| n \in \mathbb{N_0}\} $ КСЯ по сл 1
>
> $L_1 \cap L_2 = \{a^n b^n a^n| n \in \mathbb{N_0}\} $ - не КСЯ по лемме о накачке
>
> $L_1 \cap L_2 = \phi(L_3)$
>
> $L_3 = \{a^n b^n c^n| n \in \mathbb{N_0}\}$
>
> $\phi(a) = a, \phi(b) = b, \phi(c) =a$
>
> Для дополнения просто через Де Моргана можно доказать
__Теорема__(о пересечении КСЯ и РЯ)
Пересечения КСЯ с рег. языком - КСЯ
_Д-во_:
> L = L(G), G = ($\Sigma, \Gamma$, P, S) - ксг
>
> A = ($\Sigma, Q, \delta, q_0$,F), M = L(A) - ря
>
> $L \cap M$
>
> $A_{f_i}$ =($\Sigma, Q, \delta, q_0$,f), f $\in $ F
>
> M =$ \cup_{f_i \in F} L(A_{f_i})$
>
> $L \cap M = L \cap \cup_{f_i \in F} L(A_{f_i}) = \cup_{f_i \in F} L \cap L(A_{f_i})$
>
> => достаточно рассмотреть автомат с одним закл состоянием
>
> $A = (\Sigma, Q, \delta, q_0, f) $
>
> $H = (\Sigma, \bar{\Gamma}, \bar{P}, \bar{S})$
>
> $\bar{\Gamma} = Q x (\Gamma \cup \Sigma) x Q$
>
> $\bar{S} = (q_0, S, f)$
>
> $\bar{P}: 1) если (A -> X_1,.., X_n) \in P$, то для любого набора состояний $p, q, r_1,..., r_{n-1}$
>
> $(p, A, q) → (p, X_1,r_1)(r_1, X_2, r_2)...(r_{n-1 }X_n q) \in \bar{P}$
>
> первый не имеет отношения к грамматике
>
> 2) если $\delta(p, a) = q, то (p, a, q) → a \in \bar{P}$
>
> L(H) = L $\cap$ M
>
> $w \in L(H)$
>
> Вывод w: сначала правила вида 1)
>
> пусть w = $a_1...a_n$
>
> $\bar{S} =>_H^* (q_0, a_1, r_1)(r_1, a_2, r_2) ... (r_{n-1}, a_n, f) =>^+ a_1...a_n$
>
> все переходы эквивалентны, то есть по сути мы доказали в обе стороны
>
> $w \in L \cap M$
#### Алгоритм Кока-Янгера-Касами
определить вхождение слова в КСЯ
G = $(\Sigma, \Gamma, P, S) $- в ХНФ
w $\in $ L(G) $\Rightarrow \forall$ i,j; i<j
$\exists A \in \Gamma$, (A $\rightarrow$ BC) $\in$ P:
A $\rightarrow$ w[i,..,j]
B $\rightarrow$ w[i,..,k]
C $\rightarrow$ w[k+1,..,j]
i $\le$ k $\le$ j
Таблица T (верхнетреуг-я матрица размера nxn |w|=n)
$T_{ij} $- ее клеточки
$T_{ij} = \{A|A \Rightarrow_G^+ w[i,..., i+j-1]\}$ - нетерминалы начиная с позиции i длины j(подслова опред слова)
первый столбец заполняется по правилам вида A $\rightarrow$ a из ХНФ
$T_{ij} = \{A|\exists (A \rightarrow BC) \in P: B \in T_{ik}, C \in T_{(i+k-1,j-k)}\} i \le k < j-1$
Остальные столбцы заполним, перебрав все возможные "распилы" строки на 2 части:
$T_{ij} = \{A | \exists (A \rightarrow BC) \in P, B \in T_{ik}, C \in T_{i+k-1, j-k}, i \le k < j-1 \}$
Если в последней клетке есть аксиома, то w $\in$ L(G)
Если в $T_{ij}$ есть $S$, то в строке есть подстрока, принадлежащая $L(G)$ длины $j$ с позиции $i$
**Пример**
$S → A'A|BB'|SS$
$A → A'A|A'D|c$
$D → CB'$
$B → BB'|A'D|c$
$C → A'D|c$
$A' → a$
$B' → b$
$w = aacbcb$
строка - позиция
столбец - длина
| A' | - | S, A | S,A | - | S |
| ----- | ------- | ------- | ---- | ---- | ---- |
| A' | S,A | A, B, C | - | - | нет |
| A,B,C | S, B, D | - | S | нет | нет |
| B' | - | - | нет | нет | нет |
| A,B,C | S,B,D | нет | нет | нет | нет |
| B' | нет | нет | нет | нет | нет |
$w[1,2]=w[1,1]w[2,2]$ — всего один способ поделить на 2 части
$w[1,3]=w[1,1]w[2,3]=w[1,2]w[3,3]$ — можно поделить двумя способами:
- с позиции 1 длины 1 + с позиции 2 длины 2;
- с позиции 1 длины 2 + с позиции 3 длины 1.
**Смысл**: берём значение из ячейки слева ($X$), из ячейки справа ($Y$), и ищем нетерминал ($Z$), из которого выводится последовательность $XY$ ($Z \rightarrow XY$). Если нашли такой терминал, то записываем.
**Сложность**: $n*n$ — таблица, $n$ — распилы и поиск, итого $O(n^3)$
> 26.03.2019
$a^nb^n$ не распознается ДКА
S $\rightarrow $ aSb|$\lambda$
A=($\Sigma$, Q, $\delta, q_0$, F)
|Q| = n

#### МП-автоматы
PDA(push-down automaton)
автомат состоит из управляющего устройства у него есть 2 ленты, одна из них потенциально бесконечная
входная лента содержит слово
с входной ленты можно читать, из стека можно читать и туда можно писать (из стека можно читать только вершину)
внизу лежит символ дна, который називается набла $\nabla$
а справа в слове лежит болт (у меня будет решетка #)

Как происходит один шаг работы автомата
находимя в каком-то состоянии, обозреваем символ входной строки и это один символ, и в стеке один символ и он из алфавита стека
входной
(q, a , B) $\rightarrow (q', \{_, \rightarrow \}, \gamma) - $команды (*)
на основании этой тройки автомат принимает решение,что ему делать
в стек может записываться произвольная цепочка
когда автомат закончил свою работу - оказался в заключительном состоянии и м ыдочитали строку до конца
**_Опр:_** МП - автомат - семерка M = ($\Sigma, \Gamma, Q, \delta, i_o, F, \gamma$)
$\Sigma$ - взодной алфавит
$\Gamma$ - стековый алфавит
Q - мн-во состояний
$\delta$ - мн-во команд вида (*)
$i_0$ - нач.сост.
F - мн-во закл. сост.
$\gamma \in \Gamma^*$ - нач содерж стека
символ с вершины стека всегда снимается
вместо вершины что-то кладем, возможно 0 символов
МПА обычно представляется в виде таблицы

Скобочный язык

√ - команда допуска
(q, #, B) → √ - разбор завершен успешно
в детерминированном одна команда допуска
F = {t}
Q = {q, t}
$\gamma_0 =\lambda$
$i_0 = q$
Г = {(}

_**Опр:**_ Конфигурация автомата - (снимок его состояния) - тройка
[q, w, $\gamma$]
q - текущее состояние
w - необработанная часть входной строки
$\gamma$ - текущее содержимое стека
на множестве конфигураций автомата можно ввести отношение возможности перехода из 1-го сост-я в др-е
[q, w, $\gamma$] ╞ [q', q' $\gamma$'] - отношение
пока вершина стека пишется с лева
[q, aw, B$\gamma$] ╞ [q', w, $\gamma', \gamma$] → при выполнении команды (q, a, B) → (q', →, $\gamma'$)
[q, aw, B$\gamma$] ╞ [q', aq, , $\gamma'\gamma$]
(q, a, B) → (q', _, $\gamma'$)
_**Опр:**_МПА распознает цепочку, если он дочитал ее до конца и оказался в закл. состоянии
(вып. команду допуска)
(зак. работу с пустым стеком)
_**Опр:**_ МПА распознает w, если
[$i_o$, w, $\gamma_0$] ╞* [t, $\lambda$, $\gamma$], t $\in F$ - рефлексивно транзитивное замыкание нашего отношения
$\lambda$ - строка прочитана полностью
L(M) = {w|[$i_o$, w, $\gamma_0$] ╞* [t, $\lambda, \gamma$]}
Построим для языка $a^nb^n$ атомат

А - b не была встречена
$\lambda$ - запись пустого слова в стек
пока там лежит А, можно читать а, как только нет, уже только b и сравнивать
Пример

> 02.04.19.
#### НМПА и ДМПА
ДМПА
(q, a, B) $\rightarrow$ (q', {_, →}, $\gamma$)
не более одной команды с такой л.ч.
НМПА
(q, a, B) → 2^(Qx{_,→}xГ*)fin^
__*Теорема*__
Класс языков, распознаваемых НМПА, строга больше класса языков, распознаваемых ДМПА
_Д-во:_
> рассмотрим язык палиндромов четной длины
>
> L = {$w\overleftarrow{w} | w \in \Sigma^*, |\Sigma| \ge 2$}
>
> M = ($\Sigma, \Gamma, \delta, X)$
>
> X - символ, который указывает на то, что не было момента сравнения(середина)
>
> Г = $\Sigma$ x {X}
>
> Сравнение первой половины со второй
>
> автомат угадывает середину, поэтому он может распознать этот язык
>
> Никакой ругой язык он не распознает, потому что у него там в стеке останется еще что-то или наоборот, в стеке не хватит символов в сравнении 
>
> о/п
>
> Предположим, существует ДМПА, распознающий наш язык L.
>
> Работает по принципу сравнения
>
> x $\in \Sigma$
>
> Пусть какое-то слово w $\in \Sigma^*$
>
> $wxx\overleftarrow{w}$ принимается автоматом
>
> Раз он распознает это слово, значит от сложил в стек wx, а после этого начинает сравнение
>
> Подадим ему на вход $wxxxx\overleftarrow{w}$
>
> Из того, что распознается слово $wxx\overleftarrow{w}$, то он к сравнению переходит, когда wx на стеке, он переходит к сравнению и ломается(так как автомат детерменированный)
>
> Нам важно, чтобы на момент перехода к сравнению в стеке было столько же символов, сколько на входе
#### МПА и КСЯ
__*Теорема*__
Любой КСЯ распознается НМПА с одним состоянием и одной командой допуска.
_Д-во:_
> L - КСЯ
>
> G = ($\Sigma$, Г, P, S) - КСГ
>
> L(G) = L
>
> M = ($\Sigma \cup$ {#}, $\Sigma \cup \Gamma \cup \{\nabla\}, \delta, S$)
>
> 1) для любой a $\in \Sigma$ (B, a) → ($\gamma$, _)
>
> $\forall (B, \gamma) \in P$
>
> 2) $\forall a \in \Sigma (a, a) → (\lambda,→)$
>
> 3)($\nabla$, #) → √
>
> L = L(M)?
>
> 1. $w \in L$
>
> существует левосторонний вывод w в G
>
> S $\Rightarrow u_1B_1\gamma1 \Rightarrow u_1u_2B_2\gamma_2\Rightarrow ...\Rightarrow u_1u_2...u_{n-1}B_{n-1}\gamma_{n-1}\Rightarrow u_1u_2..u_n$
>
> $\gamma_i \in (\Sigma \cup \Gamma)^*$
>
> B → $v$
>
> $u_n = v\gamma_{n-1}$
>
> Тогда в М реализуема последовательность конфигурация
>
> В начале остаток входной строки это все слово w, а в стеке у нас лежит аксиома
>
> [w, S] = [$u_1,.., u_n$, S] ╞(1) [$u_1,.., u_n, u_1 \beta_1 \gamma_1] ╞^*(2) [u_2, .., u_n, B_1 \gamma_1]$ ╞(1)
>
> $ [u_2, u_n, u_2B_2\gamma_2] ╞^* [u_n, B_{n-1\gamma_{n-1}}] ╞ [u_n, u_n] ╞^*[\lambda, \lambda]$ $\Rightarrow w\in L(M)$
>
> 2. $w \in L(M)$
>
> [w, S]╞^*^ [$\lambda, \lambda$] - конечное число тактов m (тут стрелка на отношение)
>
> можем представить w так
>
> $w = a_1...a_m$ - закодировали команды, которые применялись на i-м такте
>
> $a_i \in \Sigma \cup\{\lambda\}$
>
> $a_i = \lambda$ - когда на i-м такте применялась команда типа (1)
>
> [w, S] ╞ [$a_1...a_m, S] ╞ [a_1...a_m, a_1...a_{i_1} B_1 \gamma_1]╞^*[a_{i_1+1}...a_m, B_1\gamma_1]╞...╞[\lambda, \lambda]$
__*Лемма*__
Произведение отработанной части входной строки на содержимое стека - левая форма G
> **Левая форма** — всё, что может возникнуть в процессе левостороннего вывода.
_Д-во:_
> Индукция по номеру такта
>
> Б.И.: n = 0
>
> $\lambda S = S$ - левая форма
>
> Пусть $a_1...a_{n-1} \cdot \gamma_{n-1}$ после n-1 такта и это левая форма по П.И.
>
> 1) $a_n \in \Sigma \Rightarrow \gamma_{n-1} = a_n\gamma_n$
>
> $B_{n-1} = B_n$
>
> 2) $a_n = \lambda \Rightarrow \gamma_{n-1} = B_{n-1}\gamma_{n-1}'$
>
> $B_{n-1} = a_1...a_{n-1}\gamma\gamma'_{n-1}$ ($B_{n-1}→\gamma) \in $P
>
> $B_{n-1} = a_1...a_{n-1}B_{n-1}\gamma'_{n-1}$ - левая форма
Продолжим доказательство
>После последнего такта
>
>$w\cdot\lambda$ - левая форма (по Лемме)
>
>$w \cdot \lambda = w \Rightarrow w\in L(G)$
__*Утверждение*__
Класс КСЯ и класс языков, распознаваемых НМПА, совпадают.
__*Следствие*__
ДМПА распознают собственный подкласс КСЯ.
_Пример:_
S → (S)S|$\lambda$

> 09.04.19
### Лексический анализ
**Лексема** — элементарная смысловая единица текста. Могут объединяться в классы эквивалентности — **токены**. Описываются токены с помощью **шаблонов**.
> Классы идентификаторов. Одноэлементные классы ключевых слов.
| Токен | Пример лексемы | Шаблон |
| ------ | --------------- | -------------------------------------- |
| if | if | `if` |
| cop | <=, >=, ==, … | `<=?|>=?|[=!]=` |
| id | pi, var23 | `[a-z]\d*` |
| number | 1.09, -2.75e-30 | `-?0|[1-9]\d*(.\d{1,})?(e-?[1-9]\d*)?` |
> Первая колонка — имя, которое будет приходить на вход синтаксическому анализатору. comparison operator
#### Распознавание лексем
Вся собранная информация сохраняется в **таблице символов** — структуре данных для хранения информации об идентификаторах.
##### **Буферизация**
| | | | | | | | | | | | | | | | | |
$\uparrow$ $\uparrow$
*begin* *current*
*begin* — начало текущей лексемы, протяжённость которой мы пытаемся определить.
*current* — текущий сканируемый символ.
Зачем два буфера? По одному символу может быть невозможно определить, какая перед нами лексема. Если указатель current дошёл до конца одного буфера, то все уже прочитанные символы можно скопировать во второй.
##### **Регистрация токена**
REG — функция, которая точно знает где начался и закончился токен. Делает запись в таблицу символов: какой это был оператор, где он находился в исходном тексте. Нужно для обработчика ошибок.
REG- — до предпоследнего символа.
Токен = <имя, атрибут>. Атрибут — ссылка на запись в таблице символов. Имя используется в лексическом анализе.
**Примеры диаграмм переходов**


##### **Ошибки**
- несуществующий переход в автомате
##### **Обработка ошибок**
> Не хотим сразу навсегда ломаться, а выдавать все ошибки за раз.
**Режим паники** — пропускаем всё, пока не встретим корректные символы.
Но можно подумать, а может ли префикс оставшийся строки быть преобразован в корректную лексему и сделать что-то из списка:
- пропуск одного символа;
- вставка пропущенного символа;
- замена символа;
- перестановка соседних символов.
### Синтаксический анализ
**Задача** — определить принадлежность слова языку, который задан некоторой КС грамматикой. Грамматика описывает **синтаксис**! Также нужно построить дерево вывода и сообщить об ошибках.
**Типы анализаторов**
- универсальные (алгоритм КЯК);
- нисходящие (восстановление дерева от корня к листьям);
- восходящие.
**Разделённая грамматика**
$\forall A \in \Gamma: (\forall (A \rightarrow \gamma) \in P$ все $\gamma$ начинаются с разных терминалов$)$
> До этого было: $A \rightarrow \gamma$ $\forall a \in Z :(A, a) \rightarrow (\gamma, —)$
> 16.04.19
### Нисходящий анализ
#### Левая рекурсия
Грамматика называется **непосредственно леворекурсивной**, если $\exists (A \rightarrow A \alpha) \in P$. Плохо, потому что грамматика не разделённая. Просто **леворекурсивной**, если $\exists (A \Rightarrow^+ A\alpha)$.
> Наталкиваясь на такую штуку, мы не можем посчитать, сколько раз было применено такое правило. Потенциальный бесконечный вывод. Но! Существует алгоритм, делающий леворекурсивную грамматику нормальной.
$A \rightarrow A\alpha_1|…|\alpha_n|\beta_1|…|\beta_m$ $\forall i :\beta_i$ не начинается с $A$
$A'$ — новый нетерминал
Заменим все рекурсивные правила на такую группу
$A \rightarrow\beta_1 A'|…|b_m A'$
$A' \rightarrow \alpha_1A'|…|\alpha_n A'|\lambda$
> Левая рекурсия - это накопление альф, и добавление в конце беты. Давайте сначала поставим бету, а потом накопим альфы, перейдя к правой рекурсии.
Но так можно устранить только непосредственную рекурсию! Нужен алгоритм для общего случая.
##### Алгоритм устранения левой рекурсии
> Недостаток — на вход нужно подавать $\lambda$-свободную грамматику. И ацикличную, по Dragon book
Ввод: $\lambda$-свободная грамматика.
Суть: находим правила, где правая часть начинается с предыдущего нетерминала. Заменяем его на то, что из него выводится.
$\Gamma = \{ A_1…A_n\}$
$for \: i=1…n:$
$for \: j=1…i-1:$ #$j<i$
Все правила вида $A_i \rightarrow A_j\alpha$ заменить на $A_i\rightarrow \beta \alpha$, где $(A_j \rightarrow \beta) \in P$
Устранить непосредственную рекурсию для $A_i$
**Доказательство корректности** — индукция по $i$
$(A_i \rightarrow A_j\alpha) \in P \Rightarrow i < j$
**БИ** $i=1$ — устранили непосредственную левую рекурсию из $A_1$ продукций
**ШИ** $A_i \rightarrow A_m\alpha$. m > 1, так как такие продукции мы уже поправили.
Если $\beta$ начинается с нетерминала, то …. ???
> Этот нетерминал уже был обработан?
После внутреннего цикла $i \le j$. Равенство — непосредственная рекурсия.
$\blacksquare$
**Пример**
$S \rightarrow Aa|AB|B$
$A \rightarrow SB|ac$
$B \rightarrow Ac|b$
Надо перенумеровать:
$S_1 \rightarrow A_2a|A_2B_3|B_3$
$A_2 \rightarrow S_1B_3|ac$ [зачёркнуто после 2 итерации]
$B_3 \rightarrow A_2c|b$
После внутреннего цикла:
$A_2 \rightarrow A_2a B_3|A_2B_3B_3|B_3B_3|ac$ [зачёркнуто после 2 итерации]
Добавим $A'$:
$A_2 \rightarrow B_3B_3A'|acA'$
$A' \rightarrow aB_3A'|B_3B_3A'|\lambda$
Третья итерация:
$B_3 \rightarrow B_3B_3A'c|acA'c|b$
Устраним непосредственную рекурсию:
$B_3 \rightarrow acA'cB'|bB'$
$B' \rightarrow B_3A'cB'|\lambda$
Готово.
#### Левая факторизация
$A \rightarrow \beta\alpha_1|\beta\alpha_2|…$
**Факторизация** — устранение всех общих префиксов.
**Альтернатива** — все правые части одного нетерминала.
Почему плохо для нисходящего анализа? Из бет выводится одно и то же, и нам нужно пройтись на неопределённую глубину, чтобы понять, какое правило было применено.
> $S \rightarrow if(B)S|if(B)S\: else S$ — не сможем узнать, а был ли else
Для каждого нетерминала, среди его альтернатив, найдём самый длинный общий префикс (необязательно у всех, хотя бы у двух). Затем введём новый нетерминал $A'$.
$A \rightarrow \beta A'$
$A' \rightarrow \alpha_1|\alpha_2$
Продолжаем, пока у альтернатив есть общий префикс.
**Пример**
$S \rightarrow Abc|AbB|AC|ABB$ [зачёркнуто после первой итерации]
$A \rightarrow Bc|b$
$B \rightarrow aa$
$C \rightarrow aA$
Самый длинный общий префикс — Ab
$S \rightarrow AbD|AC|ABB$ [зачёркнуто после второй итерации]
$D \rightarrow c|B$
Самый длинный общий префикс - A
$S \rightarrow AE$
$E \rightarrow bD|C|BB$
Готово.
#### $LL(1)$-грамматики
> [небольшая презентация, pdf](http://gas-teach.narod.ru/au/tfl/tfl08.pdf)
Чего мы хотим? В момент обозревания на стеке какого-то нетерминала и какого-то символа на входе, знать, какую команду нужно применять.
$(B, a) \rightarrow (j, \_)$?
$(B \rightarrow \gamma) \in P$
$u$|$v$
$B$
$\beta$ $uB\beta$ — левая форма
$\nabla$
Пусть $v = av'$. Тогда либо из $B$ должно выводиться что-то, начинающееся с $a$, либо, если $B$ аннулируется, тогда из $\beta$ должно выводится что-то, начинающееся с $a$.
###### FIRST
<u>Опр</u>. $FIRST(\alpha) \subseteq \Sigma \cup \{ \lambda\}$:
$a \in FIRST(\alpha) \iff \alpha \Rightarrow^* a\alpha'$
$\lambda \in FIRST(\alpha) \iff \alpha \Rightarrow^* \lambda$
> $FIRST(\alpha)$ — все терминалы, с которых могут начинаться всевозможные выводы из $\alpha$.
> Нисходящий анализ умеет работать с аннулирующими правилами. А с левой рекурсией нет. Поэтому ничего страшного, если в процессе избавления от левой рекурсии появляются аннулирующие правила.
**Пример**
$S \rightarrow AC$
$A \rightarrow abC|bB$
$B \rightarrow b$
$C \rightarrow c|\lambda$
$FIRST(AC) = \{a,b\}$
$FIRST(CA) = \{c,a,b\}$
###### FOLLOW
<u>Опр</u>. $FOLLOW(A) \subseteq \Sigma \cup \{ \dashv \}$:
$a \in FOLLOW(A) \iff S \Rightarrow^* \alpha A a\beta$
$\dashv \:\in FOLLOW(A) \iff S \Rightarrow^* \alpha A$
$FOLLOW(A) = \{c, \dashv\}$
> Множество терминалов, которые могут встретиться непосредственно справа от нетерминала $A$ в некоторой цепочке.
###### SELECT
<u>Опр</u>. $SELECT(A \rightarrow \alpha)$:
1. $FIRST(\alpha)$, если $\lambda \not \in FIRST(\alpha)$
2. $FIRST(\alpha) \setminus \{\lambda\} \cup FOLLOW(A)$, иначе
> Множество выбора правил.
> $SELECT(A \rightarrow \alpha) = FIRST(\alpha FOLLOW(A))$
###### $LL(1)$-грамматика
<u>Опр</u>. $LL(1)$-грамматика:
$\forall A \in \Gamma : \forall (A \rightarrow \beta), (A \rightarrow \alpha) \in P$:
$SELECT(A \rightarrow \alpha) \cap SELECT (A \rightarrow \beta) = \varnothing$
> LL — две левых стороны. Читаем слева направо, восстанавливаем левый вывод.
>
> 1 — достаточно прочитать один символ со входа, чтобы понять, что делать дальше
**Пример**
$E \rightarrow E+T|T$
$T \rightarrow T*F|F$
$F \rightarrow (E)|x$
Устраним рекурсию
$E \rightarrow TE'$
$E' \rightarrow +TE'|\lambda$
$T \rightarrow FT'$
$T' \rightarrow *FT'|\lambda$
$F \rightarrow (E)|x$
| | FOLLOW |
| ---- | ----------- |
| E | $\dashv$, ) |
| E' | $\dashv$, ) |
| T | +, $\dashv$ |
| T' | |
| F | |
| | FIRST |
| --------- | --------- |
| TE' | $(, x$ |
| +TE' | + |
| $\lambda$ | $\lambda$ |
| FT' | (, x |
| *FT' | * |
| (E) | ( |
| x | $\lambda$ |
> 23.04.19
Если грамматика G содержит леворекурсивное правило, то G - не LL(1)
(A→A$\alpha$) $\in$ P
(A→$\beta$) $\in$ Pб где $\beta[1]\neq A$
select (A→A$\alpha$) $\cap$ selct($\beta \neq \empty$ ?
1) a $\in$ FIRST($\beta$) => $a \in FIRST(A) \subseteq FIRST(A\alpha)$
FIRST(A) = $\bigcup\limits_{A→\beta}FIRST(\beta)$
2) $FIRST(\beta) = {\lambda}$
$select(A→\beta) = FOLLOW(A)$
FOLLOW(A)
2.1)$ a \in FIRST(\alpha) => a \in FOLLOW(A) => a \in select(A→\beta)$
$A => A\alpha => \beta\alpha => \alpha => a \in select(A→A\alpha)$
2.2) $FIRST(\alpha) = {\lambda}$
$select(A→A\alpha)$
$\lambda \in FIRST(A\alpha) => FOLLOW(A) \subseteq select(A→A\alpha)$
$A => A\alpha => \beta\alpha => \alpha => \lambda$
$FOLLOW(A) \subseteq select(A→A\alpha) \cap select(A→\beta)$
#### Алгоритм построения мн-ва FISRT
для символов грамматики
$G = <\Sigma, \Gamma, P, S>$
$\forall a \in \Sigma: FIRST(a) = \{a\}$
$\forall A...(A → \lambda) \in P: FIRST(A) = \{\lambda\}$
это просто инициализация
пока во множестве first от всех-всех символов не перестанет появляться что-нибудь новое(пока они не стабилизировались)
перебираем все правила вывода
$\forall (A→X_1, ..., X_n) \in P, n > 0$
начиная с первого символа правой части добавить в $FISRT(A) = FISRT(A)\cup(FIRST(X_i)\cap \Sigma)$
(это чтобы лямбда отсекалась, если $\lambda \in FIRST(X_i))$
смотрим, пока очередной $X_i$ можно аннулировать
продолжаем накопление, если i < n
иначе нужно добавить лямбду в множество FISRT(A)
#### Алгоритм построения мн-во FOLLOW
> Находим правые части, куда входит данный нетерминал: $B \rightarrow \alpha A\beta$. Сначала надо посмотреть на $FIRST(\beta) \setminus \{\lambda\} \subseteq FOLLOW(A)$. Если $\beta$ аннулируется ($\{\lambda\} \in FIRST(\beta)$):
>
> $S \Rightarrow^* \gamma_1B\_\gamma_2\_ \Rightarrow \gamma_1\alpha A\beta \_\gamma_2\_ \Rightarrow \gamma_1\alpha A \_\gamma_2\_ $ — $FIRST(\gamma_2) \subseteq FOLLOW(B)$
>
> Подчёркнуты $\gamma_2$
$FOLLOW(a) = \{\dashv \}$
Пока множество FOLLOW не стабилизируется, повторяем:
$\forall (A\rightarrow X_1…X_n) \in P, n > 0$
если $(X_n \in \Gamma)$
$FOLLOW(X_n) = FOLLOW(X_n) \cup FOLLOW(A)$
$i = n - 1;$
ann = true; *флаг, что хвост аннулируемый*
(*) если $i > 0$ и $X_i \in \Gamma$ и $X_i$ — терминал
$FOLLOW(X_i) = FOLLOW(X_{i+1}) \cup (FIRST(X_{i+1}...X_n) \cap \Sigma)$
> пересечение нужно, чтобы в FOLLOW не попала $\lambda$
если $\lambda \not \in FIRST(X_{i+1})$
ann = false
если ann == true и $X_i \in \Gamma$
$FOLLOW(X_i) = FOLLOW(X_i) \cup FOLLOW(A)$
$i --$; перейти к (*)
**Пример**
$E \rightarrow TE'$
$E' \rightarrow +TE'|\lambda$
$T \rightarrow FT'$
$T' \rightarrow *FT'|\lambda$
$F \rightarrow (E)|x$
| | FIRST | FOLLOW |
| ---- | ------------ | ----------------- |
| E | $(, \times$ | $\dashv, )$ |
| E' | $\lambda, +$ | $\dashv, )$ |
| T | $(, \times$ | $\dashv, +, )$ |
| T' | $\lambda, *$ | $\dashv, +, )$ |
| F | $(, \times$ | $\dashv, +, *, )$ |
> SELECT( ) == FIRST(левая часть) + FOLLOW(правая часть)
#### Построение нисходящего анализатора
по LL(1) - гр-ке
$G = <\Sigma, \Gamma, P, S>$
$M = (\overline{\Sigma}, \overline{\Gamma}, \delta, S) - ДМПА\ расп-й\ L(G)$
$\overline{\Sigma} = \Sigma \cup${#}
$\overline{\Gamma} = \Gamma \cup {\Sigma} \cup {\nabla}$
$\delta:$
$1) (\nabla$, #) → √
$2) \forall a \in \Sigma (a, a) → (\lambda, →)$
3) $\forall A \in \Gamma, \forall(A→\beta) \in P$
$(A, a) \rightarrow (\beta, _)$
$\forall a \in select(A \rightarrow \beta)$
| | + | * | x | ( | ) | # |
| -------- | ------------ | ------------ | ------------ | ------------ | ------------ | --------- |
| E | | | TE' | TE' | | |
| E' | +TE' | | | | $\lambda$ | $\lambda$ |
| T | | | FT' | FT' | | |
| T' | $\lambda$ | *FT' | | | $\lambda$ | $\lambda$ |
| F | | | x | (E) | | |
| + | $\lambda$, → | | | | | |
| * | | $\lambda$, → | | | | |
| x | | | $\lambda$, → | | | |
| ( | | | | $\lambda$, → | | |
| ) | | | | | $\lambda$, → | |
| $\nabla$ | | | | | | √ |

| | + | * | x | ( | ) | # |
| -------- | --------- | ---- | ---------------------- | ------------------ | --------- | --------- |
| E | | | TE' | TE' | | |
| E' | +TE' | | | | $\lambda$ | $\lambda$ |
| T | | | FT' | FT' | | |
| T' | $\lambda$ | *FT' | | | $\lambda$ | $\lambda$ |
| F | | | $\lambda, \rightarrow$ | (E), $\rightarrow$ | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| $\nabla$ | | | | | | √ |
Замечание
Если $А \rightarrow \alpha\beta_1|\alpha\beta_2, FIRST(\alpha) \neq {\lambda}$
$select(A \rightarrow \alpha\beta_1) \cap select(A \rightarrow \alpha\beta_2) \neq \empty$
> 07.05.19
#### Обработка синтаксических ошибок
| | x | + | * | ( | ) | # |
| :------------------------------------------------ | ---- | --------- | ------ | ----- | --------- | --------- |
| Е - новое подвыражение | TE' | 2. | 2. | TE' | 4. | 2. |
| Е' - ожидание оператора и слагаемого | 1. | TE', → | | 1. | $\lambda$ | $\lambda$ |
| T - начало операнда | FT' | 2. | 2. | FT' | 4. | 2. |
| T' - ожидание оператора и множителя | 1. | $\lambda$ | FT', → | 1. | $\lambda$ | $\lambda$ |
| F - операнд, из него выводится х или подвыражение | → | 2. | 2. | E), → | 4. | 2. |
| ) | 3. | 3. | 3. | 3. | → | 3. |
| $\nabla$ | | | | | 4. | √ |
Ошибка в случае нисходящего анализатора - попадание в пустую клетку таблицы
Либо пытаться снимать со стека, либо пропускать все со входа, пока не будет удача
Снимать со стека - плохой подход, потому что он не сможет работать
##### Типы ошибок в арифметике
1. пропущен оператор
2. пропущен операнд
3. незакрытая (
4. преждевременная )
Как будет обрабатывать?
1. добавить +
2. добавить x
3. добавить (
4. удалить ) из входного потока
Пример
1. )(x+x)(*
(x+x)+(x*x)
E$\nabla$
TE'$\nabla$
...
FT'E'$\nabla$
E)T'E'$\nabla$
...
T'E'$\nabla$
E'$\nabla$
TE'$\nabla$
FT'E'$\nabla$
E)T'E'$\nabla$
2. (x+x))(*x
(x+x)
(*x - осталось на входе, а стек пуст
E$\nabla$
TE'$\nabla$
FT'E'$\nabla$
T'E'$\nabla$
E'$\nabla$
$\nabla$
сломались до конца не дочитали
#### LL(k) - грамматики
_Опр:_ $ w \in FIRST_k(\alpha)$, если $\alpha \Rightarrow^* v$, где
1) |v| < k, w = v
2) |v| $\ge$ k, |w| = k, w - префикс v
_Опр:_ G - LL(k) - грамматика, если из сущ-я выводов
$S \Rightarrow^* wA\alpha \Rightarrow^*wv$
$S \Rightarrow^* wA\alpha \Rightarrow w\gamma\alpha \Rightarrow wu$
где $FIRST_k(u) = FIRST_k(v)$
следует, что $\beta = \gamma$
Класс грамматик
LL(1) $\sub$ LL(2) $\sub$ .. $\sub$ LL(k) $\sub$ LL(k+1)...
Пример
$S \rightarrow a^kb|a^kc$ - LL(k+1), но не LL(k)
$S \rightarrow$ abA|$\lambda$
$A \rightarrow Saa|b$
_Пример_
не LL(1):
FOLLOW(S) = {a, #}
SELECT(S → abA) $\cap$ SELECT(S→$\lambda$) = {a}
Аксимома на вершине стека бывает в 2-х случаях: либо в самом начале, либо мы можем понять, что потом добавлено
LL язык - язык, для которого существует какая-то LL(k) рамматика
не LL языки тоже существуют
Пример
$\{a^k0b^k\}\cup\{a^k1b^{2k}\}$ - не LL язык
##### Универсальный метод рекурсивного спуска
Если для любой цепочки существует число, которое ограничивает длину вывода, то можно эмулировать работу автомата
Идем по поддеревьям, если что-то не так, то идем сначала влево, а потом в самое начало
_Пример_:
$S \rightarrow aSbS|aS|c$
aacbc
> 14.05.19.
#### Восходящий синтаксический анализ
Будем рассматривать:
Приведенные, однозначные, $\lambda$ - свободные, обратимые
Обратимая - у одинаковых правых нет разных левых
r-форма(правая форма)
_Опр:_ Основа $\beta$ r-формы $\gamma$: $\gamma=\alpha\beta v, \exists (A→B) \in P$
Другими словами: $S \Rightarrow^* \alpha Av \Rightarrow \alpha\beta v \Rightarrow ...$
Вывод (правосторонний): ($\alpha_1=S, ... \alpha_n=w$)
Основа r-формы $\alpha_{i+1}:$
$\alpha_i = \alpha Av $
$\alpha_{i+1} = \alpha\beta v$
_Пример:_
S → aSAb|c
A → Ab|b
w = acbbb
Построим для этой цепочки дерево восходящим образом. Пока что нам основы будут подсказывать. Переносим все символы в стек, пока не найдём основу. Потом сворачиваем её к её нетерминалу и продолжаем.
1. $a$
2. $ac$: c соответствует основе. Уберём её, заменив на левую часть $\rightarrow aS$
3. $aSb \rightarrow aSA$
4. $aSAb$: тут на основу претендуют 3 цепочки. Но мы знаем, что лучше использовать $Ab$ $ \rightarrow aSA$
5. $aSAb \rightarrow S$
Дерево вывода:
```
S
//| \
/ / \ \
| | A \
| | / \ \
| S A | |
| | | | |
a c b b b
```
##### Технология "Перенос-свертка"
Если есть основа, то происходит свертка, если нет, то перенос
Индикатор завершения - в стеке только аксиома, а цепочка дочитана до конца
_Опр:_ <NAME> в дереве Т - поддерево высоты 1 такое, что
1) все его листья являются листьями в исходном дереве;
2) у корня К все сыновья в Т - листья в К.
Свертка - обрезание куста(смерджить листья в родительскую вершину)
Двигаемся слева направо и сворачиваем каждый раз самое левое, поэтому вывод получается правосторонний
Восстанавливаем вывод с помощью нашего метода:
S$\Rightarrow aSAb \Rightarrow aSAbb \Rightarrow aSbbb \Rightarrow acbbb$
При использовании этой технологии, у нас всегда сохраняется инвариантность:
Произведение содержимого стека на необработанную часть входной строки - r-форма
В начале стек пуст!
**_Предложение:_**
При использовании технологии "Перенос-свертка" в любой момент времени правый конец основы находится на вершине стека, либо еще не перенесен в стек.
_Д-во:_
> (1) $S \Rightarrow^* \alpha Av_1 B v_2 \overset{1}\Rightarrow \alpha Av_1uv_2 \overset{2}\Rightarrow \alpha \gamma v_1 u v_2$
>
> В форме было 2 разделённых нетерминала, мы применили правило. Значит, всё, что было после правого нетерминала стало терминалами, иначе он бы не был самым правым.
>
> (2) $S \Rightarrow ^* \alpha A v \overset{1}\Rightarrow \alpha\beta B uv \overset{2}\Rightarrow \alpha\beta \gamma uv$
>
> Из правого нетерминала получается что-то, содержащее нетерминал. Тогда он тоже самый правый и следующее правило применяется к нему.
>
> **БИ** Первый раз, когда делается свёртка, основа наверху просто по алгоритму.
>
> 1. Свернули \gamma к A
>
> Перед свёрткой, по ПИ всё ок: После свёртки:
> $v_1 u v_2$ $v_1 u v_2$
> $\gamma$ $A$
> $\alpha$ $\alpha$
> $\nabla$ $\nabla$
>
> 2.
>
> Перед свёрткой, по ПИ всё ок: После свёртки:
> $u v$ $u v$
> $\gamma$ $B$
> $\beta$ $\beta$
> $\alpha $ $\alpha$
> $\nabla$ $\nabla$
>
> $\blacksquare$
#### Способы определения основы
##### Анализ на основе отношений предшествования
Рассматриваем:
ацикличные, обратимые, $\lambda$ - свободные грамматики
Отношения на ($\Sigma \cup \Gamma)^2$
1. $\overset{\cdot}=$
X $\overset{\cdot}=Y$ если XY - подслово основы некоторой r-формы
2. <$\cdot$
X <$\cdot$ Y, если $\exists$ r-форма, ее основа начинается с Y, перед ней находится X
3. $\cdot$>
X $\cdot$> Y, если $\exists$ r-форма, ее основа заканчивается на Х, за ней находится Y

_Предложение:_
1) X $\overset{\cdot}=$ Y <=> $\exists (A \rightarrow \alpha XY\beta) \in P$
2) X <$\cdot$ Y <=> $\exists (A \rightarrow \alpha XZ\beta) \in P$
Z $\Rightarrow^+ Y\gamma$
3) X $\cdot$> Y <=> $Y \in \Sigma, \exists (A \rightarrow \alpha Z_1Z_2\beta)\in P,$
$Z_1 \Rightarrow^+ \gamma_1X, Z_2 \Rightarrow^* Y\gamma$

_Замечание:_
FIRST'(X) - символы, выводящиеся на первом месте из Х (за 1 и более шагов)
LAST'(X) - символы, выводящиеся на последнем месте из Х (за 1 или более шагов)
_Предложение в форме FIRST' и LAST':_
Для отношения больше: Y - только терминалы
1) X $\overset{\cdot}=$ Y <=> $\exists (A \rightarrow \alpha XY\beta) \in P$
2) X <$\cdot$ Y <=> $\exists (A \rightarrow \alpha XZ\beta) \in P$
$Y \in FIRST'$(Z)
3) X $\cdot$> Y <=> $Y \in \Sigma, \exists (A \rightarrow \alpha Z_1Z_2\beta)\in P,$
$X \in LAST'(Z_1), Y \in \Sigma, Y = Z_2 или Y \in FIRST'(Z_2)$
_Пример:_
S → aSAb|c
A → Ab|b
$\vdash, \dashv$
$\vdash \lessdot X$, если c Х начинается r-форма
$X \gtrdot \dashv$, если на Х заканчивается r-форма
| | S | A | a | b | c | $\dashv$ |
| -------- | ------------------ | ---------------------------- | ---------- | ------------------ | ---------- | --------- |
| S | | $\lessdot, \overset{\cdot}=$ | | $\lessdot $ | | $\gtrdot$ |
| A | | | | $\overset{\cdot}=$ | | |
| a | $\overset{\cdot}=$ | | $\lessdot$ | | $\lessdot$ | |
| b | | $\gtrdot$ | | $\gtrdot$ | | $\gtrdot$ |
| c | | $\gtrdot$ | | $\gtrdot$ | | $\gtrdot$ |
| $\vdash$ | $\lessdot$ | | $\lessdot$ | | $\lessdot$ | |
| | FIRST' | LAST' |
| ---- | ------ | ----- |
| S | a, c | b, c |
| A | A, b | b |
С тем, что выводится из соседа первым, X будет в отношении меньше
Чтобы построить $\gtrdot$ нам нужно рассмотреть пары, в которых на первом месте нетерминалов
> 21.05.2019
_Опр:_ G - грамматика простого предшествования, если она ациклична, обратима и для любой пары символов в G выполнено не более одного отношения предшествования.
_Предложение:_ Пусть G - грамматика простого предшествования, $\vdash \gamma \dashv = x_0x_1...x_nx_{n+1}$ - ее r-форма.
Тогда $x_k,...x_l$ - основа этой формы, если $x_l$ $\gtrdot x_{l+1}$ и l - минимальное с таким св-м $x_{k-1} \lessdot x_k, x_k \doteq x_{k+1} \doteq ... \doteq x_l$
> Д-во:
>
> $\vdash \gamma \dashv$ - r форма, $x_s..x_t $- ее основа
>
> $x_t \gtrdot x_{t+1}$ по опр => $t \ge l$,
>
> о.п.(Предполагаем, что есть кандидат на основу правее, чем текущая. Но это не так - у r-формы основа это самый левый куст.)
>
> 1) s>l
>
> $x_s..x_t$ - соответсвуют самому левому куст
>
> 2) $x_l \gtrdot x_{l+1}$ => не имеет правых братьев
>
> Среди левых братьев $x_l$ есть внутренний узел.
>
> 
***Пример***
$S \rightarrow aSSb|c$
| | S | a | b | c | $\dashv$ |
| -------- | ------------------ | ---------- | ------------------ | ---------- | --------- |
| S | $\overset{\cdot}=$ | $\lessdot$ | $\overset{\cdot}=$ | $\lessdot$ | $\gtrdot$ |
| a | $\overset{\cdot}=$ | $\lessdot$ | | $\lessdot$ | |
| b | | $\gtrdot$ | $\gtrdot$ | $\gtrdot$ | $\gtrdot$ |
| c | | $\gtrdot$ | $\gtrdot$ | $\gtrdot$ | $\gtrdot$ |
| $\vdash$ | $\lessdot$ | $\lessdot$ | | $\lessdot$ | |
FIRST'(S) = {a,c}
LAST'(S) = {b, c}
$\vdash acaccbb \dashv $
$\nabla\vdash acaccbb \dashv $
$\nabla \vdash \lessdot a \lessdot$
$\nabla \vdash \lessdot a \lessdot c \gtrdot$
$\nabla \vdash \lessdot a \doteq S \lessdot a \lessdot c \gtrdot$
$\nabla \vdash \lessdot a \doteq S \lessdot a \doteq S \lessdot c \gtrdot$
$\nabla \vdash \lessdot a \doteq S \lessdot a \doteq S \doteq S \doteq b \gtrdot$
$\nabla \vdash \lessdot a \doteq S \doteq S \doteq b \gtrdot$
$\nabla \vdash \lessdot S \gtrdot \dashv$
> введение внешней аксиомы из-за того, что мы читаем только вершину стека
$S' → S$
Попробуем ослабить требования.
"Больше" не пересекается, "меньше или равно" пересечем.
$X \underline{\lessdot} Y$ хотим испытывать самую длинную основу
<u>_Опр: _</u>G - грамматика слабого предшествования, если она ациклична, обратима и
1) $\not\exists\ X\ и\ Y: X \gtrdot Y\ и\ (X \lessdot Y\ или\ X \doteq Y)$
2) $\not\exists\ (A → \beta) \in P, (B → \gamma X\beta), где\ X \doteq A\ или\ X \lessdot A$
<u>_Пример:_</u>
$E \rightarrow E + T|T$
$T \rightarrow T*F|F$
$F \rightarrow (E)|X$
| | E | T | F | ( | ) | x | + | * | $\dashv$ |
| -------- | ---------------------- | ---------------------- | ---------- | ---------- | --------- | ---------- | --------- | --------- | --------- |
| E | | | | | $\doteq$ | | $\doteq$ | | $\gtrdot$ |
| T | | | | | $\gtrdot$ | | $\gtrdot$ | $\doteq$ | $\gtrdot$ |
| F | | | | | $\gtrdot$ | | $\gtrdot$ | $\gtrdot$ | $\gtrdot$ |
| ( | $\underline{\lessdot}$ | $\lessdot$ | $\lessdot$ | $\lessdot$ | | $\lessdot$ | | | |
| ) | | | | | $\gtrdot$ | | $\gtrdot$ | $\gtrdot$ | $\gtrdot$ |
| x | | | | | $\gtrdot$ | | $\gtrdot$ | $\gtrdot$ | $\gtrdot$ |
| + | | $\underline{\lessdot}$ | $\lessdot$ | $\lessdot$ | | $\lessdot$ | | | |
| * | | | $\doteq$ | $\lessdot$ | | $\lessdot$ | | | |
| $\vdash$ | $\lessdot$ | $\lessdot$ | $\lessdot$ | $\lessdot$ | | $\lessdot$ | | | |
$\vdash x+x*x \dashv$
| $\nabla\vdash \lessdot$ | x+x*x |
| ------------------------------------------------------------ | ---------- |
| $\nabla\vdash\lessdot x \gtrdot$ | +x*x |
| $\nabla \vdash \lessdot F \gtrdot$ | +x*x |
| $\nabla \vdash \lessdot T \gtrdot$ | . |
| $\nabla \vdash \lessdot E$ | . |
| $\nabla \vdash \lessdot E \doteq +$ | x*x |
| $\nabla \vdash \lessdot E \doteq + \lessdot x \gtrdot$ | *x$\dashv$ |
| $\nabla \vdash \lessdot E \doteq + \lessdot T \doteq *$ | x$\dashv$ |
| $\nabla \vdash \lessdot E \doteq + \lessdot T \doteq * \lessdot x \gtrdot$ | . |
| $\nabla \vdash \lessdot E \doteq + \lessdot T \lessdot * \doteq F \gtrdot$ | . |
| $\nabla \vdash \lessdot E \doteq + \lessdot T \gtrdot$ | . |
| $\nabla \vdash \lessdot E \gtrdot \dashv$ | . |
> 28.05.19.
#### Отношения операторного предшествования
Операторная грамматика(двух нетерминалов подряд в правой части не встречается)
_Пример_
E → E+E|E*E|(E)|x
_Замечание:_
Как определять основы?
Если цепочка aEb входит в r-форму и ровно один из терминалов a, b принадлежит основе, то и E принадлежит основе.
Это следует из того, что не только в правых частях не может быть двух соседних нетерминалов, но и в ее r-форме.
Как определить края основы?
Найти самое левое больше и ближайшее к нему меньшее, то что между ними - основа и вот как в предыдущем замечании края определяем.
$a \lessdot b$ - a имеет меньший приоритет
$a \overset{\cdot}= b$ - a и b сворачиваются одновременно
$a \gtrdot b$ - a имеет больший приоритет
$\vdash \lessdot a$ - с а может начинаться r-форма
$a \gtrdot \dashv$ - на а может заканчиваться r-форма
Правила:
Операнды сворачиваются раньше всех
Операторы имеющие больший приоритет сворачиваются раньше, чем имеющие меньший приоритет
Между одинаковыми: если лево-ассоциативный, то левый, если право-ассоциативный, то правый.
Унарные сворачиваются раньше всех.
Выражение в скобках раньше выражения вне скобок.
Отношения строятся только между нетерминалами.
Пример:
E → E+E|E*E|(E)|-E|min(E, E)|x
| | x | ( | ) | - | + | * | min | ; | $\dashv$ |
| -------- | ---------- | ------------------ | ------------------ | ---------- | ---------- | ---------- | ---------- | ------------------ | --------- |
| x | | | $\gtrdot$ | | $\gtrdot$ | $\gtrdot$ | | $\gtrdot$ | $\gtrdot$ |
| ( | $\lessdot$ | $\lessdot$ | $\overset{\cdot}=$ | $\lessdot$ | $\lessdot$ | $\lessdot$ | $\lessdot$ | $\overset{\cdot}=$ | |
| ) | | | $\gtrdot$ | | $\gtrdot$ | $\gtrdot$ | | $\gtrdot$ | $\gtrdot$ |
| - | $\lessdot$ | $\lessdot$ | $\gtrdot$ | $\lessdot$ | $\gtrdot$ | $\gtrdot$ | $\lessdot$ | $\gtrdot$ | $\gtrdot$ |
| + | $\lessdot$ | $\lessdot$ | $\gtrdot$ | $\lessdot$ | $\gtrdot$ | $\lessdot$ | $\lessdot$ | $\gtrdot$ | $\gtrdot$ |
| * | $\lessdot$ | $\lessdot$ | $\gtrdot$ | $\lessdot$ | $\gtrdot$ | $\gtrdot$ | $\lessdot$ | $\gtrdot$ | $\gtrdot$ |
| min | | $\overset{\cdot}=$ | | | | | | | |
| ; | $\lessdot$ | $\lessdot$ | $\overset{\cdot}=$ | $\lessdot$ | $\lessdot$ | $\lessdot$ | $\lessdot$ | | |
| $\dashv$ | $\lessdot$ | $\lessdot$ | | $\lessdot$ | $\lessdot$ | $\lessdot$ | $\lessdot$ | | |
x * -min(x; x+x)
$\vdash \lessdot x \gtrdot$
$\vdash_E \lessdot * \lessdot - \lessdot min \overset{\cdot}= ( \lessdot x \gtrdot)$
$\vdash_E \lessdot * \lessdot - \lessdot min \overset{\cdot}= (_E \overset{\cdot}= ;_E \lessdot +_E \gtrdot$
Что включить в основу
Видим в стеке 2 нетерминала , берем их в основу
$\vdash_E \lessdot * \lessdot - \lessdot min \overset{\cdot}= (_E \overset{\cdot}= ;_E \overset{\cdot}=) \gtrdot$
$\vdash_E \lessdot * \lessdot -_E \gtrdot$
$\vdash_E \lessdot *_E \gtrdot$
$\vdash_E \dashv$
Таблица не так и нужна, достаточно иметь 2 функции.
Каждому терминалу поставим в соответсиве 2 числа $a \in \Sigma$ l(a)$\in N$ - слева, r(a)$\in N$ - справа
l(a) < r(b), если a $\lessdot b$
l(a) = r(b), если $a \overset{\cdot}= b$
l(a) > r(b), если $a \gtrdot b$
Нужно построить двудольный граф
$l_a → r_b$, если l(a) > r(b)
$r_b → l_a$, если l(a) < r(b)
если в графе не оказалось циклов, то нужно взять самый длинный путь.
|
11ba6c3e81477e4e782220856927d7d4641a337a
|
[
"Markdown"
] | 2 |
Markdown
|
goodoldlameme/lections
|
163a519cef3a53c7f078c6273e295243bd8818e0
|
45f5edc2fd9a92359f20c7a502c8c159fdbdaa7d
|
refs/heads/master
|
<repo_name>dannyrodlab/SPYDER_BIOSTATS<file_sep>/scripts/20190523_BIOSTATS_PROJECT_Data_Analysis.py
# -*- coding: utf-8 -*-
"""
Created on Thu May 23 19:09:44 2019
@author: BATMAN
"""
## Set folders
import os
PATH_INPUT = os.path.abspath("./input/")
if not(os.path.exists(PATH_INPUT)): os.mkdir('input')
assert os.path.exists(PATH_INPUT), "Oh no! Input folder is missing :("
PATH_FIGURES = os.path.abspath("./figures/")
if not(os.path.exists(PATH_FIGURES)): os.mkdir('figures')
assert os.path.exists(PATH_FIGURES), "Oh no! Figures folder is missing :("
## Data type
EXT_DATA = '.xlsx'
EXT_FIG = '.png'
## Read data
PATH_DATA = os.path.join(PATH_INPUT, '20190523_BIOSTATS_PROJECT_Data_Columns'+ EXT_DATA)
assert os.path.exists(PATH_DATA), "Oh no! Data is missing :("
## Figure parameters
figures_size = (8,8)
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
import scipy.stats as stats
import datetime
df = pd.read_excel(PATH_DATA)
print(df.head())
list(df)
# %%
## Read variables
#[rows, colums] = df.shape
## Get current time
now = datetime.datetime.now()
NAME_TIME = now.strftime("%Y%m%d-%H%M")
plt.figure(1)
plt.plot(df.count().sort_values(),'bo')
plt.xticks(rotation=45)
plt.ylabel('Numero de datos')
plt.tight_layout()
## Name your child
NAME_FIGURE_1 = 'DATA_SIZES'
PATH_FIGURE_1 = os.path.join(PATH_FIGURES, NAME_TIME + '_' + NAME_FIGURE_1 + EXT_FIG)
plt.savefig( PATH_FIGURE_1 , dpi=100 )
plt.figure(2)
meds = df.median()
meds = meds.sort_values()
boxplot = df[meds.index].boxplot(rot=45,fontsize=12)
plt.ylabel('Tiempo de juego [segundos]')
plt.tight_layout()
## Name your child
NAME_FIGURE_2 = 'BOXPLOT'
PATH_FIGURE_2 = os.path.join(PATH_FIGURES, NAME_TIME + '_' + NAME_FIGURE_2 + EXT_FIG)
plt.savefig( PATH_FIGURE_2 , dpi=100 )
# %%
##<NAME> Test
results_KW = np.zeros((7,2))
results_KW[0] = stats.kruskal(df['Alcohol'].notnull(),df['Ninguna'].notnull())
results_KW[1] = stats.kruskal(df['Cigarrillo'].notnull(),df['Ninguna'].notnull())
results_KW[2] = stats.kruskal(df['Café'].notnull(),df['Ninguna'].notnull())
results_KW[3] = stats.kruskal(df['Chocolate'].notnull(),df['Ninguna'].notnull())
results_KW[4] = stats.kruskal(df['Marihuana'].notnull(),df['Ninguna'].notnull())
results_KW[5] = stats.kruskal(df['Bebida energizante'].notnull(),df['Ninguna'].notnull())
results_KW[6] = stats.kruskal(df['Alcohol'].notnull(),df[
'Cigarrillo'].notnull(),df[
'Café'].notnull(),df[
'Chocolate'].notnull(),df[
'Ninguna'].notnull(),df[
'Marihuana'].notnull(),df[
'Bebida energizante'].notnull())
#Creating pandas dataframe from numpy array
df_KW = pd.DataFrame({'Statistic':results_KW[:,0],'p-value':results_KW[:,1]})
df_KW.rename(index={0:'Alcohol',1:'Cigarrillo',2:'Café',3:'Chocholate',4:'Marihuana',5:'Bebida energizante', 6: 'Todos'})
print(df_KW)
# %%
## Mann Whitney Test
stats.mannwhitneyu(df['Café'],df['Ninguna'])
|
d7699a41b29b9341c0a2a80b6289a7248815b274
|
[
"Python"
] | 1 |
Python
|
dannyrodlab/SPYDER_BIOSTATS
|
7c9767745d94cff4827e1f9f14cee2b5d0a7db66
|
a2c1c4b7db74e2dc04163c6541f4319d38e161c4
|
refs/heads/master
|
<repo_name>LuchoMoreno/PROG-III<file_sep>/ClasesProgramacion/Clase_06/administracion.php
<?php
$queHago = isset($_POST['queHago']) ? $_POST['queHago'] : NULL;
$host = "localhost";
$user = "root";
$pass = "";
switch ($queHago) {
case "Establecer_Conexion":
try{
$conStr = 'mysql:host=localhost;dbname=cdcol;charset=utf8';
$pdo = new PDO($conStr, $user, $pass);
$resultado = $objPDO->query("SELECT * FROM cds");
$arrayOBJ = $resultado->fechAll();
foreach($arrayOBJ as $arrayResultados)
{
echo $arrayResultados;
}
}
catch (PDOException $e)
{
echo "ERROR! " . $e->getmessage() . "<br/>";
}
break;
case "traerCDS":
break;
default:
echo ":(";
}
<file_sep>/ClasesProgramacion/Clase_09_PPT/clases/Ejercicios.php
<?php
require_once './clases/Usuario.php';
class Ejercicios{
// EJERCICIO 1.
public function VerificarBaseDeDatos($request, $response, $next)
{
// METODO POST.
if ($request->isPost())
{
$response->getBody()->write("DESDE MIDDLEWARE - POST // ");
$array = $request->getParsedBody();
$JSONRecibido = json_decode($array['usuario']);
$usuario = new Usuario();
$clase = new stdClass();
$clase = $usuario->ExisteEnBD($JSONRecibido->correo,$JSONRecibido->clave);
// ESTA LINEA SE GENERA SI EL USUARIO EXISTE EN LA BASE DE DATOS.
if($clase->existe == true)
{
if ($JSONRecibido->perfil == 0) // SI EXISTE, Y ES USUARIO COMUN.
{
$response->getBody()->write("..... USTED ES USUARIO COMUN." . " SU NOMBRE ES: " . $JSONRecibido->nombre);
$response = $next($request, $response);
}
if ($JSONRecibido->perfil == 1) // SI EXISTE, Y ES USUARIO ADMINISTRADOR.
{
$response->getBody()->write("..... USTED ES ADMINISTRADOR." . " SU NOMBRE ES: " . $JSONRecibido->nombre);
$response = $next($request, $response);
}
}
// ESTA LINEA SE GENERA EN CASO QUE EL USUARIO NO EXISTA.
else
{
$response->getBody()->write("El usuario no existe!");
}
}
return $response;
}
// EJERCICIO 2.
public function AgregarUnUsuario($request, $response, $next)
{
if ($request->isPost())
{
$array = $request->getParsedBody();
$JSONRecibido = json_decode($array['usuario']);
$usuario = new Usuario();
$usuario->nombre = $JSONRecibido->nombre;
$usuario->apellido = $JSONRecibido->apellido;
$usuario->clave = $JSONRecibido->clave;
$usuario->correo = $JSONRecibido->correo;
$usuario->perfil = $JSONRecibido->perfil;
$usuario->estado = $JSONRecibido->estado;
$usuario->foto = NULL;
if ($usuario->perfil == 1)
{
echo $usuario->InsertarUsuario();
$response = $next($request, $response);
echo "<br> El usuario se agrego porque SI es administrador. <br>";
}
else
{
echo "El usuario no se puede agregar porque no es administrador.";
}
}
return $response;
}
// EJERCICIO 3.
public function EliminarUnUsuario($request, $response, $next)
{
if ($request->isPost())
{
$array = $request->getParsedBody();
$JSONRecibido = json_decode($array['usuario']);
$usuario = new Usuario();
$usuario->nombre = $JSONRecibido->nombre;
$usuario->apellido = $JSONRecibido->apellido;
$usuario->clave = $JSONRecibido->clave;
$usuario->correo = $JSONRecibido->correo;
$usuario->perfil = $JSONRecibido->perfil;
$usuario->estado = $JSONRecibido->estado;
$usuario->foto = NULL;
if ($usuario->perfil == 2)
{
echo $usuario->EliminarUsuario($usuario);
$response = $next($request, $response);
echo "<br> El usuario se elimino porque es SUPER-ADMIN. <br>";
}
else
{
echo "El usuario no se elimino. Es usuario comun / administrador.";
}
}
return $response;
}
}
?><file_sep>/ClasesProgramacion/Clase_09/index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
// VERIFICADORA.
// DETERMINAR VERBO.
require_once './clases/verificadora.php';
require_once './vendor/autoload.php';
$config['displayErrorDetails'] = true;
$config['addContentLengthHeader'] = false;
/*
¡La primera línea es la más importante! A su vez en el modo de
desarrollo para obtener información sobre los errores
(sin él, Slim por lo menos registrar los errores por lo que si está utilizando
el construido en PHP webserver, entonces usted verá en la salida de la consola
que es útil).
La segunda línea permite al servidor web establecer el encabezado Content-Length,
lo que hace que Slim se comporte de manera más predecible.
*/
$app = new \Slim\App(["settings" => $config]);
$app->get('[/]', function (Request $request, Response $response) {
$response->getBody()->write("GET => SlimFramework");
return $response;
});
$app->post('[/]', function (Request $request, Response $response) {
$response->getBody()->write("POST => SlimFramework");
return $response;
});
$app->put('[/]', function (Request $request, Response $response) {
$response->getBody()->write("PUT => SlimFramework");
return $response;
});
$app->delete('[/]', function (Request $request, Response $response) {
$response->getBody()->write("DELETE => SlimFramework");
return $response;
});
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
$app->group('/credenciales', function ()
{
$this->post('/', function (Request $request, Response $response) {
$response->getBody()->write(" DESDE API => GRUPO - POST");
return $response;
});
$this->get('/', function (Request $request, Response $response) {
$response->getBody()->write(" DESDE API => GRUPO - GET");
return $response;
});
})->add(function ($request, $response, $next) {
if ($request->isGet())
{
$response->getBody()->write("DESDE MIDDLEWARE - GET // ");
$response = $next($request, $response);
}
if ($request->isPost())
{
$response->getBody()->write("DESDE MIDDLEWARE - POST // ");
$array = $request->getParsedBody();
var_dump($request->getParsedBody());
$JSONRecibido = json_decode($array['json']);
$JSONRecibido->nombre;
if ($JSONRecibido->tipo == "Administrador")
{
$response->getBody()->write("..... USTED ES ADMINISTRADOR." . " SU NOMBRE ES: " . $JSONRecibido->nombre);
$response = $next($request, $response);
}
else
{
$response->getBody()->write("...... USTED NO ES ADMINISTRADOR. ");
}
}
return $response;
});
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
$app->group('/credenciales/POO', function ()
{
$this->post('/', function (Request $request, Response $response) {
$response->getBody()->write(" DESDE API => GRUPO - POST");
return $response;
});
$this->get('/', function (Request $request, Response $response) {
$response->getBody()->write(" DESDE API => GRUPO - GET");
return $response;
});
})->add(\Verificadora :: class . ':Verificar');
$app->run();<file_sep>/ClasesProgramacion/Clase_02/aplicacion_19.php
<?php
/* Aplicación Nº 19 (Figuras geométricas)
La clase FiguraGeometrica posee: todos sus atributos protegidos, un constructor por defecto,
un método getter y setter para el atributo _color , un método virtual ( ToString ) y dos
métodos abstractos: Dibujar (público) y CalcularDatos (protegido). */
class FiguraGeometrica
{
protected $_color;
protected $_perimetro;
protected $_superficie;
public function __construct()
{
}
public function GetColor()
{
return $this->_color;
}
public function SetColor($color)
{
$this->_color = $color;
}
abstract public function Dibujar();
abstract protected function CalcularDatos();
}
?><file_sep>/ClasesProgramacion/Clase_07_mod/test_pdf.php
<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/usuario.php';
header('content-type:application/pdf');
$mpdf = new \Mpdf\Mpdf(['orientation' => 'P',
'pagenumPrefix' => 'Página nro. ',
'pagenumSuffix' => ' - ',
'nbpgPrefix' => ' de ',
'nbpgSuffix' => ' páginas']);//P-> vertical; L-> horizontal
$mpdf->SetHeader('{DATE j-m-Y}||{PAGENO}{nbpg}');
//alineado izquierda | centro | alineado derecha
$mpdf->setFooter('{DATE Y}|Programacón III|{PAGENO}');
$ArrayUsuarios = usuario::TraerTodosLosUsuarios();
$grilla = '<table class="table" border="1" align="center">
<thead>
<tr>
<th> ID </th>
<th> NOMBRE </th>
<th> APELLIDO </th>
<th> CORREO </th>
<th> CLAVE </th>
<th> PERFIL </th>
<th> ESTADO </th>
<th> FOTO </th>
</tr>
</thead>';
var_dump($ArrayUsuarios);
$grilla .= '</table>';
?>
<file_sep>/ClasesProgramacion/Clase_01/aplicacion_09.php
<?php
/*
Aplicación Nº 9 (Carga aleatoria)
Definir un Array de 5 elementos enteros y asignar a cada uno de ellos un número (utilizar la
función rand ). Mediante una estructura condicional, determinar si el promedio de los números
son mayores, menores o iguales que 6. Mostrar un mensaje por pantalla informando el
resultado.
*/
$acumulador = 0;
for ($i=0; $i<5; $i++)
{
$vector[$i] = rand(1, 100);
$valor = $vector[$i];
$acumulador = $acumulador + $valor;
}
var_dump($vector);
echo "<br>";
echo "La suma es: ", $acumulador;
$promedio = $acumulador / 6;
if ($promedio == 6)
{
echo "El promedio es igual a 6";
}
else if ($promedio < 6)
{
echo "El promedio es menor a 6";
}
else
{
"El promedio es mayor a 6";
}
?><file_sep>/ClasesProgramacion/Clase_03/escribir.php
<?php
$abrir = fopen("saludo.txt", "w+");
$escribir = fwrite($abrir, "Hola mundo!");
if ($escribir > 0)
{
echo "Se pudo escribir";
}
else
{
echo "Male sal";
}
fwrite($abrir, "<br>");
fwrite($abrir, "Luciano");
fwrite($abrir, "<br>");
fwrite($abrir, "Moreno");
fclose($abrir);
?><file_sep>/Clase 05 -- 16-09/Clase 05 -- Bases/BaseDeDatos(2)/JavaScript/app.ts
/// <reference path="ajax.ts" />
namespace Main{
let ajax : Ajax = new Ajax();
export function EjecutarTraerTodos():void {
let parametros:string = `queHago=TraerTodos_Usuarios`;
ajax.Post("administracion.php",
Success,
parametros,
Fail);
}
export function EjecutarTraerPorID():void {
var idObtenida : string = EjecutarObtenerID();
let parametros:string = `queHago=TraerTodos_PorID&id=` + idObtenida;
ajax.Post("administracion.php",
Success,
parametros,
Fail);
}
export function EjecutarObtenerID():string {
var idObtenida : string = (<HTMLInputElement> document.getElementById("txtID")).value;
return idObtenida;
}
export function EjecutarTraerPorEstado():void {
var estadoObtenido : string = EjecutarObtenerEstado();
let parametros:string = `queHago=TraerTodos_PorEstado&estado=` + estadoObtenido;
ajax.Post("administracion.php",
Success,
parametros,
Fail);
}
export function EjecutarObtenerEstado():string {
var estadoObtenido : string = (<HTMLInputElement> document.getElementById("txtEstado")).value;
return estadoObtenido;
}
function Success(retorno:string):void {
console.clear();
console.log(retorno);
(<HTMLDivElement>document.getElementById("divResulado")).innerHTML = retorno;
}
function Fail(retorno:string):void {
console.clear();
console.log(retorno);
alert("Ha ocurrido un ERROR!!!");
}
}<file_sep>/ClasesProgramacion/Clase_01/aplicacion_01.php
// Dato un numero X, lo que devuelva sea la
// tabla de multiplicar de dicho numero;
<?php
function MostrarTabla($x)
{
for ($i=0; $i<10; $i++)
{
$resultado = $x * $i;
echo"<br>";
printf("%d x %d = %d ", $x, $i, $resultado);
}
}
MostrarTabla(3);
?><file_sep>/ClasesProgramacion/Clase_09_PPT/index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
// VERIFICADORA.
// DETERMINAR VERBO.
require_once './clases/Ejercicios.php';
require_once './vendor/autoload.php';
$config['displayErrorDetails'] = true;
$config['addContentLengthHeader'] = false;
/*
¡La primera línea es la más importante! A su vez en el modo de
desarrollo para obtener información sobre los errores
(sin él, Slim por lo menos registrar los errores por lo que si está utilizando
el construido en PHP webserver, entonces usted verá en la salida de la consola
que es útil).
La segunda línea permite al servidor web establecer el encabezado Content-Length,
lo que hace que Slim se comporte de manera más predecible.
*/
$app = new \Slim\App(["settings" => $config]);
$app->get('[/]', function (Request $request, Response $response) {
$response->getBody()->write("GET => SlimFramework");
return $response;
});
$app->post('[/]', function (Request $request, Response $response) {
$response->getBody()->write("POST => SlimFramework");
return $response;
});
$app->put('[/]', function (Request $request, Response $response) {
$response->getBody()->write("PUT => SlimFramework");
return $response;
});
$app->delete('[/]', function (Request $request, Response $response) {
$response->getBody()->write("DELETE => SlimFramework");
return $response;
});
///////////////////////////////////////////////////////////////////////////////////////
////////// EJERCICIOS QUE ESTAN EN EL .TXT //////////
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
// 1) --- Hacer un middleware de aplicacion que tome usuario y contraseña y verifique en BD.
// 2) --- Hacer middleware de grupo, solo para post, que permita agregar un nuevo usuario, si el perfil es -- admin.
// 3) --- Hacer middleware de grupo, solo para delete, que permita borrar un usuario, si el perfil es -- super_admin.
// 4) --- Hacer middleware de ruta, solo para put y get, que tome el tiempo de demora entre que entra y sale la peticion.
///////////////////////////////////////////////////////////////////////////////////////
// PARA PROBAR ESTE EJERCICIO, ESCRIBIR EN POSTMAN:
// url: http://localhost/Clase_09_PPT/ejercicios/Uno
// key: usuario value: {"nombre":"Luciano","correo":"<EMAIL>","clave":"7319","perfil":"1"}
// body -> x-www-form-urlencoded.
$app->post('/ejercicios/Uno', function (Request $request, Response $response) {
$response->getBody()->write("<br> POST => SlimFramework - Felicidades. Entraste al SLIM pasando por el middleware!!");
return $response;
})->add(\Ejercicios :: class . ':VerificarBaseDeDatos');
$app->group('/grupoEjercicios', function ()
{
// url: http://localhost/Clase_09_PPT/grupoEjercicios/dos
// key: usuario value: {"nombre":"Nuevo","apellido":"Usuario","correo":"<EMAIL>","clave":"1234","perfil":"1","estado":"1", "foto":"NULL"}
// body -> x-www-form-urlencoded.
$this->post('/dos', function (Request $request, Response $response) {
$response->getBody()->write("<br> POST => SlimFramework - Felicidades. Entraste al SLIM pasando por el middleware!!");
return $response;
})->add(\Ejercicios :: class . ':AgregarUnUsuario');
// url: http://localhost/Clase_09_PPT/grupoEjercicios/tres
// key: usuario value: {"nombre":"Nuevo","apellido":"Usuario","correo":"<EMAIL>","clave":"1234","perfil":"2","estado":"1", "foto":"NULL"}
// body -> x-www-form-urlencoded.
$this->post('/tres', function (Request $request, Response $response) {
$response->getBody()->write("<br> POST => SlimFramework - Felicidades. Entraste al SLIM pasando por el middleware!!");
return $response;
})->add(\Ejercicios :: class . ':EliminarUnUsuario');
});
$app->run();<file_sep>/ClasesProgramacion/Clase_10_Octavio/cdcol.sql
-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 04-11-2019 a las 16:02:59
-- Versión del servidor: 10.1.38-MariaDB
-- Versión de PHP: 7.3.2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `cdcol`
--
CREATE DATABASE IF NOT EXISTS `cdcol` DEFAULT CHARACTER SET utf8 COLLATE utf8_spanish2_ci;
USE `cdcol`;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `cds`
--
CREATE TABLE `cds` (
`titel` varchar(200) COLLATE latin1_general_ci DEFAULT NULL,
`interpret` varchar(200) COLLATE latin1_general_ci DEFAULT NULL,
`jahr` int(11) DEFAULT NULL,
`id` bigint(20) UNSIGNED NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
--
-- Volcado de datos para la tabla `cds`
--
INSERT INTO `cds` (`titel`, `interpret`, `jahr`, `id`, `created_at`, `updated_at`, `deleted_at`) VALUES
('Beauty', 'Ryuichi Sakamoto', 1990, 1, '2019-05-22 17:22:54', '2019-05-22 17:24:39', NULL),
('Goodbye Country (Hello Nightclub)', 'Groove Armada', 2001, 4, '2019-05-22 17:22:54', '2019-05-22 17:24:39', NULL),
('cambiado', 'Matalico', 2666, 5, '2019-05-22 17:22:54', '2019-05-22 22:56:19', NULL),
(NULL, NULL, NULL, 7, '2019-05-22 17:22:54', '2019-05-22 17:24:39', NULL),
('Album negri', 'Matalico', 2020, 11, '2019-05-22 22:35:52', '2019-05-22 22:35:52', NULL);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuario`
--
CREATE TABLE `usuario` (
`nombre` varchar(50) COLLATE utf8_spanish2_ci NOT NULL,
`clave` varchar(50) COLLATE utf8_spanish2_ci NOT NULL,
`perfil` varchar(50) COLLATE utf8_spanish2_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Volcado de datos para la tabla `usuario`
--
INSERT INTO `usuario` (`nombre`, `clave`, `perfil`) VALUES
('Lucho', '123', 'admin'),
('Juli', '456', 'user'),
('Nani', '789', 'user');
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/ClasesProgramacion/Clase_03_abm/administracion.php
<?php
require 'clases\producto.php';
$opcion = "ALTA";
switch($opcion)
{
case "ALTA":
$producto = new Producto("Lalala", "1234");
if(Producto::Guardar($producto))
{
echo "Exitoso";
}
else
{
echo "Error";
}
case 2:
}
?><file_sep>/ClasesProgramacion/Clase_08/index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require_once './vendor/autoload.php';
$config['displayErrorDetails'] = true;
$config['addContentLengthHeader'] = false;
/*
¡La primera línea es la más importante! A su vez en el modo de
desarrollo para obtener información sobre los errores
(sin él, Slim por lo menos registrar los errores por lo que si está utilizando
el construido en PHP webserver, entonces usted verá en la salida de la consola
que es útil).
La segunda línea permite al servidor web establecer el encabezado Content-Length,
lo que hace que Slim se comporte de manera más predecible.
*/
$app = new \Slim\App(["settings" => $config]);
$app->get('[/]', function (Request $request, Response $response) {
$response->getBody()->write("GET => Bienvenido!!! a SlimFramework");
return $response;
});
$app->post('[/]', function (Request $request, Response $response) {
$response->getBody()->write("POST => Bienvenido!!! a SlimFramework");
return $response;
});
$app->put('[/]', function (Request $request, Response $response) {
$response->getBody()->write("PUT => Bienvenido!!! a SlimFramework");
return $response;
});
$app->delete('[/]', function (Request $request, Response $response) {
$response->getBody()->write("DELETE => Bienvenido!!! a SlimFramework");
return $response;
});
// Los parametros van entre { }
// El nombre: Obligatorio - Se pone con {} por ser un parametro.
// El apellido: Oopcional - Se pone con [] por opcional, con {} por ser un parametro.
$app->get('/parametros/{nombre}[/{apellido}]', function (Request $request, Response $response, $args) {
$nombrePam = $args['nombre'];
$apellidoPam = $args['apellido'];
$response->getBody()->write("El nombre obligatorio: " . $nombrePam . " y el apellido opcional: " . $apellidoPam);
return $response;
});
// Grupo 1 - La primer funcion POST muestra los parametros enviados.
// - La segunda funcion GET recibe parametros y crea un JSON.
$app->group('/json', function ()
{
$this->post('/', function (Request $request, Response $response) {
var_dump($request->getParsedBody());
var_dump($request->getUploadedFiles());
$fotoArray = $request->getUploadedFiles();
$destino="./fotos/";
$nombre=$fotoArray['foto']->getClientFilename();
$extension= explode(".", $nombre);
$fotoArray['foto']->moveTo ($destino . $extension[0] . "." . $extension[1]);
});
$this->get('/', function (Request $request, Response $response) {
$std = new stdClass();
$std->nombre = 'Lucho';
$std->apellido = 'Moreno';
$nuevaRta = $response->withJson($std, 200);
return $nuevaRta;
});
// EN POSTMAN HAY QUE PONER:
// "KEY: json" // "VALUE: {"nombre":"Luciano","apellido":"Moreno"}"
// y en x-www-form...."
$this->put('/', function (Request $request, Response $response) {
$array = $request->getParsedBody();
$JSONRecibido = json_decode($array['json']);
$std = new stdClass();
$std->nombre = $JSONRecibido->apellido;
$std->apellido = $JSONRecibido->nombre;
$nuevaRta = $response->withJson($std, 200);
return $nuevaRta;
});
});
/*
COMPLETAR POST, PUT Y DELETE
*/
$app->run();<file_sep>/ClasesProgramacion/Clase_04/subirFoto.php
<?php
require 'clases/archivo.php';
if (Archivo :: Subir())
{
echo "Se pudo subir la imagen.";
echo "<br>";
Archivo :: MostrarArrayArchivo();
}
?><file_sep>/ClasesProgramacion/Clase_01/index.php
<?php
echo "Hola ";
echo "mundo";
echo "<br>";
$nombre = "luCIAno";
$apellido = "moReNO";
$nombreModificado = strtolower($nombre);
$nombreModificado2 = ucfirst($nombreModificado);
$apellidoModificado = strtolower($apellido);
$apellidoModificado2 = ucfirst($apellidoModificado);
echo $nombreModificado2 . $apellidoModificado2;
?><file_sep>/README.md
### :computer: PROG III (2019) (Segundo cuatrimestre)
- (Recordar que LAB III y PROG III se cursan como materias independientes)
### :diamonds:CLASES
- En cada carpeta se encuentra cada clase, con su respectiva fecha. Y dentro, los archivos dados en la clase (PPT, Archivos de ejemplos)
- por el profesor.
-
### :diamonds: Carpeta: ClasesProgramacion.
- Archivos programados en la clase por cuenta propia.
-
### :diamonds: PARCIALES
-
-
### :diamonds: FINALES
-
-
### :diamonds: PROG III - Resumen Cursada.docx
- Resumen de las diapositivas dadas en clase.
-
<file_sep>/ClasesProgramacion/Clase_03/ingreso.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="test1.php" method="get" >
<td>Datos personales:</td>
<td colspan="2" align="right">
<input type="textbox" name="Nombre" />
</td>
<td colspan="2" align="right">
<input type="textbox" name="Apellido" />
</td>
<td colspan="2" align="right">
<input type="reset" value="Limpiar" />
</td>
<td colspan="2" align="right">
<input type="submit" id="btnEnviar" value="Enviar" />
</td>
</form>
</body>
</html><file_sep>/ClasesProgramacion/Clase_04/mostrarInfo.php
<?php
//MUESTRA LA INFO CONTENIDA EN $_GET
echo "GET<br/>";
var_dump($_FILES);
echo "<br/>";
<file_sep>/Clase 05 -- 16-09/Clase 05 -- Bases/BaseDeDatos(3)/administracion.php
<?php
$queHago = isset($_POST['queHago']) ? $_POST['queHago'] : NULL;
$host = "localhost";
$user = "root";
$pass = "";
$base = "productos";
$base2 = "mercado";
switch ($queHago) {
case "TraerTodos_Usuarios":
$con = @mysqli_connect($host, $user, $pass, $base2);
$sql = "SELECT `id`, `nombre`, `apellido`, `clave`, `perfil`, `estado` FROM `usuarios`";
$rs = $con->query($sql);
while ($row = $rs->fetch_object()) {
$user_arr[] = $row;
}
//INICIO TABLA
$table = "<table border='1'>
<tr>
<td>ID</td>
<td>Nombre</td>
<td>Apellido</td>
<td>Perfil</td>
<td>Estado</td>
</tr>";
//INICIO TABLA
//DATOS
if (mysqli_affected_rows($con) > 0) {
for ($i = 0; $i < mysqli_affected_rows($con); $i++) {
$table .= "<tr>
<td>" . $user_arr[$i]->id . "</td>
<td>" . $user_arr[$i]->nombre . "</td>
<td>" . $user_arr[$i]->apellido . "</td>
<td>" . $user_arr[$i]->perfil . "</td>
<td>" . $user_arr[$i]->estado . "</td>
</tr>";
}
} else {
$table .= "<tr>
<td align='center' colspan='5'>NO EXISTEN USUARIOS</td>
</tr>";
}
//DATOS
//CIERRO TABLA
$table .= "</table>";
//CIERRO TABLA
//MUESTRO LA TABLA POR ECHO
echo "<pre>";
echo ($table);
echo "</pre>";
echo "<pre>";
var_dump($user_arr);
echo "</pre>";
//CIERRO CONEXION
mysqli_close($conection);
break;
case "TraerTodos_PorID":
$con = @mysqli_connect($host, $user, $pass, $base2);
$id = $_POST["id"];
$sql = "SELECT `id`, `nombre`, `apellido`, `clave`, `perfil`, `estado` FROM `usuarios` WHERE `id` =" . $id;
$rs = $con->query($sql);
while ($row = $rs->fetch_object()) {
$user_arr[] = $row;
}
$table = "<table border='1'>
<tr>
<td>ID</td>
<td>Nombre</td>
<td>Apellido</td>
<td>Perfil</td>
<td>Estado</td>
</tr>";
if (mysqli_affected_rows($con) > 0) {
for ($i = 0; $i < mysqli_affected_rows($con); $i++) {
$table .= "<tr>
<td>" . $user_arr[$i]->id . "</td>
<td>" . $user_arr[$i]->nombre . "</td>
<td>" . $user_arr[$i]->apellido . "</td>
<td>" . $user_arr[$i]->perfil . "</td>
<td>" . $user_arr[$i]->estado . "</td>
</tr>";
}
} else {
$table .= "<tr>
<td align='center' colspan='5'>NO EXISTEN USUARIOS</td>
</tr>";
}
$table .= "</table>";
echo "<pre>";
echo ($table);
echo "</pre>";
echo "<pre>";
var_dump($user_arr);
echo "</pre>";
mysqli_close($con);
break;
case "TraerTodos_PorEstado":
$con = @mysqli_connect($host, $user, $pass, $base2);
$estado = $_POST["estado"];
$sql = "SELECT `id`, `nombre`, `apellido`, `clave`, `perfil`, `estado` FROM `usuarios` WHERE `estado` =" . $estado;
$rs = $con->query($sql);
$user_arr = NULL;
while ($row = $rs->fetch_object()) {
$user_arr[] = $row;
}
$table = "<table border='1'>
<tr>
<td>ID</td>
<td>Nombre</td>
<td>Apellido</td>
<td>Perfil</td>
<td>Estado</td>
</tr>";
if (mysqli_affected_rows($con) > 0) {
for ($i = 0; $i < mysqli_affected_rows($con); $i++) {
$table .= "<tr>
<td>" . $user_arr[$i]->id . "</td>
<td>" . $user_arr[$i]->nombre . "</td>
<td>" . $user_arr[$i]->apellido . "</td>
<td>" . $user_arr[$i]->perfil . "</td>
<td>" . $user_arr[$i]->estado . "</td>
</tr>";
}
} else {
$table .= "<tr>
<td align='center' colspan='5'>NO EXISTEN USUARIOS</td>
</tr>";
}
$table .= "</table>";
echo "<pre>";
echo ($table);
echo "</pre>";
echo "<pre>";
var_dump($user_arr);
echo "</pre>";
mysqli_close($con);
break;
case "CargarNuevoUsuario":
$cargado = $_POST["cargar"];
$con = @mysqli_connect($host, $user, $pass, $base2);
$sql = $cargado;
$rs = $con->query($sql);
mysqli_close($con);
echo "Codigo generado: " + $cargado;
break;
default:
echo ":(";
}
<file_sep>/ClasesProgramacion/Clase_04/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Único archivo</h1>
<a href="ingreso.php" class="list-group-item list-group-item-info" ><p class="list-group-item-text">Subir archivo</p></a>
<a href="mostrarInfo.php" class="list-group-item list-group-item-info" ><p class="list-group-item-text">Mostrar Informacion</p></a>
</body>
</html>Clase_04\mostrarInfo.php<file_sep>/ClasesProgramacion/Clase_03/leer.php
<?php
$archivo = fopen ("saludo.txt", "r");
while(!feof($archivo))
{
echo fgets($archivo); // fgets: devuelve una linea
}
fclose($archivo);
?><file_sep>/Clase 05 -- 16-09/Clase 05 -- Bases/BaseDeDatos(3)/JavaScript/app.ts
/// <reference path="ajax.ts" />
namespace Main{
let ajax : Ajax = new Ajax();
export function EjecutarTraerTodos():void {
let parametros:string = `queHago=TraerTodos_Usuarios`;
ajax.Post("administracion.php",
Success,
parametros,
Fail);
}
//////////////////////////////////////////////////////
export function EjecutarTraerPorID():void {
var idObtenida : string = EjecutarObtenerID();
let parametros:string = `queHago=TraerTodos_PorID&id=` + idObtenida;
ajax.Post("administracion.php",
Success,
parametros,
Fail);
}
export function EjecutarObtenerID():string {
var idObtenida : string = (<HTMLInputElement> document.getElementById("txtID")).value;
return idObtenida;
}
//////////////////////////////////////////////////////
export function EjecutarTraerPorEstado():void {
var estadoObtenido : string = EjecutarObtenerEstado();
let parametros:string = `queHago=TraerTodos_PorEstado&estado=` + estadoObtenido;
ajax.Post("administracion.php",
Success,
parametros,
Fail);
}
export function EjecutarObtenerEstado():string {
var estadoObtenido : string = (<HTMLInputElement> document.getElementById("txtEstado")).value;
return estadoObtenido;
}
//////////////////////////////////////////////////////
export function RedireccionarNuevoUsuario():void {
window.location.href = 'nuevoUsuario.html';
}
export function ObtenerTodosLosDatos():string {
var nombreObtenido : string = (<HTMLInputElement> document.getElementById("dataNombre")).value;
var apellidoObtenido : string = (<HTMLInputElement> document.getElementById("dataApellido")).value;
var claveObtenida : string = (<HTMLInputElement> document.getElementById("dataClave")).value;
var datosCompletos : string = "INSERT INTO `usuarios`(`nombre`, `apellido`, `clave`, `perfil`, `estado`) VALUES " + "("+"'"+nombreObtenido+"'" + "," + "'"+apellidoObtenido +"'"+ "," +"'"+claveObtenida+"'" + "," + "1,1)";
return datosCompletos;
}
export function EjecutarCargarUsuario():void {
var usuario : string = ObtenerTodosLosDatos();
let parametros:string = `queHago=CargarNuevoUsuario&cargar=` + usuario;
ajax.Post("administracion.php",
Success,
parametros,
Fail);
}
//////////////////////////////////////////////////////
function Success(retorno:string):void {
console.clear();
console.log(retorno);
(<HTMLDivElement>document.getElementById("divResulado")).innerHTML = retorno;
}
function Fail(retorno:string):void {
console.clear();
console.log(retorno);
alert("Ha ocurrido un ERROR!!!");
}
}<file_sep>/ClasesProgramacion/Clase_04/clases/archivo.php
<?php
class Archivo{
public static function Subir() : bool {
// recuperar toda la info del archivo y aplicar una validación del archivo que se intenta subir
// si la validación es correcta va a validar el archivo y lo guarda
$uploadOk = TRUE;
$destino="./archivos/".$_FILES["archivo"]["name"];
$esImagen = getimagesize($_FILES["archivo"]["tmp_name"]);
$tipoArchivo = pathinfo($destino, PATHINFO_EXTENSION);
if($esImagen === FALSE) {//NO ES UNA IMAGEN
//SOLO PERMITO CIERTAS EXTENSIONES
if($tipoArchivo != "doc" && $tipoArchivo != "txt" && $tipoArchivo != "rar")
{
echo "Solo son permitidos archivos con extension DOC, TXT o RAR.";
$uploadOk = FALSE;
}
}
else {// ES UNA IMAGEN
//SOLO PERMITO CIERTAS EXTENSIONES
if($tipoArchivo != "jpg" && $tipoArchivo != "jpeg" && $tipoArchivo != "gif" && $tipoArchivo != "png")
{
echo "Solo son permitidas imagenes con extension JPG, JPEG, PNG o GIF.";
$uploadOk = FALSE;
}
}
move_uploaded_file($_FILES["archivo"]["tmp_name"],$destino);
$uploadOk = TRUE;
return $uploadOk;
}
public static function MostrarArrayArchivo()
{
echo "<br/>";
var_dump($_FILES);
echo "<br/>";
}
}
?><file_sep>/ClasesProgramacion/Clase_03_abm/clases/producto.php
<?php
class Producto
{
private $nombre;
private $cod_barra;
public function __construct($nombreParametro = NULL, $cod_barraParametro = NULL)
{
$this->nombre = $nombreParametro;
$this->cod_barra = $cod_barraParametro;
}
public function ToString() : strings
{
return $this->nombre + "--" + $this->cod_barra;
}
public static function Guardar (Producto $obj) : bool
{
$retorno;
$abrir = fopen("producto.txt", "w+");
$escribir = fwrite($abrir, $obj->ToString());
if ($escribir > 0)
{
echo "Se pudo escribir";
$retorno = true;
}
else
{
echo "Male sal";
$retorno = false;
}
return $retorno;
}
}
?>
<file_sep>/ClasesProgramacion/Clase_02/aplicacion_15.php
<?php
/*
Aplicación Nº 15 (Potencias de números)
Mostrar por pantalla las primeras 4 potencias de los números del uno 1 al 4 (hacer una función
que las calcule invocando la función pow ).
*/
function MostrarPotencia($x)
{
for ($i=1; $i<5; $i++)
{
$potencia = math.pow($i, $i);
echo $potencia;
}
}
MostrarPotencia(3);
?><file_sep>/ClasesProgramacion/Clase_07_codigos/CodigoDeVero/test_usuario.php
<?php
//'existe_bd' -> "usuario_login" JSON(Correo y clave)
//Esta pagina me devuelve otro objeto json(existe(bool))
//Setear la variable de sesion
session_start();
include_once ("usuario.php");
include_once ("AccesoDatos.php");
$logeo = isset($_POST["usuario"]) ? $_POST["usuario"] : NULL;
$objeto = json_decode($logeo);
$usuario = new Usuario();
$clase = new stdClass();
$clase = $usuario->ExisteEnBD($objeto->correo,$objeto->clave);
if($clase->existe == true)
{
$_SESSION["perfilUsuario"] =$clase->usuario->perfil;
}
echo json_encode($clase);
?><file_sep>/ClasesProgramacion/Clase_04/clases/producto.php
<?php
require "archivo.php";
class Producto
{
private $nombre;
private $cod_barra;
private $_path;
public function __construct($nombre=null,$codbarra=null,$file=null){
if($nombre!=null && $codbarra!=null && $file!=null){
$this->_nombre=$nombre;
$this->_codbarra=$codbarra;
//$this->_path="./archivo/".$_FILES["archivo"]["name"];
$this->_path="./archivo/".$file;
}
}
public function toString(){
return $this->_codbarra ." -- ". $this->_nombre." -- " .$this->_path. "\r\n";
}
public static function Guardar($producto){
$path= "./archivos/productos.txt";
Archivo::Subir();
$archivo=fopen($path,"a");
//$producto->file;
if(fwrite($archivo,$producto->toString()))
{
fclose($archivo);
return true;
}
else
{
return false;
}
}
public static function TraerTodoslosProductos(){
$productos= array();
//$producs= array();
$path= "archivos/productos.txt";
$archivo=fopen($path,"r");
while(!feof($archivo)){
$a=explode("-",fgets($archivo));
if(isset($a[1])){
array_push($productos,new Producto($a[0],$a[1],$a[2]));
}
}
fclose($archivo);
/* for ($i=0; $i <count($productos) ; $i++) {
if(isset($productos[1])){
$prod= new Producto($productos[0],$productos[1],$productos[2]);
array_push($producs,$prod);
}else{
break;
}
}*/
return $productos;
}
}
?>
<file_sep>/ClasesProgramacion/Clase_09/clases/verificadora.php
<?php
class Verificadora
{
// SI FUERA CON ARRAY. SERIA:
// $array = $request->getParsedBody();
// $nombreArray = $array['nombre'];
// SI ES UN JSON SERIA:
// $array = $request->getParsedBody();
// $JSONRecibido = json_decode($array['json']);
// EN POSTMAN:
// key: json // value : {"nombre":"Lucho","tipo":"Administrador","clave":"123"}
// FUNCION QUE VERIFICA QUE EL USUARIO EXISTA - SI ES ADMINISTRADOR.
public function Verificar($request, $response, $next)
{
// METODO POST.
if ($request->isPost())
{
$response->getBody()->write("DESDE MIDDLEWARE - POST // ");
$array = $request->getParsedBody();
$JSONRecibido = json_decode($array['json']);
// CREO UNA NUEVA STDCLASS, PARA ASIGNAR LO RECIBIDO DEL JSON.
$std = new stdClass;
$std->nombre = $JSONRecibido->nombre;
$std->clave = $JSONRecibido->clave;
// ESTO VERIFICA QUE EL USUARIO EXISTA.
if (Verificadora :: ExisteUsuario($std))
{
// ESTO VERIFICA QUE EL USUARIO SEA ADMINISTRADOR.
if ($JSONRecibido->tipo == "Administrador")
{
$response->getBody()->write("..... USTED ES ADMINISTRADOR." . " SU NOMBRE ES: " . $JSONRecibido->nombre);
$response = $next($request, $response);
}
}
// ESTA LINEA SE GENERA EN CASO QUE EL USUARIO NO EXISTA.
else
{
$response->getBody()->write("El usuario no existe!");
}
}
// METODO GET.
if ($request->isGet())
{
$response->getBody()->write("DESDE MIDDLEWARE - GET // ");
$response = $next($request, $response);
}
return $response;
}
// FUNCION QUE VERIFIA QUE EL USUARIO EXISTA EN UN BLOC DE NOTAS.
private static function ExisteUsuario($obj)
{
$bandera = false;
// ABRE EL ARCHIVO
$archivo = fopen ("./usuarios.txt", "r");
// LEE TODO EL ARCHIVO.
while(!feof($archivo))
{
// OBTIENE LINEA A LINEA, SIN INCLUIR EL /n
$linea = trim(fgets($archivo));
// DIVIDE CADA LINEA EN UN ARRAY. EN CADA POSICION HAY UN ELEMENTO.
$extension = explode("-", $linea);
// RETORNA TRUE SI EL USUARIO EXISTE. VERIFICA NOMBRE Y CLAVE.
if ($extension[0] == $obj->nombre && $extension[2] == $obj->clave)
{
$bandera = true;
break;
}
}
// CIERRA EL ARCHIVO.
fclose($archivo);
return $bandera;
}
}
?>
|
fad1dd5fb02bdd34e879c1958d29b21f8d34610a
|
[
"Markdown",
"Hack",
"SQL",
"PHP",
"TypeScript"
] | 28 |
Markdown
|
LuchoMoreno/PROG-III
|
cf4677069a35a8b059a2f673d0764865b3d33dee
|
2aa13a063922f3d31ab71468dce5a4e2f791517b
|
refs/heads/master
|
<file_sep>Welcome to the Zoo
You should have a Zoo and the Zoo should have a collection of Pens for Animals to go in.
Create an interactive program which allows the user (the Zookeeper!) to:
1.) Create new Animals (animals should have a "species," "size," and "gender")
1.) Set up new Pens
2.) Remove Pens
3.) Add an Animal to a Pen
4.) Remove Animals from pens
5.) Display all the Animals in a Pen
6.) Display all the Animals in the Zoo
Bonus (choose any or all)
a. Your program should also allow the Zookeeper to add BabyAnimals to Pens. BabyAnimal should utilize Animal as a Prototype.
b. Your program should not allow the zookeeper to add more than (4) total Animals or (10) total BabyAnimals to a Pen.
c. Your program should not allow the zookeeper to add a BabyAnimal to a Pen unless you already have a male Animal and a female Animal living in the Pen.
d. Your program should include Habitats, which should describe what a given Animal's habitat is like (desert, forest, hot, cold, etc.).
Please let me know if you have any questions. You'll also have some time to work on this assignment in class tomorrow after lecture.
|
3eef3feb5d6d622ace9f7ee5ffb5481b6c6d9ad0
|
[
"Markdown"
] | 1 |
Markdown
|
apprentice-gamma/the_zoo
|
572a7e15e2cf99cc806f8ec2eff76d8340334ade
|
12e166a0397346edd8903310a3f6cfc78690e6e8
|
refs/heads/master
|
<repo_name>nitrobanko/projet_2<file_sep>/README.md
Maquette recrée en site web responsive
|
d41b4c93a9fb137293e2eeaa87b487220235e5b7
|
[
"Markdown"
] | 1 |
Markdown
|
nitrobanko/projet_2
|
1bc0df8379aa46b722793cae609c4c0bf664e8f7
|
56a74af7ac015e561f13ce4cb4b955ff5deb8682
|
refs/heads/master
|
<repo_name>kojibhy/Python-scripts<file_sep>/email_scout/scout.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Python 3.4
# made by <EMAIL>
# version 0.0.1
# pip install bs4
import re, os
import argparse
import urllib.request, urllib.error, urllib.parse
from bs4 import BeautifulSoup
class Spider:
def __init__(self):
self.tasklist = []
self.perfected = []
self.fond_mails = {}
def add_task(self, request):
main_link = urllib.parse.urlparse(request)
if request in self.perfected:
pass
elif request in self.tasklist:
pass
else:
self.tasklist.append(request)
def srch_page(self, request):
html = urllib.request.urlopen(request).read().decode()
mailsrch = re.compile(r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+")
found = mailsrch.findall(html)
for item in found:
self.fond_mails[item] = 1
def spider_searcher(self, request):
found_links = []
search = re.compile(r'^/\w+')
html = urllib.request.urlopen(request).read().decode()
pars_link = urllib.parse.urlparse(request)
soup = (BeautifulSoup(html, "html.parser")).findAll('a')
for link in soup:
newlink = str(link).split(' ')[1].split('"')[1]
if 'http' in newlink:
found_links.append(newlink)
elif search.findall(newlink):
found_links.append(newlink)
else:
pass
for url in found_links:
request_link = urllib.parse.urlparse(url)
self.add_task(pars_link[0] + '://' + pars_link[1] + request_link[2])
def spider(self):
while len(self.tasklist) != 0:
for item in self.tasklist:
self.printall(item)
try:
self.spider_searcher(item)
except (KeyboardInterrupt, EOFError) as err:
raise
except:
pass
try:
self.srch_page(item)
except (KeyboardInterrupt, EOFError) as err:
raise
except:
pass
self.perfected.append(str(item))
del self.tasklist[self.tasklist.index(item)]
def __str__(self):
found= ''
for items in list(self.fond_mails):
found += '{}\n'.format(items)
return found
def printall(self, request):
print('+' * 64, '\n [+] current link in process = {}'.format(request),
'\n [*] request links left= {}\n'.format(len(self.tasklist)),
'[*] response links status= {}\n'.format(len(self.perfected)),
'[*] Emails found not sorted = {}\n'.format(len(self.fond_mails)),
'Press Ctrl+C to exit\n')
def filewriter(self):
found = ''
for items in list(self.fond_mails):
try:
found += '{}\n'.format(str(items))
except:
pass
return found
def main():
site_parse = Spider()
site_parse.add_task(args['url'])
print('Start Program...')
try:
site_parse.spider()
except KeyboardInterrupt:
print('\n\n[-] KeyboardInterrupt = Exit')
print('Program Ends...')
print(site_parse,'\n [+] all results write in found_emails.txt')
with open('found_emails.txt', 'w') as file:
file.write(site_parse.filewriter())
file.close()
parser = argparse.ArgumentParser(description='Site Email spider')
parser.add_argument('-u', '--url', help='set url in format http://exemple.com', required=True)
args = vars(parser.parse_args())
if __name__ == "__main__":
main()
<file_sep>/empire/flaskserver.py
from flask import Flask
from flask import request
app = Flask(__name__)
import subprocess
import random
def user_agent():
ua_pool= [
'Mozilla/5.0 (compatible; U; ABrowse 0.6; Syllable) AppleWebKit/420+ (KHTML, like 11)',
'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/13.10586',
'Mozilla/5.0 (Linux; Android 6.0; HTC One M9 Build/MRA58K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36'
]
ua = random.choice(ua_pool)
return ua
def shell_generator():
out = subprocess.Popen(['python', 'empire', '-s', 'launcher', '-o', 'Listener=mylistener', 'UserAgent={ua}'.format(ua=user_agent())],
stdout=subprocess.PIPE)
c = out.stdout.read().decode().split('\n')[1]
return c
@app.route("/", methods=['GET', 'POST'])
def home():
valid = (request.data).decode()
print(valid.__len__())
print('HELOO NEW VISITOR:')
if valid.__len__() != 0:
#Place for Your PowerShell
html = shell_generator()
print('return: \n', html)
print('Return powershell')
else:
html = 'error'
print('Return error')
return html
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000)
<file_sep>/shells/XORshell/XORclient.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python all
# made by <EMAIL>
# need pycrypto https://www.dlitz.net/software/pycrypto/
import os
import subprocess
import argparse
from socket import socket, AF_INET, SOCK_STREAM
from Crypto.Cipher import XOR
parser = argparse.ArgumentParser(description='XOR Shell Client')
parser.add_argument('-a','--host', help='set lhost', required=True)
parser.add_argument('-p','--port', help='set lport', required=True)
parser.add_argument('-k','--key', help='set XOR key', required=True)
args = vars(parser.parse_args())
myHOST = args['host']
myPORT = int(args['port'])
key = args['key']
def encrypter(cleardata):
data = XOR.XORCipher(key)
return data.encrypt(cleardata)
def decrypter(cleardata):
data = XOR.XORCipher(key)
return data.decrypt(cleardata)
def client():
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.connect((myHOST, myPORT))
while True:
output = ''
data = (decrypter(sockobj.recv(1024))).decode('cp866')
if data[:2] == 'cd':
try:
os.chdir(data[3:])
except:
output += 'enter cd error'
if len(data) > 0:
cmd = subprocess.Popen(data[:], shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
output = (cmd.stdout.read() + cmd.stderr.read()).decode('cp866')
sockobj.send(encrypter(output + (os.getcwd() + '> ')))
sockobj.close()
try:
client()
except:
print('An error occured')
<file_sep>/toolkit/fap.py
#! /usr/bin/env python3
import os, sys
import subprocess
import argparse
class FakeAccessPoint(object):
def __init__(self, iface, gateway,channel,name,password=<PASSWORD>,debug=False):
"""iface, gateway,channel,name,password=None,debug=False"""
self.iface=iface
self.gateway=gateway
self.channel=channel
self.name =name
self.password=<PASSWORD>
#BASE CONFIG
self.debug=debug
self.temp= os.path.join(os.getcwd(), 'temp')
self.config_hostapd_name= 'hostapd.conf'
self.config_dnsmasq_name='dnsmasq.conf'
def main(self):
# Work with interface and other things
self.stop()
self.call_subprocess(['ifconfig', self.iface, '10.16.1.1', 'netmask', '255.255.255.0'])
status, msg = self.call_subprocess(['hostapd','-B','-t', os.path.join(self.temp,self.config_hostapd_name)])
if 'AP-DISABLED' in msg:
print('ERROR:\n {msg}'.format(msg=msg))
sys.exit()
else:
self.call_subprocess(['dnsmasq', '-C', os.path.join(self.temp,self.config_dnsmasq_name)])
self.call_subprocess(['sysctl', '-w', 'net.ipv4.ip_forward=1'])
# Clean UP IPTABLES + add new Rules
self.call_subprocess(
['iptables', '-A', 'FORWARD', '-i', self.gateway, '-o', self.iface, '-m', 'state', '--state',
'ESTABLISHED,RELATED', '-j', 'ACCEPT'])
# iptables -A FORWARD -i wlan1 -o wlan0 -j ACCEPT
self.call_subprocess(['iptables', '-A', 'FORWARD', '-i', self.iface, '-o', self.gateway, '-j', 'ACCEPT'])
# iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
self.call_subprocess(
['iptables', '-A', 'FORWARD', '-m', 'conntrack', '--ctstate', 'ESTABLISHED,RELATED', '-j', 'ACCEPT'])
# iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
self.call_subprocess(['iptables', '-t', 'nat', '-A', 'POSTROUTING', '-o', self.gateway, '-j', 'MASQUERADE'])
print('[+] AP-ENABLED')
def call_subprocess(self,command):
if self.debug:
print(' '.join(command))
call = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
msg_ok = call.stdout.read()
msg_error= call.stderr.read()
if msg_error.__len__() !=0:
if self.debug:
print(msg_error.decode())
return False, msg_error.decode()
else:
if self.debug:
print(msg_ok.decode())
return True, msg_ok.decode()
def start(self):
self.check_file_exists(self.temp, self.config_hostapd_name)
self.check_file_exists(self.temp, self.config_dnsmasq_name)
# create hostapd config
self.hostapd()
self.dnsmasq()
self.main()
def stop(self):
commands_pool = [
['killall', 'hostapd'],
['killall', 'dnsmasq'],
['service', 'hostapd', 'stop'],
['service', 'dnsmasq', 'stop'],
['ifconfig', self.iface, '0.0.0.0'],
]
for key in commands_pool:
self.call_subprocess(key)
return True
def hostapd(self):
# base config template for hostapd
config = []
config.append('interface={iface}'.format(iface=self.iface))
config.append('driver=nl80211')
config.append('ssid={name}'.format(name=self.name))
config.append('hw_mode=g')
config.append('channel={channel}'.format(channel=self.channel))
config.append('macaddr_acl=0')
config.append('ignore_broadcast_ssid=0')
if self.password is not None:
config.append('wpa=2')
config.append('wpa_passphrase={password}'.format(password=self.password))
config_template = '\n'.join(config)
self.save_config(os.path.join(self.temp,self.config_hostapd_name), config_template)
def dnsmasq(self):
config = []
config.append('no-resolv')
config.append('server=8.8.8.8')
config.append('server=192.168.3.11')
config.append('interface={iface}'.format(iface=self.iface))
config.append('listen-address=10.16.1.1') # you can add as Parametr if you want
config.append('bind-interfaces')
config.append('dhcp-range=10.16.1.1,10.16.1.250,255.255.255.0,12h')
config.append('dhcp-option=3,10.16.1.1')
config.append('dhcp-option=6,10.16.1.1')
config_template= '\n'.join(config)
self.save_config(os.path.join(self.temp, self.config_dnsmasq_name), config_template)
def save_config(self, path,config):
with open(path, 'w') as file:
file.write(config)
def check_file_exists(self, path,filename):
if os.path.exists(path):
if os.path.exists(os.path.join(path,filename)):
os.remove(os.path.join(path,filename))
if self.debug:
print('[*] Remove Temp Files {}'.format(filename))
else:
if self.debug:
print('[*] no config {}'.format(filename))
else:
pass
else:
os.mkdir(path)
if self.debug:
print('[+] making new path: {}'.format(path))
if __name__=="__main__":
def parse_args():
parser = argparse.ArgumentParser(description='Create WIFI Accesspoint')
parser.add_argument(
'-i',
'--iface',
help=(
"Select iface"
),
required=True
)
parser.add_argument(
'-g',
'--gateway',
help=(
"Select iface for gateway"
),
required=True
)
parser.add_argument(
'-s',
'--ssid',
help=(
"Select Name for FAP"
),
default=' '
)
parser.add_argument(
'-p',
'--password',
help=(
"Select Password"
)
)
parser.add_argument(
'-c',
'--channel',
help=(
"Select Channel"
),
default=6
)
parser.add_argument(
'-d',
'--debug',
help=(
"Select iface"
),
action='store_true'
)
parser.add_argument(
'--stop',
help=(
"Select iface"
),
action='store_true'
)
return parser.parse_args()
args=parse_args()
if args.password and (len(args.password) < 8 or len(args.password) > 64):
sys.exit('[-] Password must be beetween 8 and 63 printable characters')
if args.password == '':
password=None
else:
password = args.password
if args.stop:
commands_pool = [
['killall', 'hostapd'],
['killall', 'dnsmasq'],
['service', 'hostapd', 'stop'],
['service', 'dnsmasq', 'stop']
]
for key in commands_pool:
subprocess.Popen(key, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
fap=FakeAccessPoint(iface=args.iface, gateway=args.gateway,channel=args.channel,name=args.ssid,debug=args.debug, password=<PASSWORD>)
fap.start()<file_sep>/shells/shell/clien.py
#!/usr/bin/env python3
# Python all
# -*- coding: utf-8 -*-
# made by <EMAIL>
import os
import subprocess
from socket import socket, AF_INET, SOCK_STREAM
myHOST = '192.168.44.128'
myPORT = 9999
def client():
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.connect((myHOST, myPORT))
while True:
output = ''
data = (sockobj.recv(1024)).decode()
if data[:2] == 'cd':
try:
os.chdir(data[3:])
except:
output += 'enter cd error'
if len(data) > 0:
cmd = subprocess.Popen(data[:], shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
output = (cmd.stdout.read() + cmd.stderr.read())
sockobj.send((output + (os.getcwd() + '> ').encode('utf-8', errors='ignore')))
sockobj.close()
client()
<file_sep>/shells/shell/server.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python 3.4
# made by <EMAIL>
import argparse, sys
import signal
from socket import *
parser = argparse.ArgumentParser(description='Simple email bruteforcer')
parser.add_argument('-a','--host', help='set lhost', required=True)
parser.add_argument('-p','--port', help='set lport', required=True)
args = vars(parser.parse_args())
host = args['host']
port = int(args['port'])
print('\n\n\n')
print('[+] SERVER IP:', host)
print('[+] SERVER HOST:', port)
def server():
print('[+] Server start listening port.........\n')
while True:
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.bind((host, port))
sockobj.listen(5)
while True:
connection, adress = sockobj.accept()
try:
print('[#] Have new connection ==>>', adress)
while True:
try:
cmd = str(input('#input cmd: '))
if cmd == 'quit':
print('connection from adress {} close......'.format(adress))
connection.close()
sockobj.close()
if len(str.encode(cmd)) > 0:
connection.send(cmd.encode())
client_data = (connection.recv(1024))
try:
print(client_data.decode('utf-8', errors='ignore')+'\n')# English
except:
print(client_data.decode('cp866', errors='ignore')+'\n')# Russian
except:
break
except KeyboardInterrupt:
print("W: interrupt received, stopping…")
connection.close()
sockobj.close()
except Exception:
connection.close()
print('[-] Connection Reset Error: [WinError 10054] for {}'.format(adress),
'\n\n\n[*]wait for new Connections')
if __name__ == "__main__":
server()
<file_sep>/my_wifi.py
import os
import sys
import subprocess
import argparse
import time
BASE_DIR = os.getcwd()
args = 0
def parse_args():
# Create the arguments
parser = argparse.ArgumentParser(description='WIFI AP')
parser.add_argument(
"-i",
"--interface",
help=("Select wlan* interface. " +
"default 'wlan0'"
)
)
parser.add_argument(
"-g",
"--gateway",
help=("Select gateway interface. " +
"default 'eth0'"
)
)
parser.add_argument(
"-s",
"--ssid",
help=("Enter the ESSID Name for Access Point. " +
"Example: --ssid 'Free WiFi'." +
"default name 'Free-WIFI'"
)
)
parser.add_argument(
"-pK",
"--presharedkey",
help=("Add WPA/WPA2 protection on the rogue Access Point. " +
"Example: -pK s3cr3tp4ssw0rd"))
parser.add_argument(
"-c",
"--channel",
help=("select channel. " +
"default '6'"))
return parser.parse_args()
def make_config(wlan=None,name=None,chanel=None, password=None):
print('[+] Building config AP interface....\n[+] interface= {wifi_wlan}\n[+] ssid= {wifi_name}\n[+] channel= {wifi_chanel}\n[+] wpa_passphrase= {pwd}'.format(
wifi_wlan=wlan, wifi_name=name, wifi_chanel=chanel, pwd=<PASSWORD>))
hostapd = (
'interface={wifi_wlan}\n'
'driver=nl80211\n'
'ssid={wifi_name}\n'
'hw_mode=g\n'
'channel={wifi_chanel}\n'
'macaddr_acl=0\n'
'ignore_broadcast_ssid=0\n'.format(wifi_wlan=wlan, wifi_name=name, wifi_chanel=chanel))
if password != None:
hostapd += ('wpa=2\n'
'wpa_passphrase={<PASSWORD>').format(pwd=<PASSWORD>)
dnsmasq= ('interface={wifi_wlan}\n'
'dhcp-range=10.0.0.10,10.0.0.250,12h\n'
'dhcp-option=3,10.0.0.1\n'
'dhcp-option=6,10.0.0.1\n'
'server=8.8.8.8\n'
'log-queries\n'
'log-facility=/var/log/dnsmasq.log\n').format(wifi_wlan=wlan)
with open('hostapd.conf', 'w') as config_hostapd:
config_hostapd.write(hostapd)
config_hostapd.close()
with open('dnsmasq.conf', 'w') as config_dnsmasq:
config_dnsmasq.write(dnsmasq)
config_dnsmasq.close()
def check_args(args):
"""Checks the given arguments for logic errors."""
if args.presharedkey and (len(args.presharedkey) < 8 or len(args.presharedkey) > 64):
sys.exit('[-] Pre-shared key must be between 8 and 63 printable characters.')
if args.interface == None:
args.interface = 'wlan0'
print('[*] default value wlan0')
if args.gateway == None:
args.gateway = 'eth0'
print('[*] default value eth0')
if args.ssid == None:
args.ssid = 'Free-WIFI'
print('[*] default name Free-WIFI')
if args.channel == None:
args.channel = '6'
print('[*] default channel 6')
def start_extentions(wlan=None, gateway=None):
subprocess.call('killall hostapd', shell=True)
subprocess.call('killall dnsmasq', shell=True)
time.sleep(3)
hostapd_conf_dir = BASE_DIR + '/' + 'hostapd.conf'
dnsmasq_conf_dir = BASE_DIR + '/' + 'dnsmasq.conf'
iptables = "iptables --table nat -A POSTROUTING -o {0} -j MASQUERADE".format(gateway)
os.system("gnome-terminal -e 'bash -c \"hostapd -t {} ; exec bash\"'".format(hostapd_conf_dir))
os.system("gnome-terminal -e 'bash -c \"dnsmasq -C {} -d; exec bash\"'".format(dnsmasq_conf_dir))
time.sleep(3)
subprocess.call('sysctl -w net.ipv4.ip_forward=1', shell=True)
subprocess.call('service network-manager stop', shell=True)
subprocess.call('ifconfig {0} 10.0.0.1'.format(wlan), shell=True)
subprocess.call('ifconfig {0} up'.format(wlan), shell=True)
subprocess.call(iptables, shell=True)
def start_app():
args = parse_args()
check_args(args)
make_config(wlan=args.interface, name=args.ssid, chanel=args.channel,password=args.p<PASSWORD>key)
start_extentions(wlan=args.interface,gateway=args.gateway)
if __name__ == "__main__":
start_app()
<file_sep>/empire/macros-obfuscator.py
import string
import random
import argparse
parser = argparse.ArgumentParser(description='macrogenerator')
parser.add_argument('-u','--url', help='setup url for generate-macross', required=True)
args = vars(parser.parse_args())
random_pool_names = []
def generator(size=6, chars=string.ascii_lowercase+ string.ascii_uppercase):
variable = ''
for _ in range(size):
variable += random.choice(chars)
if variable in random_pool_names:
variable += random.choice(chars)
random_pool_names.append(variable)
return variable
#------------------------------ URL obfuscate Options-----------------
def main():
var_url_name = generator()
var_result = generator()
var_http = generator()
var_computer = generator()
var_wmiservice= generator()
var_startup = generator()
var_config= generator()
var_process = generator()
senselessly = generator(size=79)
senselessly2 = generator(size=79)
#------------------------------ URL obfuscate Options-----------------
url_compiler = ''
for item in range(0, url.__len__(), 4):
if item == 0:
url_compiler += '{URL} = "{context}"\n'.format(URL=var_url_name, context=url[item: item+4])
else:
url_compiler += '{URL} = {URL} + "{context}"\n'.format(URL=var_url_name, context=url[item: item + 4])
macross = r"""
Sub Auto_Open()
Dim {strResult} As String
Dim {objHTTP} As Object
Dim {URL} As String
'{senselessly2}'
Set {objHTTP} = CreateObject("Win" & "Http.Win" & "HttpRequest.5.1")
{url_config}
'{senselessly}'
{objHTTP}.Open "GET", {URL}, False
{objHTTP}.send ("{URL}")
{strResult} = {objHTTP}.responseText
Const HIDDEN_WINDOW = 0
{strComputer} = "."
Set {objWMIService} = GetObject("winmgmts:\\" & {strComputer} & "\root\cimv2")
Set {objStartup} = {objWMIService}.Get("Win32_ProcessStartup")
Set {objConfig} = {objStartup}.SpawnInstance_
{objConfig}.ShowWindow = HIDDEN_WINDOW
Set {objProcess} = GetObject("winmgmts:\\" & {strComputer} & "\root\cimv2:Win32_Process")
'{senselessly}'
{objProcess}.Create {strResult}, Null, {objConfig}, intProcessID
'{senselessly2}'
End Sub
""".format(strResult=var_result,
objHTTP=var_http,
strComputer=var_computer,
objWMIService=var_wmiservice,
objStartup=var_startup,
objConfig=var_config,
objProcess=var_process,
URL=var_url_name,
url_config=url_compiler,
senselessly=senselessly,
senselessly2=senselessly2)
print('--'*60)
print(macross)
print('--'*60)
if __name__ == "__main__":
url = args['url']
main()<file_sep>/toolkit/flask-test.py
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def home():
html = 'HERE CAN BE PHISHING PAGE FOR {}'.format(request.base_url)
return html
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)<file_sep>/toolkit/dns_sp.py
#! /usr/bin/env python3
# Browser DNS chrome://net-internals/dns#dns
# Read info http://www.networksorcery.com/enp/protocol/dns.htm#QR
# https://www.chromium.org/hsts
# https://cs.chromium.org/chromium/src/net/http/transport_security_state_static.json
from scapy.all import *
from netfilterqueue import NetfilterQueue
# Build spoof pool for test
spoof_pool= [
'bbc.com.',
'vk.com.',
'm.vk.com.',
'ukr.net.',
'mail.ru.',
'yahoo.com.',
'rambler.com.',
'facebook.com.'
]
class DnsSpooferNetFilter():
def __init__(self, ipaddress, debug=False):
self.redirect = ipaddress
self.debug = debug
def wrapper(self, qname):
for key in spoof_pool:
if key in qname:
return True
return False
def response_msg(self, pkt):
qtype = pkt[DNS].qd.qtype
if qtype!=28:
# if qtype != IPV6
answer= DNSRR(
rrname=pkt[DNS].qd.qname.decode(),
type=pkt[DNS].qd.qtype,
ttl=1200,
rdata=self.redirect
)
question = DNSQR(
qname=pkt[DNS].qd.qname.decode(),
qtype=pkt[DNS].qd.qtype,
qclass=pkt[DNS].qd.qclass
)
ip_layer = IP(
dst=pkt[IP].src,
src=pkt[IP].dst
)
udp_layer = UDP(
dport=pkt[UDP].sport,
sport=pkt[UDP].dport
)
dns_layer = DNS(
id=pkt[DNS].id,
qr=1,
aa=1,
qd=question,
an=answer
)
new_payload = ip_layer / udp_layer / dns_layer
return new_payload
else:
return pkt
def callback(self, packet):
payload = packet.get_payload()
pkt = IP(payload)
if not pkt.haslayer(DNSQR):
packet.accept()
else:
qname = pkt[DNS].qd.qname.decode()
if self.debug:
print(
'else-block: {decor}\n'
'{payload}\n'
'else-block: {decor}\n'.format(decor='-'*60, payload=pkt._do_summary())
)
if self.wrapper(qname):
new_payload = self.response_msg(pkt)
if self.debug:
print(
'payload block: {decor}\n'
'{payload}\n'
'payload block: {decor}\n'.format(decor='-' * 60, payload=payload)
)
print()
new_payload.show()
packet.set_payload(new_payload.build())
for _ in range(100):
send(new_payload, verbose=True)
packet.accept()
else:
packet.accept()
def main(self):
try:
self.q = NetfilterQueue()
self.q.bind(0,self.callback)
self.q.run()
except KeyboardInterrupt:
self.stop()
except Exception as error:
print('[-] Exception {error}'.format(error=error))
def start(self):
print('DNS Netfilter Start....')
#iptables -t nat -A PREROUTING -p udp --dport 53 -j NFQUEUE --queue-num 1
command = [
'iptables',
'-A',
'OUTPUT',
'-p',
'udp',
'--dport',
'53',
'-j',
'NFQUEUE',
]
if self.subprocess_call(command=command):
self.main()
else:
import sys
sys.exit()
def stop(self):
print('Stop Proxy change IP tables')
command = [
'iptables',
'-X'
]
command2 = [
'iptables',
'-F'
]
self.subprocess_call(command=command)
self.subprocess_call(command=command2)
def subprocess_call(self,command):
call = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = call.stdout.read()
error = call.stderr.read()
if error.__len__() !=0:
print(error.decode())
return False
else:
print(output.decode())
return True
if __name__ == "__main__":
dns = DnsSpooferNetFilter(ipaddress='192.168.0.105', debug=True)
dns.start()<file_sep>/email_spoofing/simple_spoofer.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Python 3.4
# made by <EMAIL>
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import make_header
from email.utils import make_msgid
from email.utils import formatdate
class EmailSender():
def __init__(self, **kwargs):
self.login = kwargs['login']
self.password = kwargs['<PASSWORD>']
self.host = kwargs['host']
self.port = int(kwargs['port'])
self.from_email = kwargs['from_email']
self.from_text = kwargs['from_text']
self.to = kwargs['to']
self.subject = kwargs['subject']
self.message_text = kwargs['message_text']
def masseges(self):
msg = MIMEMultipart()
msg['Message-ID'] = make_msgid()
msg['Date'] = formatdate(localtime=True)
msg['From'] = make_header([('{}'.format(self.from_text), 'UTF-8'), ('<' + self.from_email + '>', 'us-ascii')])
msg['To'] = self.to
msg['Subject'] = self.subject
msg['User-Agent'] = 'Horde Application Framework 5'
msg['Content-Disposition'] = "inline"
msg['Content-Transfer-Encoding'] = "8bit"
msg.attach(MIMEText(self.message_text, _subtype='html', _charset='utf-8'))
return(msg)
def chainsend(self):
server = smtplib.SMTP_SSL(self.host, self.port)
authentication = server.login(self.login, self.password)
echo = server.ehlo()
awere = server.sendmail(self.from_email, self.to, self.masseges().as_string())
server.quit()
if __name__ == '__main__':
print('Debug mode')
d = EmailSender(**{'login': '',
'password': '',
'host': 'smtp.mail.ru',
'port': 465,
'from_email': '',
'from_text': '',
'to': '',
'subject': '',
'message_text': '<img src="" width="500" height="900" align="center" />'
})
d.chainsend()
<file_sep>/README.md
# Python-scripts
<font color='#B22222'>
<h3>Python scripts for cyber security:</h3>
</font>
<file_sep>/simple-email_bruteforce.py
#!/usr/bin/env python3
# Python 3.4
# bruteforce over SMTP + SSL
# made by Xtr3am3r.0k and gbnk0
import smtplib
import email
import sys
import time
import os
import argparse
import threading
parser = argparse.ArgumentParser(description='Simple email bruteforcer')
parser.add_argument('-v','--victim-email', help='Specify the victims email', required=True)
parser.add_argument('-s','--victim-smtp', help='Set the victims smtp server (exemple: smtp.mail.ru)', required=True)
parser.add_argument('-p','--smtp-port', help='Set the smtp port', required=True)
parser.add_argument('-d','--dictionnary', help='Set the dictionnary', required=True)
args = vars(parser.parse_args())
victim_mail = args['victim_email']
smtp_server = args['victim_smtp']
port = args['smtp_port']
dict_brut = args['dictionnary']
#Process for MultiThread
def try_password(password, smtp_server, port, victim_mail):
passwd = password.rstrip()
print("[*] try password: {} ".format(passwd))
try:
smtp = smtplib.SMTP_SSL(smtp_server, int(port))
smtp.ehlo()
answer, status = smtp.login(victim_mail, passwd)
if status == b'Authentication succeeded':
print("\n[+] Cool Password Found: {}".format(passwd))
sys.exit(0)
else:
raise ConnectionResetError
except:
time.sleep(1)
pass
with open(dict_brut,'r') as dictbrut:
for list_pass in dictbrut:
t = threading.Thread(target=try_password, args=(list_pass, smtp_server, port, victim_mail))
t.start()<file_sep>/cover_script/shelter_folder.py
#!/usr/bin/env python
# Python 3.4
# <EMAIL>
# Github: https://github.com/xtr3m3rok
import os
import shutil
from winreg import *
def CU_Editor(path,name):
keyVal = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run'
newkeys = r"{0}{1}{2}".format(path,'\\',name)
try:
key = OpenKey(HKEY_CURRENT_USER, keyVal, 0, KEY_ALL_ACCESS)
except:
key = CreateKey(HKEY_CURRENT_USER, keyVal)
SetValueEx(key, "{}".format(name[:-4]), 0, REG_SZ, newkeys)
CloseKey(key)
def LM_Editor(path,name):
keyVal = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run'
newkeys = r"{0}{1}{2}".format(path,'\\',name)
try:
key = OpenKey(HKEY_LOCAL_MACHINE, keyVal, 0, (KEY_WOW64_64KEY + KEY_ALL_ACCESS))
except:
key = CreateKey(HKEY_LOCAL_MACHINE, keyVal)
SetValueEx(key, "{}".format(name[:-4]), 0, REG_SZ, newkeys)
CloseKey(key)
def main_start():
os.mkdir('new_dir')
shutil.copy2('test_exe/putty.exe', 'new_dir')
os.rename('new_dir', 'con3.{ED7BA470-8E54-465E-825C-99712043E01C}')
my_path = os.getcwd() +'\\'+ 'con3.{ED7BA470-8E54-465E-825C-99712043E01C}'
try:
LM_Editor(my_path, 'putty.exe')
except:
CU_Editor(my_path, 'putty.exe')
if __name__ == "__main__":
main_start()
|
6a7a8e818ee2c7dbaafcf4cb7883725c70e56f18
|
[
"Markdown",
"Python"
] | 14 |
Markdown
|
kojibhy/Python-scripts
|
8b4d59a9dc5848f9092dc382842139e6931f6694
|
1357786ee7474a5afe63bf3a1e8f151fb43756f3
|
refs/heads/master
|
<repo_name>Petar-Ralicheski/status-updater<file_sep>/src/index.js
import React from 'react'
import ReactDOM, { render } from 'react-dom'
import StatusManager from './components/StatusManager'
import './index.scss'
render(<StatusManager />, document.getElementById("root"));<file_sep>/src/components/StatusList.js
import React, {Component} from 'react'
import StatusMessage from './StatusMessage'
class StatusList extends Component {
constructor(props) {
super(props);
}
// for network requests, after component renders
// componentDidMount() {
// // get messages right after component is rendered
// this.getStatusMessages();
// }
displayStatusMessages() {
return this.props.statuses.map(
function(status) {
return (
<li key={status.id}>
<StatusMessage
msg={status.msg}
type={this.props.messageTypes[status.type]}
time={status.time}
/>
</li>
);
}.bind(this)
);
}
render() {
if(this.props.isLoaded === true) {
return <ul id="status-list">{this.displayStatusMessages()}</ul>;
} else {
return(
<div id="status-list" className="loading">
<h1>Loading...</h1>
<div className="spinner">
<div className="bounce1"></div>
<div className="bounce2"></div>
<div className="bounce3"></div>
</div>
</div>
)
}
}
}
export default StatusList<file_sep>/src/components/StatusMessage.js
import React from 'react'
const StatusMessage = (props) => {
var statusDate = date.parse(props.time, "YYYY-MM-DD, HH:mm"),
dateFormat = "M/D/Y, h:mm A";
return (
<div className="status-message">
{props.msg}
<span className="name">— {props.type}</span>
<span className="time">{date.format(statusDate, dateFormat)}</span>
</div>
);
}
export default StatusMessage<file_sep>/src/components/StatusManager.js
import React, {Component} from 'react'
import ReactDOM, { render } from 'react-dom'
import StatusList from './StatusList'
import PostForm from './PostForm'
class StatusManager extends Component {
constructor(props) {
super(props);
// just a property, doesn't have to be state
this.messageTypes = {
management: "Management",
dining: "Dining Services",
ops: "Operations",
plumbing: "Plumbing",
pool: "Pool"
};
this.apiUrl = "http://localhost:8080/status_api";
this.state = {
statuses: [],
isLoaded: false
};
this.addStatusMessage = this.addStatusMessage.bind(this);
}
componentDidMount() {
// get messages right after component is rendered
this.getStatusMessages();
}
// Get Data from Server
getStatusMessages() {
axios.get(this.apiUrl + "/get.php?delay=3").then(
function updateAxiosGet(response){
this.setState({
statuses: response.data,
isLoaded: true
});
}.bind(this));
}
addStatusMessage(status) {
var updatedStatuses = this.state.statuses.slice(0);
updatedStatuses.push(status);
this.setState({
statuses: updatedStatuses
});
}
render() {
return (
<React.Fragment>
<div id="post-status">
<PostForm messageTypes={this.messageTypes} apiUrl={this.apiUrl}
addStatusMessage={this.addStatusMessage}/>
</div>
<StatusList messageTypes={this.messageTypes}
statuses={this.state.statuses}
isLoaded={this.state.isLoaded}
/>
</React.Fragment>
);
}
}
export default StatusManager
|
3918db96a8ab5df4cbf6c66b735a45f834d80273
|
[
"JavaScript"
] | 4 |
JavaScript
|
Petar-Ralicheski/status-updater
|
0aca990d4698ca763f9002fc355855cbbc0ea7f3
|
a5b1d97f40e8fc149b66957ac362c9c5f92975fd
|
refs/heads/master
|
<repo_name>tignear/Road-of-Gold<file_sep>/Road-of-Gold/Road-of-Gold/Planet.cpp
#include"Planet.h"
#include"Scuttle.h"
#include"Urban.h"
#include"EnergyData.h"
#include"ItemData.h"
#include<lua.hpp>
#include<lauxlib.h>
#include<lualib.h>
Planet::Planet()
: mapTexture()
, timeSpeed(0)
, sandglass()
{
incidentsLua = luaL_newstate();
luaL_openlibs(incidentsLua);
//日付の取得
lua_pushcfunction(incidentsLua, [](lua_State* l) {
lua_pushinteger(l, planet.sandglass.year());
lua_pushinteger(l, planet.sandglass.month());
lua_pushinteger(l, planet.sandglass.day());
return 3;
});
lua_setglobal(incidentsLua, "getDate");
//Scuttle追加関数
lua_pushcfunction(incidentsLua, [](lua_State* l) {
const auto& title = CharacterSet::FromUTF8(lua_tostring(l, 1));
const auto& document = CharacterSet::FromUTF8(lua_tostring(l, 2));
const auto& button = CharacterSet::FromUTF8(lua_tostring(l, 3));
scuttles.emplace_back(title, document, button);
return 0;
});
lua_setglobal(incidentsLua, "addScuttle");
//Print
lua_pushcfunction(incidentsLua, [](lua_State* l) {
switch (lua_type(l, 1))
{
case LUA_TNIL:
Print << L"NIL";
break;
case LUA_TBOOLEAN:
Print << L"BOOLEAN :" << (lua_toboolean(l, 1) == 1 ? L"true" : L"false");
break;
case LUA_TLIGHTUSERDATA:
Print << L"LIGHTUSERDATA";
break;
case LUA_TNUMBER:
Print << L"NUMBER :" << int(lua_tonumber(l, 1));
break;
case LUA_TSTRING:
Print << L"STRING :" << CharacterSet::FromUTF8(lua_tostring(l, 1));
break;
case LUA_TTABLE:
Print << L"TABLE";
break;
case LUA_TFUNCTION:
Print << L"FUNCTION";
break;
case LUA_TUSERDATA:
Print << L"USERDATA";
break;
case LUA_TTHREAD:
Print << L"THREAD";
break;
}
return 0;
});
lua_setglobal(incidentsLua, "print");
//clearPrint
lua_pushcfunction(incidentsLua, [](lua_State* l) {
ClearPrint();
l; //警告避け
return 0;
});
lua_setglobal(incidentsLua, "clearPrint");
//Output
lua_pushcfunction(incidentsLua, [](lua_State* l) {
switch (lua_type(l, 1))
{
case LUA_TNIL:
Output << L"NIL";
break;
case LUA_TBOOLEAN:
Output << L"BOOLEAN :" << (lua_toboolean(l, 1) == 1 ? L"true" : L"false");
break;
case LUA_TLIGHTUSERDATA:
Output << L"LIGHTUSERDATA";
break;
case LUA_TNUMBER:
Output << L"NUMBER :" << int(lua_tonumber(l, 1));
break;
case LUA_TSTRING:
Output << L"STRING :" << CharacterSet::FromUTF8(lua_tostring(l, 1));
break;
case LUA_TTABLE:
Output << L"TABLE";
break;
case LUA_TFUNCTION:
Output << L"FUNCTION";
break;
case LUA_TUSERDATA:
Output << L"USERDATA";
break;
case LUA_TTHREAD:
Output << L"THREAD";
break;
}
return 0;
});
lua_setglobal(incidentsLua, "output");
//マップディレクトリを渡す
lua_pushcfunction(incidentsLua, [](lua_State* l) {
lua_pushstring(l, planet.mapPath.narrow().c_str());
return 1;
});
lua_setglobal(incidentsLua, "getMapPath");
//音の再生
lua_pushcfunction(incidentsLua, [](lua_State* l) {
planet.audios.emplace_back(CharacterSet::FromUTF8(lua_tostring(l, 1)));
planet.audios.back().play();
lua_pushboolean(l, planet.audios.back().isPlaying());
return 1;
});
lua_setglobal(incidentsLua, "playAudio");
//BGMの設定
lua_pushcfunction(incidentsLua, [](lua_State* l) {
planet.bgm = Audio(CharacterSet::FromUTF8(lua_tostring(l, 1)));
planet.bgm.setLoop(true);
planet.bgm.setVolume(lua_isnumber(l, 2) ? lua_tonumber(l, 2) : 1.0);
planet.bgm.play();
lua_pushboolean(l, planet.bgm.isPlaying());
return 1;
});
lua_setglobal(incidentsLua, "setBGM");
//getNumEnergy(energyType,urban)
lua_pushcfunction(incidentsLua, [](lua_State* l) {
auto* urban = getUrban(CharacterSet::FromUTF8(lua_tostring(l, 2)));
if (urban == nullptr) lua_pushinteger(l, 0);
else
{
int energyType = getEnergyType(CharacterSet::FromUTF8(lua_tostring(l, 1)));
if (energyType == -1) lua_pushinteger(l, 0);
else
{
for (auto& e : urban->energies)
{
if (e.energyType == energyType)
{
lua_pushinteger(l, e.numEnergy);
return 1;
}
}
lua_pushinteger(l, 0);
}
}
return 1;
});
lua_setglobal(incidentsLua, "getNumEnergy");
//setEnergy(energyType,urban,num)
lua_pushcfunction(incidentsLua, [](lua_State* l) {
auto* urban = getUrban(CharacterSet::FromUTF8(lua_tostring(l, 2)));
if (urban == nullptr) lua_pushboolean(l, false);
else
{
int energyType = getEnergyType(CharacterSet::FromUTF8(lua_tostring(l, 1)));
if (energyType == -1) lua_pushboolean(l, false);
else
{
urban->energies.remove_if([&energyType](Energy& e) { return e.energyType == energyType; });
urban->energies.emplace_back(energyType, int(lua_tointeger(l, 3)));
lua_pushboolean(l, true);
}
}
return 1;
});
lua_setglobal(incidentsLua, "setEnergy");
//getNumProductionPerDay(itemType,urban)
lua_pushcfunction(incidentsLua, [](lua_State* l) {
auto* urban = getUrban(CharacterSet::FromUTF8(lua_tostring(l, 2)));
if (urban == nullptr) lua_pushinteger(l, 0);
else
{
int itemType = getItemType(CharacterSet::FromUTF8(lua_tostring(l, 1)));
if (itemType == -1) lua_pushinteger(l, 0);
else lua_pushinteger(l, urban->shelves[itemType].tradeLog.numProduction[1]);
}
return 1;
});
lua_setglobal(incidentsLua, "getNumProductionPerDay");
}<file_sep>/Road-of-Gold/Road-of-Gold/loadData.cpp
#include"BiomeData.h"
#include"EnergyData.h"
#include"CitizenData.h"
#include"VehicleData.h"
#include"ItemData.h"
#include"Data.h"
int BiomeData::id() const { return int(this - &biomeData.front()); }
int CitizenData::id() const { return int(this - &citizenData.front()); }
int EnergyData::id() const { return int(this - &energyData.front()); }
int ItemData::id() const { return int(this - &itemData.front()); }
int VehicleData::id() const { return int(this - &vehicleData.front()); }
void loadData()
{
JSONReader json;
json.open(L"assets/data/itemData.json");
for (auto j : json.arrayView()) itemData.emplace_back(j);
Output << L"ItemDataの読み込み完了 size = " << itemData.size();
json.open(L"assets/data/biomeData.json");
for (auto j : json.arrayView()) biomeData.emplace_back(j);
Output << L"BiomeDataの読み込み完了 size = " << biomeData.size();
json.open(L"assets/data/energyData.json");
for (auto j : json.arrayView()) energyData.emplace_back(j);
Output << L"EnergyDataの読み込み完了 size = " << energyData.size();
json.open(L"assets/data/citizenData.json");
for (auto j : json.arrayView()) citizenData.emplace_back(j);
Output << L"CitizenDataの読み込み完了 size = " << citizenData.size();
json.open(L"assets/data/vehicleData.json");
for (auto j : json.arrayView()) vehicleData.emplace_back(j);
Output << L"VehicleDataの読み込み完了 size = " << vehicleData.size();
}
CitizenData::CitizenData(const JSONValue& _json)
: name(_json[L"Name"].getOr<String>(L""))
, wage(_json[L"Wage"].getOr<int>(0))
, product(_json[L"Product"])
, needEnergyType(getEnergyType(_json[L"NeedEnergy"].getString()))
{}
BiomeData::BiomeData(const JSONValue& _json)
: name(_json[L"Name"].getOr<String>(L""))
, color(_json[L"Color"].getOr<String>(L"#FFFFFF"))
, movingCost(_json[L"MovingCost"].getOr<double>(1.0))
, isSea(_json[L"IsSea"].getOr<bool>(false))
{}
EnergyData::EnergyData(const JSONValue& _json)
: name(_json[L"Name"].getOr<String>(L""))
{}
ItemData::ItemData(const JSONValue& _json)
: name(_json[L"Name"].getOr<String>(L""))
, value(_json[L"Value"].getOr<int>(0))
, volume(_json[L"Volume"].getOr<int>(0))
, color(_json[L"Color"].getOr<String>(L"#FFFFFF"))
, icon(_json[L"Icon"].getOr<String>(L""))
{}
VehicleData::VehicleData(const JSONValue& _json)
: name(_json[L"Name"].getOr<String>(L""))
, speed(_json[L"Speed"].getOr<double>(1.0))
, volume(_json[L"Volume"].getOr<int>(100))
, range(_json[L"Range"].getOr<double>(1.0))
, isShip(_json[L"IsShip"].getOr<bool>(false))
, icon(_json[L"Icon"].getOr<String>(L""))
, constructionCost(_json[L"ConstructionCost"].getOr<int>(1000))
, tier(_json[L"Tier"].getOr<int>(0))
{}
EnergyData* getEnergyData(const String& _name)
{
for (auto& e : energyData)
{
if (e.name == _name) return &e;
}
return nullptr;
}
CitizenData* getCitizenData(const String& _name)
{
for (auto& e : citizenData)
{
if (e.name == _name) return &e;
}
return nullptr;
}
BiomeData* getBiomeData(const String& _name)
{
for (auto& e : biomeData)
{
if (e.name == _name) return &e;
}
return nullptr;
}
ItemData* getItemData(const String& _name)
{
for (auto& e : itemData)
{
if (e.name == _name) return &e;
}
return nullptr;
}
VehicleData* getVehicleData(const String& _name)
{
for (auto& e : vehicleData)
{
if (e.name == _name) return &e;
}
return nullptr;
}
int getEnergyType(const String& _name)
{
for (auto& e : energyData)
{
if (e.name == _name) return e.id();
}
return -1;
}
int getBiomeType(const String& _name)
{
for (auto& e : biomeData)
{
if (e.name == _name) return e.id();
}
return -1;
}
int getItemType(const String& _name)
{
for (auto& e : itemData)
{
if (e.name == _name) return e.id();
}
return -1;
}
int getCitizenType(const String& _name)
{
for (auto& e : citizenData)
{
if (e.name == _name) return e.id();
}
return -1;
}
int getVehicleType(const String& _name)
{
for (auto& e : vehicleData)
{
if (e.name == _name) return e.id();
}
return -1;
}<file_sep>/Road-of-Gold/Assets-Manager/united.h
#pragma once
#include <HamFramework.hpp>
Array<String> itemList =
{
L"itemData.json",
L"citizenData.json",
L"energyData.json",
L"vehicleData.json"
};
struct GameData
{
int selectedSceneID = 0;
int selectedItemType = 0;
int selectedVehicleType = 0;
int selectedEnergyType = 0;
int selectedCitizenType = 0;
};
using MyApp = SceneManager<String, GameData>;
bool itemIsExist(const String& _itemName);
bool energyIsExist(const String& _energyName);
|
aa69a9ffe85b7b1ee020bb5bf08f85c05db1e8d3
|
[
"C",
"C++"
] | 3 |
C
|
tignear/Road-of-Gold
|
6d263198eaa647fef8519547d96130caadbf5d15
|
730d1c042be869ead5ea2ecf65e2a6da0159b286
|
refs/heads/main
|
<file_sep>const quizDB = [
{
question: "Q1:Smaple Queation 1?",
a: "option1",
b: "option2",
c: "option3",
d: "option4",
ans: "ans4"
},
{
question: "Q1:Smaple Queation 2?",
a: "option1",
b: "option2",
c: "option3",
d: "option4",
ans: "ans1"
},
{
question: "Q1:Smaple Queation 3?",
a: "option1",
b: "option2",
c: "option3",
d: "option4",
ans: "ans4"
},
{
question: "Q1:Smaple Queation 4?",
a: "option1",
b: "option2",
c: "option3",
d: "option4",
ans: "ans1"
}
]
export{quizDB}
|
0599f06139a182c0e06d9ab9d8eb4347c8e3feaf
|
[
"JavaScript"
] | 1 |
JavaScript
|
awsomeakash/Quiz-Website-
|
30708eacaea7c84db117982dfe1b9f6505c4a3bb
|
8ce8cb7c9e3a7c0cbb64165a0c926d3d4dff4aee
|
refs/heads/main
|
<file_sep>- Hello, I’m @Siinaus and IRL Siina
- Right now I'm still an IT-student but soon frontend developer. This is my last year in school.
- I'm familiar with Angular and I know something about React and Svelte. That's what I can help you with.
- I know the basics about backend develop too but I would love to be better at that so I could become a Fullstack developer one day. ✨
|
fce42b5306c55457bf8fb7f21b1750c579aafcb5
|
[
"Markdown"
] | 1 |
Markdown
|
Siinaus/Siinaus
|
d55bcfbf2027a05ab9ceeafda57a0dfc2b05ffdb
|
4299bf0dec0452c45da7d8ae9d2ec5740aeb141f
|
refs/heads/master
|
<file_sep><?xml version='1.0' encoding='UTF-8'?>
<pyvcp>
<table>
<tablesticky sticky="n"/>
<tablerow/>
<label text="digital-in-08" font="helvetica -12 bold"/>
<label text="digital-in-12" font="helvetica -12 bold"/>
<label text="digital-in-13" font="helvetica -12 bold"/>
<label text="digital-out-02" font="helvetica -12 bold"/>
<label text="digital-out-04" font="helvetica -12 bold"/>
<label text="digital-out-07" font="helvetica -12 bold"/>
<tablerow/>
<led halpin="digital-in-08"/>
<led halpin="digital-in-12"/>
<led halpin="digital-in-13"/>
<checkbutton halpin="digital-out-02"/>
<checkbutton halpin="digital-out-04"/>
<checkbutton halpin="digital-out-07"/>
<tablerow/>
<label text="analog-in-00" font="helvetica -12 bold"/>
<label text="analog-in-01" font="helvetica -12 bold"/>
<label text="analog-in-02" font="helvetica -12 bold"/>
<label text="analog-in-03" font="helvetica -12 bold"/>
<label text="analog-in-04" font="helvetica -12 bold"/>
<label text="analog-in-05" font="helvetica -12 bold"/>
<tablerow/>
<number halpin="analog-in-00" format="-2.4f"/>
<number halpin="analog-in-01" format="-2.4f"/>
<number halpin="analog-in-02" format="-2.4f"/>
<number halpin="analog-in-03" format="-2.4f"/>
<number halpin="analog-in-04" format="-2.4f"/>
<number halpin="analog-in-05" format="-2.4f"/>
<tablerow/>
<bar halpin="analog-in-00b" min_="0" max_="5"/>
<bar halpin="analog-in-01b" min_="0" max_="5"/>
<bar halpin="analog-in-02b" min_="0" max_="5"/>
<bar halpin="analog-in-03b" min_="0" max_="5"/>
<bar halpin="analog-in-04b" min_="0" max_="5"/>
<bar halpin="analog-in-05b" min_="0" max_="5"/>
<tablerow/>
<label text="analog-out-03" font="helvetica -12 bold"/>
<label text="analog-out-05" font="helvetica -12 bold"/>
<label text="analog-out-06" font="helvetica -12 bold"/>
<label text="analog-out-09" font="helvetica -12 bold"/>
<label text="analog-out-10" font="helvetica -12 bold"/>
<label text="analog-out-11" font="helvetica -12 bold"/>
<tablerow/>
<scale resolution="0.1" halpin="analog-out-03" min_="0" max_="5" orient="h"/>
<scale resolution="0.1" halpin="analog-out-05" min_="0" max_="5" orient="h"/>
<scale resolution="0.1" halpin="analog-out-06" min_="0" max_="5" orient="h"/>
<scale resolution="0.1" halpin="analog-out-09" min_="0" max_="5" orient="h"/>
<scale resolution="0.1" halpin="analog-out-10" min_="0" max_="5" orient="h"/>
<scale resolution="0.1" halpin="analog-out-11" min_="0" max_="5" orient="h"/>
</table>
</pyvcp>
<file_sep># Arduino HAL Interface
Arduino Interface for LinuxCNC HAL.
## Features
* 6 10-bit analog inputs
* 6 8-bit PWM "analog" outputs
* 6 digital inputs/outputs (partition chosen when component is loaded)
## Installing
`pip install git+https://github.com/kurtjacobson/arduino-hal-interface.git`
Author: <NAME>
https://emergent.unpythonic.net/01198594294
<file_sep>// HAL userspace component to interface with Arduino board
// Copyright (C) 2007 <NAME> <<EMAIL>>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
void setup() {
Serial.begin(9600);
}
uint8_t adc=0;
uint8_t firstbyte=0;
uint8_t pinmap[6] = {2,4,7,8,12,13};
uint8_t dacpinmap[6] = {3,5,6,9,10,11};
void loop() {
while(Serial.available()) {
uint8_t byte = Serial.read();
if(((firstbyte & 0x80) == 0x80) && ((byte & 0x80) == 0)) {
// got a packet
uint16_t payload = (firstbyte << 7) | byte;
uint8_t address = (firstbyte >> 4) & 7;
uint8_t dac = payload & 0xff;
uint8_t dir = (payload & 0x100) == 0x100;
uint8_t out = (payload & 0x200) == 0x200;
if(address < 6) {
analogWrite(dacpinmap[address], dac);
digitalWrite(pinmap[address], out);
pinMode(pinmap[address], dir);
}
}
firstbyte = byte;
}
uint16_t v = analogRead(adc) | (adc << 11);
if(digitalRead(pinmap[adc])) v |= (1<<10);
Serial.write((v >> 7) | 0x80);
Serial.write(v & 0x7f);
adc = (adc + 1) % 6;
}
<file_sep>#!/usr/bin/python
# HAL userspace component to interface with Arduino board
# Copyright (C) 2007 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import serial
import hal
import sys
import time
def encode(addr, data):
if data < 0 or data > 2048: raise ValueError, "data %02d out of range" % data
if addr < 0 or addr > 8: raise ValueError, "address %02d out of range" % addr
b1 = 0x80 | (addr << 4) | (data >> 7)
b2 = data & 0x7f
return chr(b1) + chr(b2)
PORT = "/dev/ttyUSB0"
def run(port=PORT, nout=6):
if nout > 6 or nout < 0:
raise SystemExit, "Number of digital outputs must be from 0 to 6"
pinmap = [2,4,7,8,12,13]
dacpinmap = [3,5,6,9,10,11]
ser = serial.Serial(port, 9600, timeout=2)
c = hal.component("arduino")
for pin in range(6):
c.newpin("analog-in-%02d" % pin, hal.HAL_FLOAT, hal.HAL_OUT)
c.newparam("analog-in-%02d-offset" % pin, hal.HAL_FLOAT, hal.HAL_RW)
c.newparam("analog-in-%02d-gain" % pin, hal.HAL_FLOAT, hal.HAL_RW)
c.newpin("analog-out-%02d" % dacpinmap[pin], hal.HAL_FLOAT, hal.HAL_IN)
c.newparam("analog-out-%02d-offset" % dacpinmap[pin], hal.HAL_FLOAT, hal.HAL_RW)
c.newparam("analog-out-%02d-scale" % dacpinmap[pin], hal.HAL_FLOAT, hal.HAL_RW)
c['analog-in-%02d-gain' % pin] = 1.0
c['analog-out-%02d-scale' % dacpinmap[pin]] = 1.0
for pin in range(nout):
c.newpin("digital-out-%02d" % pinmap[pin], hal.HAL_BIT, hal.HAL_IN)
c.newparam("digital-out-%02d-invert" % pinmap[pin], hal.HAL_BIT, hal.HAL_RW)
for pin in range(nout, 6):
c.newpin("digital-in-%02d" % pinmap[pin], hal.HAL_BIT, hal.HAL_OUT)
c.newpin("digital-in-%02d-not" % pinmap[pin], hal.HAL_BIT, hal.HAL_OUT)
c.newparam("digital-in-%02d-pullup" % pinmap[pin], hal.HAL_BIT, hal.HAL_RW)
print "ready"
c.ready()
firstbyte = 0
state = 0
try:
while 1:
while ser.inWaiting():
byte = ord(ser.read())
if firstbyte & 0x80 == 0x80 and byte & 0x80 == 0:
v = (firstbyte << 7) | byte
pin = (v >> 11) & 7
if pin < 6:
if pin >= nout:
b = v & 1024
c['digital-in-%02d' % pinmap[pin]] = b != 0
c['digital-in-%02d-not' % pinmap[pin]] = b == 0
gain = c['analog-in-%02d-gain' % pin] or 1.
offset = c['analog-in-%02d-offset' % pin]
value = (v & 1023) / 1023. * 5.0 * gain + offset
c['analog-in-%02d' % pin] = value
firstbyte = byte
scale = c['analog-out-%02d-scale' % dacpinmap[state]] or 1.
offset = c['analog-out-%02d-offset' % dacpinmap[state]]
data = (c['analog-out-%02d' % dacpinmap[state]] - offset) / scale / 5
data = int(data * 255 + 0.5)
if data < 0: data = 0
if data > 255: data = 255
if state < nout:
out = not c['digital-out-%02d' % pinmap[state]]
invert = not c['digital-out-%02d-invert' % pinmap[state]]
if out != invert:
data |= 0x200
data = data | 0x100
else:
pullup = c['digital-in-%02d-pullup' % pinmap[state]]
if pullup:
data |= 0x200
data = data | (state << 11)
ser.write(chr(0x80 | (data >> 7)))
ser.write(chr(data & 0x7f))
state = (state+1) % 6
time.sleep(.001)
except (KeyboardInterrupt,):
raise SystemExit, 0
def main():
# entry point when running as a script
kwargs = {}
if len(sys.argv) > 1:
kwargs['port'] = sys.argv[1]
if len(sys.argv) > 2:
kwargs['nout'] = int(sys.argv[2])
run(**kwargs)
if __name__ == "__main__":
main()
|
51674b287c75af113a5426ecf546e0f72c6c47ab
|
[
"XML",
"Markdown",
"C++",
"Python"
] | 4 |
XML
|
KurtJacobson/arduino-hal-interface
|
41d838ce53451ff15d4be4a188a06652c14b91be
|
0a4940e489ee07d78fd285aea4a21fd83076ff37
|
refs/heads/master
|
<repo_name>findby/repository-utils<file_sep>/README.md
# repository-utils
设计模式、工具、案例demo记录
|
4e8bd0b5de3ee1570a0323b5359ae449460d791f
|
[
"Markdown"
] | 1 |
Markdown
|
findby/repository-utils
|
c170e1a7bd13b2cfb0bab0b97294b8eb41d1eb3a
|
55d9dcce22ecb4e7c9f2fb549ee0b6ba70a4fea0
|
refs/heads/master
|
<repo_name>CheckTech/CorelDraw2019KorPatch<file_sep>/CorelDraw2019KorPatch/frmMain.cs
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Media;
// 로컬 리포지토리 빈폴더 만들어 등록부터 한다
// 소스를 복사하고 sln을 클릭
// 팀탐색기에서 GitHub를 연결후 커밋후 동기화한다
namespace CorelDraw2019KorPatch
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
ResourceSave();
}
private void ResourceSave()
{
string strFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
@"\AppData\Roaming\Corel\CorelDRAW Graphics Suite 2019\Draw\Workspace\_default.cdws";
// _default.cdws파일이 존재하면 CorelDraw2019가 설치된걸로 간주
FileInfo fileInfo = new FileInfo(strFolder);
if (fileInfo.Exists)
{
try
{
var _default = Properties.Resources._default;
FileStream file = new FileStream(strFolder, FileMode.Create);
file.Write(_default, 0, _default.Length);
file.Close();
FinalBeep("CorelDraw2019가 한글화가 되었습니다!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error Accessing Resourc!");
}
}
else
{
FinalBeep("CorelDraw2019를 설치하고 실행하세요!");
}
}
private void FinalBeep(string msg)
{
// Console.Beep();
DingDongDaengDong();
lblMsg.ForeColor = Color.Red;
lblMsg.Text = msg;
btnStart.Text = "종 료";
Delay(2000);
this.Close();
}
private static void DingDongDaengDong()
{
Stream st = Properties.Resources.DingDongDaengDong;
SoundPlayer snd = new SoundPlayer(st);
snd.Play();
}
private static DateTime Delay(int MS)
{
DateTime ThisMoment = DateTime.Now;
TimeSpan duration = new TimeSpan(0, 0, 0, 0, MS);
DateTime AfterWards = ThisMoment.Add(duration);
while (AfterWards >= ThisMoment)
{
System.Windows.Forms.Application.DoEvents();
ThisMoment = DateTime.Now;
}
return DateTime.Now;
}
//private void Filecopy()
//{
// string fileName = "_default.cdws";
// string sourcePath = Environment.CurrentDirectory;
// string targetPath = Environment.CurrentDirectory + @"\AA";
// // string targetPath = @"C:\Users\user\AppData\Roaming\Corel\CorelDRAW Graphics Suite 2019\Draw\Workspace";
// string sourceFile = Path.Combine(sourcePath, fileName);
// string destFile = Path.Combine(targetPath, fileName);
// Directory.CreateDirectory(targetPath);
// File.Copy(sourceFile, destFile, true);
//}
}
}
|
b2b9a470be4e3a4466a3c9a54139eb7a0753a131
|
[
"C#"
] | 1 |
C#
|
CheckTech/CorelDraw2019KorPatch
|
3ddecf3689cf63179dacf732e6075d5f3d3a588e
|
6dce5c9fbd70487b552267202ef45b2150fdb003
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.