language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C++
UTF-8
826
2.890625
3
[ "BSD-3-Clause" ]
permissive
#include <fstream> #include <sstream> #include <algorithm> #include "file_io.hh" std::string message_from_file(const std::string& fname) {std::string msg; std::ifstream ifs(fname); std::ostringstream oss; oss << ifs.rdbuf(); msg = oss.str(); return msg; } void message_to_file(const std::string& msg, const std::string& fname) { std::ofstream ofs(fname); ofs << msg; } File_type file_type_of(const std::string& fname) { int extension_pos = fname.find_last_of('.'); if (extension_pos != -1) { std::string extension = fname.substr(extension_pos + 1); std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); if (extension == "wav") { return File_type::WAV; } else if (extension == "bmp") { return File_type::BMP; } } return File_type::UNKNOWN; }
Java
UTF-8
1,886
2.203125
2
[]
no_license
/* * 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 bpvip.controller.dto; import bpvip.entity.Proizvodjac; import java.io.Serializable; /** * * @author Admin */ public class UredjajDTO implements Serializable { private int IDUredjaj; private String naziv; private String boja; private String model; private double cena; private ProizvodjacDTO proizvodjac; public UredjajDTO() { proizvodjac = new ProizvodjacDTO(); } public UredjajDTO(int IDUredjaj, String naziv, String boja, String model, double cena, ProizvodjacDTO proizvodjac) { this.IDUredjaj = IDUredjaj; this.naziv = naziv; this.boja = boja; this.model = model; this.cena = cena; this.proizvodjac = proizvodjac; } public int getIDUredjaj() { return IDUredjaj; } public void setIDUredjaj(int IDUredjaj) { this.IDUredjaj = IDUredjaj; } public String getNaziv() { return naziv; } public void setNaziv(String naziv) { this.naziv = naziv; } public String getBoja() { return boja; } public void setBoja(String boja) { this.boja = boja; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public double getCena() { return cena; } public void setCena(double cena) { this.cena = cena; } public ProizvodjacDTO getProizvodjac() { return proizvodjac; } public void setProizvodjac(ProizvodjacDTO proizvodjac) { this.proizvodjac = proizvodjac; } }
Java
UTF-8
3,765
3.203125
3
[]
no_license
package org.ip.sesion07; public class Fraccion implements Comparable { private int numerador; private int denominador; private static int numFracciones; public Fraccion() { this.numerador = 0; this.denominador = 1; Fraccion.numFracciones += 1; } public Fraccion(int numerador, int denominador) { this.numerador = numerador; this.denominador = denominador; Fraccion.numFracciones += 1; } public Fraccion(Fraccion fraccion) { this.numerador = fraccion.numerador; this.denominador = fraccion.denominador; Fraccion.numFracciones += 1; } @Override public boolean equals(Object obj) { boolean iguales = false; if(obj instanceof Fraccion) { Fraccion fraccion = (Fraccion) obj; if(this.numerador == fraccion.numerador && this.denominador == fraccion.denominador) { iguales = true; } } return iguales; } public int getNumerador() { return this.numerador; } public int getDenominador() { return this.denominador; } public static int getNumFracciones() { return Fraccion.numFracciones; } public String toString() { return this.numerador + "/" + this.denominador; } public Fraccion sumar(Fraccion fraccion) { int numerador1 = fraccion.denominador * this.numerador; int numerador2 = fraccion.numerador * this.denominador; int denominador = this.denominador * fraccion.denominador; Fraccion auxiliar = new Fraccion(); auxiliar.numerador = numerador1 + numerador2; auxiliar.denominador = denominador; return auxiliar; } public static Fraccion sumar(Fraccion fraccion1, Fraccion fraccion2) { int numerador1 = fraccion1.denominador * fraccion2.numerador; int numerador2 = fraccion1.numerador * fraccion2.denominador; int denominador = fraccion1.denominador * fraccion2.denominador; Fraccion auxiliar = new Fraccion(); auxiliar.numerador = numerador1 + numerador2; auxiliar.denominador = denominador; return auxiliar; } public Fraccion restar(Fraccion fraccion) { int numerador1 = fraccion.denominador * this.numerador; int numerador2 = fraccion.numerador * this.denominador; int denominador = this.denominador * fraccion.denominador; Fraccion auxiliar = new Fraccion(); auxiliar.numerador = numerador1 - numerador2; auxiliar.denominador = denominador; return auxiliar; } public Fraccion multiplicar(Fraccion fraccion) { Fraccion auxiliar = new Fraccion(); auxiliar.numerador = this.numerador * fraccion.numerador; auxiliar.denominador = fraccion.denominador * this.denominador; return auxiliar; } public Fraccion dividir(Fraccion fraccion) { Fraccion auxiliar = new Fraccion(); auxiliar.numerador = this.numerador * fraccion.denominador; auxiliar.denominador = fraccion.numerador * this.denominador; return auxiliar; } private int mcd(int u, int v) { int dividendo = Math.abs(u); int divisor = Math.abs(v); if (v > u){ int auxiliar = u; u = v; v = auxiliar; } while(dividendo % divisor != 0) { int auxiliar = divisor; divisor = dividendo % divisor; dividendo = auxiliar; } return divisor; } public Fraccion simplificar() { int mcd = this.mcd(this.numerador, this.denominador); this.numerador /= mcd; this.denominador /= mcd; return this; } @Override public int compareTo(Object obj) { int soy = 0; if(obj instanceof Fraccion) { Fraccion fr = (Fraccion) obj; double numero1 = (Double.valueOf(this.getNumerador()) / Double.valueOf(this.getDenominador())); double numero2 = (Double.valueOf(fr.getNumerador()) / Double.valueOf(fr.getDenominador())); if(numero1 > numero2) { soy = 1; } else if (numero1 < numero2) { soy = 0; } else { soy = -1; } } return soy; } }
C++
GB18030
237
2.765625
3
[]
no_license
/*鷨±*/ #include <stdio.h> #include <string.h> #define MAXSIZE 100 int main(void) { char a[MAXSIZE]; int i; gets(a); for (i = strlen(a)-1; i >= 0; i--) putchar(a[i]); return 0; }
Java
UTF-8
5,035
3.09375
3
[]
no_license
package model; import java.util.*; import java.util.regex.Pattern; import java.util.regex.Matcher; public class RegexChecker { private ArrayList<String> firstNameList; private ArrayList<String> lastNameList; private Matcher emailMatcher; private Pattern emailPattern; private Matcher phoneMatcher; private Pattern phonePattern; private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; private static final String PHONE_PATTERN = "^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$"; public RegexChecker() { this.firstNameList = new ArrayList<String>(); this.lastNameList = new ArrayList<String>(); emailPattern = Pattern.compile(EMAIL_PATTERN); phonePattern = Pattern.compile(PHONE_PATTERN); buildFirstNameList(); buildLastNameList(); } //key words for lists private void buildFirstNameList() { this.firstNameList.add("~"); this.firstNameList.add("`"); this.firstNameList.add("@"); this.firstNameList.add("#"); this.firstNameList.add("$"); this.firstNameList.add("%"); this.firstNameList.add("^"); this.firstNameList.add("&"); this.firstNameList.add("*"); this.firstNameList.add("("); this.firstNameList.add(")"); this.firstNameList.add("_"); this.firstNameList.add("-"); this.firstNameList.add("+"); this.firstNameList.add("="); this.firstNameList.add("|"); this.firstNameList.add(":"); this.firstNameList.add(";"); this.firstNameList.add("<"); this.firstNameList.add(">"); this.firstNameList.add("1"); this.firstNameList.add("2"); this.firstNameList.add("3"); this.firstNameList.add("4"); this.firstNameList.add("5"); this.firstNameList.add("6"); this.firstNameList.add("7"); this.firstNameList.add("8"); this.firstNameList.add("9"); this.firstNameList.add("0"); this.firstNameList.add(" "); this.firstNameList.add("{"); this.firstNameList.add("}"); this.firstNameList.add("["); this.firstNameList.add("]"); this.firstNameList.add("."); } //"" private void buildLastNameList() { this.lastNameList.add("~"); this.lastNameList.add("`"); this.lastNameList.add("!"); this.lastNameList.add("@"); this.lastNameList.add("#"); this.lastNameList.add("$"); this.lastNameList.add("%"); this.lastNameList.add("^"); this.lastNameList.add("&"); this.lastNameList.add("*"); this.lastNameList.add("("); this.lastNameList.add(")"); this.lastNameList.add("_"); this.lastNameList.add("-"); this.lastNameList.add("+"); this.lastNameList.add("="); this.lastNameList.add("{"); this.lastNameList.add("}"); this.lastNameList.add("["); this.lastNameList.add("]"); this.lastNameList.add("|"); this.lastNameList.add(":"); this.lastNameList.add(";"); this.lastNameList.add(">"); this.lastNameList.add("<"); this.lastNameList.add("."); this.lastNameList.add(","); this.lastNameList.add("1"); this.lastNameList.add("2"); this.lastNameList.add("3"); this.lastNameList.add("4"); this.lastNameList.add("5"); this.lastNameList.add("6"); this.lastNameList.add("7"); this.lastNameList.add("8"); this.lastNameList.add("9"); this.lastNameList.add("0"); this.lastNameList.add(" "); } public String firstNameChecker(String firstName) { String firstStatus = null; if (firstName.length() > 2 && firstName.length() < 30) { for (int currentSymbol = 0; currentSymbol < firstNameList.size(); currentSymbol++) { if (firstName.contains(firstNameList.get(currentSymbol))) { return firstStatus = "First Name: Status code 400: contains invalid character"; } else { firstStatus = "First Name: All good"; } } } else { firstStatus = "First Name: too long or too short"; } return firstStatus; } public String lastNameChecker(String lastName) { String lastStatus = null; if (lastName.length() > 2 && lastName.length() < 40) { for (int currentSymbol = 0; currentSymbol < lastNameList.size(); currentSymbol++) { if (lastName.contains(lastNameList.get(currentSymbol))) { return lastStatus = "Last Name: Status code 400: contains invalid character"; } else { lastStatus = "Last Name: All good"; } } } else { lastStatus = "Last Name: too long or too short"; } return lastStatus; } public String emailChecker(String email) { String emailStatus = ""; emailMatcher = emailPattern.matcher(email); if (emailMatcher.matches() == true) { emailStatus = "Email: all good"; } else { emailStatus = "Email: invalid email"; } return emailStatus; } public String phoneChecker(String phone) { String phoneStatus = ""; phoneMatcher = phonePattern.matcher(phone); if (phone.length() == 10) { if (phoneMatcher.matches() == true) { phoneStatus = "Phone: all good"; } else { phoneStatus = "Phone: invalid"; } } else { phoneStatus = "Phone: I DEMAMND 10 DIGITS!"; } return phoneStatus; } }
C++
UTF-8
726
2.96875
3
[]
no_license
#ifndef _PELICULA_H_ #define _PELICULA_H_ #include <iostream> #include <string> #include "lista.h" using namespace std; class Pelicula{ private: string nombre; string genero; int puntaje; string director; Lista<string>* actores; public: Pelicula(string nombre,string genero,string director,int puntaje); string obtener_nombre(); string obtener_genero(); string obtener_director(); int obtener_puntaje(); void agregar_actor(string nuevo_actor); Lista<string>* obtener_lista_de_actores(); /*void asignar_nombre(string nuevo_nombre); void asignar_director(string nuevo_director); void asignar_genero(string nuevo_genero); void asignar_puntaje(int nuevo_puntaje);*/ }; #endif
Swift
UTF-8
1,678
2.546875
3
[ "MIT" ]
permissive
// // MGJViewController.swift // WLRRoute.swift // // Created by 伯驹 黄 on 2017/3/2. // Copyright © 2017年 伯驹 黄. All rights reserved. // import UIKit var titleWithHandlers: [String: () -> UIViewController] = [:] var titles: [String] = [] class MGJViewController: UITableViewController { static func register(with title: String, handler: @escaping () -> UIViewController) { titles.append(title) titleWithHandlers[title] = handler } override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return titleWithHandlers.keys.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) cell.accessoryType = .disclosureIndicator cell.textLabel?.text = titles[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let controller = titleWithHandlers[titles[indexPath.row]]?() else { return } controller.hidesBottomBarWhenPushed = true navigationController?.pushViewController(controller, animated: true) } }
PHP
UTF-8
4,448
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Core; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Spatie\Permission\Models\Role; use DB; class UserController extends Controller { protected $entity; public function __construct () { $this->middleware('permission:listar usuarios|crear usuarios|editar usuarios|eliminar roles', ['only' => ['index', 'store']]); $this->middleware('permission:crear usuarios', ['only' => ['create', 'store']]); $this->middleware('permission:editar usuarios', ['only' => ['edit', 'update']]); $this->middleware('permission:eliminar usuarios', ['only' => ['destroy']]); $this->entity = app(\App\User::class); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { if ( $request->q ) $data = $this->entity ->where('username', 'like', '%'.$request->q.'%') ->orWhere('email', 'like', '%'.$request->q.'%') ->orWhere('fullname', 'like', '%'.$request->q.'%') ->orderByDesc('created_at')->paginate(12); else $data = $this->entity->orderByDesc('created_at')->paginate(12); return view('admin::core.user.index', [ 'users' => $data, 'q' => $request->q ]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $roles = Role::pluck('name', 'name')->all(); return view('admin::core.user.create', [ 'roles' => $roles ]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(\App\Http\Requests\Core\UserStoreRequest $request) { $user = new $this->entity; $user->username = strtolower($request->username); $user->fullname = $request->fullname; $user->email = $request->email; $user->email_verified_at = now(); $user->password = bcrypt('password_'.$request->username); $user->save(); $information = new \App\Entities\Core\Information(); $information->user_id = $user->id; $information->save(); $user->assignRole($request->roles); session()->flash('message', 'Usuario Registrado Exitosamente'); return redirect()->route('users.index'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $user = $this->entity->find($id); abort_unless($user, 404); return view('admin::core.user.show', [ 'user' => $user ]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $user = $this->entity->find($id); abort_unless($user, 404); $roles = Role::pluck('name', 'name')->all(); return view('admin::core.user.edit', [ 'user' => $user, 'roles' => $roles ]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(\App\Http\Requests\Core\UserUpdateRequest $request, $id) { $user = $this->entity->find($id); $user->username = $request->username; $user->fullname = $request->fullname; $user->email = $request->email; $user->password = bcrypt('password_'.$request->username); $user->status = $request->status; $user->save(); DB::table('model_has_roles')->where('model_id', $id)->delete(); $user->assignRole($request->roles); session()->flash('message', 'Usuario Actualizado Exitosamente'); return redirect()->route('users.index'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
Markdown
UTF-8
1,475
3.171875
3
[ "Apache-2.0" ]
permissive
--- layout: post title: "CSS3画红心" description: "" category: css3 tags: [CSS3] --- 多多的红心: [红心](/red-heart.html) [/red-heart.html](/red-heart.html) ###`红心` <div id="heart">&nbsp;</div> <br/> <style type="text/css"> #heart{ position: relative; width: 300px; height: 270px; } #heart:after, #heart:before{ position: absolute; content: ""; left: 150px; top: 0; width: 150px; height: 240px; background: red; border-radius: 75px 75px 0 0; -webkit-transform: rotate(-45deg); -moz-transform: rotate(-45deg); -webkit-transform-origin: 0 100%; -moz-transform-origin: 0 100%; } #heart:after{ left: 0; -webkit-transform: rotate(45deg); -moz-transform: rotate(45deg); -webkit-transform-origin: 100% 100%; -moz-transform-origin: 100% 100%; } </style> ```css #heart{ position: relative; width: 300px; height: 270px; } #heart:after, #heart:before{ position: absolute; content: ""; left: 150px; top: 0; width: 150px; height: 240px; background: red; border-radius: 75px 75px 0 0; -webkit-transform: rotate(-45deg); -moz-transform: rotate(-45deg); -webkit-transform-origin: 0 100%; -moz-transform-origin: 0 100%; } #heart:after{ left: 0; -webkit-transform: rotate(45deg); -moz-transform: rotate(45deg); -webkit-transform-origin: 100% 100%; -moz-transform-origin: 100% 100%; } ```css
Markdown
UTF-8
42,137
3.046875
3
[]
no_license
--- layout: post title: "Casas de california" date: 2020-08-17 20:12:00 -0500 category: Machine-Learning --- Modelo de Machine Learning que ayuda a predecir el valor de una casa en California dependiendo ciertos factores <!--more--> ## Descripción del conjunto de datos Primeras 5 filas del conjunto de datos ```python housing = pd.read_csv("data/housing.csv") housing.head() ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>longitude</th> <th>latitude</th> <th>housing_median_age</th> <th>total_rooms</th> <th>total_bedrooms</th> <th>population</th> <th>households</th> <th>median_income</th> <th>median_house_value</th> <th>ocean_proximity</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>-122.23</td> <td>37.88</td> <td>41.0</td> <td>880.0</td> <td>129.0</td> <td>322.0</td> <td>126.0</td> <td>8.3252</td> <td>452600.0</td> <td>NEAR BAY</td> </tr> <tr> <th>1</th> <td>-122.22</td> <td>37.86</td> <td>21.0</td> <td>7099.0</td> <td>1106.0</td> <td>2401.0</td> <td>1138.0</td> <td>8.3014</td> <td>358500.0</td> <td>NEAR BAY</td> </tr> <tr> <th>2</th> <td>-122.24</td> <td>37.85</td> <td>52.0</td> <td>1467.0</td> <td>190.0</td> <td>496.0</td> <td>177.0</td> <td>7.2574</td> <td>352100.0</td> <td>NEAR BAY</td> </tr> <tr> <th>3</th> <td>-122.25</td> <td>37.85</td> <td>52.0</td> <td>1274.0</td> <td>235.0</td> <td>558.0</td> <td>219.0</td> <td>5.6431</td> <td>341300.0</td> <td>NEAR BAY</td> </tr> <tr> <th>4</th> <td>-122.25</td> <td>37.85</td> <td>52.0</td> <td>1627.0</td> <td>280.0</td> <td>565.0</td> <td>259.0</td> <td>3.8462</td> <td>342200.0</td> <td>NEAR BAY</td> </tr> </tbody> </table> </div> Información del conjunto de datos ```python housing.info() ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table class="tg"> <thead> <tr> <th class="tg-0lax">#</th> <th class="tg-0lax">Column</th> <th class="tg-0lax">Non-Null Count</th> <th class="tg-0lax">Dtype</th> </tr> </thead> <tbody> <tr> <td class="tg-0lax">0</td> <td class="tg-0lax">longitude</td> <td class="tg-0lax">20640 non-null</td> <td class="tg-0lax">float64</td> </tr> <tr> <td class="tg-0lax">1</td> <td class="tg-0lax">latitude</td> <td class="tg-0lax">20640 non-null</td> <td class="tg-0lax">float64</td> </tr> <tr> <td class="tg-0lax">2</td> <td class="tg-0lax">housing_median_age</td> <td class="tg-0lax">20640 non-null</td> <td class="tg-0lax">float64</td> </tr> <tr> <td class="tg-0lax">3</td> <td class="tg-0lax">total_rooms</td> <td class="tg-0lax">20640 non-null</td> <td class="tg-0lax">float64</td> </tr> <tr> <td class="tg-0lax">4</td> <td class="tg-0lax">total_bedrooms</td> <td class="tg-0lax">20433 non-null</td> <td class="tg-0lax">float64</td> </tr> <tr> <td class="tg-0lax">5</td> <td class="tg-0lax">population</td> <td class="tg-0lax">20640 non-null</td> <td class="tg-0lax">float64</td> </tr> <tr> <td class="tg-0lax">6</td> <td class="tg-0lax">households</td> <td class="tg-0lax">20640 non-null</td> <td class="tg-0lax">float64</td> </tr> <tr> <td class="tg-0lax">7</td> <td class="tg-0lax">median_income</td> <td class="tg-0lax">20640 non-null</td> <td class="tg-0lax">float64</td> </tr> <tr> <td class="tg-0lax">8</td> <td class="tg-0lax">median_house_value</td> <td class="tg-0lax">20640 non-null</td> <td class="tg-0lax">float64</td> </tr> <tr> <td class="tg-0lax">9</td> <td class="tg-0lax">ocean_proximity</td> <td class="tg-0lax">20640 non-null</td> <td class="tg-0lax">object</td> </tr> <tr> <td class="tg-0lax"></td> <td class="tg-0lax"></td> <td class="tg-0lax"></td> <td class="tg-0lax"><b>dtypes</b>: float64(9), object(1)</td> </tr> </tbody> </table> </div> Podemos observar que la columna "total_bedrooms" tiene 207 valores nulos y la columna "ocean_proximity" es de tipo objeto, ya que leímos los datos desde un csv podemos inferir que son de tipo texto. Veremos el contenido de la columna "ocean_proximity" ```python housing['ocean_proximity'].value_counts() ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table class="tg"> <tbody> <tr> <td>1H OCEAN</td> <td>9136</td> </tr> <tr> <td>INLAND</td> <td>6551</td> </tr> <tr> <td>NEAR OCEAN</td> <td>2658</td> </tr> <tr> <td>NEAR BAY</td> <td>2290</td> </tr> <tr> <td>ISLAND</td> <td>5</td> </tr> <tr> <td><b>Name</b>: ocean_proximity</td> <td><b>dtype</b>: int64</td> </tr> </tbody> </table> </div> Al parecer la columna "ocean_proximity" es una variable categórica de 5 niveles Ahora generaremos las estadísticas descriptivas del conjunto de datos ```python housing.describe() ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>longitude</th> <th>latitude</th> <th>housing_median_age</th> <th>total_rooms</th> <th>total_bedrooms</th> <th>population</th> <th>households</th> <th>median_income</th> <th>median_house_value</th> </tr> </thead> <tbody> <tr> <th>count</th> <td>20640.000000</td> <td>20640.000000</td> <td>20640.000000</td> <td>20640.000000</td> <td>20433.000000</td> <td>20640.000000</td> <td>20640.000000</td> <td>20640.000000</td> <td>20640.000000</td> </tr> <tr> <th>mean</th> <td>-119.569704</td> <td>35.631861</td> <td>28.639486</td> <td>2635.763081</td> <td>537.870553</td> <td>1425.476744</td> <td>499.539680</td> <td>3.870671</td> <td>206855.816909</td> </tr> <tr> <th>std</th> <td>2.003532</td> <td>2.135952</td> <td>12.585558</td> <td>2181.615252</td> <td>421.385070</td> <td>1132.462122</td> <td>382.329753</td> <td>1.899822</td> <td>115395.615874</td> </tr> <tr> <th>min</th> <td>-124.350000</td> <td>32.540000</td> <td>1.000000</td> <td>2.000000</td> <td>1.000000</td> <td>3.000000</td> <td>1.000000</td> <td>0.499900</td> <td>14999.000000</td> </tr> <tr> <th>25%</th> <td>-121.800000</td> <td>33.930000</td> <td>18.000000</td> <td>1447.750000</td> <td>296.000000</td> <td>787.000000</td> <td>280.000000</td> <td>2.563400</td> <td>119600.000000</td> </tr> <tr> <th>50%</th> <td>-118.490000</td> <td>34.260000</td> <td>29.000000</td> <td>2127.000000</td> <td>435.000000</td> <td>1166.000000</td> <td>409.000000</td> <td>3.534800</td> <td>179700.000000</td> </tr> <tr> <th>75%</th> <td>-118.010000</td> <td>37.710000</td> <td>37.000000</td> <td>3148.000000</td> <td>647.000000</td> <td>1725.000000</td> <td>605.000000</td> <td>4.743250</td> <td>264725.000000</td> </tr> <tr> <th>max</th> <td>-114.310000</td> <td>41.950000</td> <td>52.000000</td> <td>39320.000000</td> <td>6445.000000</td> <td>35682.000000</td> <td>6082.000000</td> <td>15.000100</td> <td>500001.000000</td> </tr> </tbody> </table> </div> Graficaremos un histograma de cada columna ```python housing.hist(bins=50, figsize=(20,15)) plt.show() ``` ![png](/images/end-to-end/end-to-end-1.png) Se pueden observar varias cosas en estos histogramas 1. El ingreso medio no parece expresado en dolares. Los datos fueron escalados y limitados a 15 para grandes ingresos medios, y a 5 para los ingresos medios más bajos. Los números representan decenas de miles de dolares. 2. La edad media de la vivienda y el valor medio de la vivienda también fueron limitados. 3. Los atributos tienen escalas muy diferentes. 4. Varios histogramas tienen una larga cola: Se extienden más a la derecha de la mediana que a la izquierda. ## Crear conjunto de pruebas Segmentaremos y clasificaremos la columna "median_income" en 5 contenedores. De esta forma crearemos una columna categórica que nos servirá para separar los datos equitativamente. ```python housing["income_cat"] = pd.cut(housing["median_income"], bins=[0., 1.5, 3.0, 4.5, 6., np.inf], labels=[1, 2, 3, 4, 5]) ``` ```python housing["income_cat"].value_counts() ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <tbody> <tr> <td>3</td> <td>7236</td> </tr> <tr> <td>2</td> <td>6581</td> </tr> <tr> <td>4</td> <td>3639</td> </tr> <tr> <td>5</td> <td>2362</td> </tr> <tr> <td>1</td> <td>822</td> </tr> <tr> <td><b>Name</b>: income_cat</td> <td><b>dtype</b>: int64</td> </tr> </tbody> </table> </div> Ahora crearemos separaremos el conjunto de pruebas usando la nueva columna categórica. ```python from sklearn.model_selection import StratifiedShuffleSplit split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42) for train_index, test_index in split.split(housing, housing["income_cat"]): strat_train_set = housing.loc[train_index] strat_test_set = housing.loc[test_index] ``` Comprobaremos que ambos conjuntos tienen la misma proporción de ingresos medios. ```python strat_test_set["income_cat"].value_counts() / len(strat_test_set) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <tbody> <tr> <td>3</td> <td>0.350533</td> </tr> <tr> <td>2</td> <td>0.318798</td> </tr> <tr> <td>4</td> <td>0.176357</td> </tr> <tr> <td>5</td> <td>0.114583</td> </tr> <tr> <td>1</td> <td>0.039729</td> </tr> <tr> <td><b>Name</b>: income_cat</td> <td><b>dtype</b>: float64</td> </tr> </tbody> </table> </div> ```python housing["income_cat"].value_counts() / len(housing) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <tbody> <tr> <td>3</td> <td>0.350581</td> </tr> <tr> <td>2</td> <td>0.318847</td> </tr> <tr> <td>4</td> <td>0.176308</td> </tr> <tr> <td>5</td> <td>0.114438</td> </tr> <tr> <td>1</td> <td>0.039826</td> </tr> <tr> <td><b>Name</b>: income_cat</td> <td><b>dtype</b>: float64</td> </tr> </tbody> </table> </div> Podemos observar que ambos conjuntos tienen una proporción similar. Procederemos a eliminar la columna categórica que creamos. ```python for set_ in (strat_train_set, strat_test_set): set_.drop("income_cat", axis=1, inplace=True) ``` ## Visualizar los datos ```python housing = strat_train_set.copy() ``` ```python housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4, s=housing["population"]/100, label="population", figsize=(10,7), c="median_house_value", cmap=plt.get_cmap("jet"), colorbar=True, ) plt.legend(); ``` ![png](/images/end-to-end/end-to-end-2.png) Podemos apreciar que las casas con un mayor precio están ubicadas cerca de la costa ## Buscar correlaciones ```python corr_matrix = housing.corr() ``` ```python corr_matrix["median_house_value"].sort_values(ascending=False) ``` El coeficiente de correlación se distribuye de -1 a 1, si el valor es cercano a -1 significa que dos columnas tienen una correlación negativa, si es cercano a 1 significa que dos columnas tienen una correlación positiva, si el valor es 0 significa que no existe una correlación entre las dos columnas. <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <tbody> <tr> <td>median_house_value</td> <td>1.000000</td> </tr> <tr> <td>median_income</td> <td>0.687160</td> </tr> <tr> <td>total_rooms</td> <td>0.135097</td> </tr> <tr> <td>housing_median_age</td> <td>0.114110</td> </tr> <tr> <td>households</td> <td>0.064506</td> </tr> <tr> <td>total_bedrooms</td> <td>0.047689</td> </tr> <tr> <td>population</td> <td>-0.026920</td> </tr> <tr> <td>longitude</td> <td>-0.047432</td> </tr> <tr> <td>latitude</td> <td>-0.142724</td> </tr> <tr> <td>Name: median_house_value</td> <td>dtype: float64</td> </tr> </tbody> </table> </div> Ya que "median_house_value" es la columna que estamos evaluando da 1 exacto, la columna que tiene una mayor correlación es "median_income" lo que nos dice que las casas con un mayor precio en un vecindario son aquellas cuyos residentes tienen un ingreso medio mayor. Graficaremos las 3 columnas con una mayor correlación, para intentar apreciarlo mejor ```python from pandas.plotting import scatter_matrix attributes = ["median_house_value", "median_income", "total_rooms", "housing_median_age"] scatter_matrix(housing[attributes], figsize=(12, 8)); ``` ![png](/images/end-to-end/end-to-end-3.png) Ahora nos centraremos a la gráfica con una mayor correlación "median_house_value" ```python housing.plot(kind="scatter", x="median_income", y="median_house_value", alpha=0.1); ``` ![png](/images/end-to-end/end-to-end-4.png) Esta gráfica revela unas cuantas cosas. Primero, la correlación es muy fuerte; puedes ver claramente la tendencia y los puntos no están muy dispersos. Segundo, el límite de precio es claramente visible como una línea horizontal a los \\$500,000, pero también se revelan otras líneas menos obvias: una línea horizontal alrededor de \\$450,000, otra alrededor de \\$350,000, y tal vez una alrededor de \\$280,000 y algunas debajo de eso. ## Experimentar con combinaciones de atributos Crearemos nuevas columnas para intentar buscar algunas con mayor correlación ```python housing["rooms_per_household"] = housing["total_rooms"]/housing["households"] housing["bedrooms_per_room"] = housing["total_bedrooms"]/housing["total_rooms"] housing["population_per_household"]=housing["population"]/housing["households"] ``` ```python corr_matrix = housing.corr() corr_matrix["median_house_value"].sort_values(ascending=False) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <tbody> <tr> <td>median_house_value</td> <td>1.000000</td> </tr> <tr> <td>median_income</td> <td>0.687160</td> </tr> <tr> <td>rooms_per_household</td> <td>0.146285</td> </tr> <tr> <td>total_rooms</td> <td>0.135097</td> </tr> <tr> <td>housing_median_age</td> <td>0.114110</td> </tr> <tr> <td>households</td> <td>0.064506</td> </tr> <tr> <td>total_bedrooms</td> <td>0.047689</td> </tr> <tr> <td>population_per_household</td> <td>-0.021985</td> </tr> <tr> <td>population</td> <td>-0.026920</td> </tr> <tr> <td>longitude</td> <td>-0.047432</td> </tr> <tr> <td>latitude</td> <td>-0.142724</td> </tr> <tr> <td>bedrooms_per_room</td> <td>-0.259984</td> </tr> <tr> <td><b>Name</b>: median_house_value</td> <td><b>dtype</b>: float64</td> </tr> </tbody> </table> </div> El nuevo atributo "bedrooms_per_room" está más correlacionado con el valor medio de las viviendas que el número de habitaciones o dormitorios. Aparentemente casas con un ratio dormitorios/habitaciones más bajo tienden a ser más caras. El atributo "rooms_per_household" es más informativo que el total de habitaciones en un distrito - obviamente las casas más grandes son más caras ## Preparar los datos ```python housing = strat_train_set.drop("median_house_value", axis=1) housing_labels = strat_train_set["median_house_value"].copy() ``` ### Limpieza de datos Primero nos encargaremos de los valores nulos, rellenaremos esos valores con la mediana de la columna ```python from sklearn.impute import SimpleImputer imputer = SimpleImputer(strategy="median") ``` Ya que el SimpleImputer solo puede trabajar con valores numéricos retiraremos la columnas no numéricas ```python housing_num = housing.drop("ocean_proximity", axis=1) ``` Ahora crearemos el imputer ```python imputer.fit(housing_num) ``` Valores que usará el imputer para rellenar las columnas ```python imputer.statistics_ ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <thead> <tr> <td>-118.51</td> <td>34.26</td> <td>29.0</td> <td>2119.5</td> <td>433.0</td> <td>1164.0</td> <td>408.0</td> <td>3.5409</td> </tr> </thead> </table> </div> Aplicaremos el imputer ```python X = imputer.transform(housing_num) ``` ```python housing_tr = pd.DataFrame(X, columns=housing_num.columns) ``` Ahora nos encargaremos de las columnas categóricas, en este caso "ocean_proximity" ```python housing_cat = housing[["ocean_proximity"]] ``` ```python housing_cat.head(10) ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: left;"> <th></th> <th>ocean_proximity</th> </tr> </thead> <tbody> <tr> <th>17606</th> <td>&lt;1H OCEAN</td> </tr> <tr> <th>18632</th> <td>&lt;1H OCEAN</td> </tr> <tr> <th>14650</th> <td>NEAR OCEAN</td> </tr> <tr> <th>3230</th> <td>INLAND</td> </tr> <tr> <th>3555</th> <td>&lt;1H OCEAN</td> </tr> <tr> <th>19480</th> <td>INLAND</td> </tr> <tr> <th>8879</th> <td>&lt;1H OCEAN</td> </tr> <tr> <th>13685</th> <td>INLAND</td> </tr> <tr> <th>4937</th> <td>&lt;1H OCEAN</td> </tr> <tr> <th>4861</th> <td>&lt;1H OCEAN</td> </tr> </tbody> </table> </div> Usaremos el algoritmo OneHotEncoder para crear una columna por cada nivel de la variable categórica, si una fila pertenece a un nivel entonces el valor que tendrá en la columna será 1 en otro caso será 0 ```python from sklearn.preprocessing import OneHotEncoder cat_encoder = OneHotEncoder() housing_cat_1hot = cat_encoder.fit_transform(housing_cat) ``` Crearemos una clase que nos permita automatizar la inclusion de la nueva columna que creamos anteriormente, gracias a esta clase podremos darnos una idea si perjudica o ayuda al modelo. ```python from sklearn.base import BaseEstimator, TransformerMixin # column index rooms_ix, bedrooms_ix, population_ix, households_ix = 3, 4, 5, 6 class CombinedAttributesAdder(BaseEstimator, TransformerMixin): def __init__(self, add_bedrooms_per_room = True): # no *args or **kargs self.add_bedrooms_per_room = add_bedrooms_per_room def fit(self, X, y=None): return self # nothing else to do def transform(self, X): rooms_per_household = X[:, rooms_ix] / X[:, households_ix] population_per_household = X[:, population_ix] / X[:, households_ix] if self.add_bedrooms_per_room: bedrooms_per_room = X[:, bedrooms_ix] / X[:, rooms_ix] return np.c_[X, rooms_per_household, population_per_household, bedrooms_per_room] else: return np.c_[X, rooms_per_household, population_per_household] attr_adder = CombinedAttributesAdder(add_bedrooms_per_room=False) housing_extra_attribs = attr_adder.transform(housing.values) ``` Le echaremos un vistazo a la nueva tabla ```python housing_extra_attribs = pd.DataFrame( housing_extra_attribs, columns=list(housing.columns)+["rooms_per_household", "population_per_household"], index=housing.index) housing_extra_attribs.head() ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>longitude</th> <th>latitude</th> <th>housing_median_age</th> <th>total_rooms</th> <th>total_bedrooms</th> <th>population</th> <th>households</th> <th>median_income</th> <th>ocean_proximity</th> <th>rooms_per_household</th> <th>population_per_household</th> </tr> </thead> <tbody> <tr> <th>17606</th> <td>-121.89</td> <td>37.29</td> <td>38</td> <td>1568</td> <td>351</td> <td>710</td> <td>339</td> <td>2.7042</td> <td>&lt;1H OCEAN</td> <td>4.62537</td> <td>2.0944</td> </tr> <tr> <th>18632</th> <td>-121.93</td> <td>37.05</td> <td>14</td> <td>679</td> <td>108</td> <td>306</td> <td>113</td> <td>6.4214</td> <td>&lt;1H OCEAN</td> <td>6.00885</td> <td>2.70796</td> </tr> <tr> <th>14650</th> <td>-117.2</td> <td>32.77</td> <td>31</td> <td>1952</td> <td>471</td> <td>936</td> <td>462</td> <td>2.8621</td> <td>NEAR OCEAN</td> <td>4.22511</td> <td>2.02597</td> </tr> <tr> <th>3230</th> <td>-119.61</td> <td>36.31</td> <td>25</td> <td>1847</td> <td>371</td> <td>1460</td> <td>353</td> <td>1.8839</td> <td>INLAND</td> <td>5.23229</td> <td>4.13598</td> </tr> <tr> <th>3555</th> <td>-118.59</td> <td>34.23</td> <td>17</td> <td>6592</td> <td>1525</td> <td>4459</td> <td>1463</td> <td>3.0347</td> <td>&lt;1H OCEAN</td> <td>4.50581</td> <td>3.04785</td> </tr> </tbody> </table> </div> Crearemos una pipeline que nos permita hacer todo el pre-procesamiento anterior de una forma más cómoda, primero nos enfocaremos a las columnas numéricas, aprovecharemos para estadarizar los valores de las columnas. ```python from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler num_pipeline = Pipeline([ ('imputer', SimpleImputer(strategy="median")), ('attribs_adder', CombinedAttributesAdder()), ('std_scaler', StandardScaler()), ]) housing_num_tr = num_pipeline.fit_transform(housing_num) ``` Ahora crearemos una pipeline para todo el conjunto de datos ```python from sklearn.compose import ColumnTransformer num_attribs = list(housing_num) cat_attribs = ["ocean_proximity"] full_pipeline = ColumnTransformer([ ("num", num_pipeline, num_attribs), ("cat", OneHotEncoder(), cat_attribs), ]) housing_prepared = full_pipeline.fit_transform(housing) ``` ## Seleccionar un modelo y entrenarlo ### Entrenamiento y evaluación en el conjunto de entrenamiento Probaremos varios modelos para encontrar el que tenga mejores resultados Primero intentaremos con un modelo de regresión lineal ```python from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(housing_prepared, housing_labels) ``` Intentaremos hacer unas cuantas predicciones con este modelo ```python # let's try the full preprocessing pipeline on a few training instances some_data = housing.iloc[:5] some_labels = housing_labels.iloc[:5] some_data_prepared = full_pipeline.transform(some_data) print("Predictions:", lin_reg.predict(some_data_prepared)) print("Labels:", list(some_labels)) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <thead> <tr> <th>Predictions</th> <td>210644.60</td> <td>317768.80</td> <td>210956.43</td> <td>59218.98</td> <td>189747.55</td> </tr> </thead> <tbody> <tr> <th>Labels</th> <td>286600.00</td> <td>340600.00</td> <td>196900.00</td> <td>46300.00</td> <td>254500.00</td> </tr> </tbody> </table> </div> Ahora que tenemos tanto los valores predichos como los valores reales usaremos algunas métricas para evaluar el rendimiento del modelo Primero provaremos el error medio cuadrado ```python from sklearn.metrics import mean_squared_error housing_predictions = lin_reg.predict(housing_prepared) lin_mse = mean_squared_error(housing_labels, housing_predictions) lin_rmse = np.sqrt(lin_mse) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <thead> <tr> <th>lin_rmse</th> <td>68628.19</td> </tr> </thead> </table> </div> Ahora probaremos con el error medio absoluto ```python from sklearn.metrics import mean_absolute_error lin_mae = mean_absolute_error(housing_labels, housing_predictions) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <thead> <tr> <th>lin_mae</th> <td>49439.89</td> </tr> </thead> </table> </div> Ahora probaremos un árbol de decisión ```python from sklearn.tree import DecisionTreeRegressor tree_reg = DecisionTreeRegressor(random_state=42) tree_reg.fit(housing_prepared, housing_labels) ``` Ya que tenemos el modelo creado lo usaremos para hacer predicciones y verificar su rendimiento ```python housing_predictions = tree_reg.predict(housing_prepared) tree_mse = mean_squared_error(housing_labels, housing_predictions) tree_rmse = np.sqrt(tree_mse) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <thead> <tr> <th>tree_rmse</th> <td>0.00</td> </tr> </thead> </table> </div> El cuadrado medio nos dio un resultado 0, lo cual significa que el modelo acertó todas las predicciones, sin embargo esto puede implicar que el modelo se haya sobreajustado, lo que nos dice que aunque haya acertado en el conjunto de entrenamiento es posible que falle con nueva información ### Evaluación usando Cross validation Ya que el modelo parece que sobreajustó las predicciones usaremos un algoritmo que divide el conjunto en cierto número de partes iguales, en nuestro caso lo dividiremos en 10 partes, entonces entrena el modelo con 9 de las partes y hace las predicciones con la parte restante, esto la hará 10 veces, tomando diferentes partes cada vez. ```python from sklearn.model_selection import cross_val_score scores = cross_val_score(tree_reg, housing_prepared, housing_labels, scoring="neg_mean_squared_error", cv=10) tree_rmse_scores = np.sqrt(-scores) ``` Ya que tenemos calculados los valores los imprimiremos ```python def display_scores(scores): print("Scores:", scores) print("Mean:", scores.mean()) print("Standard deviation:", scores.std()) display_scores(tree_rmse_scores) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <tbody> <tr> <th>Scores</th> <td>70194.33</td> <td>66855.16</td> <td>72432.58</td> <td>70758.73</td> <td>71115.88</td> </tr> <tr> <th></th> <td>75585.14</td> <td>70262.86</td> <td>70273.63</td> <td>75366.87</td> <td>71231.65</td> </tr> <tr> <th>Mean</th> <td>71407.68</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <th>Standard deviation</th> <td>2439.43</td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> Haremos lo mismo con la regresión lineal ```python lin_scores = cross_val_score(lin_reg, housing_prepared, housing_labels, scoring="neg_mean_squared_error", cv=10) lin_rmse_scores = np.sqrt(-lin_scores) display_scores(lin_rmse_scores) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <tbody> <tr> <th>Scores</th> <td>66782.73</td> <td>66960.11</td> <td>70347.95</td> <td>74739.57</td> <td>68031.13</td> </tr> <tr> <th></th> <td>71193.84</td> <td>64969.63</td> <td>68281.61</td> <td>71552.91</td> <td>67665.10</td> </tr> <tr> <th>Mean</th> <td>69052.46</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <th>Standard deviation</th> <td>2731.67</td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> Ahora probaremos un bosque aleatorio ```python from sklearn.ensemble import RandomForestRegressor forest_reg = RandomForestRegressor(n_estimators=100, random_state=42) forest_reg.fit(housing_prepared, housing_labels) ``` ```python housing_predictions = forest_reg.predict(housing_prepared) forest_mse = mean_squared_error(housing_labels, housing_predictions) forest_rmse = np.sqrt(forest_mse) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <tbody> <tr> <th>forest_rmse</th> <td>18603.51</td> </tr> </tbody> </table> </div> ```python from sklearn.model_selection import cross_val_score forest_scores = cross_val_score(forest_reg, housing_prepared, housing_labels, scoring="neg_mean_squared_error", cv=10) forest_rmse_scores = np.sqrt(-forest_scores) display_scores(forest_rmse_scores) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <tbody> <tr> <th>Scores</th> <td>49519.80</td> <td>47461.91</td> <td>50029.02</td> <td>52325.28</td> <td>49308.39</td> </tr> <tr> <th></th> <td>53446.37</td> <td>48634.80</td> <td>47585.73</td> <td>53490.10</td> <td>50021.58</td> </tr> <tr> <th>Mean</th> <td>50182.30</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <th>Standard deviation</th> <td>2097.08</td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> Parece ser que el modelo que mejor rindió fue el del bosque aleatorio Ahora que tenemos nuestro modelo lo afinaremos para que de mejores resultados, para eso usaremos GridSearchCV para encontrar el valor de los hyper-parametros más adecuado ```python from sklearn.model_selection import GridSearchCV param_grid = [ # try 12 (3×4) combinations of hyperparameters {'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]}, # then try 6 (2×3) combinations with bootstrap set as False {'bootstrap': [False], 'n_estimators': [3, 10], 'max_features': [2, 3, 4]}, ] forest_reg = RandomForestRegressor(random_state=42) # train across 5 folds, that's a total of (12+6)*5=90 rounds of training grid_search = GridSearchCV(forest_reg, param_grid, cv=5, scoring='neg_mean_squared_error', return_train_score=True) grid_search.fit(housing_prepared, housing_labels) ``` Ahora veremos cual es la mejor combinación de hyper-parametros ```python grid_search.best_params_ ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <tbody> <tr> <th>max_features</th> <td>8</td> </tr> <tr> <th>n_estimators</th> <td>30</td> </tr> <tr> <th>bootstrap</th> <td>True</td> </tr> </tbody> </table> </div> Calcularemos el error medio cuadrado para cada combinación de hyper-parametros para verificar que la combinación sea correcta ```python cvres = grid_search.cv_results_ for mean_score, params in zip(cvres["mean_test_score"], cvres["params"]): print(np.sqrt(-mean_score), params) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <thead> <tr> <th>mean_squared_error</th> <th>bootstrap</th> <th>max_features</th> <th>n_estimators</th> </tr> </thead> <tbody> <tr> <td>63669.11</td> <td>True</td> <td>2</td> <td>3</td> </tr> <tr> <td>55627.09</td> <td>True</td> <td>2</td> <td>10</td> </tr> <tr> <td>53384.57</td> <td>True</td> <td>2</td> <td>30</td> </tr> <tr> <td>60965.95</td> <td>True</td> <td>4</td> <td>3</td> </tr> <tr> <td>52741.04</td> <td>True</td> <td>4</td> <td>10</td> </tr> <tr> <td>50377.40</td> <td>True</td> <td>4</td> <td>30</td> </tr> <tr> <td>58663.93</td> <td>True</td> <td>6</td> <td>3</td> </tr> <tr> <td>52006.19</td> <td>True</td> <td>6</td> <td>10</td> </tr> <tr> <td>50146.51</td> <td>True</td> <td>6</td> <td>30</td> </tr> <tr> <td>57869.25</td> <td>True</td> <td>8</td> <td>3</td> </tr> <tr> <td>51711.12</td> <td>True</td> <td>8</td> <td>10</td> </tr> <tr> <td>49682.27</td> <td>True</td> <td>8</td> <td>30</td> </tr> <tr> <td>62895.06</td> <td>False</td> <td>2</td> <td>3</td> </tr> <tr> <td>54658.17</td> <td>False</td> <td>2</td> <td>10</td> </tr> <tr> <td>59470.40</td> <td>False</td> <td>3</td> <td>3</td> </tr> <tr> <td>52724.98</td> <td>False</td> <td>3</td> <td>10</td> </tr> <tr> <td>57490.56</td> <td>False</td> <td>4</td> <td>3</td> </tr> <tr> <td>51009.49</td> <td>False</td> <td>4</td> <td>10</td> </tr> </tbody> </table> </div> Ahora buscaremos las columnas que aportan más al modelo, en otras palabras, las columnas que afectan más al precio de una vivienda ```python feature_importances = grid_search.best_estimator_.feature_importances_ feature_importances ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <tbody> <tr> <th>feature_importances</th> <td>7.334e-02</td> <td>6.290e-02</td> <td>4.114e-02</td> <td>1.467e-02</td> </tr> <tr> <td></td> <td>1.410e-02</td> <td>1.487e-02</td> <td>1.425e-02</td> <td>3.661e-01</td> </tr> <tr> <td></td> <td>5.641e-02</td> <td>1.087e-01</td> <td>5.335e-02</td> <td>1.031e-02</td> </tr> <tr> <td></td> <td>1.647e-01</td> <td>6.028e-05</td> <td>1.960e-03</td> <td>2.856e-03</td> </tr> </tbody> </table> </div> Obtuvimos lo que afecta cada columna en el precio, sin embargo nos falta anotar cada columna con su valor. ```python extra_attribs = ["rooms_per_hhold", "pop_per_hhold", "bedrooms_per_room"] #cat_encoder = cat_pipeline.named_steps["cat_encoder"] # old solution cat_encoder = full_pipeline.named_transformers_["cat"] cat_one_hot_attribs = list(cat_encoder.categories_[0]) attributes = num_attribs + extra_attribs + cat_one_hot_attribs sorted(zip(feature_importances, attributes), reverse=True) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <tbody> <tr> <td>0.3661</td> <td>median_income</td> </tr> <tr> <td>0.1647</td> <td>INLAND</td> </tr> <tr> <td>0.1087</td> <td>pop_per_hhold</td> </tr> <tr> <td>0.0733</td> <td>longitude</td> </tr> <tr> <td>0.0629</td> <td>latitude</td> </tr> <tr> <td>0.0564</td> <td>rooms_per_hhold</td> </tr> <tr> <td>0.0533</td> <td>bedrooms_per_room</td> </tr> <tr> <td>0.0411</td> <td>housing_median_age</td> </tr> <tr> <td>0.0148</td> <td>population</td> </tr> <tr> <td>0.0146</td> <td>total_rooms</td> </tr> <tr> <td>0.0142</td> <td>households</td> </tr> <tr> <td>0.0141</td> <td>total_bedrooms</td> </tr> <tr> <td>0.0103</td> <td>&lt;1H OCEAN</td> </tr> <tr> <td>0.0028</td> <td>NEAR OCEAN</td> </tr> <tr> <td>0.0019</td> <td>NEAR BAY</td> </tr> <tr> <td>6.0280e-05</td> <td>ISLAND</td> </tr> </tbody> </table> </div> Ahora probaremos nuestro modelo con el conjunto de pruebas que separamos en un principio ```python final_model = grid_search.best_estimator_ X_test = strat_test_set.drop("median_house_value", axis=1) y_test = strat_test_set["median_house_value"].copy() X_test_prepared = full_pipeline.transform(X_test) final_predictions = final_model.predict(X_test_prepared) final_mse = mean_squared_error(y_test, final_predictions) final_rmse = np.sqrt(final_mse) ``` <div class="table-wrapper"> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table> <tbody> <tr> <th>final_rmse</th> <td>47730.22</td> </tr> </tbody> </table> </div> El resultado final nos dice que nuestro modelo puede predecir el valor de una casa en California con un margen de error de $47,730.22 Para ver el repositorio completo [¡Click aquí!](https://github.com/KevinDaniel-S/MachineLearning/tree/master/Proyecto%20de%20Punta%20a%20punta)
C++
UTF-8
740
2.84375
3
[]
no_license
#ifndef REPLAYMEMORY_H #define REPLAYMEMORY_H #include "crabtensor.h" /** Experience: 5-tuple (state_1, action_1, reward, state_2, action_2) */ typedef struct Experience{ CRAbTensor state1, state2; int action1, action2; CRAbTensor reward; bool empty; }Experience; class ReplayMemory{ public: ReplayMemory(int size); bool push(CRAbTensor state1, int action1, CRAbTensor reward, CRAbTensor state2, int action2); Experience pop(); Experience * getAll(); Experience operator [](int index); int memorySize(); int * sample(int miniBatchSize); int * sampleByReward(int miniBatchSize); private: Experience * list; int size, front, rear, queueSize; }; #endif // REPLAYMEMORY_H
Python
UTF-8
1,634
2.984375
3
[]
no_license
import unittest from unittest import mock from datetime import datetime from ..reader import FileReader # ListReader, HTTPReader from ..reader import HTTPReader class FileReaderTest(unittest.TestCase): @mock.patch("builtins.open", mock.mock_open(read_data=""" GOOG,2014-02-11T14:10:22.13,5 AAPL,2014-02-11T00:00:00.0,8 """)) def test_FileReader_returns_the_file_content(self): reader = FileReader("stocks.txt") updater = reader.get_updates() update = next(updater) self.assertEqual(("GOOG", datetime(2014, 2,11,14,10, 22, 130000), 5), update) import re class HTTPReaderSyntaxTest(unittest.TestCase): def assert_has_correct_syntax(self, entry): """ Verify that we have a string, datetime-type object and valid digits """ if re.match("[\w]*", entry[0]) is None: raise self.failureException("Wrong symbol: {}".format(entry[0])) if not isinstance(entry[1], datetime): raise self.failureException("Wrong symbol: {}".format(entry[0])) if re.match("[\d]*", str(entry[2])) is None: raise self.failureException("Wrong symbol: {}".format(entry[2])) class HTTPReaderTest(HTTPReaderSyntaxTest): # def testHTTPReader_returns_valid_format1(self): # reader = HTTPReader(["GOOG"]) # updater = reader.get_updates() # update = next(updater) # self.assertEqual(("GOOG", datetime(2015, 5,29,20,0), 532), update) def testHTTPReader_returns_valid_format2(self): reader = HTTPReader(["GOOG"]) updater = reader.get_updates() update = next(updater) self.assert_has_correct_syntax(update)
JavaScript
UTF-8
1,036
3.296875
3
[]
no_license
function weatherBalloon( cityZIP ) { var key = '{yourkey}'; fetch('https://api.openweathermap.org/data/2.5/weather?zip=' + cityZIP+ '&appid=' + "f13d8c523b86e058f40d4b5332b9edca") .then(function(resp) { return resp.json() }) // Convert data to json .then(function(data) { drawWeather(data); }) .catch(function() { // catch any errors }); } window.onload = function() { var zip = window.prompt("Enter your ZIP: "); alert("Your ZIP is " + zip); weatherBalloon(zip); } function drawWeather( d ) { var min_celcius = Math.round(parseFloat(d.main.temp_min)-273.15); var max_celcius = Math.round(parseFloat(d.main.temp_max)-273.15); document.getElementById('main').innerHTML = d.weather[0].main; document.getElementById('description').innerHTML = d.weather[0].description; document.getElementById('min_temp').innerHTML = min_celcius + '&deg;'; document.getElementById('max_temp').innerHTML = max_celcius + '&deg;'; document.getElementById('location').innerHTML = d.name; }
C++
UTF-8
315
3.296875
3
[]
no_license
//program to add digit of number #include<stdio.h> #include<conio.h> int main() { int num,sum=0,dig; printf("enter a five digit number ="); scanf("%d",&num); while(num!=0) { dig=num%10; sum=sum+dig; num=num/10; } printf("sum of digits=%d ",sum); getch(); }
Java
UTF-8
403
2.0625
2
[]
no_license
package com.jyannis.serviceb; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @RestController public class TestController { /** * 上传文件 * @param file * @return */ @PostMapping("/upload") public String upload(@RequestPart("file") MultipartFile file){ return file.getOriginalFilename(); } }
Java
UTF-8
3,220
1.609375
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.xfinity.playnow; import android.content.pm.ApplicationInfo; import com.comcast.cim.android.application.AppUpgradeHelper; import com.comcast.cim.config.CALConfiguration; import com.comcast.cim.container.CALContainer; import com.comcast.cim.container.PlayerContainer; import com.xfinity.playerlib.PlayerApplication; import com.xfinity.playerlib.config.DeveloperConfiguration; import com.xfinity.playerlib.config.PlayerConfiguration; import com.xfinity.playnow.config.DenverStagingConfiguration; import com.xfinity.playnow.config.MrQaConfiguration; import com.xfinity.playnow.config.ProductionConfiguration; import com.xfinity.playnow.config.SprintQaConfiguration; import com.xfinity.playnow.config.StagingConfiguration; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // Referenced classes of package com.xfinity.playnow: // PlayNowAppUpgradHelper public class PlayNowContainer extends PlayerContainer { private static final Logger LOG = LoggerFactory.getLogger(com/xfinity/playnow/PlayNowContainer); private static String configVersion = ""; private PlayerConfiguration configuration; public PlayNowContainer(PlayerApplication playerapplication) { super(playerapplication); } public static void initialize(PlayerApplication playerapplication) { com/xfinity/playnow/PlayNowContainer; JVM INSTR monitorenter ; instance = new PlayNowContainer(playerapplication); CALContainer.setInstance(instance); com/xfinity/playnow/PlayNowContainer; JVM INSTR monitorexit ; return; playerapplication; throw playerapplication; } public AppUpgradeHelper createAppUpgradeHelper() { return new PlayNowAppUpgradHelper(getApplication(), userManager, getSharedPreferences(), downloadsManager, getPersistentEntityCache(), getPersistentCaptionsCache(), getVideoBookmarkDAO()); } public List getAvailableConfigurations() { ArrayList arraylist = new ArrayList(); arraylist.add(new ProductionConfiguration()); arraylist.add(new StagingConfiguration()); arraylist.add(new DenverStagingConfiguration()); arraylist.add(new SprintQaConfiguration()); arraylist.add(new MrQaConfiguration()); return arraylist; } public volatile CALConfiguration getConfiguration() { return getConfiguration(); } public PlayerConfiguration getConfiguration() { if (configuration == null) { if ((getApplication().getApplicationInfo().flags & 2) != 0) { configuration = new DeveloperConfiguration(getAvailableConfigurations(), new ProductionConfiguration(), getSharedPreferences()); } else { configuration = new ProductionConfiguration(); } } return configuration; } public String getConfigurationVersion() { return configVersion; } }
Swift
UTF-8
1,444
2.8125
3
[]
no_license
// // ContentView.swift // Tiles // // Created by soohong ahn on 2021/07/20. // import SwiftUI struct ContentView: View { var body: some View { NavigationView{ GeometryReader { geometry in ZStack { Image("background") .resizable() .aspectRatio(geometry.size, contentMode: .fill) .edgesIgnoringSafeArea(.all) VStack { Spacer() Image("mainLogo") .resizable() .frame(width: 300, height: 300, alignment: .center) Spacer() NavigationLink( destination: GameView(), label:{ Image("playButton") .frame(width: 200, height: 50, alignment: .center) }) NavigationLink( destination: AboutView(), label:{ Image("aboutButton") .frame(width: 200, height: 50, alignment: .center) }) Spacer() } } } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { Group { ContentView() } } }
Java
GB18030
386
2.71875
3
[]
no_license
package cn.hj_01; class Fu{ public void show(){ System.out.println("ǾԴ,κ˲÷ !"); } } class Zi extends Fu{ public void show(){ System.out.println("һ"); } } public class ZiDemo { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Zi z = new Zi(); z.show(); } }
Java
UTF-8
5,883
2.453125
2
[]
no_license
/* * AppUtil.java * v1.0 * July 2019 * Copyright ©2019 Footprnt Inc. */ package com.example.footprnt.Util; import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Environment; import android.text.format.DateUtils; import android.util.Log; import android.widget.Toast; import com.example.footprnt.R; import com.google.android.gms.maps.model.LatLng; import org.json.JSONArray; import org.json.JSONException; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; /** * Utility functions used throughout application * * @author Clarisa Leu, Jocelyn Shen * @version 1.0 * @since 2019-07-22 */ public class AppUtil { /** * Helper function to determine if there is network connection * * @param context * @return true if there is connection, false otherwise */ public static boolean haveNetworkConnection(Context context) { boolean haveConnectedWifi = false; boolean haveConnectedMobile = false; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] netInfo = cm.getAllNetworkInfo(); for (NetworkInfo ni : netInfo) { if (ni.getTypeName().equalsIgnoreCase("WIFI")) if (ni.isConnected()) haveConnectedWifi = true; if (ni.getTypeName().equalsIgnoreCase("MOBILE")) if (ni.isConnected()) haveConnectedMobile = true; } return haveConnectedWifi || haveConnectedMobile; } /** * Helper method to parse JSONArray into ArrayList of Strings * * @param arr to parse * @return arr as ArrayList of Strings */ public static ArrayList<String> parseJSONArray(JSONArray arr) throws JSONException { ArrayList<String> list = new ArrayList<>(); if (arr == null) { return new ArrayList<>(); } for (int i = 0; i < arr.length(); i++) { list.add(arr.getString(i)); } return list; } /** * Helper method to check if valid email * * @param email * @return true if valid email, false otherwise */ public static boolean isValidEmail(String email) { String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\." + "[a-zA-Z0-9_+&*-]+)*@" + "(?:[a-zA-Z0-9-]+\\.)+[a-z" + "A-Z]{2,7}$"; Pattern pat = Pattern.compile(emailRegex); if (email == null) return false; return pat.matcher(email).matches(); } /** * Helper function to get the photo file uri * * @param context * @param fileName * @return photo file Uri */ public static File getPhotoFileUri(Context context, String fileName) { File mediaStorageDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), String.valueOf(R.string.app_name)); if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) { Log.d(String.valueOf(R.string.app_name), "failed to create directory"); } File file = new File(mediaStorageDir.getPath() + File.separator + fileName); return file; } /** * Helper function to get address from point * * @param context * @param point with latitude and longitude * @return address */ public static String getAddress(Context context, LatLng point) { try { Geocoder geo = new Geocoder(context, Locale.getDefault()); List<Address> addresses = geo.getFromLocation(point.latitude, point.longitude, 1); if (addresses.isEmpty()) { return "Waiting for location..."; } else { if (addresses.size() > 0) { String address = (addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() + ", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName()); address = address.replaceAll(" null,", ""); address = address.replaceAll(", null", ""); return address; } } } catch (Exception e) { e.printStackTrace(); // getFromLocation() may sometimes fail return null; } return null; } /** * Gets the relative date of post * * @param rawJsonDate raw data from parse object * @return relative time ago */ public static String getRelativeTimeAgo(String rawJsonDate) { SimpleDateFormat sf = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy", Locale.ENGLISH); sf.setLenient(true); String relativeDate = ""; try { long dateMillis = sf.parse(rawJsonDate).getTime(); relativeDate = DateUtils.getRelativeTimeSpanString(dateMillis, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS).toString(); } catch (java.text.ParseException e) { e.printStackTrace(); } return relativeDate; } /** * Helper method to handle errors, log them, and alert user * * @param context context of where error is * @param TAG filter for logcat * @param message message to displace * @param error error that occurred * @param alertUser alert the user or not */ public static void logError(Context context, String TAG, String message, Throwable error, boolean alertUser) { Log.e(TAG, message, error); if (alertUser) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } } }
PHP
UTF-8
714
2.921875
3
[ "MIT" ]
permissive
<?php namespace Lamoda\Metric\Storage; /** * @internal */ final class StorageRegistry { /** @var array MetricStorageInterface[] */ private $storages = []; public function register(string $name, MetricStorageInterface $storage): void { $this->storages[$name] = $storage; } /** * @param string $name * * @return MetricStorageInterface * * @throws \OutOfBoundsException */ public function getStorage(string $name): MetricStorageInterface { if (!array_key_exists($name, $this->storages)) { throw new \OutOfBoundsException('Unknown storage in registry: ' . $name); } return $this->storages[$name]; } }
Python
UTF-8
187
2.71875
3
[]
no_license
from sense_hat import SenseHat from time import sleep while True: sense = SenseHat() sense.clear() temp = sense.get_temperature_from_pressure() print(temp) sleep(5)
Python
UTF-8
2,024
2.546875
3
[ "Apache-2.0" ]
permissive
# Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. # # WSO2 Inc. licenses this file to you 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. import unittest import logging logging.basicConfig(level=logging.INFO) from PySiddhi.DataTypes.LongType import LongType from PySiddhi.core.event.Event import Event class BasicTests(unittest.TestCase): def test_data(self): logging.info("Test GetData and SetData Methods") event = Event(1, [2, LongType(3)]) self.assertListEqual(event.getData(), [2, LongType(3)], "GetData not equal to data given in constructor") self.assertTrue(type(event.getData(1)) == LongType, "Type of Parameter is not LongType") event.setData([1, 2]) self.assertListEqual(event.getData(), [1, 2], "GetData not equal to data set by SetData") def test_copyFromAndToString(self): logging.info("Test CopyFrom and ToString methods") event = Event(1, [2, LongType(3)]) event2 = Event(2) event2.copyFrom(event) self.assertEqual(str(event), str(event2), "ToString forms of copy is not equal") def test_Equals(self): logging.info("Test CopyFrom and ToString methods") event = Event(1, [2, LongType(3)]) event2 = Event(1, [2, LongType(3)]) self.assertEqual(event, event2, "Copy is not equal") event2 = Event(1, [2, 3]) self.assertNotEqual(event, event2, "Should not be equal due to Type diference") if __name__ == '__main__': unittest.main()
TypeScript
UTF-8
921
3.421875
3
[ "MIT" ]
permissive
export const levels = { debug: Symbol('debug'), info: Symbol('info'), clear: Symbol('clear'), }; export function createLogger( onLog: (level: 'info' | 'debug', ...messages: string[]) => void, onClear: () => void ) { return function log(...messages: any[]) { const clear = messages[messages.length - 1] === levels.clear; if (clear) { onClear(); return; } const info = messages[messages.length - 1] === levels.info; const debug = messages[messages.length - 1] === levels.debug; if (info || debug) { messages.pop(); } onLog(info ? 'info' : 'debug', ...messages); }; } export type Log = (...args: [...any[]]) => void; export function createDefaultLogger() { return createLogger( (level, ...messages) => level === 'info' && console.log(...messages), console.clear ); }
Go
UTF-8
12,026
2.8125
3
[ "MIT" ]
permissive
package main import ( "fmt" "io/ioutil" "log" "net/http" "os" "strings" "encoding/json" "bytes" "time" "sync" ) type Key struct { Encoding string `json:"encoding"` Data string `json:"data"` } type Value struct { Encoding string `json:"encoding"` Data string `json:"data"` } type MyData struct { Key `json:"key"` Value `json:"value"` } type MyDatas struct { dataList MyData } type ErrorResponse struct { RCode int RMessage string } type SetResponse struct { KeysFailed []Key `json:"keys_failed"` KeysAdded int `json:"keys_added"` } type MakeQueryRequest struct { Encoding string `json:"encoding"` Data string `json:"data"` } type QueryResponse struct { Value bool `json:"value"` Key struct { Data string `json:"data"` Encoding string `json:"encoding"` } `json:"key"` } type FetchResponse struct { Value struct { Data string `json:"data"` Encoding string `json:"encoding"` } `json:"value"` Key struct { Data string `json:"data"` Encoding string `json:"encoding"` } `json:"key"` } var url string const SUCCESS int = 200 const PARTIAL_SUCCESS int = 206 const INTERNAL_SERVER_ERROR int = 500 const OTHER_ERROR int = 501 func handler(w http.ResponseWriter, r *http.Request, total_servers int, server_list []string, ip_list []string, port_list []string) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Headers", "X-Requested-With") contents, _ := ioutil.ReadAll(r.Body) if (r.URL.Path == "/set") { set_handler(w, r, total_servers, ip_list, port_list, contents) } else if (r.URL.Path == "/fetch" && r.Method == "POST") { fetch_handler(w, r, total_servers, ip_list, port_list, contents) } else if (r.URL.Path == "/fetch" && r.Method == "GET") { fetch_handler_all(w, r, total_servers, ip_list, port_list) } else if (r.URL.Path == "/query") { query_handler(w, r, total_servers, ip_list, port_list, contents) } else { error_handler(w, &ErrorResponse{RCode: OTHER_ERROR, RMessage: "invalid_api_key"}) } } func fetch_handler_all(w http.ResponseWriter, r *http.Request, total_servers int, ip_list []string, port_list []string) { var i = 0 resps := make([]*http.Response, 0) respsChan := make(chan *http.Response) var wg sync.WaitGroup wg.Add(total_servers) for i < total_servers { url = strings.Join([]string{"http://", string(ip_list[i]), ":", string(port_list[i]), r.URL.Path}, "") response, err := http.NewRequest("GET", url, nil) if err != nil { os.Exit(2) } else { go func(response *http.Request) { defer wg.Done() response.Header.Set("Content-Type", "application/json") client := &http.Client{} resp_received, err := client.Do(response) if err != nil { panic(err) } else { respsChan <- resp_received } time.Sleep(time.Second * 2) }(response) } i++ } go func() { for response := range respsChan { resps = append(resps, response) } }() wg.Wait() send_message, r_code := format_fetch_response(resps) success_handler(w, send_message, r_code) } func query_handler_jsonToObj(total_servers int, contents []uint8) (map[int][]MakeQueryRequest, int) { var d []MakeQueryRequest err1 := json.Unmarshal(contents, &d) if err1 != nil { os.Exit(1) } server_ele := 0 struct_map := make(map[int][]MakeQueryRequest) for _, elem := range d { temp_struct := MakeQueryRequest{ Encoding: elem.Encoding, Data: elem.Data, } index := hash_function(elem.Data) % total_servers struct_map[index] = append(struct_map[index], temp_struct) server_ele ++ } return struct_map, server_ele } func query_handler(w http.ResponseWriter, r *http.Request, total_servers int, ip_list []string, port_list []string, contents []uint8) { struct_map, _ := query_handler_jsonToObj(total_servers, contents) i := 0 var wg sync.WaitGroup wg.Add(len(struct_map)) respsChan := make(chan *http.Response) resps := make([]*http.Response, 0) for i < total_servers { if val, ok := struct_map[i]; ok { json_obj, _ := json.Marshal(val) url = strings.Join([]string{"http://", string(ip_list[i]), ":", string(port_list[i]), r.URL.Path}, "") response, err := http.NewRequest("POST", url, bytes.NewBuffer(json_obj)) if err != nil { os.Exit(2) } else { go func(response *http.Request) { defer response.Body.Close() defer wg.Done() response.Header.Set("Content-Type", "application/json") client := &http.Client{} resp_received, err := client.Do(response) if err != nil { panic(err) } else { respsChan <- resp_received } time.Sleep(time.Second * 2) }(response) } } i++ } go func() { for response := range respsChan { resps = append(resps, response) } }() wg.Wait() send_message, r_code := format_query_response(resps) success_handler(w, send_message, r_code) } func format_query_response(responses []*http.Response) ([]byte, int) { output := make([]QueryResponse, 0) code := SUCCESS for _, response := range responses { if response.StatusCode >= SUCCESS { body, error := ioutil.ReadAll(response.Body) if error != nil { log.Fatal(error) } var back_response []QueryResponse json.Unmarshal(body, &back_response) output = append(output, back_response...) } else { code = PARTIAL_SUCCESS } response.Body.Close() } body, err := json.Marshal(output) if err != nil { return nil, INTERNAL_SERVER_ERROR } return body, code } func fetch_handler_jsonToObj(total_servers int, contents []uint8) (map[int][]MakeQueryRequest, int) { var d []MakeQueryRequest err1 := json.Unmarshal(contents, &d) if err1 != nil { os.Exit(1) } server_ele := 0 struct_map := make(map[int][]MakeQueryRequest) for _, elem := range d { temp_struct := MakeQueryRequest{ Encoding: elem.Encoding, Data: elem.Data, } index := hash_function(elem.Data) % total_servers struct_map[index] = append(struct_map[index], temp_struct) server_ele ++ } return struct_map, server_ele } func fetch_handler(w http.ResponseWriter, r *http.Request, total_servers int, ip_list []string, port_list []string, contents []uint8) { struct_map, _ := fetch_handler_jsonToObj(total_servers, contents) i := 0 var wg sync.WaitGroup wg.Add(len(struct_map)) respsChan := make(chan *http.Response) resps := make([]*http.Response, 0) for i < total_servers { if val, ok := struct_map[i]; ok { json_obj, _ := json.Marshal(val) url = strings.Join([]string{"http://", string(ip_list[i]), ":", string(port_list[i]), r.URL.Path}, "") response, err := http.NewRequest("POST", url, bytes.NewBuffer(json_obj)) if err != nil { os.Exit(2) } else { go func(response *http.Request) { defer response.Body.Close() defer wg.Done() response.Header.Set("Content-Type", "application/json") client := &http.Client{} resp_received, err := client.Do(response) if err != nil { panic(err) } else { respsChan <- resp_received } time.Sleep(time.Second * 2) }(response) } } i++ } go func() { for response := range respsChan { resps = append(resps, response) } }() wg.Wait() send_message, r_code := format_fetch_response(resps) success_handler(w, send_message, r_code) } func format_fetch_response(responses []*http.Response) ([]byte, int) { output := make([]FetchResponse, 0) code := SUCCESS for _, response := range responses { if response.StatusCode >= SUCCESS { body, error := ioutil.ReadAll(response.Body) if error != nil { log.Fatal(error) } var back_response []FetchResponse json.Unmarshal(body, &back_response) output = append(output, back_response...) } else { code = PARTIAL_SUCCESS } response.Body.Close() } body, err := json.Marshal(output) if err != nil { return nil, INTERNAL_SERVER_ERROR } return body, code } func set_handler_jsonToObj(total_servers int, contents []uint8) (map[int][]MyData, int) { var d []MyData err1 := json.Unmarshal(contents, &d) if err1 != nil { os.Exit(1) } server_ele := 0 struct_map := make(map[int][]MyData) for _, elem := range d { temp_struct := MyData{ Key: Key{ Encoding: elem.Key.Encoding, Data: elem.Key.Data, }, Value: Value{ Encoding: elem.Value.Encoding, Data: elem.Value.Data, }, } index := hash_function(elem.Key.Data) % total_servers struct_map[index] = append(struct_map[index], temp_struct) server_ele ++ } return struct_map, server_ele } func set_handler(w http.ResponseWriter, r *http.Request, total_servers int, ip_list []string, port_list []string, contents []uint8) { struct_map, _ := set_handler_jsonToObj(total_servers, contents) i := 0 var wg sync.WaitGroup wg.Add(len(struct_map)) respsChan := make(chan *http.Response) resps := make([]*http.Response, 0) for i < total_servers { if val, ok := struct_map[i]; ok { json_obj, _ := json.Marshal(val) url = strings.Join([]string{"http://", string(ip_list[i]), ":", string(port_list[i]), r.URL.Path}, "") response, err := http.NewRequest(http.MethodPut, url, bytes.NewBuffer(json_obj)) if err != nil { os.Exit(2) } else { go func(response *http.Request) { defer response.Body.Close() defer wg.Done() response.Header.Set("Content-Type", "application/json") client := &http.Client{} resp_received, err := client.Do(response) if err != nil { panic(err) } else { respsChan <- resp_received } time.Sleep(time.Second * 2) }(response) } } i++ } go func() { for response := range respsChan { resps = append(resps, response) } }() wg.Wait() send_message, r_code := format_set_response(resps) success_handler(w, send_message, r_code) } func format_set_response(responses []*http.Response) ([]byte, int) { failed_map := make([]Key, 0) count_of_keys := 0 code := SUCCESS for _, response := range responses { if response.StatusCode >= SUCCESS { body, error := ioutil.ReadAll(response.Body) if error != nil { log.Fatal(error) } var back_response SetResponse json.Unmarshal(body, &back_response) count_of_keys += back_response.KeysAdded failed_map = append(failed_map, back_response.KeysFailed...) } else { code = PARTIAL_SUCCESS } response.Body.Close() } res := SetResponse{KeysAdded: count_of_keys, KeysFailed: failed_map} if len(failed_map) > 0 { code = PARTIAL_SUCCESS } body, err := json.Marshal(res) if err != nil { return nil, INTERNAL_SERVER_ERROR } return body, code } func success_handler(w http.ResponseWriter, reply []byte, code int) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) w.Write(reply) } func error_handler(w http.ResponseWriter, e *ErrorResponse) { resp, error := json.Marshal(e) if error != nil { http.Error(w, error.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(e.RCode) w.Write(resp) } func hash_function(str string) (int) { i := 0 sum := 0 for i = 0; i < len(str); i++ { sum = sum + int(str[i]) } return sum } func distribute_servers(length int, server_list []string) ([]string, []string) { var ip_list = make([]string, length) var port_list = make([]string, length) for i := 0; i < length; i++ { ip_port := strings.Split(server_list[i], ":") ip_list[i] = ip_port[0] port_list[i] = ip_port[1] } return ip_list, port_list } func main() { arg := os.Args[1:] server_list := arg[1:] total_servers := len(server_list) ip_list, port_list := distribute_servers(total_servers, server_list) if arg[0] != "-p" { fmt.Println("Incorrect flag variable, exiting....") return } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { handler(w, r, total_servers, server_list, ip_list, port_list) }) fmt.Println("Proxy up and running!!!") err := http.ListenAndServe("localhost:8500", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
TypeScript
UTF-8
4,635
2.71875
3
[]
no_license
import { TMTaskQueue } from '../task-mng'; import { EDEventDispatcher } from '../event-dispatcher'; import { WizardStage } from './wizard-stage'; export type WizFlagCallback = () => boolean; export type WizNextStageCallback = (stage: WizardStage) => WizardStage; export type WizStageNavOutEnabledCallback = (stage: WizardStage) => boolean; export type WizStageIsCompleteCallback = (stage: WizardStage) => boolean; export type WizScenario = string[]; /** * Can be used to trigger a hook in the stage component when prev/next is triggered. * If the callback returns false, navigation is prevented. */ export type WizStageNavOutHookCallback = (stage: WizardStage) => boolean; /** * "External Function" - Call only by passing it to Wizard.callExternalFunction() to prevent the wizard from getting stuck due to uncaught Errors in the external script */ export type WizStageSubmitCallback = () => boolean | Promise<boolean>; export type WizardEventName = 'init' | 'dirty' | 'goTo' | 'stageStateChange' | 'wizardComplete'; export abstract class WizardBase extends TMTaskQueue { protected _nav: WizNavStrategy; protected _ev: EDEventDispatcher; protected _dirty = false; protected _init = false; _debug = false; abstract currentStage: WizardStage; constructor(navStrategy: WizNavStrategyConstructor) { super(); this._nav = wizCreateNavStrategy(navStrategy, () => this.onNavInit()); let allowedEvents: WizardEventName[] = ['init', 'dirty', 'goTo', 'stageStateChange', 'wizardComplete']; this._ev = new EDEventDispatcher(allowedEvents); } set debug(val: boolean) { this._debug = this._nav.debug = Boolean(val); } get debug() { return this._debug; } protected onNavInit() { if (this._init) return; this._init = true; if (this.debug) { console.log('Wizard.onNavInit: Initialized.'); } this._ev.notifyListeners('init'); this._ev.notifyListeners('goTo', this.currentStage); } protected setDirty(dirty = true) { this._dirty = dirty; } static callExternalFunction(func: () => any): any | Promise<any> { try { return func(); } catch (e) { setTimeout(() => { throw e });//rethrow 'e' after the return when synchronous functions fail return false; } } } /** * isNavigateable?: boolean - If stage can be navigated to directly (not by next/prev command). */ export interface WizardStageData { id: string; label?: string; isNavigateable?: boolean; contentData?: any; nextStage?: WizardStage; complete?: boolean; } /** * allowForward?: boolean - Overrides forward navigation prohibition, which is inforced by WizNavStrategy.setCurrentStage. * Forward navigation refers to direct navigation beyond 'maxReachedStage'. * In order to display wizard progreess, forward navigation requires all stage labels to be set before navigating forward. * force?: boolean - Wizard: overrides isNavigateableStage result. * strategy classes: overrides checking prevDisabled/nextDisabled. */ export interface WizNavOpts { allowForward?: boolean; force?: boolean; } //nav strategy export interface WizNavStrategyConstructor { new(_onInit?: () => void): WizNavStrategy; } export function wizCreateNavStrategy(ctor: WizNavStrategyConstructor, _onInit?: () => void): WizNavStrategy { return new ctor(_onInit); } export interface WizNavStrategy { length: number; currentStageIndex: number; currentStage: WizardStage; maxReachedStage: WizardStage; prevStage: WizardStage; nextStage: WizardStage; hasPrevStage: boolean; hasNextStage: boolean; isInFirstStage: boolean; isInLastStage: boolean; prevDisabled: boolean; prevEnabled: boolean; nextDisabled: boolean; nextEnabled: boolean; debug: boolean; setStages(stages: WizardStageData[]): Promise<WizardStage[]>; getStages(): WizardStage[]; getStage(stageId: string): WizardStage; hasStage(stageId: string): boolean; hasStageInCurrentScenario(stageId: string): boolean; getFirstStage(): WizardStage; getLastStage(): WizardStage; isFirstStage(stageId: string): boolean; isLastStage(stageId: string): boolean; setCurrentStage(stageId: string, opts: WizNavOpts): Promise<boolean>; setScenario(scenario?: WizScenario): Promise<boolean>; getScenario(): WizScenario; start(data: WizScenario | string): Promise<WizardStage | boolean>; prev(opts: WizNavOpts): Promise<WizardStage | false>; next(opts: WizNavOpts): Promise<WizardStage | false>; getProgress(to: 'current' | 'maxReached'): WizardStage[]; resetMaxReachedStage(): void; } //nav strategy
Go
UTF-8
2,633
2.578125
3
[]
no_license
package ffmpeg import ( "errors" "fmt" "github.com/cute-angelia/go-utils/syntax/icmd" "github.com/cute-angelia/go-utils/syntax/itime" "math/rand" "regexp" "strconv" "strings" "time" ) func (c Component) cutOne(sec string, mp4path string, savePic string) error { status := icmd.Exec(c.config.FfmpegPath, []string{ "-loglevel", "error", "-y", "-ss", sec, "-t", "1", "-i", mp4path, "-vframes", "1", savePic, }, c.config.Timeout) // log.Println(ijson.Pretty(status)) if len(status.Stderr) > 0 { err := errors.New(strings.Join(status.Stderr, "")) return err } return nil } // 截取视频第几秒图片 func (c *Component) GetCutPictureOneRandom(mp4path string, savePic string) error { rand.Seed(time.Now().UnixNano()) videoLen, _ := c.GetVideoLength(mp4path) cutsec := rand.Intn(videoLen) sec := strconv.Itoa(cutsec) return c.cutOne(sec, mp4path, savePic) } func (c *Component) GetCutPictureOne(mp4path string, cutsec int, savePic string) error { videoLen, _ := c.GetVideoLength(mp4path) if cutsec > videoLen { return errors.New(fmt.Sprintf("视频长度(%d)小于剪辑秒数(%d)", videoLen, cutsec)) } sec := strconv.Itoa(cutsec) return c.cutOne(sec, mp4path, savePic) } // 截取视频图片,按x秒 func (c *Component) GetCutPictures(mp4path string, cutsec int, saveDir string) error { var outputerror string videoLen, _ := c.GetVideoLength(mp4path) for i := 0; i < videoLen; i = i + cutsec { sec := strconv.Itoa(i) status := icmd.Exec(c.config.FfmpegPath, []string{ "-loglevel", "error", "-y", "-ss", sec, "-t", "1", "-i", mp4path, "-vframes", "1", saveDir + "/" + strings.Join(itime.ConvertVideoSecToStr(int64(i)), "-") + ".jpg", }, c.config.Timeout) // log.Println(ijson.Pretty(status)) if len(status.Stderr) > 0 { outputerror += strings.Join(status.Stderr, "") } } return errors.New(outputerror) } // 获取视频时长 s func (c *Component) GetVideoLength(mp4path string) (int, error) { var length int // 查询长度 status := icmd.Exec(c.config.FfmpegPath, []string{ "-i", mp4path, }, c.config.Timeout) // Duration: 00:22:08.60 video_length_regexp, _ := regexp.Compile(`Duration: (\d\d:\d\d:\d\d).\d\d`) str := video_length_regexp.FindStringSubmatch(strings.Join(status.Stderr, "")) if len(str) > 0 { // str = "2006-01-02" + strings.TrimPrefix(str, "Duration:") strtime := "2006-01-02 " + str[1] if videotime, err := time.Parse("2006-01-02 15:04:05", strtime); err != nil { length = 0 } else { length = videotime.Hour()*3600 + videotime.Minute()*60 + videotime.Second() } } return length, nil }
Markdown
UTF-8
2,669
3.34375
3
[]
no_license
# Read: 08 - OO Design **SOLID - First 5 Principles of Object Oriented Design** * *SOLID* - acronym for the first five object-oriented design principles, and it stands for: - S - Single-responsiblity Principle - This principle states that a class should have one and only one reason to change, in other words a class should have only one job. - O - Open-closed Principle - This principle states that objects or entities should be open for extension but closed for modification. A class should be extendable without modifying the class itself. - L - Liskov Substitution Principle - This principle states that let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T. The meaning of this statement is that every subclass or derived class should be substitutable for their base or parent class. - I - Interface Segregation Principle - This principle states that a client should never be forced to implement an interface that it doesn’t use, or clients shouldn’t be forced to depend on methods they do not use. - D - Dependency Inversion Principle - This principle states that entities must depend on abstractions, not on concretions. It states that the high-level module must not depend on the low-level module, but they should depend on abstractions. Also this allows for decoupling. **SOLID principles in real life** * S - single responsibility principle - class or module should have only one reason to change - Real life example - the "duck" vehicle are street legal and water-capable, and they only change from driving on land to going out on the water, and from being driven in the water to land. * O - open/closed principle - a class that does what it needs to flawlessly and does not need to be changed later, but can be extended. - Real life example - a smart phone that doesn't need to be changed itself, but you can add apps on the phone. * L - liskov substitution principle - any child type of a parent type should be able to stand in for that parent - Real life example - Cooking stew with various ingredients in the stew, while asking if the ingredients are edible or not. * I - interface segregation principle - don't want to force clients to depend on things they don't actually need - Real life example - The soup of the day on a menu at a restuarant. The reason why it only says soup of the day is because it changes everyday. * D - dependency inversion - depends upon abstractions rather than upon concrete details - Real life example - Using a credit card to pay groceries with, and the clerk swiping your credit card with a visa machine.
Markdown
UTF-8
2,259
3.84375
4
[]
no_license
# 1073 多选题常见计分法 (20分) 批改多选题是比较麻烦的事情,有很多不同的计分方法。有一种最常见的计分方法是:如果考生选择了部分正确选项,并且没有选择任何错误选项,则得到50%分数;如果考生选择了任何一个错误的选项,则不能得分。本题就请你写个程序帮助老师批改多选题,并且指出哪道题的哪个选项错的人最多。 ## 输入格式: 输入在第一行给出两个正整数$N(≤1000)$和$M(≤100)$,分别是学生人数和多选题的个数。随后$M$行,每行顺次给出一道题的满分值(不超过5的正整数)、选项个数(不少于2且不超过5的正整数)、正确选项个数(不超过选项个数的正整数)、所有正确选项。注意每题的选项从小写英文字母`a`开始顺次排列。各项间以1个空格分隔。最后$N$行,每行给出一个学生的答题情况,其每题答案格式为`(选中的选项个数 选项1 ……)`,按题目顺序给出。注意:题目保证学生的答题情况是合法的,即不存在选中的选项数超过实际选项数的情况。 ## 输出格式: 按照输入的顺序给出每个学生的得分,每个分数占一行,输出小数点后1位。最后输出错得最多的题目选项的信息,格式为:`错误次数 题目编号(题目按照输入的顺序从1开始编号)-选项号`。如果有并列,则每行一个选项,按题目编号递增顺序输出;再并列则按选项号递增顺序输出。行首尾不得有多余空格。如果所有题目都没有人错,则在最后一行输出`Too simple`。 ## 输入样例1: ``` 3 4 3 4 2 a c 2 5 1 b 5 3 2 b c 1 5 4 a b d e (2 a c) (3 b d e) (2 a c) (3 a b e) (2 a c) (1 b) (2 a b) (4 a b d e) (2 b d) (1 e) (1 c) (4 a b c d) ``` ## 输出样例1: ``` 3.5 6.0 2.5 2 2-e 2 3-a 2 3-b ``` ## 输入样例2: ``` 2 2 3 4 2 a c 2 5 1 b (2 a c) (1 b) (2 a c) (1 b) ``` ## 输出样例2: ``` 5.0 5.0 Too simple ``` ## 思路 这题比较复杂,题目要求的是“所有 错了‘所有题中所有选项错了最多的选项’错的次数 的选项”而不是“错的最多的题的错的最多的选项”。超时的话多提交一次。
Shell
UTF-8
896
2.953125
3
[]
no_license
#!/bin/bash #SBATCH -n 8 # Number of cores #SBATCH -N 1 # Ensure that all cores are on one machine #SBATCH -t 0-01:00 # Runtime in D-HH:MM #SBATCH -p serial_requeue # Partition to submit to #SBATCH --mem-per-cpu=1000 # Memory pool for all cores (see also --mem-per-cpu) #SBATCH -o ./logs/provR%j.out # File to which STDERR will be written #SBATCH -e ./logs/provR%j.err # File to which STDERR will be written # tell odyssey where to look for R libraries export R_LIBS_USER=$HOME/apps/R:$R_LIBS_USER # echo the doi to the error file echo $2 >&2 doi_direct="$1/$2" # suppress R output by redirecting to /dev/null echo "Attempting to run and generate data provenance for raw R scripts in dataset..." Rscript --default-packages=methods,datasets,utils,grDevices,graphics,stats \ get_dataset_reprod.R $doi_direct "n" &> /dev/null
Java
UTF-8
5,530
2.296875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2019-2020 The Polypheny Project * * 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. * * This file incorporates code covered by the following terms: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you 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. */ package org.polypheny.db.plan; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Utilities for {@link Context}. */ public class Contexts { public static final EmptyContext EMPTY_CONTEXT = new EmptyContext(); private Contexts() { } /** * Returns a context that returns null for all inquiries. */ public static Context empty() { return EMPTY_CONTEXT; } /** * Returns a context that wraps an object. * * A call to {@code unwrap(C)} will return {@code target} if it is an instance of {@code C}. */ public static Context of( Object o ) { return new WrapContext( o ); } /** * Returns a context that wraps an array of objects, ignoring any nulls. */ public static Context of( Object... os ) { final List<Context> contexts = new ArrayList<>(); for ( Object o : os ) { if ( o != null ) { contexts.add( of( o ) ); } } return chain( contexts ); } /** * Returns a context that wraps a list of contexts. * * A call to {@code unwrap(C)} will return the first object that is an instance of {@code C}. * * If any of the contexts is a {@link Context}, recursively looks in that object. Thus this method can be used to chain contexts. */ public static Context chain( Context... contexts ) { return chain( ImmutableList.copyOf( contexts ) ); } private static Context chain( Iterable<? extends Context> contexts ) { // Flatten any chain contexts in the list, and remove duplicates final List<Context> list = new ArrayList<>(); for ( Context context : contexts ) { build( list, context ); } switch ( list.size() ) { case 0: return empty(); case 1: return list.get( 0 ); default: return new ChainContext( ImmutableList.copyOf( list ) ); } } /** * Recursively populates a list of contexts. */ private static void build( List<Context> list, Context context ) { if ( context == EMPTY_CONTEXT || list.contains( context ) ) { return; } if ( context instanceof ChainContext ) { ChainContext chainContext = (ChainContext) context; for ( Context child : chainContext.contexts ) { build( list, child ); } } else { list.add( context ); } } /** * Context that wraps an object. */ private static class WrapContext implements Context { final Object target; WrapContext( Object target ) { this.target = Objects.requireNonNull( target ); } @Override public <T> T unwrap( Class<T> clazz ) { if ( clazz.isInstance( target ) ) { return clazz.cast( target ); } return null; } } /** * Empty context. */ public static class EmptyContext implements Context { @Override public <T> T unwrap( Class<T> clazz ) { return null; } } /** * Context that wraps a chain of contexts. */ private static final class ChainContext implements Context { final ImmutableList<Context> contexts; ChainContext( ImmutableList<Context> contexts ) { this.contexts = Objects.requireNonNull( contexts ); for ( Context context : contexts ) { assert !(context instanceof ChainContext) : "must be flat"; } } @Override public <T> T unwrap( Class<T> clazz ) { for ( Context context : contexts ) { final T t = context.unwrap( clazz ); if ( t != null ) { return t; } } return null; } } }
Java
UTF-8
6,408
2.1875
2
[]
no_license
// // Translated by CS2J (http://www.cs2j.com): 2015-12-12 7:53:49 PM // package ApexEngine.Rendering; import java.util.HashMap; import ApexEngine.Math.Vector2f; import ApexEngine.Math.Vector3f; import ApexEngine.Math.Vector4f; public class Material { public static final String MATERIAL_NAME = "matname"; public static final String MATERIAL_ALPHADISCARD = "alpha_discard"; public static final String MATERIAL_BLENDMODE = "blendmode"; // 0 = opaque, 1 = transparent public static final String MATERIAL_DEPTHTEST = "depthtest"; public static final String MATERIAL_DEPTHMASK = "depthmask"; public static final String MATERIAL_FACETOCULL = "cullface"; // 0 = back, 1 = front public static final String MATERIAL_CULLENABLED = "cullenable"; public static final String MATERIAL_CASTSHADOWS = "cast_shadows"; public static final String COLOR_DIFFUSE = "diffuse"; public static final String COLOR_SPECULAR = "specular"; public static final String COLOR_AMBIENT = "ambient"; public static final String TEXTURE_DIFFUSE = "diffuse_map"; public static final String TEXTURE_NORMAL = "normal_map"; public static final String TEXTURE_SPECULAR = "specular_map"; public static final String TEXTURE_HEIGHT = "height_map"; public static final String TEXTURE_ENV = "env_map"; public static final String SPECULAR_EXPONENT = "spec_exponent"; public static final String SHININESS = "shininess"; public static final String ROUGHNESS = "roughness"; public static final String METALNESS = "metalness"; public static final String TECHNIQUE_SPECULAR = "spec_technique"; public static final String TECHNIQUE_PER_PIXEL_LIGHTING = "per_pixel_lighting"; private Vector2f tmpVec2 = new Vector2f(); private Vector3f tmpVec3 = new Vector3f(); private Vector4f tmpVec4 = new Vector4f(); public HashMap<String, Object> values = new HashMap<String, Object>(); protected ApexEngine.Rendering.RenderManager.Bucket bucket = ApexEngine.Rendering.RenderManager.Bucket.Opaque; private Shader shader, depthShader, normalsShader; public Material() { setValue(COLOR_DIFFUSE, new Vector4f(1.0f)); setValue(COLOR_SPECULAR, new Vector4f(1.0f)); setValue(COLOR_AMBIENT, new Vector4f(0.0f)); setValue(TECHNIQUE_SPECULAR, 1); setValue(TECHNIQUE_PER_PIXEL_LIGHTING, 1); setValue(SHININESS, 0.5f); setValue(ROUGHNESS, 0.2f); setValue(METALNESS, 0.0f); setValue(SPECULAR_EXPONENT, 20f); setValue(MATERIAL_BLENDMODE, 0); setValue(MATERIAL_CASTSHADOWS, 1); setValue(MATERIAL_DEPTHMASK, true); setValue(MATERIAL_DEPTHTEST, true); setValue(MATERIAL_ALPHADISCARD, 0.1f); setValue(MATERIAL_CULLENABLED, true); setValue(MATERIAL_FACETOCULL, 0); } public HashMap<String, Object> getValues() { return values; } public Material setName(String name) { return setValue(MATERIAL_NAME, name); } public String getName() { return getString(MATERIAL_NAME); } public ApexEngine.Rendering.RenderManager.Bucket getBucket() { return bucket; } public void setBucket(ApexEngine.Rendering.RenderManager.Bucket value) { bucket = value; } public Material setValue(String name, Object val) { if (values.containsKey(name)) { values.put(name, val); return this; } values.put(name, val); return this; } public Object getValue(String name) { if (values.containsKey(name)) return values.get(name); else return null; } public Texture getTexture(String name) { Object obj = getValue(name); if (obj != null && obj instanceof Texture) { return (Texture) obj; } return null; } public String getString(String name) { Object obj = getValue(name); if (obj != null && obj instanceof String) { return (String) obj; } return ""; } public int getInt(String name) { Object obj = getValue(name); if (obj != null && obj instanceof Integer) { return (Integer) obj; } return 0; } public boolean getBool(String name) { Object obj = getValue(name); if (obj != null) { if (obj instanceof Boolean) { return (Boolean) obj; } else if (obj instanceof Integer) { return (Integer) obj != 0; } else if (obj instanceof Float) { return (Float) obj != 0.0f; } } return false; } public float getFloat(String name) { Object obj = getValue(name); if (obj != null && obj instanceof Float) { return (Float) obj; } return 0.0f; } public Vector2f getVector2f(String name) { Object obj = getValue(name); if (obj != null && obj instanceof Vector2f) { return (Vector2f) obj; } return tmpVec2; } public Vector3f getVector3f(String name) { Object obj = getValue(name); if (obj != null && obj instanceof Vector3f) { return (Vector3f) obj; } return tmpVec3; } public Vector4f getVector4f(String name) { Object obj = getValue(name); if (obj != null && obj instanceof Vector4f) { return (Vector4f) obj; } return tmpVec4; } public Shader getShader() { return shader; } public void setShader(Shader value) { shader = value; } public Shader getDepthShader() { return depthShader; } public void setDepthShader(Shader value) { depthShader = value; } public Shader getNormalsShader() { return normalsShader; } public void setNormalsShader(Shader value) { normalsShader = value; } public Material clone() { Material res = new Material(); res.setBucket(this.getBucket()); res.setShader(this.getShader()); res.setDepthShader(this.getDepthShader()); res.setNormalsShader(this.getNormalsShader()); for (String str : values.keySet()) { res.setValue(str, values.get(str)); } return res; } }
C++
UTF-8
926
3.609375
4
[]
no_license
//Nearest greatest right #include <iostream> #include <bits/stdc++.h> using namespace std; void findNGR(int arr[], int size); int main(){ int size; cout << "Enter the size of array :"; cin >> size; int arr[size]; for(int i = 0; i < size; i++){ cin >> arr[i]; } findNGR(arr, size); return 0; } void findNGR(int arr[], int size){ stack<int> s; vector<int> v; for(int i = size-1; i >= 0; i--){ if(s.empty()){ v.push_back(-1); }else if(s.top() > arr[i]){ v.push_back(s.top()); }else{ while(!s.empty() && s.top() <= arr[i]){ s.pop(); } if(s.empty()){ v.push_back(-1); }else{ v.push_back(s.top()); } } s.push(arr[i]); } for(int i = size-1; i>=0; i--){ cout << v.at(i) << " "; } }
Java
UTF-8
1,138
3.328125
3
[]
no_license
import java.util.*; public class C4Q43 { public static void main(String... args) { BTree root = BTree.createInstance(10, true); root.print(); Random r = new Random(); int i = r.nextInt(BTree.getDepth(root)); System.out.println(i); printLevel(root, i); System.out.println(); printAll(root); } public static void printLevel(BTree root, int level) { if (root == null) return; if (level == 0) System.out.printf("%3d", root.getValue()); else { printLevel(root.getLeft(), level - 1); printLevel(root.getRight(), level - 1); } } public static void printAll(BTree root) { LinkedList<BTree> level = new LinkedList<BTree>(); LinkedList<BTree> q = new LinkedList<BTree>(); q.add(root); q.add(new BTree(Integer.MIN_VALUE)); while (q.size() != 0) { BTree n = q.remove(); if (n.getValue() == Integer.MIN_VALUE) { for (BTree t : level) System.out.printf("%3d", t.getValue()); System.out.println(); level.clear(); if (q.size() != 0) q.add(n); } else { if (n.getLeft() != null) q.add(n.getLeft()); if (n.getRight() != null) q.add(n.getRight()); level.add(n); } } } }
Java
UTF-8
5,098
2.078125
2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package fi.riista.feature.harvestpermit.season; import com.fasterxml.jackson.annotation.JsonProperty; import fi.riista.feature.common.dto.BaseEntityDTO; import fi.riista.feature.common.entity.Has2BeginEndDates; import fi.riista.feature.gamediary.GameSpecies; import fi.riista.feature.gamediary.GameSpeciesDTO; import fi.riista.util.F; import fi.riista.validation.DoNotValidate; import org.joda.time.LocalDate; import javax.annotation.Nonnull; import javax.validation.Valid; import javax.validation.constraints.AssertTrue; import java.util.List; import java.util.Map; public class HarvestSeasonDTO extends BaseEntityDTO<Long> implements Has2BeginEndDates { @Nonnull public static HarvestSeasonDTO createWithSpeciesAndQuotas(final @Nonnull HarvestSeason season, final List<HarvestQuota> quotas) { final HarvestSeasonDTO dto = create(season); final GameSpecies species = season.getSpecies(); dto.setSpecies(GameSpeciesDTO.create(species)); dto.setGameSpeciesCode(species.getOfficialCode()); if (quotas != null) { dto.setQuotas(F.mapNonNullsToList(quotas, HarvestQuotaDTO::create)); } return dto; } @Nonnull public static HarvestSeasonDTO create(final @Nonnull HarvestSeason season) { final HarvestSeasonDTO dto = new HarvestSeasonDTO(); dto.setId(season.getId()); dto.setName(season.getNameLocalisation().asMap()); dto.copyDatesFrom(season); dto.setEndOfReportingDate(season.getEndOfReportingDate()); dto.setEndOfReportingDate2(season.getEndOfReportingDate2()); return dto; } private Long id; private Integer rev; private Map<String, String> name; @JsonProperty(access = JsonProperty.Access.READ_ONLY) @DoNotValidate private GameSpeciesDTO species; private int gameSpeciesCode; private LocalDate beginDate; private LocalDate endDate; private LocalDate endOfReportingDate; private LocalDate beginDate2; private LocalDate endDate2; private LocalDate endOfReportingDate2; @AssertTrue public boolean isEndOfReportingDateValid() { return endOfReportingDate != null && (endOfReportingDate.isEqual(endDate) || endOfReportingDate.isAfter(endDate)); } @AssertTrue public boolean isSecondPeriodValid() { final boolean allNull = F.allNull(beginDate2, endDate2, endOfReportingDate2); final boolean allSet = F.allNotNull(beginDate2, endDate2, endOfReportingDate2); final boolean endOfReportingDateOrderValid = endOfReportingDate2 != null && (endOfReportingDate2.isEqual(endDate2) || endOfReportingDate2.isAfter(endDate2)); return allNull || (allSet && endOfReportingDateOrderValid); } @Valid private List<HarvestQuotaDTO> quotas; @Override public Long getId() { return id; } @Override public void setId(final Long id) { this.id = id; } @Override public Integer getRev() { return rev; } @Override public void setRev(final Integer rev) { this.rev = rev; } public Map<String, String> getName() { return name; } public void setName(final Map<String, String> name) { this.name = name; } public GameSpeciesDTO getSpecies() { return species; } public void setSpecies(final GameSpeciesDTO species) { this.species = species; } @Override public LocalDate getBeginDate() { return beginDate; } @Override public void setBeginDate(LocalDate beginDate) { this.beginDate = beginDate; } @Override public LocalDate getEndDate() { return endDate; } @Override public void setEndDate(LocalDate endDate) { this.endDate = endDate; } public LocalDate getEndOfReportingDate() { return endOfReportingDate; } public void setEndOfReportingDate(LocalDate endOfReportingDate) { this.endOfReportingDate = endOfReportingDate; } @Override public LocalDate getBeginDate2() { return beginDate2; } @Override public void setBeginDate2(LocalDate beginDate2) { this.beginDate2 = beginDate2; } @Override public LocalDate getEndDate2() { return endDate2; } @Override public void setEndDate2(LocalDate endDate2) { this.endDate2 = endDate2; } public LocalDate getEndOfReportingDate2() { return endOfReportingDate2; } public void setEndOfReportingDate2(LocalDate endOfReportingDate2) { this.endOfReportingDate2 = endOfReportingDate2; } public List<HarvestQuotaDTO> getQuotas() { return quotas; } public void setQuotas(List<HarvestQuotaDTO> quotas) { this.quotas = quotas; } public int getGameSpeciesCode() { return gameSpeciesCode; } public void setGameSpeciesCode(final int gameSpeciesCode) { this.gameSpeciesCode = gameSpeciesCode; } }
Java
UTF-8
5,299
2.109375
2
[ "Apache-2.0" ]
permissive
package aurelienribon.bodyeditor; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import com.badlogic.gdx.math.Vector2; import org.apache.commons.io.FileUtils; import org.json.JSONException; import aurelienribon.bodyeditor.io.JsonIo; import aurelienribon.bodyeditor.models.PolygonModel; import aurelienribon.bodyeditor.models.RigidBodyModel; import aurelienribon.utils.io.FilenameHelper; import aurelienribon.utils.notifications.ChangeableObject; /** * @author Aurelien Ribon | http://www.aurelienribon.com/ */ public class IoManager extends ChangeableObject { public static final String PROP_PROJECTFILE = "projectFile"; private File projectFile; public File getProjectFile() { return projectFile; } public File getProjectDir() { return projectFile.getParentFile(); } public void setProjectFile(File projectFile) { this.projectFile = projectFile; firePropertyChanged(PROP_PROJECTFILE); } public void exportToFile() throws IOException, JSONException { assert projectFile != null; String str = JsonIo.serialize(); FileUtils.writeStringToFile(projectFile, str, StandardCharsets.UTF_8); } public String toDefoldComponentString(String path, int id) { return String.format("embedded_components {" + System.lineSeparator() + " id: \"collisionobject" + id + "\" " + System.lineSeparator() + " type: \"collisionobject\" " + System.lineSeparator() + " data: \"collision_shape: \\\"/" + path + "\\\"\\n\" " + System.lineSeparator() + " \"type: COLLISION_OBJECT_TYPE_STATIC\\n\" " + System.lineSeparator() + " \"mass: 0.0\\n\" " + System.lineSeparator() + " \"friction: 0.1\\n\" " + System.lineSeparator() + " \"restitution: 0.5\\n\" " + System.lineSeparator() + " \"group: \\\"default\\\"\\n\" " + System.lineSeparator() + " \"mask: \\\"default\\\"\\n\" " + System.lineSeparator() + " \"linear_damping: 0.0\\n\" " + System.lineSeparator() + " \"angular_damping: 0.0\\n\" " + System.lineSeparator() + " \"locked_rotation: false\\n\" " + System.lineSeparator() + " \"\" " + System.lineSeparator() + " position { " + System.lineSeparator() + " x: 0.0 " + System.lineSeparator() + " y: 0.0 " + System.lineSeparator() + " z: 0.0 " + System.lineSeparator() + " } " + System.lineSeparator() + " rotation { " + System.lineSeparator() + " x: 0.0 " + System.lineSeparator() + " y: 0.0 " + System.lineSeparator() + " z: 0.0 " + System.lineSeparator() + " w: 1.0 " + System.lineSeparator() + " } " + System.lineSeparator() + "} " + System.lineSeparator()); } public void exportToDefoldFile() throws IOException, JSONException { assert projectFile != null; File path = getProjectDir(); String modelName = ""; File defoldDirectory = new File(path + "/defold"); FileUtils.deleteDirectory(defoldDirectory); for (RigidBodyModel model : Ctx.bodies.getModels()) { modelName = model.getName(); modelName = modelName.replaceAll("[^a-zA-Z0-9\\.\\-]", "_"); modelName = FilenameHelper.trim(modelName); String componentString = ""; int i = 0; for (PolygonModel polygon : model.getPolygons()) { String shapeStringContainer = ""; shapeStringContainer += "shape_type: TYPE_HULL" + System.lineSeparator(); for (Vector2 vertex : polygon.vertices) { shapeStringContainer += "data: " + (vertex.x - model.getOrigin().x) + System.lineSeparator(); shapeStringContainer += "data: " + (vertex.y - model.getOrigin().y) + System.lineSeparator(); shapeStringContainer += "data: 0" + System.lineSeparator(); } i++; File filePath = new File(path + "/defold/" + modelName + "/" + modelName + "_" + i + ".convexshape"); FileUtils.writeStringToFile(filePath, shapeStringContainer, StandardCharsets.UTF_8); componentString += toDefoldComponentString(modelName + "/" + modelName + "_" + i + ".convexshape", i); } File filePath = new File(path + "/defold/" + modelName + "/" + modelName + ".go"); FileUtils.writeStringToFile(filePath, componentString, StandardCharsets.UTF_8); i = 0; } } public void importFromFile() throws IOException, JSONException { assert projectFile != null; assert projectFile.isFile(); Ctx.bodies.getModels().clear(); String str = FileUtils.readFileToString(projectFile, StandardCharsets.UTF_8); JsonIo.deserialize(str); } public String buildImagePath(File imgFile) { return FilenameHelper.getRelativePath(imgFile.getPath(), projectFile.getParent()); } public File getImageFile(String imgPath) { if (imgPath == null) return null; File file = new File(projectFile.getParent(), imgPath); return file; } }
Rust
UTF-8
3,357
3.15625
3
[]
no_license
use rust_sls_common::{ Error, generic_error::GenericError, serde_date }; use serde::{Deserialize, Serialize}; use sha2::{Sha256, Digest}; use serde_json::Value; use chrono::NaiveDate; use std::str; use regex::Regex; #[derive(Deserialize, Debug, Serialize)] pub struct User { pub email: String, pub password: String, pub name: String, #[serde(with = "serde_date")] pub birthday: NaiveDate, pub document: String, pub extra: Option<Value> } impl User { pub fn validate(&self) -> Result<(), Error>{ let re = Regex::new(r"^([a-z0-9_+]([a-z0-9_+.]*[a-z0-9_+])?)@([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})")?; if !re.is_match(self.email.clone().as_str()) { return Err(Box::new(GenericError { description: "invalid_email".to_string() })); } if self.password.chars().count() < 4 { return Err(Box::new(GenericError { description: "password_to_short".to_string() })); } Ok(()) } pub fn hash_password(&mut self) { let mut hasher = Sha256::new(); hasher.update(self.password.clone()); let result = hasher.finalize(); self.password = format!("{:x}", result); } } #[cfg(test)] mod tests { use super::*; pub trait Mock { fn mock() -> Self; } impl Mock for User { fn mock() -> Self { User { email: "email@email.com".to_string(), password: "password".to_string(), name: "Usuario".to_string(), birthday: NaiveDate::from_ymd(1999, 06, 21), document: "00000000000".to_string(), extra: None } } } #[tokio::test] async fn user_email_must_be_valid() { let mut user = User::mock(); user.email = "email".to_string(); match user.validate() { Ok(_) => assert!(false), Err(err) => assert_eq!(err.to_string(), "invalid_email") } let mut user = User::mock(); user.email = "email.com".to_string(); match user.validate() { Ok(_) => assert!(false), Err(err) => assert_eq!(err.to_string(), "invalid_email") } let user = User::mock(); match user.validate() { Ok(_) => assert!(true), Err(_) => assert!(false) } } #[tokio::test] async fn user_password_must_have_more_then_4_characters() { let mut user = User::mock(); user.password = "pas".to_string(); match user.validate() { Ok(_) => assert!(false), Err(err) => assert_eq!(err.to_string(), "password_to_short") } let mut user = User::mock(); user.password = "pass".to_string(); match user.validate() { Ok(_) => assert!(true), Err(_) => assert!(false) } let user = User::mock(); match user.validate() { Ok(_) => assert!(true), Err(_) => assert!(false) } } #[tokio::test] async fn must_hash_password_with_sh2() { let mut user = User::mock(); user.hash_password(); let mut hasher = Sha256::new(); hasher.update("password"); let result = hasher.finalize(); assert_eq!(user.password, format!("{:x}", result)); } }
Java
UTF-8
1,467
1.992188
2
[ "Apache-2.0" ]
permissive
package com.toparchy.platform.security.model; public enum ApplicationRealm { AH; // AH("Anhui", "安徽"), BJ("Geijing", "北京"), FJ("Fujian", "福建"), GS("Gansu", // "甘肃"), GD("Guangdong", "广东"), GX("Guangxi", "广西"), GZ("Guizhou", // "贵州"), HI("Hainan", "海南"), HE("Hebei", "河北"), HA("Henan", "河南"), HL( // "Heilongjiang", "黑龙江"), HB("Hubei", "湖北"), HN("Hunan", "湖南"), JL( // "Jilin", "吉林"), JS("Jiangsu", "江苏"), JX("Jiangxi", "江西"), LN( // "Liaoning", "辽宁"), NM("Inner Mongoria IM", "内蒙古自治区"), NX("Ningxia", // "宁夏"), QH("Qinghai", "青海"), SD("Shandong", "山东"), SX("Shanxi", "山西"), SN( // "Shaanxi", "陕西"), SH("Shanghai", "上海"), SC("Sichuan", "四川"), TJ( // "Tianjin", "天津"), XZ("Tibet", "西藏"), XJ("Xinjiang", "新疆"), YN( // "Yuannan", "云南"), ZJ("Zhejiang", "浙江"), CQ("Chongqing", "重庆"), MO( // "Macao", "澳门"), HK("Hong Kong", "香港"), TW("Taiwan", "台湾"); private ApplicationRealm() { } private ApplicationRealm(String _name, String _value) { this._name = _name; this._value = _value; } private String _name; private String _value; public String get_name() { return _name; } public void set_name(String _name) { this._name = _name; } public String get_value() { return _value; } public void set_value(String _value) { this._value = _value; } }
Markdown
UTF-8
9,565
2.625
3
[]
no_license
* 1 本法依憲法第一百零六條制定之。 * 2 監察院行使憲法所賦予之職權。 * 3 監察院得分設委員會,其組織以法律定之。 * 3.1 監察院監察委員,須年滿三十五歲,並具有左列資格之一:一、曾任中央民意代表一任以上或省(市)議員二任以上,聲譽卓著者。二、任簡任司法官十年以上,並曾任高等法院、高等法院檢察署以上司法機關司法官,成績優異者。三、曾任簡任職公務員十年以上,成績優異者。四、曾任大學教授十年以上,聲譽卓著者。五、國內專門職業及技術人員高等考試及格,執行業務十五年以上,聲譽卓著者。六、清廉正直,富有政治經驗或主持新聞文化事業,聲譽卓著者。前項所稱之服務或執業年限,均計算至次屆監察委員就職前一日止。 > 釋:一、本條新增。二、依照憲法增修條文第十五條第二項規定,監察委員已非由選舉產生,原公職人員選舉罷免法所定之監察委員候選資格,已不再適用。爰參照司法院組織法及考試院組織法規範大法官及考試委員資格之例,於本法中增訂監察委員資格,以為總統提名依據。三、監察委員既負糾彈重任,並須富專業素養與經驗,其年齡自不宜太輕,爰參照原公職人員選舉罷免法對監察委員候選年齡之規定,明定須年滿三十五歲,為監察委員之必備條件。 * 4 監察院設審計部,其職掌如左:一、監督政府所屬全國各機關預算之執行。二、核定政府所屬全國各機關收入命令及支付命令。三、審核政府所屬全國各機關財務收支及審定決算。四、稽察政府所屬全國各機關財務及財政上不法或不忠於職務之行為。五、考核政府所屬全國各機關財務效能。六、核定各機關人員對於財務上之責任。七、其他依法律應行辦理之審計事項。審計部之組織,另以法律定之。 > 釋:審計法於六十一年五月一日令公布,其中第二條所規定審計職權由四項增修為七項,則現行監察院組織法第四條規定審計部職掌亦應修正以免分歧。 * 5 審計長綜理審計總處事務。 * 6 監察院院長綜理院務,並監督所屬機關;監察院院長因事故不能視事時,由副院長代理其職務。監察院院長出缺時,由副院長代理;其代理期間至總統提名繼任院長經立法院同意,總統任命之日為止。監察院院長、副院長同時出缺時,由總統就監察委員中指定一人代理院長;其代理期間至總統提名繼任院長、副院長經立法院同意,總統任命之日為止。監察院院長、副院長及監察委員出缺時,其繼任人之任期,至原任期屆滿之日為止。 > 釋:立法院已於93年8月23日第5屆第5會期第1次臨時會第3次會議通過憲法修正案,廢除國民大會;並於94年6月7日經國民大會予以複決通過。且依憲法增修條文第七條第二項,監察院院長、副院長、監察委員均由總統提名,並經立法院同意任命之。第六條中第二項及第三項中「經國民大會同意」之文字,均應配合修正為:「經立法院同意」。爰將第二項及第三項中之「國民大會」修正為:「立法院」。 * 7 監察院會議,由院長副院長及監察委員組織之,以院長為主席。 * 8 監察委員得分赴各地巡迴監察,行使彈劾糾舉之職權。 * 9 監察院置秘書長一人,特任,承院長之命,處理本院事務,並指揮監督所屬職員;副秘書長一人,職務列簡任第十四職等,承院長之命,襄助秘書長處理本院事務。 > 釋:一、參照其他四院之例,增置副秘書長一人,承院長之命,襄助秘書長處理本院事務。二、由主任秘書調整改置,員額並未增加。三、條文內容酌作修正。 * 10 監察院設監察業務處、監察調查處、公職人員財產申報處、秘書處、綜合規劃室、資訊室,分別掌理左列事項,並得分組或分科辦事:一、關於人民書狀之收受、處理及簽辦事項。二、關於糾舉、彈劾事項。三、關於調查案件之協查事項。四、關於公職人員財產申報事項。五、關於會議紀錄、公報編印及發行事項。六、關於文書收發、保管及印信典守事項。七、關於出納及庶務事項。八、關於綜合計畫之研擬及研究發展與考核事項。九、關於資訊系統之整體規劃及管理事項。十、關於協調、聯繫及新聞發布事項。十一、其他有關事項。 > 釋:一、因應本院實際運作,並參考中央院級組織架構及層級,將現行秘書處分組、室辦事,調整改為處、室層級平行,並得分組、科辦事,所掌理之事項,並配合修正。二、為加強人民陳情之受理與書狀之審查、簽辦及公務人員違法失職案件之糾彈、處分與監試等監察業務,成立監察業務處,處內分三組及陳情受理中心,以收統合作業之功效。三、為協助監察委員行使調查權,成立專業性專責單位「監察調查處」,以提昇調查案件效能,促進廉能目標之實現,實屬必要。四、「公職人員財產申報法」於修正公布施行後,應向本院申報財產之公職人員人數激增,申報業務更趨複雜,乃成立公職人員財產申報處,專責辦理公職人員財產申報業務。五、將現有行政室與研考室合併成立「綜合規劃室」。 * 11 (刪除) > 釋:一、本條刪除。二、因現行條文職稱無職等規定,且屬本院員額規定,爰依一般組織法律體例併入第十二條。 * 12 監察院置參事四人至六人、處長四人,職務均列簡任第十二職等至第十三職等;研究委員四人至六人,職務列簡任第十一職等至第十三職等;副處長四人,職務列簡任第十一職等至第十二職等;調查官二十四人至二十八人,職務列簡任第十職等至第十二職等;主任二人、陳情受理中心主任一人、組長十三人、專門委員二人,職務均列簡任第十職等至第十一職等;秘書十八人至二十三人,職務列薦任第八職等至第九職等,其中十一人,職務得列簡任第十職等至第十二職等;科長八人,職務列薦任第九職等;調查專員二十四人至二十八人,職務列薦任第八職等至第九職等;專員十人至十六人、分析師二人,職務均列薦任第七職等至第九職等;設計師二人,職務列薦任第六職等至第八職等;調查員二十四人至二十八人、科員十五人至二十三人、速記員二人至四人,職務均列委任第五職等或薦任第六職等至第七職等;護士二人、助理員四人至八人、操作員二人、藥劑員一人,職務均列委任第四職等至第五職等,其中護士一人、助理員四人、操作員一人,職務得列薦任第六職等;辦事員十人至十八人,職務列委任第三職等至第五職等;書記十七人,職務列委任第一職等至第三職等。本法修正施行前僱用之現職書記,其未具公務人員任用資格者,得占用前項書記職缺繼續其僱用至離職時為止。 > 釋:一、現行第十一條併入本條。二、主任秘書改置為副秘書長,並配合現行條文第十條及第十三條之修正,將組織編制職稱、官等及員額重新調整,並增列職等。三、配合監察調查處之成立,將簡任調查專員、稽核及編纂職稱修正為調查官。四、配合資訊室之成立,增置分析師、設計師、操作員職稱。五、修正條文第十三條會計室、統計室、人事室及政風室所需工作人員,除主管人員外,合併於本條總員額中。六、因應業務需要,須進用特殊專業人才,爰增列本條第二項。 * 13 監察院設會計室、統計室、人事室及政風室,依法律規定,分別辦理歲計、會計、統計、人事及政風事項。會計室置會計主任一人,統計室置統計主任一人,人事室、政風室各置主任一人,職務均列簡任第十職等至第十一職等;其餘所需工作人員,就本法所定員額內派充之。 > 釋:一、配合「政風機構人員設置條例」之施行,增設「政風室」。二、為求簡化,將會計處縮編為會計室,並分科辦事。三、會計室、統計室、人事室、政風室除主管人員於本條文明定外,其餘所需工作人員,合併就修正條文第十二條所定總員額中統籌派充之。 * 13.1 監察院應為每位委員聘用助理一人,與監察委員同進退。 > 釋:一、本條新增。二、目前每位監察委員配屬約聘專員一人,鑒於委員助理工作量及職責均相當繁重,亟需將助理法制化,爰增訂本條,並明定與監察委員同進退。 * 14 監察院會議規則及處務規程,由監察院定之。 > 釋:本條刪除,不保留條次。 * 15 本法自公布日施行。 > 釋:一、現行條文第二項及第三項乃階段性之施行規定,已無保留必要,爰予刪除。二、本法之修正已無另訂施行日期之必要,爰參照一般立法例,修正第一項文字為「本法自公布日施行」,俾臻明確。 * 16 本法施行日期以命令定之。 > 釋:條次修改。
PHP
UTF-8
2,235
3.109375
3
[]
no_license
<?php $array = array("firstname" => "", "name" => "", "email" => "", "phone" => "", "message" => "", "firstnameError" => "", "nameError" => "", "phoneError" => "", "messageError" => "","isSuccess" => false); $emailto = "test@test.com"; if ($_SERVER['REQUEST_METHOD'] == "POST") { $array['firstname'] = verifyInput($_POST['firstname']); $array['name'] = verifyInput($_POST['name']); $array['email'] = verifyInput($_POST['email']); $array['phone'] = verifyInput($_POST['phone']); $array['message'] = verifyInput($_POST['message']); $array['isSuccess'] = true; $emailText = ""; if (empty($array['firstname'])) { $array['firstnameError'] = "je veux connaître ton prénom"; $array['isSuccess'] = false; }else{ $emailText .= "firstname: {$array['firstname']}\n"; } if (empty($array['name'])) { $array['nameError'] = "Et même ton nom"; $array['isSuccess'] = false; } else { $emailText .= "name: {$array['name']}\n"; } if(!isEmail($array['email'])){ $array['emailError'] = " Ce n'est pas un email valide !"; $array['isSuccess'] = false; } else { $emailText .= "email: {$array['email']}\n"; } if(!isPhone($array['phone'])){ $array['phoneError'] = " Que des chiffres et des espaces "; $array['isSuccess'] = false; } else { $emailText .= "phone: {$array['phone']}\n"; } if (empty($array['message'])) { $array['messageError'] = "Que veux tu me dire ?"; $array['isSuccess'] = false; } else { $emailText .= "message: {$array['message']}\n"; } if($array['isSuccess']){ $headers = "From: {$array['firstname']} {$array['name']} <{$array['email']}>\r\n\Reply-To: {$array['email']}"; mail($emailto, "un message de votre site",$emailText,$headers); } echo json_encode($array); } function verifyInput($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } function isEmail($var){ return filter_var($var, FILTER_VALIDATE_EMAIL); } function isPhone ($var){ // expression régulière return preg_match("/^[0-9 ]*$/", $var); }
C
UTF-8
1,516
2.5625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_vector.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tefroiss <tefroiss@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/05/25 16:35:14 by tefroiss #+# #+# */ /* Updated: 2020/06/15 15:04:14 by tefroiss ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/cubvector.h" static inline void init_method(t_vector *new) { new->add = ft_vec_add; new->sub = ft_vec_sub; new->mul = ft_vec_mul; new->div = ft_vec_div; new->dot = ft_vec_dot; new->add_scalar = ft_vec_add_scalar; new->sub_scalar = ft_vec_sub_scalar; new->mul_scalar = ft_vec_mul_scalar; new->div_scalar = ft_vec_div_scalar; new->length = ft_vec_length; new->direction = ft_vec_direction; new->update = ft_vec_update; new->normalise = ft_vec_normalise; new->dist = ft_vec_dist; } t_vector ft_vector(double x, double y) { t_vector new; new.x = x; new.y = y; init_method(&new); return (new); }
Python
UTF-8
1,055
3.1875
3
[]
no_license
def encode(tm): tm_list = [] for instruction in tm: state = binary(int(instruction[0])) state = expand(state) first_symbol = simplify(instruction[1]) tm_list.append(state) tm_list.append(first_symbol) if len(instruction) == 3: second_symbol = simplify(instruction[2]) tm_list.append(second_symbol) tm_string = ''.join(tm_list) tm_string = cut(tm_string) natural_representation = int(tm_string, 2) return natural_representation def binary(integer): return "{0:b}".format(integer) def simplify(symbol): if symbol == '0': return '0' elif symbol == '1': return '10' elif symbol == 'R': return '110' elif symbol == 'L': return '1110' else: return '11110' def expand(string): str = '' for char in string: str = str + simplify(char) return str def cut(string): if len(string) >= 3: return string[:-3] else: return string import pdb; pdb.set_trace()
Java
UTF-8
1,074
2
2
[]
no_license
package com.trendyol.scheduler.controller; import com.trendyol.scheduler.controller.sample.SampleJobController; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @WebMvcTest(SampleJobController.class) public class SampleJobControllerTest { @Autowired private MockMvc mockMvc; @Test public void it_should_invoke_sample_job_endpoint() throws Exception { //Given //When ResultActions resultActions = mockMvc.perform(get("/job/invoke")); //Then resultActions.andExpect(status().isOk()); } }
C++
UTF-8
12,934
2.71875
3
[]
no_license
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <string> using namespace std; bool DEBUG; class task_set { public: int p[10]; //periods in milli-seconds double c[10]; // worst-case execution times in micro-seconds //double e_c[10]; long hyper_period; }; bool preemptive_edf_schedule(task_set set, int n, int c_time = 0, int w = 1) { //cout << endl; long hyper_period = set.hyper_period * 1000; //microseconds //cout << "hyper_period: " <<hyper_period << endl; bool active_jobs[10]; double remaining_execution[10]; for(int i = 0; i < n; i++) { active_jobs[i] = false; remaining_execution[i] = 0; } int current_task = -1; // task index of highest priority job int previous_task = 0; long last_empty_slot = -1; int halt_execution = 0; long time_elapsed; for(time_elapsed = 1; time_elapsed <= hyper_period; time_elapsed++) { //find job released for(int i = 0; i < n; i++) { if(((time_elapsed - 1) % (set.p[i] * 1000)) == 0) // new job has been released of a task { //cout << "at t= " << time_elapsed << " : " ; //cout << "J(" << i + 1 << "," << (time_elapsed / (set.p[i] * 1000)) +1 <<") " << endl; //check if the previous job still needs time if(remaining_execution[i] != 0) { if(DEBUG) cout << "preemptive: J(" << i + 1 << "," << (time_elapsed / (set.p[i] * 1000)) +1 << ") has missed deadline at t= " << time_elapsed - 1 << " us, exe_remain: " << remaining_execution[i] << " us" << endl; return false; } // activate the job, set the execution time active_jobs[i] = true; remaining_execution[i] = set.c[i] * w; //cout << "Acitve job: " << set.p[i]*1000 << " Ex_remaining: " << remaining_execution[i] << endl; } } // check for highest priority current_task = -1; for(int i = 0; i < n; i++) { if(active_jobs[i]) { current_task = i; /*if ((current_task != previous_task) && (remaining_execution[previous_task] != 0)) { cout << "at t= " << time_elapsed-1 << ", J(" << previous_task+1 << "," << (time_elapsed / (set.p[previous_task] * 1000)) +1 << ") with remaining_execution: " <<remaining_execution[previous_task] << " of us, has been preempted by J(" << current_task+1 << "," << (time_elapsed / (set.p[current_task] * 1000)) +1 << ") !" << endl; }*/ //cout << "at t = " << time_elapsed << " active job: " << "J(" << i+1 <<"," << (time_elapsed / (set.p[i] * 1000)) +1 << ")" << endl; break; } } if (current_task == -1) // no jobs to execute { if(last_empty_slot == -1) { last_empty_slot = time_elapsed - 1; //cout << "last_empty_slot: " << last_empty_slot << endl; } continue; } // check for the context switch time if(previous_task != current_task) { if(last_empty_slot == -1) { halt_execution = c_time; } else if(time_elapsed - 1 - last_empty_slot < c_time) { halt_execution = time_elapsed - 1 - last_empty_slot; } } if(halt_execution == 0) { remaining_execution[current_task]--; //execute one time unit last_empty_slot = -1; if(remaining_execution[current_task] == 0) //inactivate job if all execution done { active_jobs[current_task] = false; remaining_execution[current_task] = 0; //cout << "at t = " << time_elapsed << ", J(" << current_task+1 <<"," << (time_elapsed / (set.p[current_task] * 1000)) +1 << ") finished!" <<endl; //time_elapsed += c_time; // add switch time since starting a new job } } //check at any particular time what jobs are active /*if (time_elapsed == 1) { cout << "at t = " << time_elapsed << endl; for(int i = 0; i < n; i++) { if(active_jobs[i]) cout << "J(" << i+1 <<"," << (time_elapsed / (set.p[i] * 1000)) +1 << ") , remaining_execution: " << remaining_execution[i] << endl; } }*/ if(halt_execution > 0) halt_execution--; previous_task = current_task; } return true; } bool non_preemptive_edf_schedule(task_set set, int n, int c_time = 0, int w = 1) { //cout << endl; long hyper_period = set.hyper_period * 1000; //microseconds //cout << "hyper_period: " <<hyper_period << endl; bool active_jobs[10]; double remaining_execution[10]; for(int i = 0; i < n; i++) { active_jobs[i] = false; remaining_execution[i] = 0; } int current_task = -1; // task index of highest priority job int previous_task = 0; long last_empty_slot = -1; int halt_execution = 0; long time_elapsed; for(time_elapsed = 1; time_elapsed <= hyper_period; time_elapsed++) { //find job released for(int i = 0; i < n; i++) { if(((time_elapsed - 1) % (set.p[i] * 1000)) == 0) // new job has been released of a task { //cout << "at t= " << time_elapsed << " : " ; //cout << "J(" << i + 1 << "," << (time_elapsed / (set.p[i] * 1000)) +1 <<") " << endl; //check if the previous job still needs time if(remaining_execution[i] != 0) { if(DEBUG) cout << "non-preemptive: J(" << i + 1 << "," << (time_elapsed / (set.p[i] * 1000)) +1 << ") has missed deadline at t= " << time_elapsed - 1 << " us, exe_remain: " << remaining_execution[i] << " us" << endl; return false; } // activate the job, set the execution time active_jobs[i] = true; remaining_execution[i] = set.c[i] * w; //cout << "Acitve job: " << set.p[i]*1000 << " Ex_remaining: " << remaining_execution[i] << endl; } } // check if the current task is still running if(remaining_execution[previous_task] != 0) { current_task = previous_task; } else { // previous task finished, check for highest priority task now current_task = -1; for(int i = 0; i < n; i++) { if(active_jobs[i]) { current_task = i; //cout << "at t = " << time_elapsed << " active job: " << "J(" << i+1 <<"," << (time_elapsed / (set.p[i] * 1000)) +1 << ")" << endl; break; } } } if (current_task == -1) // no jobs to execute { if(last_empty_slot == -1) { last_empty_slot = time_elapsed - 1; //cout << "last_empty_slot: " << last_empty_slot << endl; } continue; } // check for the context switch time if(previous_task != current_task) { if(last_empty_slot == -1) { halt_execution = c_time; } else if(time_elapsed - 1 - last_empty_slot < c_time) { halt_execution = time_elapsed - 1 - last_empty_slot; } } if(halt_execution == 0) { remaining_execution[current_task]--; //execute one time unit last_empty_slot = -1; if(remaining_execution[current_task] == 0) //inactivate job if all execution done { active_jobs[current_task] = false; remaining_execution[current_task] = 0; //cout << "at t = " << time_elapsed << ", J(" << current_task+1 <<"," << (time_elapsed / (set.p[current_task] * 1000)) +1 << ") finished!" <<endl; } } //check at any particular time what jobs are active /*if (time_elapsed == 1) { cout << "at t = " << time_elapsed << endl; for(int i = 0; i < n; i++) { if(active_jobs[i]) cout << "J(" << i+1 <<"," << (time_elapsed / (set.p[i] * 1000)) +1 << ") , remaining_execution: " << remaining_execution[i] << endl; } }*/ if(halt_execution > 0) halt_execution--; previous_task = current_task; } return true; } int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a%b); } int lcm(int a [], int n) { int res = 1; for (int i = 0; i < n; i++) { res = (res*a[i])/gcd(res, a[i]); } return res; } double cal_utilization(task_set set, int n, double w) { double utilization = 0; for (int i = 0; i < n; i++) { double temp_uti = (w * set.c[i]) / (set.p[i] * 1000); utilization += temp_uti; } if (utilization > 1) return -100; return utilization; } bool utilizaiton_condtion(task_set set, int n, int w = 1) { double utilization = 0; for (int i = 0; i < n; i++) { double temp_uti = (w * set.c[i]) / (set.p[i] * 1000); utilization += temp_uti; } return (utilization <=1)? true : false; //return utilization; } //jeffay condition bool non_preemptive_condition(task_set set, int n) { int p_1 = set.p[0] * 1000; //cout << "P_1 : " << p_1 << endl; for(int i = 1; i < n; i++) { int p_i = set.p[i] * 1000; double c_i = set.c[i]; //cout << "p_i: " << p_i << " c_i: " << c_i << endl; //int L = p_1 + (p_i - p_1); for(int x = p_1 +1; x < p_i; x++) { double temp_cost = c_i; //cout << "Temp cost: " <<temp_cost << endl; for(int j = 0; j < i-1; j++) { temp_cost += (floor(((x - 1) * 1.0)/ (set.p[j] * 1000)) * set.c[j]); } if(x < temp_cost) { cout << "Failed Jeffay test : L = " << x << " cost = " << temp_cost << endl; return false; } } } return true; } void quick_sort(task_set & arr, int left, int right) { int i = left, j = right; int pivot = arr.p[left]; while (i <= j) { while (arr.p[i] < pivot) i++; while (arr.p[j] > pivot) j--; if (i <= j) { int tmp, tmc; tmp = arr.p[i]; tmc = arr.c[i]; arr.p[i] = arr.p[j]; arr.c[i] = arr.c[j]; arr.p[j] = tmp; arr.c[j] = tmc; i++; j--; } }; if (left < j) quick_sort(arr, left, j); if (i < right) quick_sort(arr, i, right); } int main(int argc, char* argv[]) { if(argc > 2) { cout << endl; cout << "Usage: g++ hw3_q1.cpp -o out && ./out arg1" << endl; cout << "arg1: true or false (DEBUG activate or deactivate)" << endl; cout << endl; exit(1); } if(argc ==2) { string str(argv[1]); if(str == "true"){DEBUG = true;} else{DEBUG = false;} } else{ DEBUG = false; } srand(time(NULL)); //task tasks [25][10]; // 25 task sets each having 10 periodic tasks int context_switch_time[5] = {6, 206, 406, 806, 1006}; task_set task_system[25]; int no_of_task_set = 0; do{ task_set candidate_set; for (int j = 0; j < 10; j++) { int period = rand() % 8 + 3; // generate random periods between 3 - 10 milli-seconds int exe_time = rand() % 501 + 1; // execution time between 1 - 500 micro seconds if(exe_time <= 0) exe_time = 1; candidate_set.p[j]= period; candidate_set.c[j] = exe_time; } quick_sort(candidate_set, 0, 9); if (utilizaiton_condtion(candidate_set, 10) && non_preemptive_condition(candidate_set, 10)) { candidate_set.hyper_period = lcm(candidate_set.p, 10); task_system[no_of_task_set] = candidate_set; no_of_task_set++; /*for(int j=0; j < 10; j++) { cout << "T"<< j+1 << ": " <<candidate_set.p[j] << " " << candidate_set.c[j] / 1000 << endl; } cout << endl;*/ } }while(no_of_task_set < 25); /* * ***************************************************Context switch time*********************************** */ for(int c=0; c < 5; c++) { cout << "================ context switch time: " << context_switch_time[c] <<" us =======================" << endl; if(!DEBUG) cout << "Scheduling tasks ..." << endl; int preemptive_w = 0; int non_preemptive_w = 0; double preemptive_uti = 0; double non_preemptive_uti = 0; for(int i = 0; i < no_of_task_set; i++) { //task system if(DEBUG){ cout << "Tasks (p_i, c_i), (time in ms): "; for(int l = 0; l < 10; l++) { cout << "(" << task_system[i].p[l] << "," << task_system[i].c[l] / 1000 << ") "; } cout << endl; } //preemptive test int j; for(j = 2;; j++) { if(!preemptive_edf_schedule(task_system[i], 10, context_switch_time[c], j)) // context switch time 6 { preemptive_w += (j -1); preemptive_uti += cal_utilization(task_system[i], 10, j-1); break; } } //non-preemptive test int k; for(k = 2;; k++) { if(!non_preemptive_edf_schedule(task_system[i], 10, context_switch_time[c], k)) // context switch time 6 { non_preemptive_w += (k -1); non_preemptive_uti += cal_utilization(task_system[i], 10, k-1); break; } } if(DEBUG) cout << "Task System: " << i+1 << ", preemptive_breakdown_w: " << j-1 << ", non-preemptive_breakdown_w: " << k-1 << endl; if(DEBUG) cout << "--------------------------------------------------------------------"<< endl; } cout << "preemptive_w_average: " << preemptive_w / (no_of_task_set * 1.0) << endl; cout << "non-preemptive_w_average: " << non_preemptive_w / (no_of_task_set * 1.0) << endl; cout << "preemptive_avg_breakdown_uti: " << preemptive_uti / (no_of_task_set * 1.0) << endl; cout << "non-preemptive_avg_breakdown_uti:: " << non_preemptive_uti / (no_of_task_set * 1.0) << endl; cout << "For context switch time: " << context_switch_time[c] << " us" << endl; cout << "=====================================================================" << endl; } // test random task set return 0; }
C++
UTF-8
4,072
2.640625
3
[]
no_license
// Host_CSR_Graph index_type node_data_type #include "host_csr_graph.h" Host_CSR_Graph::Host_CSR_Graph() { nnodes = 0; nedges = 0; row_start = NULL; edge_dst = NULL; node_data = NULL; } unsigned Host_CSR_Graph::readFromGR(char file[]) { // Copied from https://github.com/IntelligentSoftwareSystems/Galois/blob/c6ab08b14b1daa20d6b408720696c8a36ffe30cb/libgpu/src/csr_graph.cu#L176 std::ifstream cfile; cfile.open(file); int masterFD = open(file, O_RDONLY); if (masterFD == -1) { printf("Host_CSR_Graph::readFromGR: unable to open %s.\n", file); return 1; } struct stat buf; int f = fstat(masterFD, &buf); if (f == -1) { printf("Host_CSR_Graph::readFromGR: unable to stat %s.\n", file); abort(); } size_t masterLength = buf.st_size; int _MAP_BASE = MAP_PRIVATE; void* m = mmap(0, masterLength, PROT_READ, _MAP_BASE, masterFD, 0); if (m == MAP_FAILED) { m = 0; printf("Host_CSR_Graph::readFromGR: mmap failed.\n"); abort(); } auto startTime = std::chrono::system_clock::now(); // parse file uint64_t* fptr = (uint64_t*)m; __attribute__((unused)) uint64_t version = le64toh(*fptr++); assert(version == 1); uint64_t sizeEdgeTy = le64toh(*fptr++); uint64_t numNodes = le64toh(*fptr++); uint64_t numEdges = le64toh(*fptr++); uint64_t* outIdx = fptr; fptr += numNodes; uint32_t* fptr32 = (uint32_t*)fptr; uint32_t* outs = fptr32; fptr32 += numEdges; if (numEdges % 2) fptr32 += 1; // cuda. this->nnodes = numNodes; this->nedges = numEdges; printf("nnodes=%d, nedges=%d, sizeEdge=%d.\n", this->nnodes, this->nedges, sizeEdgeTy); this->allocSpace(); row_start[0] = 0; for (unsigned ii = 0; ii < this->nnodes; ++ii) { row_start[ii + 1] = le64toh(outIdx[ii]); // //noutgoing[ii] = le64toh(outIdx[ii]) - le64toh(outIdx[ii - 1]); index_type degree = this->row_start[ii + 1] - this->row_start[ii]; for (unsigned jj = 0; jj < degree; ++jj) { unsigned edgeindex = this->row_start[ii] + jj; unsigned dst = le32toh(outs[edgeindex]); if (dst >= this->nnodes) printf("\tinvalid edge from %d to %d at index %d(%d).\n", ii, dst, jj, edgeindex); this->edge_dst[edgeindex] = dst; } progressPrint(this->nnodes, ii); } cfile.close(); // probably galois doesn't close its file due to mmap. auto endTime = std::chrono::system_clock::now(); double time_in_ms = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count(); // TODO: fix MB/s printf("read %lld bytes in %0.2f ms (%0.2f MB/s)\n\r\n", masterLength, time_in_ms, (masterLength / 1000.0) / time_in_ms); return 0; } // Copied from // https://github.com/IntelligentSoftwareSystems/Galois/blob/c6ab08b14b1daa20d6b408720696c8a36ffe30cb/libgpu/src/csr_graph.cu#L28 unsigned Host_CSR_Graph::allocSpace() { assert(this->nnodes > 0); if (this->row_start != NULL) // already allocated return true; size_t mem_usage = ((this->nnodes + 1) + this->nedges) * sizeof(index_type) + (this->nnodes) * sizeof(node_data_type); printf("Host memory for graph: %3u MB\n", mem_usage / 1048756); this->row_start = (index_type*)calloc(this->nnodes + 1, sizeof(index_type)); this->edge_dst = (index_type*)calloc(this->nedges, sizeof(index_type)); this->node_data = (node_data_type*)calloc(this->nnodes, sizeof(node_data_type)); return (this->row_start && this->edge_dst && this->node_data); } // Copied from https://github.com/IntelligentSoftwareSystems/Galois/blob/c6ab08b14b1daa20d6b408720696c8a36ffe30cb/libgpu/src/csr_graph.cu#L156 void Host_CSR_Graph::progressPrint(unsigned maxii, unsigned ii) { const unsigned nsteps = 10; unsigned ineachstep = (maxii / nsteps); if (ineachstep == 0) ineachstep = 1; /*if (ii == maxii) { printf("\t100%%\n"); } else*/ if (ii % ineachstep == 0) { int progress = ((size_t)ii * 100) / maxii + 1; printf("\t%3d%%\r", progress); fflush(stdout); } }
Java
UTF-8
6,162
2.1875
2
[ "MIT" ]
permissive
/* Copyright (c) 2014 zuendorf 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 shall be used for Good, not Evil. 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. */ package org.sdmlib.test.examples.helloworld.model.util; import java.util.Collection; import java.util.Collections; import org.sdmlib.test.examples.helloworld.model.Edge; import org.sdmlib.test.examples.helloworld.model.Graph; import org.sdmlib.test.examples.helloworld.model.GraphComponent; import org.sdmlib.test.examples.helloworld.model.Node; import de.uniks.networkparser.list.ObjectSet; import de.uniks.networkparser.list.SimpleSet; public class GraphSet extends SimpleSet<Graph> { private static final long serialVersionUID = 1L; public GraphPO hasGraphPO() { return new GraphPO (this.toArray(new Graph[this.size()])); } public GraphSet with(Object value) { if (value instanceof java.util.Collection) { Collection<?> collection = (Collection<?>) value; for(Object item : collection){ this.add((Graph) item); } } else if (value != null) { this.add((Graph) value); } return this; } public GraphSet without(Graph value) { this.remove(value); return this; } public NodeSet getNodes() { NodeSet result = new NodeSet(); for (Graph obj : this) { result.with(obj.getNodes()); } return result; } public GraphSet hasNodes(Object value) { ObjectSet neighbors = new ObjectSet(); if (value instanceof Collection) { neighbors.addAll((Collection<?>) value); } else { neighbors.add(value); } GraphSet answer = new GraphSet(); for (Graph obj : this) { if ( ! Collections.disjoint(neighbors, obj.getNodes())) { answer.add(obj); } } return answer; } public GraphSet withNodes(Node value) { for (Graph obj : this) { obj.withNodes(value); } return this; } public GraphSet withoutNodes(Node value) { for (Graph obj : this) { obj.withoutNodes(value); } return this; } public EdgeSet getEdges() { EdgeSet result = new EdgeSet(); for (Graph obj : this) { result.with(obj.getEdges()); } return result; } public GraphSet hasEdges(Object value) { ObjectSet neighbors = new ObjectSet(); if (value instanceof Collection) { neighbors.addAll((Collection<?>) value); } else { neighbors.add(value); } GraphSet answer = new GraphSet(); for (Graph obj : this) { if ( ! Collections.disjoint(neighbors, obj.getEdges())) { answer.add(obj); } } return answer; } public GraphSet withEdges(Edge value) { for (Graph obj : this) { obj.withEdges(value); } return this; } public GraphSet withoutEdges(Edge value) { for (Graph obj : this) { obj.withoutEdges(value); } return this; } public GraphComponentSet getGcs() { GraphComponentSet result = new GraphComponentSet(); for (Graph obj : this) { result.with(obj.getGcs()); } return result; } public GraphSet hasGcs(Object value) { ObjectSet neighbors = new ObjectSet(); if (value instanceof Collection) { neighbors.addAll((Collection<?>) value); } else { neighbors.add(value); } GraphSet answer = new GraphSet(); for (Graph obj : this) { if ( ! Collections.disjoint(neighbors, obj.getGcs())) { answer.add(obj); } } return answer; } public GraphSet withGcs(GraphComponent value) { for (Graph obj : this) { obj.withGcs(value); } return this; } public GraphSet withoutGcs(GraphComponent value) { for (Graph obj : this) { obj.withoutGcs(value); } return this; } public static final GraphSet EMPTY_SET = new GraphSet().withFlag(GraphSet.READONLY); public GraphPO filterGraphPO() { return new GraphPO(this.toArray(new Graph[this.size()])); } public String getEntryType() { return "org.sdmlib.test.examples.helloworld.model.Graph"; } public GraphSet() { // empty } public GraphSet(Graph... objects) { for (Graph obj : objects) { this.add(obj); } } public GraphSet(Collection<Graph> objects) { this.addAll(objects); } public GraphPO createGraphPO() { return new GraphPO(this.toArray(new Graph[this.size()])); } @Override public GraphSet getNewList(boolean keyValue) { return new GraphSet(); } }
Java
UTF-8
1,404
2.09375
2
[]
no_license
package com.joymeter.controlcenter.config; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * @ClassName RedisConfig * @Description TODO * redis缓存配置 * @Author liang * @Date 2018/6/26 17:33 * @Version 1.0 **/ @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { //序列化解决乱码问题 @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, String> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(factory); StringRedisSerializer stringSerializer = new StringRedisSerializer(); redisTemplate.setDefaultSerializer(stringSerializer); redisTemplate.setKeySerializer(stringSerializer); redisTemplate.setValueSerializer(stringSerializer); redisTemplate.setHashKeySerializer(stringSerializer); redisTemplate.setHashValueSerializer(stringSerializer); return redisTemplate; } }
Java
UTF-8
689
3.8125
4
[]
no_license
package replit_assignments; import java.util.*; public class Replit75 { public static void main(String[] args) { // Given a string word, if the first or last chars are 'x' or 'X', print the string without those 'x' or 'X' chars, otherwise print the string unchanged. Scanner scan = new Scanner(System.in); String word = scan.next(); if(word.startsWith("x") || word.startsWith("X")) { word = word.replaceFirst("x", ""); word = word.replaceFirst("X", ""); } if(word.endsWith("x") || word.endsWith("X")) { word = word.substring(0,word.length()-1); } System.out.println(word); } }
Java
UTF-8
661
1.789063
2
[]
no_license
package com.software.test.generatingexam.controller; import com.alibaba.fastjson.JSONObject; import com.software.test.generatingexam.service.KnowledgePointService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class KnowledgePointController { @Autowired KnowledgePointService knowledgePointService; @RequestMapping("/kps") public String getKnowledgePoints(int chapterId) { return JSONObject.toJSONString(knowledgePointService.findAllByChapterId(chapterId)); } }
Java
UTF-8
929
1.945313
2
[]
no_license
package com.redknee.topup.cts.common.jobs; import com.redknee.topup.cts.service.subscounter.SubsCounterAdminBean; import javax.enterprise.inject.spi.CDI; import lombok.extern.slf4j.Slf4j; import org.quartz.DisallowConcurrentExecution; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; @Slf4j @DisallowConcurrentExecution public class CtsSubsCounterResetJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { log.info("CtsSubsCounterResetJob: start delete expired counters"); int deletedRecords = getSubsCounterAdminBean().deleteExpiredCounters(); log.info("CtsSubsCounterResetJob: Deleted {} expired counters", deletedRecords); } public SubsCounterAdminBean getSubsCounterAdminBean() { return CDI.current().select(SubsCounterAdminBean.class).get(); } }
Shell
UTF-8
1,507
3.609375
4
[]
no_license
#! /bin/bash echo "Welcome to Employee Wage Computation Program " IS_PART_TIME=1 IS_FULL_TIME=2 EMP_RATE_PER_HR=20 MAX_HRS_IN_MONTH=100 NUM_WORKING_DAYS=20 totalEmpHrs=0 totalWorkingDays=0 totalSalary=0 declare -A dayWiseWages function calculateDailyWage() { empHrs=$1 daySalary=$(( $empHrs * $EMP_RATE_PER_HR )) echo $daySalary } function getWorkingHours() { case $1 in $IS_FULL_TIME ) empHrs=8 ;; $IS_PART_TIME ) empHrs=4 ;; *) empHrs=0 ;; esac echo $empHrs } while(( $totalWorkHours < $MAX_HRS_IN_MONTH && $totalWorkingDays < $NUM_WORKING_DAYS )) do ((totalWorkingDays++)) workHours="$( getWorkingHours $(( RANDOM%3 )) )" echo "Work hours from function getWorkingHours()::::::::::>>> $workHours " totalWorkHours=$(( $totalWorkHours + $workHours )) echo -e "TotalWorkHours: $totalWorkHours\n" empDailyWage[$totalWorkingDays]="$( calculateDailyWage $workHours )" dayWiseWages[$totalWorkingDays]="$(calculateDailyWage $workHours)" done totalSalary=$(( $totalWorkHours * $EMP_RATE_PER_HR )); echo -e "\n::::::::::::Printing Days from array::::::" echo ${!empDailyWage[@]} echo -e "\n::::::::::::Printing salary stored day wise in an array:::::::::::::::" echo ${empDailyWage[@]} echo -e "\n::::::::::::Printing Days from dictionary::::::" echo ${!dayWiseWages[@]} echo -e "\n::::::::::::Printing salary stored day wise in dictionary:::::::::::::::" echo ${dayWiseWages[@]} echo "Total salary: $totalSalary"
Java
UTF-8
1,679
1.796875
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright © 2016 Cask Data, 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. */ package co.cask.cdap.data.view; import co.cask.cdap.common.StreamNotFoundException; import co.cask.cdap.common.ViewNotFoundException; import co.cask.cdap.common.entity.EntityExistenceVerifier; import co.cask.cdap.data2.transaction.stream.StreamAdmin; import co.cask.cdap.proto.id.StreamViewId; import com.google.common.base.Throwables; import com.google.inject.Inject; /** * {@link EntityExistenceVerifier} for {@link StreamViewId stream views}. */ public class ViewExistenceVerifier implements EntityExistenceVerifier<StreamViewId> { private final StreamAdmin streamAdmin; @Inject ViewExistenceVerifier(StreamAdmin streamAdmin) { this.streamAdmin = streamAdmin; } @Override public void ensureExists(StreamViewId viewId) throws StreamNotFoundException, ViewNotFoundException { boolean exists; try { exists = streamAdmin.viewExists(viewId); } catch (StreamNotFoundException e) { throw e; } catch (Exception e) { throw Throwables.propagate(e); } if (!exists) { throw new ViewNotFoundException(viewId); } } }
Java
UTF-8
1,043
3.515625
4
[]
no_license
package taskK2; /** * Класс Окно: * может менять статус с занято на свободно и свободно на занято * может вызывать следующий талон (т.е устанавливать статус свободно) * */ import java.time.LocalTime; public class Window { private boolean isFree; // false - занято, true - свободно private int number; // номер окна private String[] purposes; // коды целей, с которыми может работать данное окно public Window(boolean isFree, int number, String[] purposes) { } /** * Метод изменяет состояние окна. * @param isFree меняет текущее состояние на переданное значение */ void setFree(boolean isFree) { } /** * Метод изменяет состояние окна на true (свободен) */ void callNext() { } }
Python
UTF-8
370
4.21875
4
[]
no_license
#第五个练习 - 全局变量和局部变量应用 tree = "我只是一颗松树" def fun_dream(): tree = "孩子们为我挂上了彩灯、礼物……我变成了一颗圣诞树 ^_^ \n" print(tree) #调用函数 print("下雪了……\n") print("========进入了梦乡========\n") fun_dream() print("==========梦醒了==========\n") print(tree)
Shell
UTF-8
1,609
3.859375
4
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
#!/bin/bash # # Extract the oxAuth OpenID private keys to PEM format for use by Passport # # Retrieve the key ids (kid) for each key from the oxAuth jwks_uri for retries in {1..10} ; do kids=$(curl -s https://$(hostname)/oxauth/restv1/jwks | jq -r ".keys[].kid") if [[ $? -ne 0 || -z "$kids" ]] ; then echo "Failed to retrieve the JWKS from oxAuth on attempt $retries" sleep 30 else break fi done # Cleanup old keys rm -rf /run/keyvault/keys umask 227 mkdir /run/keyvault/keys # Retrieve the oxAuth keystore password export gluuPW=$(/opt/gluu/bin/encode.py -d $(grep auth.userPassword /etc/gluu/conf/gluu-couchbase.properties | awk -F': ' '{print $2}')) keyStoreSecret=$(openssl enc -d -aes-256-cbc -pass env:gluuPW -in /install/community-edition-setup/setup.properties.last.enc | grep oxauth_openid_jks_pass | awk -F'=' '{print $2}') # Use the salt to encrypt the keys export encodeSalt=$(awk -F'= ' '{print $2}' /etc/gluu/conf/salt) for kid in $kids ; do echo "Extracting $kid" # Extract the individual key /opt/jre/bin/keytool -importkeystore -srckeystore /etc/certs/oxauth-keys.pkcs12 -srcstoretype pkcs12 -destkeystore /run/keyvault/keys/${kid}.p12 -alias ${kid} -srcstorepass $keyStoreSecret -deststorepass $keyStoreSecret # Convert the private key to AES-encrypted PKCS8 openssl pkcs12 -in /run/keyvault/keys/${kid}.p12 -nocerts -passin pass:${keyStoreSecret} -nodes -nocerts | openssl pkcs8 -topk8 -v2 aes256 -out /run/keyvault/keys/${kid}.pem -passout env:encodeSalt rm /run/keyvault/keys/${kid}.p12 done
Java
UTF-8
1,263
2.3125
2
[]
no_license
package com.example.demo.exception; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import com.example.demo.service.util.MethodUtils; @ControllerAdvice public class BookExceptionHandler extends ResponseEntityExceptionHandler { @Override // this method is for customization of HTTP method responses when error occurred protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(MethodUtils.prepareErrorJSON(status, ex), status); } @Override //this is to handle exceptions occured while rest request protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(MethodUtils.prepareErrorJSON(status, ex), status); } }
Python
UTF-8
1,691
3.671875
4
[]
no_license
import random import emoji """ This programme helps the user to generate random pins and passwords for day to day use and keeps a record of those. """ def pin(): pinsample = "123456789" Used = str(input("What do you intend the PIN for :")) passlen = int(input("Enter the length of PIN :")) p = "".join(random.sample(pinsample,passlen )) print("Your PIN for " + Used + " : " + p) print(Used + ":" + p, file=open('pin_output.txt','a')) #print(Used + ":" + p, file=open('output.XLSX','a')) """ The pin function executes the code to give the user a pin(numbers) of his desired length ; while the PASSWORD function looks for the length of the password and gives the user a combination of upper case,lowercase ,numeric & special characters for a strong passowrd. """ def PASSWORD(): Used = str(input("What do you intend the password for :")) passlen = int(input("Enter the length of password :")) s="abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?/+-~{}][/" p = "".join(random.sample(s,passlen )) print("Your passowrd for " + Used + " : " + p) print(Used + ":" + p, file=open('pass_output.txt','a')) def main(): while True: utility = str(input("::Type 'PIN' for pin or 'PASSWORD' for password & 'STOP' if you want to close::")) utility = utility.upper() if utility == "PASSWORD" : PASSWORD() if utility == "PIN" : pin() if utility == "STOP": break else: print("\N{grinning face}") if __name__ == '__main__': main()
TypeScript
UTF-8
1,281
2.546875
3
[ "MIT" ]
permissive
/** * makecode I2C LM75A Package. * From microbit/micropython Chinese community. * http://www.micropython.org.cn */ //% weight=20 color=#0855AA icon="\uf043" block="温度传感器" namespace LM75A{ let LM75A_BASE_ADDRESS = 0x48; let LM75A_DEGREES_RESOLUTION = 0.125; /** * 获取温度值 * @param none * @param return tempature */ //% blockId="LM75A_getTemperatureInDegrees" block="获取温度值" //% weight=70 blockGap=8 //% parts=LM75A trackArgs=0 export function getTemperatureInDegrees():number{ let real_value = 1000.00; pins.i2cWriteNumber(LM75A_BASE_ADDRESS, 0x0, NumberFormat.UInt8LE, false) let result = pins.i2cReadNumber(LM75A_BASE_ADDRESS, NumberFormat.UInt16LE, false) let lowByte = (result>>8)&0xFF let highByte = result&0xFF let refactored_value = highByte << 8 | lowByte; refactored_value = refactored_value >> 5; if (refactored_value & 0x0400){ refactored_value |= 0xF800; refactored_value = ~refactored_value + 1; real_value = refactored_value * (-1) * LM75A_DEGREES_RESOLUTION; } else{ real_value = refactored_value * LM75A_DEGREES_RESOLUTION } return real_value; } }
Markdown
UTF-8
298
2.671875
3
[]
no_license
# copy-webpack-plugin 拷贝目录或目录中的文件到output.path指定的目录中 ```js new CopyWebpackPlugin([ {from: './doc', to: 'doc'} // 拷贝根目录下的doc目录中的所有文件到output.path指定的目录下的doc目录中,to可以不写,默认为output.path目录 ]) ```
Java
UTF-8
943
2.625
3
[]
no_license
package com.helloxin.zootopia.goose.queue.utils; import java.util.UUID; /** * Created by yexin on 2019/9/20. */ public class LinkUtils { private static final ThreadLocal<LinkBean> linkHolder = new ThreadLocal<>(); //目前写了一个过滤器来拦截请求,所以如果没有;链路id,则会取一个 static { LinkBean linkBean = new LinkBean(); if(linkBean.getLinkId() == null){ linkBean.setLinkId(UUID.randomUUID().toString()); } linkHolder.set(linkBean); } //设置链路Id public static void setlinkId(String linkId){ if(null == linkHolder.get()){ linkHolder.set(new LinkBean()); } linkHolder.get().setLinkId(linkId); } //返回链路Id,如果调用是不会存在没有的情况的 public static String getLinkId(){ return linkHolder.get() == null ? "":linkHolder.get().getLinkId(); } }
Python
UTF-8
1,806
3.09375
3
[ "MIT" ]
permissive
from parts.prob_calculator import IProbCalculator from parts import data_holder as dh import numpy as np class Model(object): def __init__(self, prob_calculator: IProbCalculator, class_num: int): self.__prob_calculator = prob_calculator self.__class_index_set = np.arange(class_num) self.__class_num = class_num def calc_fitness_value(self, data: np.ndarray, class_number: int)-> float: """ モデルの適合度を算出する :param data: :param class_number: :return: """ vectorized_calculator = np.frompyfunc(self.__prob_calculator.prob_data_index_in_class, 3, 1) index_set = np.arange(len(data)) prob_set = vectorized_calculator(index_set, data, class_number) return np.prod(prob_set)*self.__prob_calculator.prob_class(class_number) def predict(self, data: np.ndarray)->int: """ モデルの適合度から該当するクラスを算出する :param data: 算出対象となるデータ :return: 一番適合度が高いクラス。判定不能な場合,-1を返す """ fitness_set = np.array([self.calc_fitness_value(data, index) for index in self.__class_index_set]) result_index = np.argmax(fitness_set) # 確率なので最大値が0以下になることはあり得ない。0以下になるときは判定不能 return result_index if fitness_set[result_index] > 0 else -1 def test(self, data_set: np.ndarray, class_set: np.ndarray)->float: predicted_set = np.array([self.predict(data) for data in data_set]) # 教師データと予測されたデータの差が0でなければ誤判定 diff = class_set - predicted_set return np.sum(diff == 0)/len(data_set)
C#
UTF-8
1,511
3.0625
3
[]
no_license
using System.Collections.Generic; using System.Runtime.Serialization; namespace ConsoleOop.Configs { /// <summary> /// 封裝Schedule物件類別 /// </summary> [DataContract] class ScheduleManager : JsonManager { /// <summary> /// 陣列儲存多筆Schedule物件 /// </summary> [DataMember] private List<Schedule> schedules { get; set; } /// <summary> /// JSON檔案位置 /// </summary> private const string path = "schedules.json"; /// <summary> /// 陣列Schedule物件總數 /// </summary> public int Count => this.schedules.Count; /// <summary> /// 索引子 indexer /// </summary> /// <param name="number">索引</param> /// <returns>Schedule物件</returns> public Schedule this[int number] => this.schedules[number]; /// <summary> /// 建構子 初始設定 /// </summary> public ScheduleManager() { this.schedules = new List<Schedule>(); } /// <summary> /// 解析JSON檔案轉成Schedule物件陣列 /// </summary> public override void ProcessJsonConfig() { var obj = this.GetJsonObject<ScheduleManager>(path); this.schedules = new List<Schedule>(); for (int i = 0; i < obj.Count; i++) { this.schedules.Add(obj[i]); } } } }
C#
UTF-8
3,028
3.25
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace AllImportantProjects { class SumRootToLeave { public SumRootToLeave() { } public int calculateSum() { InOrder id = new InOrder(); Node root = id.createTree(2); Queue myQueue = new Queue(); myQueue.Enqueue(root); int sum = 0; while (myQueue.Count > 0) { Node top = (Node)myQueue.Dequeue(); if ((top.left == null) && (top.right == null)) { sum += top.value; } if (top.left != null) { top.left.value = top.value * 10 + top.left.value; myQueue.Enqueue(top.left); } if (top.right != null) { top.right.value = top.value * 10 + top.right.value; myQueue.Enqueue(top.right); } } return sum; } public void printAllpath(Node root, int sum) { if (root == null) return; ArrayList al = new ArrayList(); ArrayList working = new ArrayList(); printSumUtil(al, root, sum, working); } public void printTreeByLevel(Node root) { if (root==null) return; Queue cur = new Queue(); Queue next = new Queue(); cur.Enqueue(root); while ((cur.Count > 0) || (next.Count > 0)) { if (cur.Count > 0) { Node temp = (Node)cur.Dequeue(); Console.Write("{0}->", temp.value); if (temp.right != null) next.Enqueue(temp.right); if (temp.left != null) next.Enqueue(temp.left); } else { Console.WriteLine(); Queue tq = next; next = cur; cur = tq; } } } private void printSumUtil(ArrayList al, Node root, int sum, ArrayList working) { if (root == null) return; if (root.value == sum) { working.Add(root.value); ArrayList temp = (ArrayList)working.Clone(); al.Add(temp); return; } working.Add(root.value); if (root.left != null) { printSumUtil(al, root.left, sum - root.value, working); } if (root.right != null) { printSumUtil(al, root.right, sum - root.value, working); } working.RemoveAt(working.Count - 1); } } }
Java
UTF-8
1,002
2.03125
2
[ "MIT" ]
permissive
package com.thelivelock.elasticsearch_autocomplete.service; import com.thelivelock.elasticsearch_autocomplete.model.User; import com.thelivelock.elasticsearch_autocomplete.repository.UserRepository; import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { @Autowired private UserRepository userRepository; public List<User> listAll() { return this.userRepository.findAll(); } public User save(User user) { return this.userRepository.save(user); } public long count() { return this.userRepository.count(); } public List<User> search(String keywords) { MatchQueryBuilder searchByCountries = QueryBuilders.matchQuery("country", keywords); return this.userRepository.search(searchByCountries); } }
Markdown
UTF-8
4,147
2.609375
3
[ "MIT" ]
permissive
<!-- PROJECT SHIELDS --> <!-- *** I'm using markdown "reference style" links for readability. *** Reference links are enclosed in brackets [ ] instead of parentheses ( ). *** See the bottom of this document for the declaration of the reference variables *** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use. *** https://www.markdownguide.org/basic-syntax/#reference-style-links --> <center> [![Forks][forks-shield]][forks-url] [![Stargazers][stars-shield]][stars-url] [![MIT License][license-shield]][license-url] [![LinkedIn][linkedin-shield]][linkedin-url] [![resume][resume-shield]][resume-url] </center> <!-- PROJECT LOGO --> <br /> <p align="center"> <a href="http://joshuapleduc.com"> <img src="https://i.imgur.com/uxx6d9j.png" alt="Logo" width="400" height="400"> </a> <h1 align="center">Joshua Perez Leduc<Br>Software Engineer | Full Stack Developer</h1> <p align="left"> I am a software engineer and full stack developer who specializes in building applications specific to the business needs of my clients. I have done work in software development, mobile app creation, front-end/back-end web, and database/server management. My background in graphic design and photography, with experience in Adobe products such as Photoshop and Illustrator, fosters an eye for visual frontend development. Programming Languages: JavaScript, Ruby Web Technologies: React.js, HTML5, CSS, Thunk, Redux, Bootstrap, Rails, Vue, Angular, Apollo, Mongoose, MongoDB, Postgres, SQLite, Firebase Fluent Languages: English, Spanish <br /><br/> <a href="joshuapleduc.com"><strong>Explore the Website Portfolio »</strong></a> <br /> </p> </p> <details open="open"> <summary><h2 style="display: inline-block">Table of Contents</h2></summary> <ol> <li> <a href="#about-the-site">About the Site</a> <ul> <li><a href="#built-with">Built With</a></li> </ul> </li> <li> <a href="#see-locally">See locally</a> </li> <li><a href="#roadmap">Roadmap</a></li> <li><a href="#license">License</a></li> <li><a href="#contact">Contact</a></li> </ol> </details> ## About The Site <a href="http://joshuapleduc.com">Go to Site</a><br/> Showcases all of my work, work experience, personal projects, and school projects alike. Dark Mode [![Website Screen Shot][product-screenshot]](https://i.imgur.com/uP3eVTE.png)<br/> Light Mode [![Website Screen Shot 2][product-screenshot2]](https://i.imgur.com/mPv9tDM.png) ### Built With * [Create React App](https://reactjs.org/docs/create-a-new-react-app.html) * [SASS](https://sass-lang.com/) * [Deployed to Netlify](https://www.netlify.com/) ### See locally 1. Clone the repo ```sh git clone https://github.com/joshpled/late2021portfolio.git ``` 2. Install NPM packages ```sh npm install ``` 3. Run locally with NPM Start ```sh npm start ``` ## Roadmap * Working on adding more information about myself ## License Distributed under the MIT License. See `LICENSE` for more information. ## Contact <h3> Joshua Perez Leduc<br/> </h3> <a href="mailto:joshuapleduc@gmail.com"> joshuapleduc@gmail.com </a> <!-- MARKDOWN LINKS & IMAGES --> <!-- https://www.markdownguide.org/basic-syntax/#reference-style-links --> [forks-shield]: https://img.shields.io/github/forks/joshpled/late2021portfolio.svg?style=for-the-badge [forks-url]: https://github.com/joshpled/late2021portfolio/network/members [stars-shield]: https://img.shields.io/github/stars/joshpled/late2021portfolio.svg?style=for-the-badge [stars-url]: https://github.com/joshpled/late2021portfolio/stargazers [license-shield]: https://img.shields.io/github/license/joshpled/late2021portfolio.svg?style=for-the-badge [license-url]: https://github.com/joshpled/late2021portfolio/blob/main/LICENSE [linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555 [linkedin-url]: https://linkedin.com/in/joshuaperezleduc/ [resume-shield]: https://img.shields.io/badge/-resume-black.svg?style=for-the-badge&logo=googledrive&colorB=555 [resume-url]: https://drive.google.com/file/d/11LjmfBuYmrrUER4FJd0eqIFtvgnfD-Qo/view
C#
UTF-8
1,046
2.546875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace Hotel19760575.Models { public class Customer { [Key, Required] [DataType(DataType.EmailAddress)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public string Email { get; set; } [Required, Display(Name = "Surname")] [RegularExpression(@"[A-Za-z'-]{2,20}")] public string Surname { get; set; } [Required, Display(Name = "Given Name")] [RegularExpression(@"[A-Za-z'-]{2,20}")] public string GivenName { get; set; } [NotMapped] public string FullName => $"{GivenName} {Surname}"; [Required, Display(Name = "Postcode")] [RegularExpression(@"[0-9]{4}")] public string Postcode { get; set; } // Navigation Properties public ICollection<Booking> TheBookings { get; set; } } }
JavaScript
UTF-8
138
3.34375
3
[]
no_license
let nums = [24,8,23,32,5,62]; function arrange(a, b) { if (a > b) return 1; if (b > a) return -1; return 0; } nums.sort(arrange);
Java
UTF-8
8,715
3.1875
3
[ "MIT" ]
permissive
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.PriorityQueue; import java.util.Comparator; /** * @author Samuel Balco <sb592@le.ac.uk> * @version 1.1 (current version number of program) * @since 2014-04-20 (the version of the package this class was first added to) */ public class AStar { private MapGraph graph; Set<Container> settledNodes; //private Set<Container> unSettledNodes; PriorityQueue<Container> unSettledNodes; private Map<Container, Container> predecessors; private Map<Container, Double> distance, heuristic_distance; private Container target; public Comparator<Container> distanceComparator = new Comparator<Container>() { @Override public int compare(Container c1, Container c2) { return (int) ((getShortestHeuristicDistance(c1) - getShortestHeuristicDistance(c2))*1000); } }; public AStar(MapGraph graph) { // create a copy of the array so that we can operate on this array this.graph = graph; } /** * This method finds the route through the graph. * * @param source The origin node wrapped in the Container class object * @param target The destination node wrapped in the Container class object * Run this to find the route through the graph. */ public void execute(Container source, Container target) { this.target = target; settledNodes = new HashSet<Container>(); //unSettledNodes = new HashSet<Container>(); unSettledNodes = new PriorityQueue<Container>(1, distanceComparator); distance = new HashMap<Container, Double>(); heuristic_distance = new HashMap<Container, Double>(); predecessors = new HashMap<Container, Container>(); distance.put(source, 0.0); heuristic_distance.put(source, Grapher.calculateDistance(source.node.lat, source.node.lon, target.node.lat, target.node.lon)); unSettledNodes.add(source); while (unSettledNodes.size() > 0) { //Container node = getMinimum(unSettledNodes); Container node = unSettledNodes.poll(); if (node == target) return; settledNodes.add(node); unSettledNodes.remove(node); findMinimalDistances(node); } } /** * Method for calculating the minimal distances and adding all the neigbors of the input node */ private void findMinimalDistances(Container node) { List<Container> adjacentNodes = getNeighbors(node); for (Container target : adjacentNodes) { if (getShortestDistance(target) > getShortestDistance(node) + getDistance(node, target)) { distance.put(target, getShortestDistance(node) + getDistance(node, target)); heuristic_distance.put(target, (distance.get(target) + Grapher.calculateDistance(target.node.lat, target.node.lon, this.target.node.lat, this.target.node.lon)) ); predecessors.put(target, node); unSettledNodes.add(target); } } } /** * Method that returns the distance between node and target */ private double getDistance(Container node, Container target) { if (node.con.containsKey(target)){ return node.con.get(target).getWeight(); } throw new RuntimeException("Should not happen"); } /** * Method that returns the neighbors for the input node */ private List<Container> getNeighbors(Container node) { List<Container> neighbors = new ArrayList<Container>(); for (MapEdge edge : node.con.values()) { if (!isSettled(edge.getDestination())) { neighbors.add(edge.getDestination()); } } return neighbors; } /** * Checks if the vertex is in the settledNodes */ private boolean isSettled(Container vertex) { return settledNodes.contains(vertex); } /** * Method that returns the distance between of the destination node * If no value is found, Double.MAX_VALUE is returned */ private double getShortestDistance(Container destination) { Double d = distance.get(destination); if (d == null) return Double.MAX_VALUE; else return d; } private double getShortestHeuristicDistance(Container destination) { Double d = heuristic_distance.get(destination); if (d == null) return Double.MAX_VALUE; else return d; } /* * This method returns the path from the source to the selected target and * NULL if no path exists (the execute method must be called otherwise no path will be returned) */ public LinkedList<Container> getPath(Container target) { LinkedList<Container> path = new LinkedList<Container>(); Container step = target; // check if a path exists if (predecessors.get(step) == null) return null; path.add(step); while (predecessors.get(step) != null) { step = predecessors.get(step); //System.out.println("step: "+step); path.add(step); } // Put it into the correct order Collections.reverse(path); return path; } /* * This static method creates a new DijkstraShortestPath object, runs the algoritm and * returns a list of MapNode objects representing the path */ public static LinkedList<MapNode> getShortestPath(MapGraph g, Container source, Container target) { AStar astar = new AStar(g); long startTime = System.currentTimeMillis(); //speed test if(g.getVertices().contains(source)) { astar.execute(source, target); long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; System.out.print("Elapsed time for route: "); System.out.println(elapsedTime); if(g.getVertices().contains(target)) { startTime = System.currentTimeMillis(); LinkedList<Container> path = astar.getPath(target); stopTime = System.currentTimeMillis(); elapsedTime = stopTime - startTime; System.out.print("Elapsed time for route reconstruction: "); System.out.println(elapsedTime); if(path != null && path.size() > 0) { LinkedList<MapNode> ret = new LinkedList<MapNode>(); for (Container c : path) { ret.add(c.node); } return ret; } } } return null; } /* * This static method creates a new DijkstraShortestPath object, runs the algoritm and * returns a list of MapEdge objects representing the path */ public static List<MapEdge> getShortestPathEdges(MapGraph g, Container source, Container target) { AStar astar = new AStar(g); if(g.getVertices().contains(source)) { long startTime = System.currentTimeMillis(); //speed test astar.execute(source, target); long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; System.out.println("--AStar--"); System.out.print("Elapsed time for route: "); System.out.println(elapsedTime); System.out.print("No of nodes searched: "); System.out.println(astar.predecessors.size()); if(g.getVertices().contains(target)) { LinkedList<Container> path = astar.getPath(target); if(path != null && path.size() > 0) { LinkedList<MapEdge> ret = new LinkedList<MapEdge>(); for (int i = 0; i < path.size()-1; ++i) { Container c = path.get(i); Container next = path.get(i+1); ret.add(c.con.get(next)); } return ret; } } } return null; } public LinkedList<MapEdge> getShortestPathEdges(Container source, Container target) { if(graph.getVertices().contains(source)) { execute(source, target); if(graph.getVertices().contains(target)) { LinkedList<Container> path = getPath(target); //System.out.println("PATH: " + path); if(path != null && path.size() > 0) { LinkedList<MapEdge> ret = new LinkedList<MapEdge>(); for (int i = 0; i < path.size()-1; ++i) { Container c = path.get(i); Container next = path.get(i+1); ret.add(c.con.get(next)); } return ret; } } } return null; } public List<MapNode> getShortestReconstructedPath(Container source, Container target, Map<Long, MapWay> ways) { List<MapEdge> l = getShortestPathEdges(source, target); List<MapNode> ret = new LinkedList<MapNode>(); for(MapEdge e : l){ ret.add(e.getSource().node); ret.addAll(Grapher.getNodesBetween(e,ways.get(e.getId()))); ret.add(e.getDestination().node); } return ret; } public static List<MapNode> getShortestReconstructedPath(MapGraph g, Container source, Container target, Map<Long, MapWay> ways) { List<MapEdge> l = getShortestPathEdges(g, source, target); List<MapNode> ret = new LinkedList<MapNode>(); for(MapEdge e : l){ ret.add(e.getSource().node); ret.addAll(Grapher.getNodesBetween(e,ways.get(e.getId()))); ret.add(e.getDestination().node); } return ret; } }
JavaScript
UTF-8
1,972
2.8125
3
[]
no_license
import React, { Component } from 'react'; import style from './GameFieldBundle.module.scss'; class GameField extends Component { constructor(props) { super(props); this.drawX = this.drawX.bind(this); this.fieldNumbers = [1,2,3,4,5,6,7,8,9]; this.fields = this.fieldNumbers.map((num) => <li id={'field-' + num} onClick={(e) => this.drawX(num, e)} key={ num }></li> ); this.fieldState = [ [0,0,0], [0,0,0], [0,0,0], ]; } drawX(num) { let elem = document.getElementById('field-' + num); let imgUrl = process.env.PUBLIC_URL + '/cross.png'; let searchField = true; elem.style.backgroundImage = `url(${imgUrl})`; if(num <= 3) { this.fieldState[0][num - 1] = 1; } else if(num >= 4 && num <= 6) { this.fieldState[1][num - 4] = 1; } else { this.fieldState[2][num - 7] = 1; } console.log(this.fieldState); while(searchField) { let x = Math.floor(Math.random() * 3); let y = Math.floor(Math.random() * 3); let fieldKey = x + y; let circField; if(this.fieldState[x][y] !== 0) { continue; } if (x === 0) { fieldKey =+ 1; } else if (x === 1) { fieldKey += 3; } else if (x === 2) { fieldKey += 5; } circField = document.getElementById('field-' + fieldKey); circField.style.backgroundImage = `url(${process.env.PUBLIC_URL + '/circle.png'})`; this.fieldState[x][y] = -1; searchField = false; } } render() { return( <div> <ul className={ style.fieldWrapper }> { this.fields } </ul> </div> ); } } export default GameField;
Java
UTF-8
794
1.609375
2
[]
no_license
/** */ package ifc2x3tc1.impl; import ifc2x3tc1.Ifc2x3tc1Package; import ifc2x3tc1.IfcPreDefinedCurveFont; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ifc Pre Defined Curve Font</b></em>'. * <!-- end-user-doc --> * <p> * </p> * * @generated */ public class IfcPreDefinedCurveFontImpl extends IfcPreDefinedItemImpl implements IfcPreDefinedCurveFont { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcPreDefinedCurveFontImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ifc2x3tc1Package.eINSTANCE.getIfcPreDefinedCurveFont(); } } //IfcPreDefinedCurveFontImpl
Java
UTF-8
471
2.3125
2
[]
no_license
package servlet; import java.io.PrintWriter; public class ServletResponse { public PrintWriter out; private String enCoding="utf-8"; public PrintWriter getOut() { return out; } public void setOut(PrintWriter out) { this.out = out; } public String getEnCoding() { return enCoding; } public void setEnCoding(String enCoding) { this.enCoding = enCoding; } public void write(String text){ } }
Java
UTF-8
1,474
2.046875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2020 Dzikoysk * * 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. */ package org.panda_lang.reposilite.metadata; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.stream.Collectors; import java.util.stream.Stream; @XmlRootElement(name = "versions") @XmlAccessorType(XmlAccessType.FIELD) final class Versions { private final Collection<String> version; Versions(Collection<String> version) { this.version = version; } Versions() { this.version = new ArrayList<>(); } Collection<String> getVersion() { return version; } static Versions of(File[] files) { return new Versions(Stream.of(files) .map(File::getName) .collect(Collectors.toList())); } }
C#
UTF-8
2,528
2.796875
3
[]
no_license
using System; using System.ComponentModel; using System.Text; namespace ID3TagLib { [Serializable] public class TermsOfUseFrame: TextFrame, ISelectableTextEncoding, ISelectableLanguage, IEquatable<TermsOfUseFrame> { private TextEncoding encoding; private string language; protected internal TermsOfUseFrame(string frameID, FrameFlags flags) : base(frameID, flags) { encoding = TextEncoding.IsoLatin1; language = String.Empty; } public TextEncoding Encoding { get { return encoding; } set { if (!Enum.IsDefined(typeof(TextEncoding), value)) { throw new InvalidEnumArgumentException("value", (int)value, typeof(TextEncoding)); } encoding = value; } } public string Language { get { return language; } set { FrameUtil.CheckLanguage(value); language = value; } } public override bool Equals(object obj) { return Equals(obj as TermsOfUseFrame); } public bool Equals(TermsOfUseFrame other) { if (other == null) { return false; } return base.Equals(other) && encoding == other.encoding && language.Equals(other.language); } public override int GetHashCode() { int hashCode = base.GetHashCode(); hashCode ^= (int)encoding; hashCode ^= language.GetHashCode(); return hashCode; } public override object Clone() { TermsOfUseFrame obj = (TermsOfUseFrame)base.Clone(); obj.encoding = encoding; obj.language = language; return obj; } public override string ToString() { StringBuilder sBuild = new StringBuilder(base.ToString()); sBuild.Append("Encoding: "); sBuild.AppendLine(encoding.ToString()); sBuild.Append("Language: "); sBuild.AppendLine(language); return sBuild.ToString(); } protected override byte[] EncodeContentCore(ID3v2Tag tag) { byte[] rawData; Encoding e = StringEncoder.GetEncoding(encoding); rawData = new byte[StringEncoder.ByteCount(Text, e, false) + 4]; rawData[0] = (byte)encoding; StringEncoder.WriteLatin1String(rawData, 1, 3, language); StringEncoder.WriteString(rawData, 4, Text, e, false); return rawData; } protected override void DecodeContentCore(byte[] rawData, ID3v2Tag tag) { Encoding e; int bytesRead; StringDecoder.ParseEncodingByte(rawData, 0, 4, out e, out encoding); language = StringDecoder.DecodeLatin1String(rawData, 1, 3); Text = StringDecoder.DecodeString(rawData, 4, -1, e, out bytesRead); } } }
SQL
UTF-8
2,109
3.046875
3
[ "MIT" ]
permissive
-- migrate:up create procedure _add_example_data_0() modifies sql data begin set @userid = uuid_to_bin('17fbf1c6-34bd-11eb-af43-f4939feddd82', 1); set @otheruser = uuid_to_bin('972084d4-34cd-11eb-8f13-f4939feddd82', 1); set @sysid = uuid_to_bin('6b61d9ac-2e89-11eb-be2a-4dc7a6bcd0d9', 1); set @othersysid = uuid_to_bin('6513485a-34cd-11eb-8f13-f4939feddd82', 1); set @extime = timestamp('2020-12-01 01:23'); set @sysdef = '{ "name": "Test PV System", "boundary": { "nw_corner": {"latitude": 32.05, "longitude": -110.95}, "se_corner": {"latitude": 32.01, "longitude": -110.85} }, "ac_capacity": 10.0, "dc_ac_ratio": 1.2, "albedo": 0.2, "tracking": { "tilt": 20.0, "azimuth": 180.0 } }'; insert into users (auth0_id, id, created_at) values ( 'auth0|6061d0dfc96e2800685cb001', @userid, @extime ),( 'auth0|invalid', @otheruser, @extime ); insert into systems (id, user_id, name, definition, created_at, modified_at) values ( @sysid, @userid, 'Test PV System', @sysdef, @extime, @extime ),( @othersysid, @otheruser, 'Other system', '{}', @extime, @extime ); end; create procedure _remove_example_data_0() modifies sql data begin set @userid = uuid_to_bin('17fbf1c6-34bd-11eb-af43-f4939feddd82', 1); set @sysid = uuid_to_bin('6b61d9ac-2e89-11eb-be2a-4dc7a6bcd0d9', 1); set @othersysid = uuid_to_bin('6513485a-34cd-11eb-8f13-f4939feddd82', 1); set @otheruser = uuid_to_bin('972084d4-34cd-11eb-8f13-f4939feddd82', 1); delete from systems where id = @sysid; delete from systems where id = @othersysid; delete from users where id = @userid; delete from users where id = @otheruser; end; create procedure add_example_data () modifies sql data begin CALL _add_example_data_0; end; create procedure remove_example_data () modifies sql data begin call _remove_example_data_0; end; -- migrate:down drop procedure _remove_example_data_0;-- drop procedure remove_example_data; drop procedure _add_example_data_0; drop procedure add_example_data;
C#
UTF-8
1,138
3.6875
4
[ "MIT" ]
permissive
/******************************************************************** * * 34. Write a program to check if a string starts with a specified word. * * By: Jesus Hilario Hernandez * Last Updated: October 14th 2017 * * ********************************************************************/ using System; public class Exercise_34 { public static void Main() { /************************ * Jesus' Solution ************************/ Console.Write("Input a string: "); var string1 = Convert.ToString(Console.ReadLine()); // Console.WriteLine(string1.Substring(5) == "Hello"); /******************************************* * Jesus' Solution After checking response *******************************************/ Console.WriteLine(string1.StartsWith("Hello")); /************************** * W3resource's Solution **************************/ string str; Console.Write("Input a string : "); str = Console.ReadLine(); var condition1 = (str.Length < 6 && str.Equals("Hello")); var condition2 = (str.StartsWith("Hello") && str[5] == ' '); Console.WriteLine(condition1 || condition2); } }
C++
UTF-8
3,741
2.90625
3
[ "BSD-3-Clause", "MIT" ]
permissive
// Copyright 2006 David D. Diel, MIT License #include <malloc.h> #include <math.h> #include <stdio.h> #include <memory.h> #include "mex.h" /*** helper function prototypes ***/ signed char manageFeatures(unsigned char*,double,double,double,int,int); /* MATLAB function [outmask,status]=MEXmanageFeatures(mask,x,y,r) % coordinates are defined in sub-element matrix notation % % ARGUMENTS: % mask = UInt8 array that defines acceptable regions by its non-zero elements (m-by-n) % x,y = sub-pixel feature positions, skipped if NaN (K-by-1) or (1-by-K) % r = the number of pixels to occupy around each feature (1-by-1) % % RETURNS: % outmask = UInt8 mask showing open regions where new features could be found (m-by-n) % status = Int8 returns a code, defined as follows: % -2 = dead / feature overlap % -1 = dead / lost in tracking % 1 = alive / inactive */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { int cnt,m,n,k,K; double *x,*y; double r; unsigned char *mask,*outmask; signed char *status; int outdims[2]; /* check for proper number of inputs */ if(nrhs != 4) { mexErrMsgTxt("Usage [status,outmask]=MEXmanageFeatures(mask,x,y,r)"); } else if(nlhs > 2) { mexErrMsgTxt("Too many output arguments"); } /* the inputs must be of the correct type */ if( mxIsComplex(prhs[0]) || !mxIsUint8(prhs[0]) ) { mexErrMsgTxt("First argument must be noncomplex Uint8"); } for(cnt=1;cnt<4;cnt++) { if( mxIsComplex(prhs[cnt]) || !mxIsDouble(prhs[cnt]) ) { mexErrMsgTxt("Last three arguments must be noncomplex double"); } } /* extract array sizes */ m=mxGetM(prhs[0]); n=mxGetN(prhs[0]); /* check list lengths */ if( (mxGetM(prhs[3])!=1) || (mxGetN(prhs[3])!=1) ) { mexErrMsgTxt("Argument dimensions are incorrect"); } k=mxGetM(prhs[1]); K=mxGetN(prhs[1]); if( (mxGetM(prhs[2])!=k) || (mxGetN(prhs[2])!=K) ) { mexErrMsgTxt("Coordinate lists must be the same size."); } mask=(unsigned char*)mxGetData(prhs[0]); x=(double*)mxGetData(prhs[1]); y=(double*)mxGetData(prhs[2]); r=*(double*)mxGetData(prhs[3]); /* allocate memory for return arguments and assign pointers */ outdims[0]=m; outdims[1]=n; plhs[0]=mxCreateNumericArray(2,outdims,mxUINT8_CLASS, mxREAL); outmask=(unsigned char*)mxGetData(plhs[0]); outdims[0]=k; outdims[1]=K; plhs[1]=mxCreateNumericArray(2,outdims,mxINT8_CLASS, mxREAL); status=(signed char*)mxGetData(plhs[1]); /* make output mask a copy of the input mask */ memcpy(outmask,mask,m*n); /* deal with empty list case */ if((k==0)||(K==0)) {return;} if(k>K) {K=k;} /* for each feature */ for(k=0;k<K;k++) { /* call the function to do the work, and change Matlab indices to C convention */ status[k]=manageFeatures(outmask,x[k]-1.0,y[k]-1.0,r,m,n); } return; } /* management by greedy territory occupancy */ signed char manageFeatures(unsigned char *mask, double x, double y, double r, int m, int n) { int xf,yf,rf; int xfm,xfp,yfm,yfp; int i,j; /* checking NaN */ if( mxIsNaN(x) || mxIsNaN(y) ) {return -1;} xf=(int)floor(x+0.5); yf=(int)floor(y+0.5); rf=(int)floor(r+0.5); xfm=xf-rf; xfp=xf+rf; yfm=yf-rf; yfp=yf+rf; /* check bounds */ if( !( (xfm>=0) && (yfm>=0) && (xfp<m) && (yfp<n) ) ) {return -1;} /* check for previous mask */ if(mask[xf+yf*m]==0) {return -2;} /* fill territory */ for(j=yfm;j<=yfp;j++) { for(i=xfm;i<=xfp;i++) { mask[i+j*m]=0; } } return 1; }
C
UTF-8
353
3.296875
3
[]
no_license
#include <stdio.h> #include "Queue.h" int emptyQueue(Queue *q) { if ((q->ll).size == 0) return 1; else return 0; } int enqueue(Queue *q, int item) { insertNode(&(q->ll), (q->ll).size, item); } int dequeue(Queue *q) { int item = ((q->ll).head)->item; removeNode(&(q->ll), 0); return item; } int front(Queue *q) { return ((q->ll).head)->item; }
C#
UTF-8
2,812
3.15625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodingCataliyst_AddictiveGame { static class Utils { public static void Position(int val, int rows, int column, out int x, out int y) { int counter = 0; for (int r = 1; r <= rows; r++) for (int c = 1; c <= column; c++) { counter++; if (counter == val) { x = r; y = c; return; } } x = 0; y = 0; } public static int ManhatanDistance(int poz1, int poz2, int rows, int column) { int x1, y1, x2, y2; Position(poz1, rows, column, out x1, out y1); Position(poz2, rows, column, out x2, out y2); return Math.Abs(x1 - x2) + Math.Abs(y1 - y2); } internal static int ValidPath(int rows, int columns, int start, int pathColor, Dictionary<int, int> pointsDictionary,string[] steps, out bool succes) { //Position(start, rows, columns, out int xstart, out int ystart); List<int> previous = new List<int>(); int initial = start; succes = false; for(int i=0;i<steps.Length;i++) { switch(steps[i]) { case "S":start += columns; break; case "N":start -= columns; break; case "W": { if (start % columns == 1) return i+1; start--; } break; case "E": { if (start % columns == 0) return i+1; start++; } break; } if (start < 0 || start > rows * columns || previous.Contains(start)) return i + 1; previous.Add(start); if (pointsDictionary.ContainsKey(start)) { if (i != steps.Length - 1) return i + 1; else if (pointsDictionary[start] != pointsDictionary[initial]) return i + 1; } else if (i == steps.Length - 1) return i + 1; } if(start!=initial) succes = true; return steps.Length; } } }
Python
UTF-8
1,685
3.25
3
[]
no_license
class Solution(object): def maxAreaRectangle(self, heights): heights = [0]+heights+[0] stack = [] maxArea = 0 for i in range(len(heights)): if not stack or heights[i]>=heights[stack[-1]]: stack.append(i) continue while(heights[stack[-1]]>heights[i]): currHeight = heights[stack[-1]] stack.pop() maxArea = max(maxArea, currHeight*(i-stack[-1]-1)) # print currHeight*(i-stack[-1]-1) stack.append(i) return maxArea def maximalRectangle(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ # 此题是之前那道的 Largest Rectangle in Histogram 的扩展,这道题的二维矩阵每一层向上都可以看做一个直方图,输入矩阵有多少行,就可以形成多少个直方图,对每个直方图都调用 Largest Rectangle in Histogram 中的方法,就可以得到最大的矩形面积。那么这道题唯一要做的就是将每一层都当作直方图的底层,并向上构造整个直方图. if not matrix or not matrix[0]: return 0 matrix[0] = map(int, matrix[0]) maxArea = self.maxAreaRectangle(matrix[0]) for i in range(1, len(matrix)): matrix[i] = map(int, matrix[i]) for j in range(len(matrix[i])): if matrix[i][j] == 1: matrix[i][j] += matrix[i-1][j] currArea =self.maxAreaRectangle(matrix[i]) maxArea = max(maxArea, currArea) return maxArea
Java
UTF-8
618
2.546875
3
[]
no_license
package com.hpdev; /** * Created by harry on 16/10/2016. */ public class Command { private String PiName; private String RoomName; private String UserName; private int Command; public Command( String roomName, String userName, int command) { RoomName = roomName; UserName = userName; Command = command; } public String getPiName() { return PiName; } public String getRoomName() { return RoomName; } public String getUserName() { return UserName; } public int getCommand() { return Command; } }
Markdown
UTF-8
207
3.078125
3
[]
no_license
**Create a function that takes two integers and checks if they are equal.** **Examples:** ***isEqual(5, 6) ➞ false*** ***isEqual(1, 1) ➞ true*** ***isEqual(36, 35) ➞ false*** *** Solving by java
JavaScript
UTF-8
7,072
2.90625
3
[]
no_license
//Dropdown function dropdown() { document.getElementById('dropdown').classList.toggle('show'); } function dropdownFilter() { var input, filter, a, i; input = document.getElementById('dropdownInput'); filter = input.value.toUpperCase(); div = document.getElementById('dropdown'); a = div.getElementsByTagName('a'); for (i = 0; i < a.length; i++) { txtValue = a[i].textContent || a[i].innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { a[i].style.display = ''; } else { a[i].style.display = 'none'; } } } //Displays the map in body > #mapid function getMap(lat, lng) { var map = L.map('mapid').setView([lat, lng], 7); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); function onMapClick(e) { console.log(e.latlng); getCountryData(e.latlng['lat'], e.latlng['lng']); }; //adds the onclick lisserner map.on('click', onMapClick); return map; } //uses lat lng to reverse geocode and geocode, returning the data function getCountryData(lat, lng){ let data = {}; $.ajax({ //gets reverseGeocoding APIs url: "libs/php/reverseGeocoding.php", type: 'POST', dataType: 'JSON', data: { lat: lat, lng: lng }, success: function(result) { data.reverseGeocoding = result; //console.log(data); //n^2 brute search for(let i=0; i < result.borders.features.length; i++){ if(result.borders.features[i].properties.iso_a2 == result.dataReverse[0].results[0].components["ISO_3166-1_alpha-2"]){ console.log(`found border, key${i}`); let tempBounds = {}; if(!result.dataReverse[0].results[0].bounds) { //some countries such dont have console.log('creating bounds'); for(let z = 0; z < result.borders.features[i].geometry.coordinates.length; z++) { for(let y = 0; y < result.borders.features[i].geometry.coordinates[z].length; y++) { for(let x = 0; x < result.borders.features[i].geometry.coordinates[z][x].length; x++) { if(result.borders.features[i].geometry.coordinates[z][x][0] > tempBounds.northeast.lng) { //check lng tempBounds.northeast.lng = result.borders.features[i].geometry.coordinates[z][x][0]; } else if(result.borders.features[i].geometry.coordinates[z][x][0] < tempBounds.southwest.lng){ tempBounds.southwest.lng = result.borders.features[i].geometry.coordinates[z][x][0]; } if(result.borders.features[i].geometry.coordinates[z][x][1] > tempBounds.northeast.lat) {//check lat tempBounds.northeast.lat = result.borders.features[i].geometry.coordinates[z][x][1]; } else if(result.borders.features[i].geometry.coordinates[z][x][1] < tempBounds.southwest.lat) { tempBounds.southwest.lat = result.borders.features[i].geometry.coordinates[z][x][1]; } } } } result.dataReverse[0].results[0].bounds = tempBounds; console.log('made bounds'); console.log(result.dataReverse[0].results[0].bounds); } $.ajax({ //gets the restCountries API url: "libs/php/restCountries.php", type: 'POST', dataType: 'JSON', data: { isoA2: result.borders.features[i].properties.iso_a2, }, success: function(restCountries) { data.restCountries = restCountries; //console.log(data); $.ajax({ //gets geocoding APIs url: "libs/php/Geocoding.php", type: 'POST', dataType: 'JSON', data: { isoA2: result.borders.features[i].properties.iso_a2, borders: result.borders.features[i], currency: data.restCountries.restCountries[0].currencies[0].code, northEastLat: result.dataReverse[0].results[0].bounds.northeast.lat, northEastLng: result.dataReverse[0].results[0].bounds.northeast.lng, southWestLat: result.dataReverse[0].results[0].bounds.southwest.lat, southWestLng: result.dataReverse[0].results[0].bounds.southwest.lng }, success: function(geocoding) { data.geocoding = geocoding; //console.log(data); }, error: function(jqXHR, textStatus, errorThrown){ console.log('error'); console.log(jqXHR, textStatus, errorThrown) } }) }, error: function(jqXHR, textStatus, errorThrown){ console.log('error'); console.log(jqXHR, textStatus, errorThrown) } }) break; } } }, error: function(jqXHR, textStatus, errorThrown){ console.log(jqXHR, textStatus, errorThrown) } }); console.log(data); return data; } function setSearchableLocations(){ $.ajax({ url: "libs/php/decode.php", type: 'POST', dataType: 'JSON', success: function(result) { console.log(result); let text = ''; for (let i = 0; i < result.features.length; i++) { text += `<a href="${result.features[i].properties.name}">${result.features[i].properties.name}</a>` } document.getElementById('Searchablelocations').innerHTML = text; }, error: function(jqXHR, textStatus, errorThrown){ console.log('error'); console.log(jqXHR, textStatus, errorThrown); } }); }
Java
UTF-8
50,598
2.609375
3
[]
no_license
package com.example.demo.service; import com.example.demo.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; @Service public class EmailService { @Autowired @Qualifier("serviceMailSender") private JavaMailSender javaMailSender; public void sendWelcomeEmail(User user){ //https://stackoverflow.com/questions/49313440/mimemessagehelper-spring-boot-to-send-email try { MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED, "UTF-8"); helper.setSubject("Welcome "+user.getUsername()+"!"); helper.setTo(user.getEmail()); helper.setFrom("Test Message<peacetestmsg@gmail.com>"); helper.setText("Greetings!(from plain text)", "<center>\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" height=\"100%\" width=\"100%\" id=\"bodyTable\">\n" + " <tr>\n" + " <td align=\"center\" valign=\"top\" id=\"bodyCell\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tr>\n" + " <td align=\"center\" valign=\"top\" id=\"templatePreheader\">\n" + "\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" \n" + " style=\" justify-content: center;\">\n" + " <tr>\n" + " <td valign=\"top\" >\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"min-width:100%;\">\n" + " <tbody >\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding:9px\" >\n" + " <table align=\"left\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"min-width:100%;\">\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding-right: 9px; padding-left: 9px; padding-top: 0; padding-bottom: 0; text-align:center;\">\n" + " <img align=\"center\" alt=\"\" src=\"https://gallery.mailchimp.com/6d5e686af3a776f67a79d56e6/images/99cf80c1-e13e-4d11-b362-99f2353760be.png\" width=\"564\" style=\"max-width:1169px; padding-bottom: 0; display: inline !important; vertical-align: bottom;\" >\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td align=\"center\" valign=\"top\" id=\"templateHeader\">\n" + "\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"justify-content: center;\">\n" + " <tr>\n" + " <td valign=\"top\" >\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"min-width:100%;\">\n" + " <tbody >\n" + " <tr>\n" + " <td valign=\"top\" >\n" + " <table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"min-width:100%;\" >\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding: 9px 18px;color: #1E2945;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;line-height: 150%;text-align: left;\">\n" + " <p style=\"line-height: 150%;color: #1E2945;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;text-align: left;\"><strong>Hi "+user.getUsername()+", welcome on board!</strong>\n" + " <br>\n" + " <br>You'll be the first to know!\n" + " <br>\n" + " <br>This app is going to be awesome and it will change your experience.\n" + " <br>&nbsp;</p>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" >\n" + " <tbody >\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding:9px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding:0 9px; flex-wrap: wrap ;justify-content: center; flex-direction: row;\">\n" + " <table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" >\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\">\n" + " <img alt=\"\" src=\"https://gallery.mailchimp.com/6d5e686af3a776f67a79d56e6/images/cb8921b8-15d6-4658-8a6e-5dac7f4ad2d6.gif\" width=\"264\" style=\"max-width:340px;\" >\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table align=\"right\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"264\">\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"color: #1F2A44;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;line-height: 150%;\">\n" + " <p style=\"color: #1F2A44;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;line-height: 150%;\">You will have full control of your animations, at anytime!</p>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" >\n" + " <tbody >\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding:9px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding:0 9px; flex-wrap: wrap ;justify-content: center; flex-direction: row-reverse;\">\n" + " <table align=\"right\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" >\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\">\n" + " <img alt=\"\" src=\"https://gallery.mailchimp.com/6d5e686af3a776f67a79d56e6/images/32e57b08-f048-4a8f-b6bd-bcd5b8cc2eaf.gif\" width=\"264\" style=\"max-width:340px;\" >\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"264\">\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"color: #1F2A44;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;line-height: 150%;\">\n" + " <p style=\"color: #1F2A44;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;line-height: 150%;\"><span >Realtime feedback, creating animations is fun!</span>\n" + " </p>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" >\n" + " <tbody >\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding:9px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding:0 9px; flex-wrap: wrap ;justify-content: center; flex-direction:row\">\n" + " <table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" >\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\">\n" + " <img alt=\"\" src=\"https://gallery.mailchimp.com/6d5e686af3a776f67a79d56e6/images/1db61e28-9379-4773-9a94-3c79ef1152dd.gif\" width=\"264\" style=\"max-width:340px;\" >\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table align=\"right\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"264\">\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"color: #1F2A44;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;line-height: 150%;\">\n" + " <p style=\"color: #1F2A44;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;line-height: 150%;\"><span >It's easy to use, everybody should be able to create amazing animations!</span>\n" + " </p>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" >\n" + " <tbody >\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding:9px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding:0 9px; flex-wrap: wrap ;justify-content: center; flex-direction: row-reverse;\">\n" + " <table align=\"right\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" >\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\">\n" + " <img alt=\"\" src=\"https://gallery.mailchimp.com/6d5e686af3a776f67a79d56e6/images/ac631a91-09ac-4f6f-b994-95dcbde08741.gif\" width=\"264\" style=\"max-width:340px;\" >\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"264\">\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"color: #1F2A44;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;line-height: 150%;\">\n" + " <p style=\"color: #1F2A44;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;line-height: 150%;\"><span >Everybody wants their animation to run smoothly, therefore this app runs on GPU whenever possible.</span>\n" + " </p>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" >\n" + " <tbody >\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding:0 9px; flex-wrap: wrap ;justify-content: center; flex-direction: row;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding:0 9px; flex-wrap: wrap ;justify-content: center; flex-direction: row;\">\n" + " <table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\">\n" + " <img alt=\"\" src=\"https://gallery.mailchimp.com/6d5e686af3a776f67a79d56e6/images/75b2c7e5-b914-4bfc-abd1-18e3a3c159a8.gif\" width=\"264\" style=\"max-width:340px;\" >\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table align=\"right\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"264\">\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"color: #1F2A44;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;line-height: 150%;\">\n" + " <p style=\"color: #1F2A44;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;line-height: 150%;\"><span >No coding required. Build prototypes or production ready animations in no time!\n" + "<br>You can add custom javascript for even more control.</span>\n" + " </p>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" >\n" + " <tbody >\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding:9px;\">\n" + " <table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"false\">\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding: 0px 9px;color: #1F2A44;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;line-height: 150%;\" width=\"564\">\n" + " <br> <span style=\"line-height:20.8px\">Please sit back and wait while I do all the work and build something great for you!</span>\n" + "\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td align=\"center\" valign=\"top\" style=\"padding:9px 9px 0 9px;\">\n" + " <img alt=\"\" src=\"https://gallery.mailchimp.com/6d5e686af3a776f67a79d56e6/images/6f25dcf1-ca58-47fe-b1a3-b53b200189e8.gif\" width=\"340\" style=\"max-width:340px;\" >\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"min-width:100%;\">\n" + " <tbody >\n" + " <tr>\n" + " <td valign=\"top\" >\n" + " <table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"min-width:100%;\" >\n" + " <tbody>\n" + " <tr>\n" + " <td valign=\"top\" style=\"padding: 9px 18px;color: #1E2945;font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;font-size: 18px;font-style: normal;font-weight: normal;line-height: 150%;\">I hope to see you soon,\n" + " <br>\n" + " <br>\n" + " <br>\n" + " <br>\n" + " Greetings from developer:\n" + " <br>\n" + " <a href=\"https://www.linkedin.com/in/ping-adam-he-peace1991/\">Ping He(Peace/Adam)</a>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </center>\n" + "\n" + "\n"); javaMailSender.send(message); }catch (MessagingException e){ e.printStackTrace(); } } public void sendResetPassword(User user,String token){ //https://stackoverflow.com/questions/49313440/mimemessagehelper-spring-boot-to-send-email try { MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED, "UTF-8"); helper.setSubject("Reset Password!"); helper.setTo(user.getEmail()); helper.setFrom("Test Message<peacetestmsg@gmail.com>"); helper.setText("Reset Password.", "<center>\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" height=\"100%\" id=\"bodyTable\" style=\"border-collapse: collapse; mso-table-lspace: 0;\n" + " mso-table-rspace: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust:\n" + " 100%; background-color: #fed149; height: 100%; margin: 0; padding: 0; width:\n" + " 100%\" width=\"100%\">\n" + " <tr>\n" + " <td align=\"center\" id=\"bodyCell\" style=\"mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; border-top: 0;\n" + " height: 100%; margin: 0; padding: 0; width: 100%\" valign=\"top\">\n" + " <!-- BEGIN TEMPLATE // -->\n" + " <!--[if gte mso 9]>\n" + " <table align=\"center\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"600\" style=\"width:600px;\">\n" + " <tr>\n" + " <td align=\"center\" valign=\"top\" width=\"600\" style=\"width:600px;\">\n" + " <![endif]-->\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"templateContainer\" style=\"border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; max-width:\n" + " 600px; border: 0\" width=\"100%\">\n" + " <tr>\n" + " <td id=\"templatePreheader\" style=\"mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; background-color: #fed149;\n" + " border-top: 0; border-bottom: 0; padding-top: 16px; padding-bottom: 8px\" valign=\"top\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnTextBlock\" style=\"border-collapse: collapse; mso-table-lspace: 0;\n" + " mso-table-rspace: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;\n" + " min-width:100%;\" width=\"100%\">\n" + " <tbody class=\"mcnTextBlockOuter\">\n" + " <tr>\n" + " <td class=\"mcnTextBlockInner\" style=\"mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%\" valign=\"top\">\n" + " <table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnTextContentContainer\" style=\"border-collapse: collapse; mso-table-lspace: 0;\n" + " mso-table-rspace: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust:\n" + " 100%; min-width:100%;\" width=\"100%\">\n" + " <tbody>\n" + " <tr>\n" + " <td class=\"mcnTextContent\" style='mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; word-break: break-word;\n" + " color: #2a2a2a; font-family: \"Asap\", Helvetica, sans-serif; font-size: 12px;\n" + " line-height: 150%; text-align: left; padding-top:9px; padding-right: 18px;\n" + " padding-bottom: 9px; padding-left: 18px;' valign=\"top\">\n" + " <a style=\"mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; color: #2a2a2a;\n" + " font-weight: normal; text-decoration: none\" target=\"_blank\" title=\"Lingo is the\n" + " best way to organize, share and use all your visual assets in one place -\n" + " all on your desktop.\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td id=\"templateHeader\" style=\"mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; background-color: #f7f7ff;\n" + " border-top: 0; border-bottom: 0; padding-top: 16px; padding-bottom: 0\" valign=\"top\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnImageBlock\" style=\"border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;\n" + " min-width:100%;\" width=\"100%\">\n" + " <tbody class=\"mcnImageBlockOuter\">\n" + " <tr>\n" + " <td class=\"mcnImageBlockInner\" style=\"mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding:0px\" valign=\"top\">\n" + " <table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnImageContentContainer\" style=\"border-collapse: collapse; mso-table-lspace: 0;\n" + " mso-table-rspace: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust:\n" + " 100%; min-width:100%;\" width=\"100%\">\n" + " <tbody>\n" + " <tr>\n" + " <td class=\"mcnImageContent\" style=\"mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-right: 0px;\n" + " padding-left: 0px; padding-top: 0; padding-bottom: 0; text-align:center;\" valign=\"top\">\n" + " <a class=\"\" style=\"mso-line-height-rule:\n" + " exactly; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; color:\n" + " #f57153; font-weight: normal; text-decoration: none\" target=\"_blank\" title=\"\">\n" + " <img align=\"center\" alt=\"Forgot your password?\" class=\"mcnImage\" src=\"https://static.lingoapp.com/assets/images/email/il-password-reset@2x.png\" style=\"-ms-interpolation-mode: bicubic; border: 0; height: auto; outline: none;\n" + " text-decoration: none; vertical-align: bottom; max-width:1200px; padding-bottom:\n" + " 0; display: inline !important; vertical-align: bottom;\" width=\"600\"></img>\n" + " </a>\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td id=\"templateBody\" style=\"mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; background-color: #f7f7ff;\n" + " border-top: 0; border-bottom: 0; padding-top: 0; padding-bottom: 0\" valign=\"top\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnTextBlock\" style=\"border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; min-width:100%;\" width=\"100%\">\n" + " <tbody class=\"mcnTextBlockOuter\">\n" + " <tr>\n" + " <td class=\"mcnTextBlockInner\" style=\"mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%\" valign=\"top\">\n" + " <table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnTextContentContainer\" style=\"border-collapse: collapse; mso-table-lspace: 0;\n" + " mso-table-rspace: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust:\n" + " 100%; min-width:100%;\" width=\"100%\">\n" + " <tbody>\n" + " <tr>\n" + " <td class=\"mcnTextContent\" style='mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; word-break: break-word;\n" + " color: #2a2a2a; font-family: \"Asap\", Helvetica, sans-serif; font-size: 16px;\n" + " line-height: 150%; text-align: center; padding-top:9px; padding-right: 18px;\n" + " padding-bottom: 9px; padding-left: 18px;' valign=\"top\">\n" + "\n" + " <h1 class=\"null\" style='color: #2a2a2a; font-family: \"Asap\", Helvetica,\n" + " sans-serif; font-size: 32px; font-style: normal; font-weight: bold; line-height:\n" + " 125%; letter-spacing: 2px; text-align: center; display: block; margin: 0;\n" + " padding: 0'><span style=\"text-transform:uppercase\">Forgot</span></h1>\n" + "\n" + "\n" + " <h2 class=\"null\" style='color: #2a2a2a; font-family: \"Asap\", Helvetica,\n" + " sans-serif; font-size: 24px; font-style: normal; font-weight: bold; line-height:\n" + " 125%; letter-spacing: 1px; text-align: center; display: block; margin: 0;\n" + " padding: 0'><span style=\"text-transform:uppercase\">your password?</span></h2>\n" + "\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnTextBlock\" style=\"border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace:\n" + " 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;\n" + " min-width:100%;\" width=\"100%\">\n" + " <tbody class=\"mcnTextBlockOuter\">\n" + " <tr>\n" + " <td class=\"mcnTextBlockInner\" style=\"mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%\" valign=\"top\">\n" + " <table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnTextContentContainer\" style=\"border-collapse: collapse; mso-table-lspace: 0;\n" + " mso-table-rspace: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust:\n" + " 100%; min-width:100%;\" width=\"100%\">\n" + " <tbody>\n" + " <tr>\n" + " <td class=\"mcnTextContent\" style='mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; word-break: break-word;\n" + " color: #2a2a2a; font-family: \"Asap\", Helvetica, sans-serif; font-size: 16px;\n" + " line-height: 150%; text-align: center; padding-top:9px; padding-right: 18px;\n" + " padding-bottom: 9px; padding-left: 18px;' valign=\"top\">Not to worry, we got you! Let’s get you a new password.\n" + " <br></br>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnButtonBlock\" style=\"border-collapse: collapse; mso-table-lspace: 0;\n" + " mso-table-rspace: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;\n" + " min-width:100%;\" width=\"100%\">\n" + " <tbody class=\"mcnButtonBlockOuter\">\n" + " <tr>\n" + " <td align=\"center\" class=\"mcnButtonBlockInner\" style=\"mso-line-height-rule:\n" + " exactly; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;\n" + " padding-top:18px; padding-right:18px; padding-bottom:18px; padding-left:18px;\" valign=\"top\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnButtonBlock\" style=\"border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; min-width:100%;\" width=\"100%\">\n" + " <tbody class=\"mcnButtonBlockOuter\">\n" + " <tr>\n" + " <td align=\"center\" class=\"mcnButtonBlockInner\" style=\"mso-line-height-rule:\n" + " exactly; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;\n" + " padding-top:0; padding-right:18px; padding-bottom:18px; padding-left:18px;\" valign=\"top\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnButtonContentContainer\" style=\"border-collapse: collapse; mso-table-lspace: 0;\n" + " mso-table-rspace: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;\n" + " border-collapse: separate !important;border-radius: 48px;background-color:\n" + " #F57153;\">\n" + " <tbody>\n" + " <tr>\n" + " <td align=\"center\" class=\"mcnButtonContent\" style=\"mso-line-height-rule:\n" + " exactly; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;\n" + " font-family: 'Asap', Helvetica, sans-serif; font-size: 16px; padding-top:24px;\n" + " padding-right:48px; padding-bottom:24px; padding-left:48px;\" valign=\"middle\">\n" + " <a href=\"http://localhost:8080/changepassword?token="+token+"\" target=\"_blank\" >Reset password</a>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnImageBlock\" style=\"border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; min-width:100%;\" width=\"100%\">\n" + " <tbody class=\"mcnImageBlockOuter\">\n" + " <tr>\n" + " <td class=\"mcnImageBlockInner\" style=\"mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding:0px\" valign=\"top\">\n" + " <table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnImageContentContainer\" style=\"border-collapse: collapse; mso-table-lspace: 0;\n" + " mso-table-rspace: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust:\n" + " 100%; min-width:100%;\" width=\"100%\">\n" + " <tbody>\n" + " <tr>\n" + " <td class=\"mcnImageContent\" style=\"mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-right: 0px;\n" + " padding-left: 0px; padding-top: 0; padding-bottom: 0; text-align:center;\" valign=\"top\"></td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td id=\"templateFooter\" style=\"mso-line-height-rule: exactly;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; background-color: #fed149;\n" + " border-top: 0; border-bottom: 0; padding-top: 8px; padding-bottom: 80px\" valign=\"top\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnTextBlock\" style=\"border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0;\n" + " -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; min-width:100%;\" width=\"100%\">\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " <!--[if gte mso 9]>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " <![endif]-->\n" + " <!-- // END TEMPLATE -->\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </center>\n"); javaMailSender.send(message); }catch (MessagingException e){ e.printStackTrace(); } } }
PHP
UTF-8
2,297
2.625
3
[ "MIT" ]
permissive
<?php namespace Lincable\Http\File; use Illuminate\Http\Request; use Lincable\Http\FileRequest; use Illuminate\Container\Container; use Illuminate\Http\File as IlluminateFile; use Lincable\Exceptions\NotResolvableFileException; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\File\File as SymfonyFile; class FileResolver { /** * Resolve the file object to a symfony file, handling the * file request operations. * * @throws \Lincable\Exceptions\NotResolvableFileException * * @param mixed $file * @return \Illuminate\Http\File */ public static function resolve($file) { switch (true) { case is_string($file): $file = new SymfonyFile($file); break; case $file instanceof FileRequest: $file = static::resolveFileRequest($file); break; case $file instanceof UploadedFile: $filename = $file->hashName(); $file = $file->move(config('lincable.temp_directory'), $filename); break; case $file instanceof IlluminateFile: return $file; break; case $file instanceof Symfonyfile: break; default: throw new NotResolvableFileException($file); } return static::toIlluminateFile($file); } /** * Convert a symfony file to illuminate file. * * @param \Symfony\Component\HttpFoundation\File\File $file * @return \Illuminate\Http\File */ public static function toIlluminateFile(SymfonyFile $file) { return new IlluminateFile($file->getPathName()); } /** * Handle a file request and resolve to a file. * * @param \Lincable\Http\FileRequest $file * @return \Symfony\Component\HttpFoundation\File\File */ public static function resolveFileRequest(FileRequest $file) { // Get the global container instance. $app = Container::getInstance(); if (! $file->isBooted()) { // Boot the file request with the current request. $file->boot($app->make(Request::class)); } return $file->prepareFile($app); } }
PHP
UTF-8
4,186
2.6875
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Eloquent as Model; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Facades\Auth; /** * Class Material * @package App\Models * @version March 5, 2020, 5:02 pm UTC * * @property \App\Models\Group group * @property \App\Models\Library library * @property \App\Models\Semester semester * @property \App\Models\User teacher * @property integer semester_id * @property integer group_id * @property integer teacher_id * @property integer library_id * @property string title * @property string description */ class Material extends Model { //use SoftDeletes; public $table = 'materials'; const CREATED_AT = 'created_at'; const UPDATED_AT = 'updated_at'; protected $dates = ['deleted_at']; public $fillable = [ 'semester_id', 'group_id', 'teacher_id', 'library_id', 'subject_id', 'title', 'description' ]; /** * The attributes that should be casted to native types. * * @var array */ protected $casts = [ 'id' => 'integer', 'semester_id' => 'integer', 'group_id' => 'integer', 'teacher_id' => 'integer', 'library_id' => 'integer', 'title' => 'string', 'description' => 'string' ]; /** * Validation rules * * @var array */ public static $rules = [ 'semester_id' => 'required', 'group_id' => 'required', 'teacher_id' => 'required', 'library_id' => 'required', 'title' => 'required', 'description' => 'required' ]; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo **/ public function group() { return $this->belongsTo(\App\Models\Group::class, 'group_id'); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo **/ public function library() { return $this->belongsTo(\App\Models\Library::class, 'library_id'); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo **/ public function semester() { return $this->belongsTo(\App\Models\Semester::class, 'semester_id'); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo **/ public function teacher() { return $this->belongsTo(\App\Models\User::class, 'teacher_id'); } public function subject() { return $this->belongsTo(Subject::class, 'subject_id'); } public static function filterData($request){ $subject_id = $request->get("subject_id"); $library_id = $request->get("library_id"); $str = "<option value='0'>Не выбранно</option>"; if($subject_id && !$library_id){ $semester = Semester::where("current",1)->first(); $groupIds = array_keys(Shedule::where(["teacher_id"=>Auth::id(),"semester_id"=>$semester->id,"subject_id"=>$subject_id])->pluck("id","group_id")->all()); $groups = Group::whereIn("id",$groupIds)->get(); if(count($groups)>0){ foreach ($groups as $group){ $str.= "<option value={$group->id}>$group->title</option>"; } } else{ $str = "<option>Ничего не найдено</option>"; } return $str; } if($subject_id && $library_id){ if($library_id == 1){ $libraries = Library::where("user_id",Auth::id())->get(); } if($library_id == 2){ $libraries = Library::all(); } if(count($libraries)>0){ foreach ($libraries as $library){ $str.= "<option value={$library->id}>$library->title</option>"; } return $str; } else{ $str = "<option>Файлы не найдены</option>"; return $str; } } else{ $str = "<option>Ничего не найдено</option>"; return $str; } } }
C#
UTF-8
1,681
2.625
3
[]
no_license
using Shop.Domain.Dto; using Shop.Domain.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Shop.Domain.Converters { public static class ItemConverter { public static ItemDto Convert(Item item) { return new ItemDto { Id = item.Id, CategoryId = item.CategoryId, DateCreate = item.DateCreate, Name = item.Name, Img = item.Img, Text = item.Text, Cost = item.Cost, Views = item.Views, Grams = item.Grams, Status = item.Status, Komplex =item.Komplex }; } public static Item Convert(ItemDto item) { return new Item { Id = item.Id, CategoryId = item.CategoryId, DateCreate = item.DateCreate, Name = item.Name, Img = item.Img, Text = item.Text, Cost = item.Cost, Views = item.Views, Grams = item.Grams, Status = item.Status, Komplex = item.Komplex }; } public static List<ItemDto> Convert(List<Item> items) { return items.Select(a => { return Convert(a); }).ToList(); } public static List<Item> Convert(List<ItemDto> albums) { return albums.Select(a => { return Convert(a); }).ToList(); } } }
PHP
UTF-8
317
2.6875
3
[ "MIT" ]
permissive
<?php namespace App\Listeners; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; class CounterListener implements ShouldQueue { use InteractsWithQueue; public function handle($event) { $x = 0; while($x < 1000) { $x++; } } }
Python
UTF-8
261
3.625
4
[]
no_license
from time import sleep def sleep_decorator(function): def wrapper(*args,**kwargs): sleep(2) return function(*args,**kwargs) return wrapper @sleep_decorator def print_num(num): return num print print_num(45) for num in range(6): print print_num(num)
JavaScript
UTF-8
1,075
2.5625
3
[ "MIT" ]
permissive
const createValidate = values => { const errors = { validate: { required: {}, regex: {} } } if (!values.name) { errors.name = 'Required' } else { const regex = new RegExp('^[a-z]+$', 'i') if (!regex.test(values.name)) { errors.name = 'Must be: a-z' } } if (!values.type) { errors.type = 'Required' } else if (['text', 'textarea'].indexOf(values.type) === -1) { errors.type = 'Unregistered type' } if (!values.title) { errors.title = 'Required' } const validate = values.validate if (validate) { const required = validate.required if (required) { if (required.isActive && !required.title) { errors.validate.required.title = 'Required' } } const regex = validate.regex if (regex) { if (regex.isActive) { if (!regex.title) { errors.validate.regex.title = 'Required' } if (!regex.regex) { errors.validate.regex.regex = 'Required' } } } } return errors } export default createValidate
TypeScript
UTF-8
3,988
2.515625
3
[]
no_license
import { Reducer, Effect, IRoute } from 'umi'; import { NoticeData } from '@/components/Notice/NoticeTary'; import { queryNotices } from '@/services/UserService'; export interface NoticeItem extends NoticeData { id: string; type: string; status: string; } export interface GlobalModelState { /** 菜单栏是否折叠 */ collapsed: boolean; /** 系统通知 */ notices: NoticeItem[]; /** 扁平路由配置 */ flatRoute: Record<string, IRoute>; } export interface GlobalModelType { namespace: 'global'; state: GlobalModelState; effects: { fetchNotices: Effect; clearNotices: Effect; changeNoticeReadState: Effect; }; reducers: { changeLayoutCollapsed: Reducer<GlobalModelState, { type: 'changeLayoutCollapsed'; payload: boolean }>; saveNotices: Reducer<GlobalModelState>; saveClearedNotices: Reducer<GlobalModelState>; changeFlatRoute: Reducer<GlobalModelState, { type: 'changeFlatRoute'; payload: Record<string, IRoute> }>; }; } const DefaultModel: GlobalModelState = { collapsed: false, notices: [], flatRoute: {}, }; const GlobalModel: GlobalModelType = { namespace: 'global', state: DefaultModel, effects: { *fetchNotices(_, { call, put, select }) { try { const notices = yield call(queryNotices); yield put({ type: 'saveNotices', payload: notices, }); const unreadCount: number = yield select( (state: { global: GlobalModelState }) => state.global.notices.filter(item => !item.read).length, ); yield put({ type: 'user/changeNotifyCount', payload: { totalCount: notices.length, unreadCount, }, }); } catch (error) { console.log('获取系统通知异常:', error); } }, *clearNotices({ payload }, { put, select }) { try { yield put({ type: 'saveClearedNotices', payload, }); const count: number = yield select((state: { global: GlobalModelState }) => state.global.notices.length); const unreadCount: number = yield select( (state: { global: GlobalModelState }) => state.global.notices.filter(item => !item.read).length, ); yield put({ type: 'user/changeNotifyCount', payload: { totalCount: count, unreadCount, }, }); } catch (error) { console.log('清除系统通知异常:', error); } }, *changeNoticeReadState({ payload }, { put, select }) { try { const notices: NoticeItem[] = yield select((state: { global: GlobalModelState }) => state.global.notices.map(item => { const notice = { ...item }; if (notice.id === payload) { notice.read = true; } return notice; }), ); yield put({ type: 'saveNotices', payload: notices, }); yield put({ type: 'user/changeNotifyCount', payload: { totalCount: notices.length, unreadCount: notices.filter(item => !item.read).length, }, }); } catch (error) { console.log('改变系统通知已读状态异常:', error); } }, }, reducers: { changeLayoutCollapsed(state = DefaultModel, { payload }) { return { ...state, collapsed: payload, }; }, saveNotices(state = DefaultModel, { payload }): GlobalModelState { return { ...state, notices: payload, }; }, saveClearedNotices(state = DefaultModel, { payload }) { return { ...state, notices: state.notices.filter((item): boolean => item.type !== payload), }; }, changeFlatRoute(state = DefaultModel, { payload }) { return { ...state, flatRoute: payload, }; }, }, }; export default GlobalModel;
Python
UTF-8
511
4.21875
4
[]
no_license
# find power (**) using recursion def power (d, n): if (n == 0): return 1; #reverse number and power if n is negative if (n < 0): d = 1.0 / d n = -n return power (d, n) #if n is even, then calculated value = (d**(n/2)) #if n is odd, then calculated value = d*(d**truncated(n/2)) pwr = power (d, n//2) if (n % 2): return d * pwr * pwr else: return pwr * pwr print (power(2,-11)) print (power(2,13)) print (power(2,11))
Java
UTF-8
905
3.359375
3
[]
no_license
package zhaoTest; /** * Created by zhaochao on 2019/7/25. */ public class ListNode { private int value; private ListNode next; public int getValue() { return value; } public void setValue(int value) { this.value = value; } public ListNode getNext() { return next; } public void setNext(ListNode next) { this.next = next; } @Override public String toString() { String string; if (next != null) { string = " " + value + " " + next.toString(); } else { string = " " + value + " "; } return string; } @Override protected ListNode clone() throws CloneNotSupportedException { ListNode listNode = new ListNode(); listNode.setNext(this.getNext()); listNode.setValue(this.getValue()); return listNode; } }
C++
UTF-8
1,323
2.890625
3
[]
no_license
// Author: Remco de Boer // Date: June 13th, 2018 // For NIKHEF Project 2018 /* === CLASS DESCRIPTION ======= This algorithm transposes al timepixes on the clipboard. Columns become rows. */ // === INCLUDES ======= #include "TTimepixTranspose.h" using namespace std; using namespace NIKHEFProject; // === ALGORITHM STEP FUNCTIONS ======= // INITIALISE FUNCTION: does nothing void TTimepixTranspose::Initialise() {} // RUN FUNCTION: gets pixels and timepixes from the clipboard and flips their (n)cols and (n)rows StatusCode TTimepixTranspose::Run() { // Flip dimensions on clipboard fRow = pNRows; fCol = pNCols; pNRows = fCol; pNCols = fRow; // Flip dimension of all timepixes fTimepixList = (TTimepixList_t*)fClipboard->Get("timepix"); fTimepixIter = fTimepixList->begin(); if( fTimepixIter != fTimepixList->end()) { (*fTimepixIter)->GetSize(fRow,fCol); (*fTimepixIter)->SetSize(fCol,fRow); } // Flip row and column of all pixels fPixelList = (TPixelList_t*)fClipboard->Get("pixels"); fPixelIter = fPixelList->begin(); if( fPixelIter != fPixelList->end()) { fRow = (*fPixelIter)->GetRow(); fCol = (*fPixelIter)->GetColumn(); (*fPixelIter)->SetRow(fCol); (*fPixelIter)->SetColumn(fCol); } } // FINALISE FUNCTION: does nothing void TTimepixTranspose::Finalise() {}
Java
UTF-8
1,334
2.125
2
[]
no_license
package com.in28minutes.login; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttributes; import com.in28minutes.todos.TodoService; @Controller @SessionAttributes("name") public class LandingController { @Autowired TodoService todoService; @RequestMapping(value = "/", method = RequestMethod.GET) public String loginRedirect(ModelMap model) { model.put("name", "Zalman"); return "landing"; } // @RequestMapping(value = "/login", method = RequestMethod.POST) // public String submitLogin(@RequestParam String name, // @RequestParam String password, // ModelMap model) { // if (userValidationService.isValid(name, password)) { //// model.addAttribute("todos", todoService.retrieveTodos(name)); //// return "list-todos"; // model.put("name", name); // model.put("password", password); // return "landing"; // } // model.put("errorMessage", "Invalid Credentials"); // return "login"; // } }
C#
UTF-8
618
2.78125
3
[ "MIT" ]
permissive
namespace CloudServices.Sender { using System; using IronMQ; public class Sender { private static void Main() { Client client = new Client("5643068273d0cd0006000007", "GkTDl7hOYke63lBeysep"); Queue queue = client.Queue("Today's demo"); Console.WriteLine("Enter messages to be sent to the IronMQ server:"); while (true) { string msg = Console.ReadLine(); queue.Push(msg); Console.WriteLine("Message sent to the IronMQ server."); } } } }
Java
UTF-8
2,621
1.992188
2
[]
no_license
package com.eugenefe.controller; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.Begin; import org.jboss.seam.annotations.Create; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Out; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.Startup; import org.jboss.seam.core.Conversation; import org.jboss.seam.core.Events; import org.jboss.seam.framework.CurrentDate; import org.jboss.seam.log.Log; import org.primefaces.event.SelectEvent; import com.eugenefe.entity.Basedate; import com.eugenefe.enums.EMaturity; import com.eugenefe.session.BasedateList; import com.eugenefe.util.FnCalendar; @Name("basedateSession") @Scope(ScopeType.SESSION) @Startup // @Scope(ScopeType.CONVERSATION) public class BasedateSession implements Serializable { @Logger private Log log; // @In(create = true) // private BasedateList basedateList; // @In private Date currentDate; private FnCalendar cal; private Date baseDate; private Date stDate; private Date endDate; public BasedateSession() { } @Create public void init(){ cal = FnCalendar.getInstance(); // cal = new FnCalendar(2013, 4, 29); baseDate = cal.getTime(); endDate =cal.getTime(); stDate = cal.minusTerm(EMaturity.Y01, true).getTime(); } // @Create public void initNew() { baseDate = currentDate; stDate = baseDate; endDate = baseDate; } // ********************************************* public void handleDateSelect(SelectEvent event) { Events.instance().raiseEvent("evtBaseDateChange", (Date) (event.getObject())); } public void handleStartDateSelect(SelectEvent event) { Events.instance().raiseEvent("evtStartDateChange", (Date) (event.getObject())); } public void handleEndDateSelect(SelectEvent event) { Events.instance().raiseEvent("evtEndDateChange", (Date) (event.getObject())); } // *********************************Getter and Setter*********************** public Date getBaseDate() { return baseDate; } public void setBaseDate(Date baseDate) { this.baseDate = baseDate; } public Date getStDate() { return stDate; } public void setStDate(Date stDate) { this.stDate = stDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } }
Markdown
UTF-8
2,507
3.171875
3
[ "MIT" ]
permissive
# array-intersection [![NPM version](https://badge.fury.io/js/array-intersection.svg)](http://badge.fury.io/js/array-intersection) > Return an array with the unique values present in _all_ given arrays using strict equality for comparisons. Based on [mout's](http://moutjs.com/) implementation of `intersection`. ## Install **Install with NPM** Install with [npm](https://www.npmjs.com/) ```bash npm i array-intersection --save ``` **Install with Bower** Install with [bower](http://bower.io/) ```bash bower install array-intersection --save ``` ## Usage ```js var intersection = require('array-intersection'); intersection(['a', 'a', 'c']) //=> ['a', 'c'] intersection(['a', 'b', 'c'], ['b', 'c', 'e']) //=> ['b', 'c'] intersection(['a', 'b', 'c'], ['b', 'c', 'e'], ['b', 'c', 'e']) //=> ['b', 'c'] ``` ## Related projects * [array-every](https://github.com/jonschlinkert/array-every): Returns true if the callback returns truthy for all elements in the given array. * [array-slice](https://github.com/jonschlinkert/array-slice): Array-slice method. Slices `array` from the `start` index up to, but not including, the `end`… [more](https://github.com/jonschlinkert/array-slice) * [array-unique](https://github.com/jonschlinkert/array-unique): Return an array free of duplicate values. Fastest ES5 implementation. * [arr-union](https://github.com/jonschlinkert/arr-union): Combines a list of arrays, returning a single array with unique values, using strict equality… [more](https://github.com/jonschlinkert/arr-union) * [filter-array](https://github.com/jonschlinkert/filter-array): Iterates over the elements in an array, returning an array with only the elements for… [more](https://github.com/jonschlinkert/filter-array) * [index-of](https://github.com/jonschlinkert/index-of): Get the index of the first element in an array that returns truthy for the… [more](https://github.com/jonschlinkert/index-of) ## Running tests Install dev dependencies: ```bash npm i -d && npm test ``` ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/array-intersection/issues/new) ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright (c) 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on May 07, 2015._
JavaScript
UTF-8
1,475
2.71875
3
[ "MIT" ]
permissive
/** * Loads classes and resources from a given JAR file. This function purges state of JVM. * @param {string} filename Path to JAR file. * @param {function} callback Function to execute when loading is over. */ js2me.loadJAR = function (file, callback) { function loadReader(reader) { zip.useWebWorkers = false; zip.workerScriptsPath = 'js/zip/'; zip.createReader(reader, function(zipReader) { zipReader.getEntries(function (entries) { js2me.addResources(entries) js2me.loadResource('META-INF/MANIFEST.MF', function (data) { var content = js2me.UTF8ToString(data); js2me.manifest = js2me.parseManifest(content); js2me.storageName = js2me.manifest['midlet-vendor'] + '/' +js2me.manifest['midlet-name'] + '//' + file.size + '/'; callback(); }); }); }, function (message) { js2me.showError(message); }); } js2me.setupJVM(function () { loadReader(new zip.BlobReader(file)); }); } js2me.loadScript = function (filename, successCallback, errorCallback) { var element = document.createElement('script'); element.src = filename; element.onload = function () { document.head.removeChild(element); //delete element.onload; //delete element.onerror; //element = undefined; successCallback(); }; element.onerror = function () { document.head.removeChild(element); //delete element.onload; //delete element.onerror; //element = undefined; errorCallback(); }; document.head.appendChild(element); };
PHP
UTF-8
2,313
2.546875
3
[]
no_license
<?php # exceedPictureLimit - Present error message to the user has exceed the picture limit # # Connection & Session setup require("common.php"); # Common functions require("functions.php"); # check if active session is not set, used to prevent unauthorised access if (!isset($_SESSION['active'])) { # if not set redirect user header("Location: login.php"); # Prevent unexpected behaviour after redirection die("Redirecting to: login.php"); # if it is set check value } else if (isset($_SESSION['active'])) { if ($_SESSION['active'] == "no") { # if value is false redirect user header("Location: login.php"); # Prevent unexpected behaviour after redirection die("Redirecting to: login.php"); } } ?> <!--Version of HTML will be written in.--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!--The xmlns attribute specifies the xml namespace for a document.--> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <!--Page Title--> <title>BH Brighton and Hove</title> <!--Metal defines which character set is used, page description, keywords, author, and other metadata--> <meta http-equiv="content-type" content="text/html; charset=UTF-8"></meta> <!--CSS describes how HTML elements should be displayed--> <link rel="stylesheet" type="text/css" href="mystyle.css"/> </head> <!--Navigation bar--> <ul> <li><a href="private.php" class="w3-margin-left"><b>BH</b> Brighton and Hove</a></li> <li><a href="private.php">Home</a></li> <li><a href="edit_account.php">Account</a></li> <li><a class="active" href="viewProperties.php">Your Properties</a></li> <li><a href="addProperty.php">Add New Property</a></li> <li><a href="logout.php">Logout</a></li> <li><a href="">Welcome to Brighton and Hove <?php echo $_SESSION['username']; ?>!</a></li> </ul> <h1>Exceed Picture Limit, Please Delete Or Replace</h1> <table align='center'> <tr> <th> <a href=viewProperties.php>Back</a> </th> </tr> </table> </body> </html>
Markdown
UTF-8
3,797
2.828125
3
[ "LicenseRef-scancode-generic-cla", "CC-BY-4.0" ]
permissive
--- layout: project title: Docking Station - OpenXC --- <div class="page-header"> <h1>Docking Station</h1> </div> The OpenXC docking station is a hardware platform that allows car enthusiasts and hackers alike to create their own hardware and easily integrate it with OpenXC. The docking station features three different docking slots, each with their own USB connection via pogo pins and embedded magnets for easy connection. Projects like the Retro Gauge can be easily modified to use the docking station. The Docking Station was originally designed and developed by Chad Bean during his summer internship at [Ford Silicon Valley Lab](http://fordsvl.com). ![OpenXC Docking Station](/projects/images/docking-station-1.png) <!-- <div class="page-header"> <h2 id="repositories"><a href="#repositories">Repositories</a></h2> </div> **Docking Station 3D Design:** The [(Insert Here)] repository contains a `.STL` file for the 3D printable docking station. However, do to the docking stations large size, often times hobbyist printers will produce a warped part. We had our docking station made from a SLA printer. --> <div class="page-header"> <h2 id="motivation"><a href="#motivation">Motivation</a></h2> </div> OpenXC is an open source project that easily allows experimenters to create applications. However, if someone wants to utilize OpenXC’s open-source hardware capabilities for prototyping there is no way to have temporary hardware affixed to that car without duct tape or other prototyping materials. ![Docking Station Installed](/projects/images/docking-station-2.png) The docking station offers a user-friendly connection from an Android device to hardware devices. The docking station also provides good insight as to how we could manufacture cars that are more modular and willing to accept new technology. Thus, you would not be stuck with a fairly new car that already has out of date systems. <div class="page-header"> <h2 id="3Ddesign"><a href="#3Ddesign">3D Docking Station Design</a></h2> </div> <!-- **GitHub Directory:** [Docking Station-3Ddesign (Insert Here)][] --> The docking station platform was designed to meet 3 goals: 1. Incorporate a modular design that could easily be adopted by hardware developers 2. Accept standard USB signals 3. Able to communicate and power auxiliary devices Since this is the first iteration of the dock a simple store-bought, powered USB hub which limits the symmetry across all three docking slots was used. If the user wishes to power auxiliary hardware from an Android device, the Android device must be docked on the left-most slot. The reason being is that this is the "host" connection for the USB hub. All slots may be used for simple charging. The powered USB hub came with an 120VAC to 5VDC wall wart that is not useful since vehicles have a 12VDC power supply. The docking station utilizes the vehicle power by splicing out two connection from the 12V lines and feeding these into a 5V @ 5A buck converter, which has plenty of power. The USB standard is only 500mA/ channel, so there is plenty of overhead to daisy-chain another USB Hub if needed. **Android Phone Dock** ![Phone Dock](/projects/images/phone-dock-3.png) This phone dock fits the Nexus 4, Galaxy S4 and other similarly-dimensioned phones with the micro usb connector centered on the bottom of the phone. It is very simplistic as far as design goes. ![Phone Dock](/projects/images/phone-dock-2.png) Pogo pins make contact with the docking station and passively relay the USB connection to a micro USB connector. There are also four 1/4" x 1/4" cylindrical magnets to hold it in place on the docking station. ![Phone Dock](/projects/images/phone-dock-1.png) <!-- **GitHub Directory:** [Phone Dock-3Ddesign (Insert Here)][] -->
Python
UTF-8
3,369
3.609375
4
[]
no_license
from tkinter import * from tkinter import messagebox from Password_Generator import * import pyperclip ''' This program uses Tkinter to create a GUI to manage information about login. messagebox is not a class so have to be imported by itself. Data will be written to a text file. Password can be manually entered or automatically generated. If generated, password is automatically copied to clipboard. Example email/username is automatically entered but if wanted it to be empty, delete line-76. ''' def create_password(): password = PasswordGenerator() # Get a password from PasswordGenerator class. new_password = password.password_generator() # Copy the generated password to the clipboard. pyperclip.copy(new_password) password_entry.insert(0, new_password) def record_data(): # Get website's name. web_name = web_entry.get().capitalize() # Get email or username. get_username = username_entry.get() # Get password. get_password = password_entry.get() # If any boxes is empty, pop up warning message box. if len(web_name) == 0 or len(get_password) < 0: messagebox.showerror(title="Warning!", message="Please fill all empty boxes.") else: # Get confirmation from user whether to save data entered. is_ok = messagebox.askokcancel(title=web_name, message=f"THESE ARE THE DETAILS ENTERED." f"\nEmail: {get_username}\nPassword: {get_password}\n" f"Is it alright to continue to save?") if is_ok: # Write data to a text file with append mode so subsequent data will be added to existing one. with open("data.txt", mode="a") as data: data.write(f"{web_name} | {get_username} | {get_password}\n") # Empty boxes for new data to be entered. web_entry.delete(0, END) password_entry.delete(0, END) # Send cursor to the first box. web_entry.focus() # Create a GUI window. window = Tk() window.title("Password Manager") window.config(padx=50, pady=50) # Add the pic using Canvas class. canvas = Canvas(width=200, height=200) photo = PhotoImage(file="logo.png") canvas.create_image(100, 100, image=photo) canvas.grid(column=1, row=0) # Create labels at desired locations. web_label = Label(text="Website:", font=("Courier", 18)) web_label.grid(column=0, row=1) username_label = Label(text="Email/Username:", font=("Courier", 18)) username_label.grid(column=0, row=2) password_label = Label(text="Password:", font=("Courier", 18)) password_label.grid(column=0, row=3) # Create boxes accordingly. web_entry = Entry(width=35) web_entry.grid(column=1, row=1, columnspan=2) web_entry.focus() username_entry = Entry(width=35) username_entry.grid(column=1, row=2, columnspan=2) username_entry.insert(0, "johndoe@gmail.com") password_entry = Entry(width=21) password_entry.grid(column=1, row=3) # Create buttons at appropriate locations. When clicked, call the respective function. generate_pass_button = Button(text="Generate Password", command=create_password) generate_pass_button.grid(column=2, row=3) add_button = Button(text="Add", width=36, command=record_data) add_button.grid(column=1, row=4, columnspan=2) # To keep the window stay on. window.mainloop()