language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
105
1.671875
2
[]
no_license
package com.example.presentationtimer; public class Task { public String name; public String time; }
Java
UTF-8
217
1.875
2
[]
no_license
package br.com.stockinfo.tsql.annotations; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Repeatable(Tables.class) public @interface Table { String name() default ""; String[] dataSource(); }
C#
UTF-8
879
2.71875
3
[]
no_license
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PoolToos { private static Dictionary<Type, Queue<Entity>> mMap = new Dictionary<Type, Queue<Entity>>(); public static T GetClass<T>() where T : Entity, new() { T t = null; Type type = typeof(T); if (mMap.ContainsKey(type)) { Queue<Entity> queue = mMap[type]; if (queue.Count > 0) { t = (T)queue.Dequeue(); t.OnReset(); } } if(t == null) t = new T(); return t; } public static void FreeClass<T>(T t) where T : Entity, new() { Type type = typeof(T); if (mMap.ContainsKey(type)) { Queue<Entity> queue = mMap[type]; queue.Enqueue(t); } } }
C#
UTF-8
4,367
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace JP { class Program { static void Main(string[] args) { bool korakOK = false; string tmp; int n = 0; while (!korakOK) { Console.WriteLine("Odaberi način rada programa:"); Console.WriteLine("0: unos sa konzole"); Console.WriteLine("1: unos iz datoteke"); Console.WriteLine("2: predefinirani ulaz"); tmp = Console.ReadLine(); korakOK = Int32.TryParse(tmp, out n); } switch (n) { case 0: UnosSaTipkovnice(); break; case 1: UnosIzDatoteke(); break; case 2: Test(); break; default: Console.WriteLine("Mogućnost: " + n + " ne postoji, program završava"); break; } } private static void UnosIzDatoteke() { Console.Write("Unesi ime datoteke: "); string file = Console.ReadLine(); StreamReader sr = new StreamReader(file); int count = Convert.ToInt32(sr.ReadLine()); List<JP> input = new List<JP>(); for (int i = 0; i < count; ++i) { input.Add(new JP(sr.ReadLine())); } JP requested = new JP(sr.ReadLine()); Generator gen = new Generator(input, requested); string res = gen.Resolve(); if (res != null) Console.WriteLine(res); else Console.WriteLine("Nije moguće izgraditi ciljni jezični procesor korištenjem raspoloživih jezičnih procesora!"); Console.ReadKey(); } private static void UnosSaTipkovnice() { bool korakOK = false; string tmp; int n = 0; while (!korakOK) { Console.WriteLine("Unesi broj jezičnih procesora u početnom skupu: "); tmp = Console.ReadLine(); korakOK = Int32.TryParse(tmp, out n); } Console.WriteLine("Unesi {0} jezična procesora, svaki u svojoj liniji u obliku:", n); Console.WriteLine("izvorniJezik,ciljniJezik,jezikIzgradnje"); List<JP> input = new List<JP>(); for (int i = 0; i < n; ++i) { tmp = Console.ReadLine(); input.Add(new JP(tmp)); } Console.WriteLine("Unesi traženi jezični procesor:"); tmp = Console.ReadLine(); JP requested = new JP(tmp); Generator gen = new Generator(input, requested); string res = gen.Resolve(); if (res != null) Console.WriteLine(res); else Console.WriteLine("Nije moguće izgraditi ciljni jezični procesor korištenjem raspoloživih jezičnih procesora!"); Console.ReadKey(); } private static void Test() { List<JP> input = new List<JP>(); input.Add(new JP("X", "Y", "a")); input.Add(new JP("X", "Y", "b")); input.Add(new JP("X", "K", "Z")); input.Add(new JP("Z", "b", "a")); input.Add(new JP("Y", "Z", "a")); input.Add(new JP("Z", "K", "a")); input.Add(new JP("K", "P", "C")); input.Add(new JP("C", "X", "a")); input.Add(new JP("X", "a", "a")); input.Add(new JP("P", "C", "a")); JP requested = new JP("X", "C", "a"); //JP requested = new JP("Z", "K", "a"); Generator gen = new Generator(input, requested); string res = gen.Resolve(); if (res != null) Console.WriteLine(res); else Console.WriteLine("Nije moguće izgraditi ciljni jezični procesor korištenjem raspoloživih jezičnih procesora!"); Console.ReadKey(); } } }
C++
UTF-8
1,680
2.59375
3
[]
no_license
#include "QTexturesDialog.h" #include "QNewSpriteDialog.h" #include <QPixmap> #include <QBoxLayout> #include "EditorController.h" QTexturesDialog::QTexturesDialog(const std::map<std::string, std::string> &textureMap, QWidget *parent) : QDialog(parent) { setupUi(this); // Add image label to layout m_image = new QLabel(this); scrollArea->setWidget(m_image); // Fill texture list for (auto texture : textureMap) { QListWidgetItem *item = new QListWidgetItem(texture.first.c_str(), textureList); item->setData(Qt::UserRole, texture.second.c_str()); } } QTexturesDialog::~QTexturesDialog() { } void QTexturesDialog::on_addButton_clicked() { QNewSpriteDialog d(this); if (d.exec()) { QListWidgetItem *item = new QListWidgetItem(d.idEdit->text(), textureList); item->setData(Qt::UserRole, d.sourceEdit->text()); textureList->setCurrentItem(item); } } void QTexturesDialog::on_deleteButton_clicked() { QListWidgetItem *curItem = textureList->currentItem(); if (curItem) { // Delete from QListWidget textureList->takeItem(textureList->row(curItem)); delete curItem; if (textureList->count() > 0) textureList->setCurrentRow(0); else on_textureList_currentItemChanged(); } } void QTexturesDialog::on_textureList_currentItemChanged() { QListWidgetItem *curItem = textureList->currentItem(); if (curItem) { // Show id, source and image idLabel->setText("ID: " + curItem->text()); sourceLine->setText(curItem->data(Qt::UserRole).toString()); QPixmap pixmap(curItem->data(Qt::UserRole).toString()); m_image->setPixmap(pixmap); } else { idLabel->setText("<No item selected>"); sourceLine->clear(); m_image->clear(); } }
C
UTF-8
2,196
2.578125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* apply_bparam_operator2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: wbraeckm <wbraeckm@student.s19.be> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/18 00:37:50 by wbraeckm #+# #+# */ /* Updated: 2020/01/20 20:22:31 by wbraeckm ### ########.fr */ /* */ /* ************************************************************************** */ #include "sh.h" void apply_hashtag_flag(t_subst *subst, t_bparam *bparam) { char *new; size_t len; len = ft_strlen(bparam->result); if (!(new = ft_uitoa(len))) { subst->err = SH_ERR_MALLOC; return ; } free(bparam->result); bparam->result = new; } /* ** NOTE: this is a really really basic implementation they do not actually match ** but rather remove start or end of string depending on which operator it is */ void apply_hashtag(t_subst *subst, t_bparam *bparam) { char *pattern; subst->err = substitute(subst->shell, bparam->word, &pattern, ~SUB_ASSIGN); if (subst->err != SH_SUCCESS) return ; bparam->result = ft_strsrepl(bparam->val, pattern, ""); free(pattern); if (!bparam->result) subst->err = SH_ERR_MALLOC; } void apply_percent(t_subst *subst, t_bparam *bparam) { char *pattern; size_t len; subst->err = substitute(subst->shell, bparam->word, &pattern, ~SUB_ASSIGN); if (subst->err != SH_SUCCESS) return ; len = ft_strlen(bparam->val); while (len--) { if (ft_strstartswith(bparam->val + len, pattern)) { bparam->result = ft_strndup(bparam->val, len); if (!bparam->result) subst->err = SH_ERR_MALLOC; break ; } } if (subst->err == SH_SUCCESS && !bparam->result) bparam->result = ft_strdup(""); if (!bparam->result) subst->err = SH_ERR_MALLOC; }
Markdown
UTF-8
1,417
2.546875
3
[]
no_license
<h1 align="center"> <img alt="BackUps" title="BackUps" src="https://raw.githubusercontent.com/AlexVictorB/BackUps/main/assets/icon.png" width="100px" /> <h2 align="center">BackUps</h2> </h1> <hr> <p align="center"> <a href="#projeto">Projeto</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#tecnologias">Tecnologias</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#screenshots">Screenshots</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#download">Download</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; </p> <hr> ## Projeto Software para realizar BackUps <br> Versão: 1.0.1 ## Tecnologias Esse projeto foi desenvolvido com as seguintes tecnologias: - Python 3.8.5 - PyQt5 (Interface Gráfica) ## Screenshots <h1 align="center"> <img alt="BackUps" title="BackUps" src="https://raw.githubusercontent.com/AlexVictorB/icons/main/backups_icons/screenshot1.png" width="350px" /> <img alt="BackUps" title="BackUps" src="https://raw.githubusercontent.com/AlexVictorB/icons/main/backups_icons/screenshot2.png" width="350px" /> <br> <hr> <img alt="BackUps" title="BackUps" src="https://raw.githubusercontent.com/AlexVictorB/icons/main/backups_icons/screenshot3.png" width="350px" </h1> ## Download <a href="https://github.com/AlexVictorB/BackUps/raw/main/build/BackUps%201.0.1.zip">Clique a aqui e faça Download<a> <br> - Apenas para Windows
Markdown
UTF-8
2,712
2.6875
3
[ "MIT" ]
permissive
# generator-simple-js [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Status][daviddm-image]][daviddm-url] > Generates the basic structure for a simple development environment using [Gulp](https://gulpjs.com/) and [browserSync](https://www.browsersync.io/). Also, may or may not include [Bootstrap](https://getbootstrap.com/) and [SASS](https://sass-lang.com/). ## Installation First, install [Yeoman](http://yeoman.io) and generator-simple-js using [npm](https://www.npmjs.com/) (we assume you have pre-installed [node.js](https://nodejs.org/) and [Gulp.js](https://gulpjs.com/)). ```bash npm install -g gulp npm install -g yo npm install -g generator-simple-js ``` Then generate your new project: ```bash yo simple-js ``` ## What do you get? Scaffold the next project directory structure: ``` . ├── gulpfile.js ├── package.json └── src ├── assets ├── css ├── index.html ├── js └── scss └── styles.scss ``` ## What's next? Once the project has been created you need to go to the project folder by typing in the terminal `cd project-folder`. Inside, you'll need to run the next command: ```bash gulp ``` That command by itself will add the required CSS and JS files to the proper folders and also will launch the project in your default browser, so you can comfortably start coding and each change made in any JS, CSS/SASS, HTML file, the browser will reload with the new changes. If you want to add more capabilities to your project, feel free to check on [Gulp.js](https://gulpjs.com/) documentation. ## Getting To Know Yeoman - Yeoman has a heart of gold. - Yeoman is a person with feelings and opinions, but is very easy to work with. - Yeoman can be too opinionated at times but is easily convinced not to be. - Feel free to [learn more about Yeoman](http://yeoman.io/). ## Contributing I'm pretty new to the Open Source community, so, every contribution will be more than helpful to me and to the project, too. I've created a template for pull requests, but if someone out there has any suggestion on improve template for the template (😆), please help on it, too. ## License MIT © [Alonso Vazquez](https://alonsovzqz.github.io/) [npm-image]: https://badge.fury.io/js/generator-simple-js.svg [npm-url]: https://npmjs.org/package/generator-simple-js [travis-image]: https://travis-ci.com/alonsovzqz/generator-simple-js.svg?branch=master [travis-url]: https://travis-ci.com/alonsovzqz/generator-simple-js [daviddm-image]: https://david-dm.org/alonsovzqz/generator-simple-js.svg?theme=shields.io [daviddm-url]: https://david-dm.org/alonsovzqz/generator-simple-js
Markdown
UTF-8
2,159
2.75
3
[]
no_license
--- author: name: markatos picture: 110243 body: working on logo for a project that will soon be known as Viral Media. <BR> <BR>This organization will be responsible for creating an interchange between professional and amateur artist to share and sample materials from one another. Mainly music. In a sense, this could become a record label of sorts. <BR> <BR>Main goal with logotype, have it work as a stencil and have all letters be connected. This is both to fit the concept of &#39;continuum&#39; and future stencil applications of the brand &#40;in urban contexts&#41;. <BR> <BR>I have been having some problems with the A. I&#39;ve tried to have have the left side curve back to the right and almost meet it &#40;#0&#41;. But then it looks too chunky between the R and A. <BR> <BR>In 1, I was trying to have it swell at the bottom to meet the R. Somewhat successful, but still looks wonky to me. I had a crossbar in there at one point, but that didn&#39;t look right at all. <BR> <BR>In 2, I have the left side coming straight down to meet an adjusted R &#40;no swell at the bottom&#41;. But then it looks like the right side of the A is higher up, due to its curvature. Also looks too wide. <BR> <BR>So, now i am thinking either talk the client out the stencil idea or go for a more traditional monocular lower case A with two cuts &#40;one at the top, and one at the bottom&#41;. <BR> <BR>Your help would be greatly appreciated. <BR> <BR><img src="http://www.typophile.com/forums/messages/29/36428.gif" alt=""> comments: - author: name: Miss Tiffany picture: 110563 body: What if the lc_a wasn&#39;t connected at the top instead of the bottom? I&#39;m thinking about fast girls at thirstype. not that yours is like that, but the letters are disconnected, similar to the idea of stencils. I think it is fast girls c-cup. <BR> <BR>Of your sketches, I think the more rigid the better. Flat and crisp in the join, but curve only in the letter where necessary. The dot over the lc_i helps. created: '2004-05-20 19:13:29' date: '2004-05-20 18:41:36' node_type: forum title: Viral ---
Java
UTF-8
266
1.796875
2
[ "Apache-2.0" ]
permissive
package de.mklinger.commons.exec.docker; /** * @author Marc Klinger - mklinger[at]mklinger[dot]de */ public class DockerCmdBuilder extends DockerCmdBuilderBase<DockerCmdBuilder> { public DockerCmdBuilder(final String... dockerCommands) { super(dockerCommands); } }
JavaScript
UTF-8
11,517
3.390625
3
[]
no_license
//require para fs(almacenar datos) //No necesita ./ por qué es nativo de node const fs =require('fs'); //Creación de un vector de estudiantes para almacenar en el Json listaCursos = []; listaAspirantes = []; const crear = (curso) => { //traemos el listado antes de agregar listar(); //objeto llamado cur let cur = { id: curso.id, nombre : curso.nombre, valor : curso.valor, descripcion: curso.descripcion, modalidad: curso.modalidad, intensidadHoraria: curso.intensidadHoraria, estado: curso.estado }; //Controlar los elementos duplicados let duplicados = listaCursos.find(buscar => buscar.id == curso.id); if (!duplicados){ listaCursos.push(cur); //console.log(listaCursos); //llama a guardar guardar(); //si no existen duplicados me devuelve la lista de cursos creado return `Curso ${curso.nombre} creado exitosamente <br>` + mostrar(); }else { return `<div class="alert alert-danger" role="alert"> El id del curso ya se encuentra en la base de datos </div>`; } } //Función para traer los datos del JSON const listar = () => { //Controlar si no existe el archivo try { //Si es constante con el tiempo se puede utilizar listaCursos = require('./listado.json'); //Traer el archivo utilizando funcion de fileSystem: se utiliza si //El Json cambia de forma asincronica //listaCursos = JSON.parse(fs.readFileSync(listado.json)); } catch (error) { listaCursos = []; } } //Función propia de json para guardar const guardar = () =>{ listar(); //datos contiene el vector listaCursos preparado //para ser almacenado como un documento let datos = JSON.stringify(listaCursos); //Se debe ingresar a la carpeta porque si se deja solo, toma la carpeta raíz fs.writeFile('./src/listado.json', datos, (err) => { if (err) throw (err); console.log('Archivo creado exitosamente'); }); } //Función para mostrar los estudiantes const mostrar = ()=>{ //Trae los elementos de json listar() //Recorreo la lista de cursos para imprimir cada uno y sus notas // \sirve para salto de linea let retorno = `<table class="table"> <thead class="thead-dark"> <th scope="col">ID</th> <th scope="col">NOMBRE</th> <th scope="col">VALOR</th> <th scope="col">DESCRIPCIÓN</th> <th scope="col">MODALIDAD</th> <th scope="col">INTENSIDAD HORARIA</th> <th scope="col">ESTADO</th> </thead> <tbody>`; listaCursos.forEach(curso => { retorno += ` <tr> <td> ${curso.id} </td> <td> ${curso.nombre} </td> <td> ${curso.valor}</td> <td> ${curso.descripcion} </td> <td> ${curso.modalidad} </td> <td> ${curso.intensidadHoraria} </td> <td> ${curso.estado} </td> </tr>`; }); retorno += `</tbody> </table>`; return retorno; } const listarCursosInteresado =()=> { //Trae los elementos de json listar() //Recorreo la lista estudiantes para imprimir cada uno y sus notas // \sirve para salto de linea let retorno = `<div class="accordion" id="accordionExample">`; i=1 listaCursos.forEach(curso => { //Solo muestra los cursos disponibles if(curso.estado =='disponible'){ retorno += `<div class="card"> <div class="card-header" id="heading${i}"> <h5 class="mb-0"> <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapse${i}" aria-expanded="true" aria-controls="collapse${i}"> Nombre del curso: ${curso.nombre} >>>Valor: ${curso.valor} <br> Descripción: ${curso.descripcion} </button> </h5> </div> <div id="collapse${i}" class="collapse" aria-labelledby="heading${i}" data-parent="#accordionExample"> <div class="card-body"> <b> Nombre:</b> ${curso.nombre} <br> <b> Valor:</b> ${curso.valor} <br> <b> Descripción:</b> ${curso.descripcion} <br> <b> Modalidad:</b> ${curso.modalidad} <br> <b> Intensidad horaria:</b> ${curso.intensidadHoraria} <br> </div> </div>`; i++; } }); retorno += `</div>`; return retorno; } const listarCursoInscribir =()=> { //Trae los elementos de json listar() //Recorreo la lista estudiantes para imprimir cada uno y sus notas // \sirve para salto de linea let retorno = `<select class="custom-select col-5" name="curso" id="cursoSeleccionado">`; listaCursos.forEach(curso => { //Solo muestra los cursos disponibles if(curso.estado == 'disponible'){ retorno += `<option value="${curso.id}">${curso.nombre}</option>`; } }); retorno += `</select>`; return retorno; } //Las siguientes funciones son para el ---------------aspirante-------------------- const inscribirAspirante = (aspirante) => { //traemos el listado antes de agregar listarAspirante(); //objeto llamado cur let aspi = { identificacion:aspirante.identificacion, nombre:aspirante.nombre, correo:aspirante.correo, telefono:aspirante.telefono, curso:aspirante.curso }; //Controla que el estudiante no se matricule 2 veces en el mismo curso let matriculado = listaAspirantes.filter(buscar => (buscar.curso == aspi.curso & buscar.identificacion == aspi.identificacion)); if (matriculado.length == 0){ listaAspirantes.push(aspi); //console.log(listaCursos); //llama a guardar guardarAspirante(); //Busco el nombre del curso con la identificacion let curso = listaCursos.find(buscar => buscar.id == aspirante.curso); //si no existen duplicados me devuelve la lista de cursos creado return `<div class="alert alert-success" role="alert"> Estudiante ${aspi.nombre} inscrito exitosamente en el curso ${curso.nombre} </div>`; }else { return `<div class="alert alert-danger" role="alert"> El estudiante ya se encuentra inscrito en el curso seleccionado </div>`; } } //Función para traer los datos del aspirante de aspirantes.json const listarAspirante = () => { //Controlar si no existe el archivo try { //Si es constante con el tiempo se puede utilizar listaAspirantes= require('./aspirantes.json'); } catch (error) { listaAspirantes = []; } } const guardarAspirante = () =>{ listarAspirante(); let datos = JSON.stringify(listaAspirantes); //Se debe ingresar a la carpeta porque si se deja solo, toma la carpeta raíz fs.writeFile('./src/aspirantes.json', datos, (err) => { if (err) throw (err); console.log('Archivo creado exitosamente(aspirantes)'); }); } const verInscritos = () => { //lista los aspirante listarAspirante(); //lista los cursos listar(); let retorno=``; //Recorro la lista de cursos y por cada uno busco los aspirantes de dicho curso for(i=0;i<listaCursos.length;i++){ let matriculado = listaAspirantes.filter(buscar => buscar.curso == listaCursos[i].id & listaCursos[i].estado =='disponible'); retorno += `<div class="card accordion" id="accordionExample"> <div class="card-header" id="heading${i}"> <h5 class="mb-0"> <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapse${i}" aria-expanded="true" aria-controls="collapse${i}"> Nombre del curso: ${listaCursos[i].nombre} </button> </h5> </div> <div id="collapse${i}" class="collapse" aria-labelledby="heading${i}" data-parent="#accordionExample"> <div class="card-body"> <form action='/eliminar_aspirante' method='post'> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">Documento</th> <th scope="col">Nombre</th> <th scope="col">Correo</th> <th scope="col">Teléfono</th> <th scope="col">Eliminar</th> </tr> </thead> <tbody>`; //si la lista de matriculado es igual a cero no hay estudiantes en el curso if (matriculado.length > 0){ matriculado.forEach(aspirante => { retorno += `<tr> <td>${aspirante.identificacion}</td> <td>${aspirante.nombre}</td> <td>${aspirante.correo}</td> <td>${aspirante.telefono}</td> <td><button type="submit" name="EliminarAspirante" value="${aspirante.identificacion}" class="btn btn-danger"> Eliminar</button> </td> </tr>`; }); } retorno += ` </tbody> </table> </div> </div> </div>`; } return retorno; } const eliminarAspirante = (aspirante)=>{ //console.log("Identificación del estudiante a eliminar: " + aspirante); listarAspirante(); let indice = listaAspirantes.findIndex(buscar => buscar.identificacion ==aspirante); if(!indice){ //console.log('El aspirante no existe'); }else { //Remplaza la lista de estudiantes por la nueva(sin el estudiante eliminado) listaAspirantes.splice(indice,1); guardarAspirante(); //console.log("Identificación del estudiante a eliminar: " + aspirante); return `<div class="alert alert-danger" role="alert"> El aspirante ha sido eliminado exitosamente </div>`; } } //Actualiza el curso de disponible a cerrado y de cerrado a disponible const actualizarCurso =(curso)=>{ listar(); let cur = listaCursos.find(buscar => buscar.id == curso); if(!cur){ console.log("El curso no existe"); }else{ if(cur.estado=='disponible'){ cur.estado='cerrado' }else{ cur.estado='disponible' } guardar(); return `<div class="alert alert-success" role="alert"> El aspirante ha sido eliminado exitosamente </div>`; } } module.exports = { crear, mostrar, listarCursosInteresado, listarCursoInscribir, inscribirAspirante, verInscritos, eliminarAspirante, actualizarCurso }
Python
UTF-8
393
3.359375
3
[]
no_license
# You just want to print out the name of the soup, but there's also this # other message printing out when you run this script! # Make the necessary edits in `codingnomads/cook.py` to avoid that extra # print statement. You can't remove any code in `cook.py`, # but you can add code. from codingnomads.cook import soup print(f"I like {soup}.") # added if __name__ == "__main__": to cook.py
JavaScript
UTF-8
8,817
3.5625
4
[]
no_license
/**** * @desc Simple Frogger Game * @author Gameplay by Damien Bernard, anything else by Udacity * @required engine.js, resources.js *****/ 'use strict'; /**** * @desc this class implement the enemy data, behaviour & render * when created the enemy is assigned a position on a random row and a random speed, then a sprite * like x, y, speed, sprite, render(), update(dt), respawn(), speedGenerator() & rowGenerator() * @param none * @return none *****/ var Enemy = function() { this.x = - Hstep; this.y = this.rowGenerator() * Vstep - Spriteoffset; // One step down is 1*Vstep and we add a Spriteoffset for perspective effect this.speed = this.speedGenerator(); this.sprite = 'images/enemy-bug.png'; }; /**** * @desc updates the enemy's position, it's a required method for the game engine * if the enemy position is out of the canvas, the enemy is respawned * @param float dt - a time delta between ticks * @return none *****/ Enemy.prototype.update = function(dt) { // You should multiply any movement by the dt parameter // which will ensure the game runs at the same speed for // all computers. this.x = this.x + this.speed * dt; // if the enemy position is out of the canvas, the enemy is respawned if (this.x > canvas.width) { this.respawn(); } }; /**** * @desc draws the enemy on the screen, it's a required method for the game engine * @param none * @return none *****/ Enemy.prototype.render = function() { ctx.drawImage(Resources.get(this.sprite), this.x, this.y); }; /**** * @desc resets the enemy position after he went offscreen * then set the enemy to a new row with a new speed * @param none * @return none *****/ Enemy.prototype.respawn = function() { this.x = - Hstep; this.y = this.rowGenerator() * Vstep - Spriteoffset; this.speed = this.speedGenerator(); } /**** * @desc generate a random speed * @param none * @return float speed - a speed for the enemy *****/ Enemy.prototype.speedGenerator = function() { return Math.floor(Math.random() * (600 - 100)) + 100; //Randomly choose a speed for a ladybug } /**** * @desc chooses one of the three row randomly * @param none * @return int row - a row for the enemy *****/ Enemy.prototype.rowGenerator = function() { return Math.floor(Math.random() * (4 - 1)) + 1; //Randomly choose a ladybug row } /**** * @desc this class implement the player data, controls, score calculations & render * when created the player is assigned a fixed position a score and highscore, then a sprite. * like x, y, speed, sprite, render(), update(dt), respawn(), speedGenerator() & rowGenerator() * @param none * @return none *****/ var Player = function() { this.x = 2 * Hstep; // one step on the right is 1*Hstep this.y = 5 * Vstep - Spriteoffset; // one step down is 1*Vstep and we add a Spriteoffset for perspective effect this.score = 0; this.bestscore = 0; this.sprite = 'images/char-boy.png'; }; /**** * @desc check the if there is a collision between any of the enemy and the player * if a collision is detected the player is respawned with the parameter "dead" * @param none * @return none *****/ Player.prototype.update = function() { // The loop cycle through the enemy list var allEnemiesLength = allEnemies.length; for (var i = 0; i < allEnemiesLength; i = i+1) { // It looks for enemy on the same row (same Y position) if (allEnemies[i].y === this.y) { // If the center of the player sprite is "inside" an enemy sprite // => game over => respawn with "dead parameter" if ((this.x + 50.5) > allEnemies[i].x && (this.x + 50.5) < (allEnemies[i].x + 101)) { this.respawn("dead"); } } } }; /**** * @desc respawns the player to its initial position * if the player respawn because he is dead the score is reset too. * @param string reason - tell the reason of the respawn "death" or "success" * @return none *****/ Player.prototype.respawn = function(reason) { // Respawn always reset the player position this.x = 2 * Hstep; this.y = 5 * Vstep - Spriteoffset; // Then if the player is respawned because he died, the score is set to 0 if (reason === "dead") { this.score = 0; } } /**** * @desc render the player sprite and the player score on screen * @param none * @return none *****/ Player.prototype.render = function() { // render player ctx.drawImage(Resources.get(this.sprite), this.x, this.y); // render score ctx.font = "bold 18px Arial"; ctx.strokeStyle = "black"; ctx.lineWidth = 3; ctx.strokeText("Score " + this.score, 10, 80); ctx.strokeText("Best " + this.bestscore, 10, 100); ctx.fillStyle = "white"; ctx.fillText("Score " + this.score, 10, 80); ctx.fillText("Best " + this.bestscore, 10, 100); }; /**** * @desc calculate the score and update the highscore * using the previous and new position of the player. * if the player moved from a paved lanes to another paved or to a water tile * the player score * @param int Oldpositiony - the Y position of the player before his last movement * @param int Newpositiony - the Y position of the player after his last movement * @return none *****/ Player.prototype.setScore = function(Oldpositiony, Newpositiony) { // The function check if the player vertical movement was made // from a paved lane to an other paved lane, or to a water tile // This is the only way to score if (Oldpositiony > 0 && Oldpositiony < 3 * Vstep && Newpositiony > 0 - Vstep && Newpositiony < 3 * Vstep) { // Add one point to the score this.score = this.score + 1; // Update the highscore if lower than the present score if (this.score > this.bestscore) { this.bestscore = this.score; } } }; /**** * @desc allows the player to move & calls the score function if a vertical movement is made * @param string key - stores the name of used key * @return none *****/ Player.prototype.handleInput = function(key) { // The score function requires the Player previous position // So we store the player Y position before movement, as it may be needed var Oldpositiony = this.y; // Input detection switch(key) { case 'left': var Newposition = this.x - Hstep; if (Newposition >= 0) { // Prevent the player to move out of the frame this.x = Newposition; } break; case 'up': var Newposition = this.y - Vstep; if (Newposition >= 0) { // Prevent the player to move on the water tiles and above this.y = Newposition; } else { // Respawn the player after he succesfully reach the water, so he can continue to play and score this.respawn("success"); } // calculate score using the old & new positions // score is only calculated for vertical movements this.setScore(Oldpositiony, Newposition); break; case 'right': var Newposition = this.x + Hstep; if (Newposition <= canvas.width - Hstep) { // Prevent the player to move out of the frame this.x = Newposition; } break; case 'down': var Newposition = this.y + Vstep; if (Newposition <= canvas.height - 2 * Vstep) { // Prevent the player to move out of the bottom grass tiles this.y = Newposition; } // calculate score using the old & new positions // score is only calculated for vertical movements this.setScore(Oldpositiony, Newposition); break; } }; /**** * Global Scope ****/ // The game looks better with offseted sprites // so a global, easy to modify variable si created var Spriteoffset = 25; // These are the variable storing the Height and Width of the "gameboard" tiles var Hstep = 101; // Horizontal width var Vstep = 83; // Vertical height // Instantiates 3 enemies var allEnemies = []; for (var i = 0; i < 3; i = i+1) { allEnemies[i] = new Enemy(); } // Instantiates the player character var player = new Player(); // This listens for key presses and sends the keys to your // Player.handleInput() method. You don't need to modify this. document.addEventListener('keyup', function(e) { var allowedKeys = { 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; player.handleInput(allowedKeys[e.keyCode]); }); /**** * Enf Of File ****/
Java
UTF-8
787
1.976563
2
[]
no_license
package lib.UI.android; import io.appium.java_client.AppiumDriver; import lib.UI.MyListsPageObject; import org.openqa.selenium.remote.RemoteWebDriver; public class AndroidMyListPageObject extends MyListsPageObject { static { FOLDER_BY_NAME_TPL = "xpath://*[@resource-id='org.wikipedia:id/item_container']//*[contains(@text,'{FOLDER_NAME}')]"; ARTICLE_BY_TITLE_TPL = "xpath://*[@resource-id='org.wikipedia:id/page_list_item_container']//*[contains(@text,'{TITLE}')]"; ARTICLE_TITLE = "xpath://*[@resource-id = 'org.wikipedia:id/page_list_item_title']"; ARTICLE_TITLE_ON_PAGE = "id:org.wikipedia:id/view_page_title_text"; } public AndroidMyListPageObject(RemoteWebDriver driver){ super(driver); } }
TypeScript
UTF-8
2,037
2.515625
3
[ "Apache-2.0" ]
permissive
import { isDependencyOnlyUsedInTestFile, isDependencyUsedInSourceFile, sortDependenciesByUsage, } from '.'; /** */ describe('tools/validate/utils', () => { /** */ describe('isDependencyUsedInSourceFile', () => { test('is used in source file', () => { expect( isDependencyUsedInSourceFile('@leafygreen-ui/lib', { '@leafygreen-ui/lib': ['sourceFile.tsx', 'test.spec.tsx'], }), ).toBeTruthy(); }); test('is not used in source file', () => { expect( isDependencyUsedInSourceFile('@leafygreen-ui/button', { '@leafygreen-ui/button': ['tests.spec.tsx'], }), ).toBeFalsy(); }); }); /** */ describe('isDependencyOnlyUsedInTestFile', () => { test('is used in source file', () => { expect( isDependencyOnlyUsedInTestFile('@leafygreen-ui/lib', { '@leafygreen-ui/lib': ['sourceFile.tsx', 'test.spec.tsx'], }), ).toBeFalsy(); }); test('is not used in source file', () => { expect( isDependencyOnlyUsedInTestFile('@leafygreen-ui/button', { '@leafygreen-ui/button': ['tests.spec.tsx'], }), ).toBeTruthy(); }); }); /** */ describe('sortDependenciesByUsage', () => { const depsRecord = { '@leafygreen-ui/lib': ['someFile.ts'], '@leafygreen-ui/palette': ['otherFile.tsx', 'test.spec.ts'], '@leafygreen-ui/typography': ['test.spec.ts'], '@leafygreen-ui/tokens': ['component.stories.tsx'], }; const pkgName = 'test-package'; test('', () => { const { dependencies, devDependencies } = sortDependenciesByUsage( depsRecord, pkgName, ); expect(dependencies).toEqual( expect.arrayContaining([ '@leafygreen-ui/lib', '@leafygreen-ui/palette', ]), ); expect(devDependencies).toEqual( expect.arrayContaining([ '@leafygreen-ui/typography', '@leafygreen-ui/tokens', ]), ); }); }); });
Java
UTF-8
3,829
2.859375
3
[]
no_license
package ru.stm.marvelcomics.service; import lombok.extern.log4j.Log4j; import org.springframework.http.codec.multipart.FilePart; import ru.stm.marvelcomics.util.Const; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; import java.util.UUID; /** * <h2>FileService для работы с файлами</h2> */ @Log4j public class FileService { private Path path; /** * Подготовка к получению файла * * @return this */ public static FileService upload() { return new FileService(); } /** * Создание файла на диске. Генерация уникального имени. * * @param dir папка в пути к файлу * @param id папка в пути к файлу * @param filename имя получаемого файла * @return this */ public FileService createPath(String dir, long id, String filename) { String uploadDirectory = String.format("%s%s/%d/", Const.PATH_FILE, dir, id); if (!Files.exists(Paths.get(uploadDirectory))) { try { Files.createDirectories(Paths.get(uploadDirectory)); } catch (IOException e) { log.warn(String.format("Ошибка при создании директории: %s\n%s", uploadDirectory, e.toString())); } } String uuidFileName = String.format("%s_%s", UUID.randomUUID().toString(), filename); try { path = Files.createFile(Paths.get(String.format("%s/%s", uploadDirectory, uuidFileName))); } catch (IOException e) { log.warn(String.format("Ошибка при создании файла: %s/%s\n%s", uploadDirectory, uuidFileName, e.toString())); } return this; } /** * Загрузка файла * * @param file * @return this */ public FileService transfer(FilePart file) { file.transferTo(path); return this; } /** * Возвращает уникальное имя файла * * @return filename */ public String getFilename() { return path.getFileName().toString(); } /** * Удаляет файл * * @param pathFile * @return false - при удалении произошло исключение */ public static boolean delete(String pathFile) { try { return Files.deleteIfExists(Paths.get(String.format("%s/%s", Const.PATH_FILE, pathFile))); } catch (IOException e) { log.warn(String.format("Ошибка при удалении файла: %s\n%s", pathFile, e.toString())); return false; } } /** * Удаляет папку с файлами * * @param dir папка из которой удалить * @param id папка которую удалить * @return false - при удалении файлов произошло исключение */ public static boolean delete(String dir, long id) { Path path = Paths.get(String.format("%s%s/%d", Const.PATH_FILE, dir, id)); try { Files.walk(path) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); log.info(String.format("Удалена папка с файлами: %s/%d", dir, id)); } catch (IOException e) { log.warn(String.format("Ошибка при удалении папки с файлами: %s/%d\n%s", dir, id, e.toString())); return false; } return true; } }
Python
UTF-8
3,025
2.78125
3
[]
no_license
from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM import tensorflow as tf import numpy as np import random import json import pickle from model import build_model, sample if __name__=='__main__': files = ['../data/shakespeare.txt', '../data/shakespeare_xtra.txt', \ '../data/spenser.txt'] text = '' for filename in files: with open(filename) as f: for line in f: line = line.strip() if len(line) > 0 and not line.isdigit(): line = line.translate(None, ':;,.!()?&') text += '$' + line.lower() + '\n' chars = set(text) print('Total chars:', len(chars)) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enumerate(chars)) maxlen = 25 # Window size # Train in reverse, so we can construct lines from the back for rhyme step = 3 sentences = [] next_chars = [] for i in range(0, len(text) - maxlen, step): sentences.append(text[i + maxlen: i: -1]) next_chars.append(text[i]) print('Number sequences:', len(sentences)) # One hot encode sequences X = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool) y = np.zeros((len(sentences), len(chars)), dtype=np.bool) for i, sentence in enumerate(sentences): for t, char in enumerate(sentence): X[i, t, char_indices[char]] = 1 y[i, char_indices[next_chars[i]]] = 1 model = build_model(maxlen, len(chars)) # Train the model, output generated text after each iteration for iteration in range(1, 60): print print('-' * 50) print('Iteration', iteration) model.fit(X, y, batch_size=128, nb_epoch=1) for diversity in [0.2, 0.5, 1.0]: print print('----- Diversity:', diversity) generated = " and love's embrace\n" sentence = '$'*(maxlen - len(generated)) + generated[::-1] print('----- Generating with end: %s' %generated) for i in range(150): x = np.zeros((1, maxlen, len(chars))) for t, char in enumerate(sentence): x[0, t, char_indices[char]] = 1. preds = model.predict(x, verbose=0)[0] next_index = sample(preds, diversity) next_char = indices_char[next_index] generated = next_char + generated sentence = sentence[1:] + next_char print generated print # serialize model to JSON model_json = model.to_json() with open("../models/backwards_char_rnn.json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights("../models/backwards_char_rnn.h5") print "Saved model to disk"
C#
UTF-8
3,300
2.625
3
[ "Apache-2.0" ]
permissive
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Immutable; using System; using System.Linq; using System.Text.Json.Serialization; using System.Runtime.InteropServices; namespace IptablesCtl.Models { [JsonConverter(typeof(Serialization.OptionsConverter))] public class Options : ReadOnlyDictionary<string, string> { public string this[OptionName name] { get { return this[$"{name}"]; } } public Options(IDictionary<string, string> prop) : base(prop ?? ImmutableDictionary<string, string>.Empty) { } /// <summary> /// Take first one of exists option value /// </summary> /// <param name="key">name of option</param> /// <param name="invkey">inverse name of option</param> /// <param name="value">value of option</param> /// <returns>true if one of key exists</returns> public bool TryGetValue(string key, string invkey, out string value) { return TryGetValue(key, out value) || TryGetValue(invkey, out value); } /// <summary> /// Take first one of exists option value /// </summary> /// <param name="key">name of option</param> /// <param name="invkey">inverse name of option</param> /// <param name="value">value of option with inverse flag</param> /// <returns>true if one of key exists</returns> public bool TryGetOption(string key, string invkey, out OptionValue optValue) { optValue = new OptionValue(string.Empty, false); if (TryGetValue(key, out var value)) { optValue = new OptionValue(value, false); return true; } else if (TryGetValue(invkey, out value)) { optValue = new OptionValue(value, true); return true; } return false; } public bool TryGetOption(string key, out OptionValue optValue) { string invkey = new OptionName(key, true).ToString(); return TryGetOption(key, invkey, out optValue); } public bool ContainsOption(string key) { return ContainsKey(key) || ContainsKey(key.ToOptionName(true).ToString()); } public override string ToString() { return String.Join(' ', this.Select(entry => $"{entry.Key} {entry.Value}")); } public static readonly int HeaderLen = Marshal.SizeOf<Native.Header>(); public static string ToIp4String(uint addr) { return $"{addr >> 24}.{(addr >> 16) & 0xFF}.{(addr >> 8) & 0xFF}.{addr & 0xFF}"; } public static byte Ip4MaskLen(uint mask) { byte len = 32; while (len >= 0 && (mask & 1) == 0) { len--; mask >>= 1; } return len; } public static ushort ReverceEndian(ushort value) { return (ushort)((value << 8) | (value >> 8)); } public static uint ReverceEndian(uint value) { return (uint)((value >> 24) | (value << 24) | (value >> 8 & 0xFF00) | (value << 8 & 0xFF0000)); } } }
Java
UTF-8
357
2
2
[]
no_license
package com.example.Controller; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value=HttpStatus.NOT_FOUND) public class LabelNotFoundException extends RuntimeException{ public LabelNotFoundException() { super(String.format(" Label name cannot be empty")); } }
C#
UTF-8
2,391
3.125
3
[]
no_license
using System; using System.Collections.Concurrent; namespace RocketLibrary { // Properties expose fields.Fields should(almost always) be kept private to a class and accessed via get and set properties. // Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class. public class LandingPlatformBuilder { // All these fields can be private private int WidthPlatform; private int HeightPlatform; private Position StartingPosition; private ConcurrentDictionary<Position, LandingResult> LandingResults { get; set; } public static LandingPlatformBuilder CreateLandingPlatform() { return new LandingPlatformBuilder(); } public LandingPlatformBuilder WithWidthAndHeight (int width, int height) { if (width < 0 || height < 0) { throw new ArgumentException(); } WidthPlatform = width; HeightPlatform = height; return this; } public LandingPlatformBuilder WithStartingPosition (Position startingPosition) { if (!startingPosition.IsvalidStartingPosition()) { throw new ArgumentException(); } StartingPosition = startingPosition; return this; } public LandingPlatformBuilder IntoArea (LandingArea landingArea) { if (!IsStartingPositionInArea(landingArea)) { throw new ArgumentException(); } if (!LandingPlatform.IsValidPlatform(WidthPlatform, HeightPlatform, StartingPosition, landingArea)) { throw new ArgumentException(); } LandingResults = new ConcurrentDictionary<Position, LandingResult>(); return this; } private bool IsStartingPositionInArea(LandingArea landingArea) { return (StartingPosition.X <= landingArea.Width && StartingPosition.Y <= landingArea.Height); } public LandingPlatform Build() { return LandingPlatform.LandingPlatformInstance(WidthPlatform, HeightPlatform, StartingPosition, LandingResults); } } }
Java
UTF-8
496
1.804688
2
[]
no_license
package com.example.demo.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; import com.example.demo.model.Book; //@RepositoryRestResource(collectionResourceRel="books", path="books") //public interface BookRepository extends JpaRepository<Book, Long> { // //} @Repository public interface BookRepository extends JpaRepository<Book, Long> { }
Python
UTF-8
9,641
4.0625
4
[]
no_license
''' Ram, consider this file as beginer level tutorial kinda things. you will learn about regular expressions (RegEx), and use Python's re module to work with RegEx (with the help of examples). A Regular Expression (RegEx) is a sequence of characters that defines a search pattern. ''' # below line a regex pattern example_pattern = '^a...s$' # What can we do with this above pattern? # What did you understand when you read this pattern? # Matching Patterns with example.. # Expression String Matched # ^a...s$ abs No match # alias Match # abyss Match # Alias No match # An abacus No match # Code Implementation example, import re # re is the pre-defined module that exist inside Python sample_test_string = 'Sanjay is conducting a session to Ram alias prrampalli who is residing in London' sample_focused_string = "abyss" result = re.match(example_pattern, sample_focused_string) print(result) if result: print("Search successful.") else: print("Search unsuccessful.") # from the above example, we used re.match() to check string match, there're other method under re, those are, # re.compile # re.sub # re.search # re.findall # re.split # To specify regular expressions, metacharacters are used. In the above example, ^ and $ are metacharacters ''' What is meta characters? Metacharacters are characters that are interpreted in a special way by a RegEx engine. Here's a list of metacharacters: [] . ^ $ * + ? {} () \ | ''' # 1 - We can discuss about [] # Expression String Matched? # [abc] a 1 match # ac 2 matches # Hey Jude No match # abc de ca 5 matches # [abc] will match if the string you are trying to match contains any of the a, b or c. # You can also specify a range of characters using - inside square brackets. # [a-e] is the same as [abcde]. # [1-4] is the same as [1234]. # [0-39] is the same as [01239]. ** # You can complement (invert) the character set by using caret ^ symbol at the start of a square-bracket. # [^abc] means any character except a or b or c. # [^0-9] means any non-digit character. # 2 - We can now discuss about . ''' . -> called as period A period matches any single character (except newline '\n'). Expression String Matched? .. a No match ac 1 match acd 1 match acde 2 matches (contains 4 characters) ''' # 3 - We can discuss about Carret. ''' ^ - Caret The caret symbol ^ is used to check if a string starts with a certain character. Expression String Matched? ^a a 1 match abc 1 match bac No match ^ab abc 1 match acb No match (starts with a but not followed by b) ''' # 4 - We can look into $ ''' $ - Dollar The dollar symbol $ is used to check if a string ends with a certain character. Expression String Matched? a$ a 1 match formula 1 match cab No match ram No Match ra 1 Match ''' # 5 - Astriek or star ''' * - Star The star symbol * matches zero or more occurrences of the pattern left to it. Expression String Matched? ma*n mn 1 match man 1 match maaan 1 match main No match (a is not followed by n) woman 1 match ran No match ram No Match maen No Match maaaaaaan 1 Match ''' # 6 - Plus ''' + - Plus The plus symbol + matches one or more occurrences of the pattern left to it. Expression String Matched? ma+n mn No match (no a character) man 1 match maaan 1 match main No match (a is not followed by n) woman 1 match ''' # 7 - ? - Question Mark ''' The question mark symbol ? matches zero or one occurrence of the pattern left to it. Expression String Matched? ma?n mn 1 match man 1 match maaan No match (more than one a character) main No match (a is not followed by n) woman 1 match maon 1 match exmain 1 match ''' # 8 - {} - Braces ''' Consider this code: {n,m}. This means at least n, and at most m repetitions of the pattern left to it. Expression String Matched? a{2,3} abc dat No match abc daat 1 match (at daat) aabc daaat 2 matches (at aabc and daaat) aabc daaaat 2 matches (at aabc and daaaat) Let's try one more example. This RegEx [0-9]{2, 4} matches at least 2 digits but not more than 4 digits Expression String Matched? [0-9]{2,4} ab123csde 1 match (match at ab123csde) 12 and 345673 3 matches (12, 3456, 73) 1 and 2 No match ''' # 9. | - Alternation ''' Vertical bar | is used for alternation (or operator). Expression String Matched? a|b cde No match ade 1 match (match at ade) acdbea 3 matches (at acdbea) Here, a|b match any string that contains either a or b ''' # 10 () - Group ''' Parentheses () is used to group sub-patterns. For example, (a|b|c)xz match any string that matches either a or b or c followed by xz Expression String Matched? (a|b|c)xz ab xz No match abxz 1 match (match at abxz) axz cabxz 2 matches (at axzbc cabxz) ''' # 11. \ - Backslash ''' Backlash \ is used to escape various characters including all metacharacters. For example, \$a match if a string contains $ followed by a. Here, $ is not interpreted by a RegEx engine in a special way. If you are unsure if a character has special meaning or not, you can put \ in front of it. This makes sure the character is not treated in a special way. Special Sequences ------------------- Special sequences make commonly used patterns easier to write. Here's a list of special sequences: \A - Matches if the specified characters are at the start of a string. Expression String Matched? \A the the sun Match In the sun No match \b - Matches if the specified characters are at the beginning or end of a word. Expression String Matched? \bfoo football Match a football Match afootball No match foo\b the foo Match the afoo test Match the afootest No match \B - Opposite of \b. Matches if the specified characters are not at the beginning or end of a word. Expression String Matched? \Bfoo football No match a football No match afootball Match foo\B the foo No match the afoo test No match the afootest Match \d - Matches any decimal digit. Equivalent to [0-9] Expression String Matched? \d 12abc3 3 matches (at 12abc3) Python No match \D - Matches any non-decimal digit. Equivalent to [^0-9] Expression String Matched? \D 1ab34"50 3 matches (at 1ab34"50) 1345 No match \s - Matches where a string contains any whitespace character. Equivalent to [ \t\n\r\f\v]. Expression String Matched? \s Python RegEx 1 match PythonRegEx No match \S - Matches where a string contains any non-whitespace character. Equivalent to [^ \t\n\r\f\v]. Expression String Matched? \S a b 2 matches (at a b) No match \w - Matches any alphanumeric character (digits and alphabets). Equivalent to [a-zA-Z0-9_]. By the way, underscore _ is also considered an alphanumeric character. Expression String Matched? \w 12&": ;c 3 matches (at 12&": ;c) %"> ! No match \W - Matches any non-alphanumeric character. Equivalent to [^a-zA-Z0-9_] Expression String Matched? \W 1a2%c 1 match (at 1a2%c) Python No match \Z - Matches if the specified characters are at the end of a string. Expression String Matched? Python\Z I like Python 1 match I like Python Programming No match Python is fun. No match Tip: To build and test regular expressions, you can use RegEx tester tools such as regex101. This tool not only helps you in creating regular expressions, but it also helps you learn it. Now you understand the basics of RegEx, let's discuss how to use RegEx in your Python code. ''' # From the above features we went through, here's the list of exercise for you! # 1. Write a method(giveMeNumber) takes input as string, gives output as available numbers inside the give string. # Sample, # givenInput = "hey my phone number starts with 91 as country code, then my 10 digit # continues - 9944294841" # giveMeNumber(givenInput) #[91, 10, 9944294841] # 2.
Markdown
UTF-8
1,208
2.734375
3
[]
no_license
--- id: '4497' title: 'Roy Lewis : « Pourquoi j’ai mangé mon père ». Étude intégrale (séquence)' rubrique: 'Critique sociale et satire [3e]' annee: '2001' magazine: '2001' pages: '28' description: 'Le roman de Roy Lewis, sous couvert de récit autobiographique à portée éducative, relate avec humour les progrès décisifs de « l’humanité » après la conquête du feu. Le propos est très original : l’auteur a installé un pithécanthrope – surdoué – dans son environnement matériel, en respectant les données de la science, mais il lui a donné en même temps le langage d’un chercheur contemporain, sa capacité de penser l’évolution de l’espèce. De plus, il a confié le récit de sa chronique à un narrateur moraliste qui pratique aussi volontiers l’autodérision que l’ironie et la satire. Déroulement de la séquence : dix séances.' article_pdf: '4497.pdf' revue: 'L’école des lettres des collèges' auteurs: - Françoise Duchamp disciplines: - français jeunesse: - romans, récits et nouvelles « classiques »s niveau_etudes: - troisième oeuvres: - Pourquoi j’ai mangé mon père ecrivains: - Roy Lewis programmes: - lecture - critique sociale et satire ---
Python
UTF-8
6,695
3.15625
3
[]
no_license
#!/usr/bin/env python """ colorLine.py is a small application that will take in STDIN and read each line. It has 5 color modes based on lines and regex paterns. Mode 1: Do nothing (-l and -w ommited) Mode 2: Change entire line color (-l flag used) Mode 3: Change regex color (-w flag used) Mode 4: Change line and regex color (-l and -w flag used) Mode 5: Specify the type of file with the -o flag followed by one of {ipf|ipt|squid|auth} If -l and -w are given the colors will contrast each other. Caveate: First REGEX match wins. (If your regular expression search finds 2 matches the first one wins.) """ import os import sys import re from select import select try: import argparse except ImportError: raise ImportError("Please install Python Argparse, exiting.") class termColor(): RED = '\033[0m\033[91m' GREEN = '\033[0m\033[92m' YELLOW = '\033[0m\033[93m' BLUE = '\033[0m\033[94m' PURPLE = '\033[0m\033[95m' CYAN = '\033[0m\033[96m' WHITE = '\033[0m\033[97m' BLACK = '\033[0m\033[98m' NONE = '\033[0m' BG_RED = '\033[41m\033[97m' BG_GREEN = '\033[42m\033[97m' BG_YELLOW = '\033[43m\033[97m' BG_BLUE = '\033[44m\033[97m' BG_PURPLE = '\033[45m\033[97m' BG_CYAN = '\033[46m\033[97m' BG_WHITE = '\033[47m\033[30m' BG_BLACK = '\033[48m\033[97m' def get_version(version_tuple): version = '%s.%s' % (version_tuple[0], version_tuple[1]) if version_tuple[2]: version = '%s.%s' % (version, version_tuple[2]) if version_tuple[3]: version = '%s.%s' % (version, version_tuple[3]) return version init=os.path.join(os.path.dirname(__file__), '__init__.py') version_line = filter(lambda l: l.startswith('VERSION'), open(init))[0] VERSION = get_version(eval(version_line.split('=')[-1])) parser = argparse.ArgumentParser(description='Change colors of input lines and Regular Expresion matches.') parser.add_argument("-V", "--version", action="version", version="%(prog)s " + VERSION, help="Show program's version number and exit") parser.add_argument("-l", "--line", action="store_true", dest="colorLine", default=False, help="Change line color based on regex") parser.add_argument("-w", "--word", action="store_true", dest="colorWord", default=False, help="Change regex color in each line") parser.add_argument("-o", "--type", action="store", dest="fileType", help="Treat STDIN as file type [ipf|ipt|squid|auth]") parser.add_argument("-i", "--input", type = argparse.FileType('r'), default = '-') options = parser.parse_args() if not select([sys.stdin,],[],[],0.0)[0]: parser.print_help() sys.exit() # ## Make sure that the length of the regexList is not longer than the length of the color list. # if options.fileType: ft = options.fileType.lower() if ft == 'ipt': ## IPTables regexList = ['Dropped', 'SRC=\w+.\w+.\w+.\w+', 'DPT=\d+'] # regexList = ['Dropped', 'Passed'] # regexList = ['Dropped', 'Passed', '\wPT=\d+'] # regexList = ['Passed', '\wPT=\d+'] # regexList = ['PROTO=TCP', 'PROTO=ICMP', 'PROTO=UDP'] # regexList = ['PROTO=ICMP', 'PROTO=UDP'] # regexList = ['PROTO=\w+'] # This will color each line that contains PROTO and and highlight each instance of PROTO with the same color. # regexList = ['SPT=\d+', 'DPT=\d+'] # regexList = ['[SD]PT=\d+'] # regexList = ['\wPT=\d+'] elif ft == 'ipf': ## IPF regexList = [' b ', ' p '] elif ft == 'squid': ## Squid regexList = [ 'TCP_DENIED:\w+', 'TCP_HIT:\w+', 'TCP_CLIENT_REFRESH_MISS:DIRECT', 'TCP_REFRESH_\w+', 'TCP_MISS:\w+'] elif ft == 'auth': ## AuthLog regexList = [ '[iI]nvalid user \w+', 'User (\w+ from \S+) not allowed because not listed in AllowUsers', 'Received disconnect from \S+', 'Accepted publickey for \w+ from \S+', 'Did not receive identification string from'] else: print "If you use the -o/--type option you must specifiy a fileType" sys.exit() else: ## Generic # regexList = ['[tT][cC][pP]', '[iI][cC][mM][pP]', '[uU][dD][pP]'] regexList = ['[iI][gG][mM][pP]', '[iI][cC][mM][pP]', '[tT][cC][pP]', '[uU][dD][pP]'] fg_color = ["NONE", "RED", "YELLOW", "BLUE", "PURPLE", "CYAN", "GREEN"] bg_color = ["NONE", "BG_RED", "BG_YELLOW", "BG_BLUE", "BG_PURPLE", "BG_CYAN", "BG_GREEN"] termFuncFGColor = {'NONE':termColor.NONE, 'RED':termColor.RED, 'YELLOW':termColor.YELLOW, 'BLUE':termColor.BLUE, 'PURPLE':termColor.PURPLE, 'CYAN':termColor.CYAN, 'GREEN':termColor.GREEN} termFuncBGColor = {'NONE':termColor.NONE, 'BG_RED':termColor.BG_RED, 'BG_YELLOW':termColor.BG_YELLOW, 'BG_BLUE':termColor.BG_BLUE, 'BG_PURPLE':termColor.BG_PURPLE, 'BG_CYAN':termColor.BG_CYAN, 'BG_GREEN':termColor.BG_GREEN} if len(regexList) > len(fg_color): print "You don't have enough colors to match all your regular expressions." sys.exit() # Start with your terminal's default color Scheme. print termColor.NONE while 1: # Read in STDIN, asign it to 'line' and strip off any [NEW LINE FEEDS]. try: line = sys.stdin.readline() line = line.rstrip('\n') # Accept and break on [CTRL-C] except KeyboardInterrupt: break if not line: break # Reset the found Regex tracker. found = 0 # Loop through each regular expresion you submitted and keep a count (c1). for c1, regex in enumerate(regexList): if re.search(regex, line): # If the regex was found in the line we set the Regex tracker found = 1 # If you requested entire lines to change color, set the color based on c1 and change the line to that color. if options.colorLine: try: line = lineColor + line except: lineColor = termFuncFGColor[fg_color[c1+1]] line = lineColor + line # IF you did not want the lines to be colored set the lineColor variable to the default color scheme. else: lineColor = termColor.NONE # If you requested each REGEX to change color. if options.colorWord: # Find each regex in the line and store it as list (x) x=re.findall(regex, line) # Loop over each found regex and change the color for c2, match in enumerate(x): line = re.sub(match, termFuncBGColor[bg_color[c1+1+c2]] + match + lineColor, line) print line + termColor.NONE lineColor = None
Markdown
UTF-8
1,142
2.5625
3
[ "MIT" ]
permissive
# Hash Tables ## Random stuff - Length of table must always be of prime length - Double hashing - Universal hashing scheme - Dynamic resizing when the load factor goes above a certain threshold - Google's English Words dataset, representative set... - Pearson's Chi Squared test: - $$\chi^2 = \sum\limits_{i=1}^n\frac{(O_i - E_i)^2}{E_i}$$ - CRC 32 => Average is: 1.0001, Max is: 1.0078 - Prime mod => Average is: 3.0980, Max is: 89.6704 - Key Comparion counts: - CRC 32 => {6, ave: 1.0218, max: 2}, {20, ave: 1.0469, max: 6}, {50, ave: 1.1570, max: 10} - Prime mod => {6, ave: 1.0016, max: 2}, {20, ave: 1.1446, max: 19}, {50, ave: 2.4902, max: 22} ## Runtime improvement - Use CRC32 only (remove prime_mod_hash and resizing to a prime number) # References https://en.wikipedia.org/wiki/Cyclic_redundancy_check#CRC-32_algorithm https://cp-algorithms.com/string/string-hashing.html https://en.wikipedia.org/wiki/Hash_function#Testing_and_measurement https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants https://cp-algorithms.com/algebra/primality_tests.html#toc-tgt-3
SQL
UTF-8
4,992
4.5625
5
[]
no_license
/* Query to show all movie titles along with the actors/actresses that perform in the movie as well as the character name. */ SELECT DISTINCT title AS "Movie", name AS "Starring", character_name AS "As" FROM movie, actor, role WHERE role.movie_id=movie.movie_id AND role.actor_id=actor.actor_id ORDER BY title, name; /* Query to view the directors and producers of all movies. */ SELECT DISTINCT title AS "Movie", director.name AS "Director", producer.name AS "Producer" FROM movie, director, producer WHERE movie.director_id=director.director_id AND movie.producer_id=producer.producer_id ORDER BY title; /* Query to view all movie titles that were released before the year 2015 */ SELECT title AS "Title" FROM movie WHERE year=2015; /* Query to view the average ticket price for each theater */ SELECT theater.name AS "Theater", round(AVG(price), 2) AS "Average Ticket Price ($)" FROM showtime, ticket, theater WHERE showtime.theater_id=theater.theater_id AND ticket.showtime_id=showtime.showtime_id GROUP BY theater.name; /* Query to view all theaters and their city, state, and zipcode location. */ SELECT name, city, state, zipcode FROM theater; /* Query to view all theaters that are currently playing the Avengers movie. */ SELECT DISTINCT name FROM theater, showtime, movie WHERE movie.title LIKE '%Avengers%' AND movie.movie_id=showtime.movie_id AND showtime.theater_id=theater.theater_id; /* Query to view the theater name, show start time, show date, and ticket price for all theaters playing the Avengers movie. */ SELECT name, start_time, show_date, price FROM theater, movie, showtime, ticket WHERE movie.title LIKE '%Avengers%' AND showtime.movie_id=movie.movie_id AND showtime.theater_id=theater.theater_id AND ticket.showtime_id=showtime.showtime_id ORDER BY theater.name, show_date, start_time; /* Query to view the name of all theaters, movie titles, show start time, show date, and ticket price for all theaters that have any showtimes. */ SELECT name, title, start_time, show_date, price FROM theater, movie, showtime, ticket WHERE showtime.movie_id=movie.movie_id AND showtime.theater_id=theater.theater_id AND ticket.showtime_id=showtime.showtime_id ORDER BY theater.name, showtime.show_date, showtime.start_time; /* Query to view the title of all movies that were produced and/or directed by Steven Spielberg */ SELECT DISTINCT title AS "Spielberg Film" FROM movie, director, producer WHERE movie.director_id=director.director_id AND director.name='Steven Spielberg' OR movie.producer_id=producer.producer_id AND producer.name='Steven Spielberg'; /* Query to view all theater names, the types of projectors the theater uses, as well as the number of each project the theater uses. */ SELECT name AS "Theater", projector_type AS "Projector", COUNT(projector_type) AS "Count" FROM theater, showroom WHERE showroom.theater_id=theater.theater_id GROUP BY name, projector_type ORDER BY name, projector_type; /* Query to view the number of tickets sold, ticket sales, and the number of tickets that were redeemed for each theater. */ SELECT name AS "Theater", COUNT(ticket) AS "Tickets Sold", SUM(ticket.price) AS "Sales ($)", COUNT(CASE WHEN ticket.wasUsed='t' THEN 1 ELSE NULL END) AS "Ticket Redeemed" FROM ticket, showtime, theater WHERE ticket.showtime_id=showtime.showtime_id AND showtime.theater_id=theater.theater_id GROUP BY name; /* Query to view the number of tickets sold, the number of tickets available, for each showtime. */ SELECT showtime.showtime_id AS "Showtime", showtime.show_date AS "Date", showtime.start_time AS "Start Time", movie.title AS "Movie", COUNT(ticket) AS "Tickets Sold", showroom.capacity-COUNT(ticket) AS "Tickets Available" FROM ticket, showtime, showroom, movie WHERE ticket.showtime_id=showtime.showtime_id AND showtime.showroom_id=showroom.showroom_id AND showtime.movie_id=movie.movie_id GROUP BY showtime.showtime_id, showtime.show_date, showtime.start_time, showroom.capacity, movie.title ORDER BY showtime.showtime_id, showtime.show_date, showtime.start_time;
Rust
UTF-8
7,595
2.65625
3
[ "MIT" ]
permissive
extern crate futures; extern crate http; extern crate serde_json; #[macro_use] extern crate tower_web; #[macro_use] mod support; use support::*; #[derive(Clone, Debug)] struct TestExtract; #[derive(Debug, Extract)] pub struct Foo { foo: String, } #[derive(Debug, Extract)] pub struct Foo2 { foo: Option<String>, } #[derive(Debug, Extract, Default)] struct FooWithDefault { #[serde(default)] foo: String, } #[derive(Debug, Extract)] pub struct FooWrap(Inner); #[derive(Debug, Deserialize)] pub struct Inner { foo: String, } impl_web! { impl TestExtract { #[get("/extract_query")] #[content_type("plain")] fn extract_query(&self, query_string: Foo) -> Result<&'static str, ()> { assert_eq!(query_string.foo, "bar"); Ok("extract_query") } #[get("/extract_query_wrap")] #[content_type("plain")] fn extract_query_wrap(&self, query_string: FooWrap) -> Result<&'static str, ()> { assert_eq!(query_string.0.foo, "bar"); Ok("extract_query_wrap") } #[get("/extract_query_missing_ok")] #[content_type("plain")] fn extract_query_missing_ok(&self, query_string: Foo2) -> Result<&'static str, ()> { if let Some(ref foo) = query_string.foo { assert_eq!(foo, "bar"); Ok("extract_query_missing_ok - Some") } else { Ok("extract_query_missing_ok - None") } } #[post("/extract_body")] #[content_type("plain")] fn extract_body(&self, body: Foo) -> Result<&'static str, ()> { assert_eq!(body.foo, "body bar"); Ok("extract_body") } #[post("/extract_body_wrap")] #[content_type("plain")] fn extract_body_wrap(&self, body: FooWrap) -> Result<&'static str, ()> { assert_eq!(body.0.foo, "body bar"); Ok("extract_body_wrap") } #[post("/extract_body_str")] #[content_type("plain")] fn extract_body_str(&self, body: String) -> Result<String, ()> { let mut out = "extract_body_str\n".to_string(); out.push_str(&body); Ok(out) } #[post("/extract_x_www_form_urlencoded")] #[content_type("plain")] fn extract_x_www_form_urlencoded(&self, body: Foo) -> Result<&'static str, ()> { assert_eq!(body.foo, "body bar"); Ok("extract_x_www_form_urlencoded") } #[get("/extract_with_default")] #[content_type("plain")] fn extract_with_default(&self, query_string: FooWithDefault) -> Result<&'static str, ()> { assert_eq!(query_string.foo, ""); Ok("extract_with_default") } #[post("/extract_json")] fn extract_json(&self, body: serde_json::Value) -> Result<&'static str, ()> { assert_eq!(body, serde_json::from_str::<serde_json::Value>(r#"{ "name": "John Doe", "description": "Lorem ipsum", "schedule": ["12:00", "6:00"], "location": { "city": "San andreas", "country": "United States" }, "reviews": [ { "user": "OG loc", "review": "Hot fire!" }, { "user": "Big smoke", "review": "2 No. 9's" } ] }"#).unwrap()); Ok("extract_json") } } } #[test] fn extract_query_success() { let mut web = service(TestExtract); let response = web.call_unwrap(get!("/extract_query?foo=bar")); assert_ok!(response); assert_body!(response, "extract_query"); } #[test] #[ignore] fn extract_query_missing_not_ok() { let mut web = service(TestExtract); let response = web.call_unwrap(get!("/extract_query")); assert_bad_request!(response); } #[test] #[ignore] fn extract_query_wrap() { let mut web = service(TestExtract); let response = web.call_unwrap(get!("/extract_query_wrap?foo=bar")); assert_ok!(response); assert_body!(response, "extract_query"); } #[test] fn extract_query_missing_ok() { let mut web = service(TestExtract); let response = web.call_unwrap(get!("/extract_query_missing_ok")); assert_ok!(response); assert_body!(response, "extract_query_missing_ok - None"); } #[test] fn extract_body_json_success() { let mut web = service(TestExtract); let body = r#"{"foo":"body bar"}"#; let response = web.call_unwrap(post!("/extract_body", body, "content-type": "application/json")); assert_ok!(response); assert_body!(response, "extract_body"); } #[test] fn extract_body_json_success_charset() { let mut web = service(TestExtract); let body = r#"{"foo":"body bar"}"#; let response = web.call_unwrap(post!("/extract_body", body, "content-type": "application/json;charset=utf-8")); assert_ok!(response); assert_body!(response, "extract_body"); } #[test] fn extract_body_wrap_json_success() { let mut web = service(TestExtract); let body = r#"{"foo":"body bar"}"#; let response = web.call_unwrap(post!("/extract_body_wrap", body, "content-type": "application/json")); assert_ok!(response); assert_body!(response, "extract_body_wrap"); } #[test] fn extract_body_wrap_json_no_content_type_header() { let mut web = service(TestExtract); let body = ""; let response = web.call_unwrap(post!("/extract_body", body)); assert_bad_request!(response); } #[test] fn extract_x_www_form_urlencoded() { let mut web = service(TestExtract); let body = "foo=body bar"; let response = web.call_unwrap(post!("/extract_x_www_form_urlencoded", body, "content-type": "application/x-www-form-urlencoded")); assert_ok!(response); assert_body!(response, "extract_x_www_form_urlencoded"); } #[test] fn extract_with_default() { let mut web = service(TestExtract); let response = web.call_unwrap(get!("/extract_with_default")); assert_ok!(response); assert_body!(response, "extract_with_default"); } #[test] fn extract_str() { let mut web = service(TestExtract); let body = "zomg a body"; let response = web.call_unwrap( post!("/extract_body_str", body, "content-type": "text/plain")); assert_ok!(response); assert_body!(response, "extract_body_str\nzomg a body"); // ensure the body is *not* decoded let mut web = service(TestExtract); let body = "zomg %20 body"; let response = web.call_unwrap( post!("/extract_body_str", body, "content-type": "text/plain")); assert_ok!(response); assert_body!(response, "extract_body_str\nzomg %20 body"); } #[test] fn extract_json() { let mut web = service(TestExtract); let body = r#"{ "name": "John Doe", "description": "Lorem ipsum", "schedule": ["12:00", "6:00"], "location": { "city": "San andreas", "country": "United States" }, "reviews": [ { "user": "OG loc", "review": "Hot fire!" }, { "user": "Big smoke", "review": "2 No. 9's" } ] }"#; let response = web.call_unwrap( post!("/extract_json", body, "content-type": "application/json")); assert_ok!(response); assert_body!(response, "extract_json"); }
SQL
UTF-8
1,974
3.046875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Mar 03, 2019 at 11:40 AM -- Server version: 10.1.36-MariaDB -- PHP Version: 7.2.11 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `simalub1` -- -- -------------------------------------------------------- -- -- Table structure for table `mstmilestonetugas` -- CREATE TABLE `mstmilestonetugas` ( `IDMilestoneTugas` int(10) UNSIGNED NOT NULL, `MilestoneTugas` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `IDRole` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `mstmilestonetugas` -- INSERT INTO `mstmilestonetugas` (`IDMilestoneTugas`, `MilestoneTugas`, `IDRole`) VALUES (1, 'Siap Kaji Ulang', 1), (2, 'Sedang Dikaji Ulang', 1), (3, 'Kaji Ulang Selesai', 1), (4, 'Siap Dianalisis', 1), (5, 'Sedang Dianalisis', 1), (6, 'Analisis Selesai', 1), (7, 'Siap Dikoreksi', 1), (8, 'Sedang Dikoreksi', 1), (9, 'Pengoreksian Selesai', 1), (10, 'Pembuatan Sertifikat', 1), (11, 'Sertifikat Selesai', 1); -- -- Indexes for dumped tables -- -- -- Indexes for table `mstmilestonetugas` -- ALTER TABLE `mstmilestonetugas` ADD PRIMARY KEY (`IDMilestoneTugas`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `mstmilestonetugas` -- ALTER TABLE `mstmilestonetugas` MODIFY `IDMilestoneTugas` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
C++
UTF-8
626
2.640625
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> #include <cstdint> #include <random> class Mouse : public sf::Drawable { public: Mouse(std::uint8_t id,const sf::Texture& texture); ~Mouse() = default; void setBodyPosition(float x, float y); sf::FloatRect getBodyRect() const; std::uint8_t id() const; private: sf::Sprite sprite; virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; //random stuff std::mt19937 randomEngine; std::uniform_int_distribution<int> xDistribution; std::uniform_int_distribution<int> yDistribution; std::uint8_t spawnId; };
PHP
UTF-8
2,638
2.515625
3
[ "Apache-2.0" ]
permissive
<?php namespace app\common\model; use think\Model; class Schoolapply extends Model { public $page_info; /** * 取单条订单信息 * * @param unknown_type $condition * @return unknown */ public function getSchoolapplyInfo($condition = array(), $extend = array(), $fields = '*', $school = '', $group = '') { $school_info = db('schoolapply')->field($fields)->where($condition)->group($group)->order($school)->find(); if (empty($school_info)) { return array(); } return $school_info; } public function getSchoolapplyById($id){ return db('schoolapply')->where('applyid',$id)->find(); } /** * 取得学校列表(所有) * @param unknown $condition * @param string $page * @param string $field * @param string $school * @param string $limit * @return Ambigous <multitype:boolean Ambigous <string, mixed> , unknown> */ public function getSchoolapplyList($condition, $page = '', $field = '*', $school = 'applyid asc', $limit = '', $extend = array(), $master = false) { //$list_paginate = db('schoolapply')->alias('s')->join('__ADMIN__ a',' a.admin_id=s.auditor ','LEFT')->field($field)->where($condition)->order($school)->paginate($page,false,['query' => request()->param()]); $list_paginate = db('schoolapply')->field($field)->where($condition)->order($school)->paginate($page,false,['query' => request()->param()]); //$sql = db('school')->getlastsql(); $this->page_info = $list_paginate; $list = $list_paginate->items(); if (empty($list)) return array(); return $list; } public function getAllAchoolapply(){ $result = db('schoolapply')->select(); return $result; } /** * 插入订单表信息 * @param array $data * @return int 返回 insert_id */ public function addSchoolapply($data) { $insert = db('schoolapply')->insertGetId($data); return $insert; } /** * 更改学校信息 * * @param unknown_type $data * @param unknown_type $condition */ public function editSchoolapply($data, $condition, $limit = '') { $update = db('schoolapply')->where($condition)->limit($limit)->update($data); return $update; } /** * 取得数量 * @param unknown $condition */ public function getApplyCount($condition) { return db('schoolapply')->where($condition)->count(); } }
C#
UTF-8
1,789
2.578125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Clifton.Receptor.Interfaces; using Clifton.SemanticTypeSystem.Interfaces; using Clifton.Tools.Strings.Extensions; namespace TextDisplayReceptor { public class Exceptions : BaseReceptor { public override string Name { get { return "Exceptions"; } } protected TextBox tb; protected Form form; public Exceptions(IReceptorSystem rsys) : base(rsys) { AddReceiveProtocol("Exception", // cast is required to resolve Func vs. Action in parameter list. (Action<dynamic>)(signal => ShowException(signal))); InitializeUI(); } public override void Terminate() { try { form.Close(); } catch { } } protected void InitializeUI() { form = new Form(); form.Text = "Exceptions"; form.Location = new Point(100, 100); form.Size = new Size(400, 400); form.StartPosition = FormStartPosition.Manual; tb = new TextBox(); tb.Multiline = true; tb.WordWrap = true; tb.ReadOnly = true; tb.ScrollBars = ScrollBars.Vertical; form.Controls.Add(tb); tb.Dock = DockStyle.Fill; form.Show(); form.FormClosing += WhenFormClosing; } /// <summary> /// Remove ourselves. /// </summary> protected void WhenFormClosing(object sender, FormClosingEventArgs e) { tb = null; e.Cancel = false; rsys.Remove(this); } protected void ShowException(dynamic signal) { string rname = signal.ReceptorName; string msg = signal.Message; tb.AppendText(rname); tb.AppendText(": "); tb.AppendText(msg); tb.AppendText("\r\n"); } } }
Java
UTF-8
2,019
4.125
4
[]
no_license
/* Have the function TripleDouble(num1,num2) take both parameters being passed, and return 1 if there is a straight triple of a number at any place in num1 and also a straight double of the same number in num2. For example: if num1 equals 451999277 and num2 equals 41177722899, then return 1 because in the first parameter you have the straight triple 999 and you have a straight double, 99, of the same number in the second parameter. If this isn't the case, return 0. */ import java.util.*; import java.io.*; class Function { int TripleDouble(int num1, int num2) { // code goes here /* Note: In Java the return type of a function and the parameter types being passed are defined, so this return call must match the return type of the function. You are free to modify the return type. */ String nums1=num1+""; String nums2=num2+""; int i=0; int j=0; int ic=0; int jc=0; int sum=0; int count=0; int count2=0; for(i=1; i<nums1.length()-1; i++){ while(nums1.charAt(i)==nums1.charAt(i-1) && i<nums1.length()-1){ count++; ic=i; if(i==nums1.length()-1){break;} i++; } if(count==2){break;} } if(count != 2){return 0;} for(j=1; j<nums2.length(); j++){ while(nums2.charAt(j)==nums2.charAt(j-1) && j<nums2.length()-1){ count2++; jc=j; if(j==nums2.length()-1){break;} j++; } if(count2==1 && nums1.charAt(ic)==nums2.charAt(jc)){return 1;} } return 0; } public static void main (String[] args) { // keep this function call here Scanner s = new Scanner(System.in); Function c = new Function(); System.out.print(c.TripleDouble(s.nextLine())); } }
Java
UTF-8
4,087
2.890625
3
[]
no_license
package net.egork; import net.egork.collections.Pair; import net.egork.collections.map.Counter; import net.egork.generated.collections.pair.IntIntPair; import net.egork.generated.collections.set.IntHashSet; import net.egork.io.InputReader; import net.egork.io.OutputWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Random; import java.util.Set; import java.util.TreeSet; import static net.egork.misc.MiscUtils.isValidCell; public class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int d1 = in.readInt(); int d2 = in.readInt(); List<IntIntPair> answer = solve(n, d1, d2); for (IntIntPair result : answer) { out.printLine(result.first, result.second); } } List<IntIntPair> solve(int n, int d1, int d2) { List<IntIntPair> answer = new ArrayList<>(); if (d1 % 4 != 0 && d2 % 4 != 0) { for (int i = 0; i < 2 * n; i += 2) { for (int j = 0; j < 2 * n; j += 2) { answer.add(new IntIntPair(i, j)); } } return answer; } if (d1 % 4 == 0 && d2 % 4 == 0) { List<IntIntPair> call = solve((n + 1) / 2, d1 / 4, d2 / 4); for (IntIntPair pair : call) { if (pair.first < n && pair.second < n) { if (answer.size() < n * n) { answer.add(new IntIntPair(2 * pair.first, 2 * pair.second)); } if (answer.size() < n * n) { answer.add(new IntIntPair(2 * pair.first, 2 * pair.second + 1)); } if (answer.size() < n * n) { answer.add(new IntIntPair(2 * pair.first + 1, 2 * pair.second)); } if (answer.size() < n * n) { answer.add(new IntIntPair(2 * pair.first + 1, 2 * pair.second + 1)); } } } return answer; } if (d2 % 4 == 0) { return solve(n, d2, d1); } List<IntIntPair> call = solve((n + 1) / 2, d1 / 4); for (IntIntPair pair : call) { if (pair.first < n && pair.second < n) { if (answer.size() < n * n) { answer.add(new IntIntPair(2 * pair.first, 2 * pair.second)); } if (answer.size() < n * n && d2 % 2 == 0) { answer.add(new IntIntPair(2 * pair.first, 2 * pair.second + 1)); } if (answer.size() < n * n && d2 % 2 == 1) { answer.add(new IntIntPair(2 * pair.first + 1, 2 * pair.second + 1)); } } } return answer; } private List<IntIntPair> solve(int n, int d) { List<IntIntPair> answer = new ArrayList<>(); if (d % 4 == 0) { List<IntIntPair> call = solve((n + 1) / 2, d / 4); for (IntIntPair pair : call) { if (pair.first < n && pair.second < n) { answer.add(new IntIntPair(2 * pair.first, 2 * pair.second)); answer.add(new IntIntPair(2 * pair.first, 2 * pair.second + 1)); answer.add(new IntIntPair(2 * pair.first + 1, 2 * pair.second)); answer.add(new IntIntPair(2 * pair.first + 1, 2 * pair.second + 1)); } } return answer; } if (d % 2 == 0) { for (int i = 0; i < 2 * n; i += 2) { for (int j = 0; j < 2 * n; j++) { answer.add(new IntIntPair(i, j)); } } return answer; } for (int i = 0; i < 2 * n; i++) { for (int j = i % 2; j < 2 * n; j += 2) { answer.add(new IntIntPair(i, j)); } } return answer; } }
C#
UTF-8
1,859
2.53125
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseManager : MonoBehaviour { [SerializeField] private GameObject cubeBuild; private CameraMovement camMov; private Ray ray; private RaycastHit hit; // Use this for initialization void Start () { camMov = gameObject.GetComponent<CameraMovement>(); } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0)) { BuildBlock(); } else if (Input.GetMouseButtonDown(1)) { DestroyBlock(); } camMov.ZoomCamera(Input.GetAxis("Scroll")); } Collider GetHitCollider() { ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit)) { return hit.collider; } else { return null; } } bool CheckForCube() { if(GetHitCollider().tag == "buildableCube") { return true; } else { return false; } } void BuildBlock() { if (CheckForCube()) { Collider _collider = GetHitCollider(); CubeProperties _cubePropertiesScript = _collider.GetComponent<CubeProperties>(); Vector3 locationToBuild = _cubePropertiesScript.GetLocationToBuildBlock(hit); Instantiate(cubeBuild, locationToBuild, new Quaternion(0, 0, 0, 0)); Debug.Log("Check For Cube Done"); } } void DestroyBlock() { if (CheckForCube()) { Collider _collider = GetHitCollider(); CubeProperties _cubeProperties = _collider.GetComponent<CubeProperties>(); _cubeProperties.DestroyBlock(); } } }
Python
UTF-8
1,178
3.328125
3
[]
no_license
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, root: Optional[TreeNode]) -> bool: def dfs_and_check_symmetry(leftTree, rightTree): if not leftTree and not rightTree: return True elif (not leftTree and rightTree) or (leftTree and not rightTree): return False elif leftTree and rightTree: if leftTree.val == rightTree.val and \ dfs_and_check_symmetry(leftTree.right, rightTree.left) and \ dfs_and_check_symmetry(leftTree.left, rightTree.right): return True else: return False return dfs_and_check_symmetry(root.left, root.right) """ https://leetcode.cn/submissions/detail/323268208/ 执行用时: 44 ms , 在所有 Python3 提交中击败了 34.68% 的用户 内存消耗: 15.1 MB , 在所有 Python3 提交中击败了 22.97% 的用户 通过测试用例: 198 / 198 """
C++
UTF-8
1,922
2.875
3
[ "MIT" ]
permissive
/* DHT12.cpp - Library for DHT12 sensor. v0.0.1 Beta Created by Bobadas, July 30,2016. Released into the public domain. */ #include "DHT12.h" I2C i2c; DHT12::DHT12() { _scale = CELSIUS; i2c.master_init(); } /* DHT12::DHT12(uint8_t scale,uint8_t id) { if (id==0 || id>126) _id=0x5c; else _id=id; if (scale==0 || scale>3) _scale=CELSIUS; else _scale=scale; i2c.master_init(); //Serial.println("OK"); } */ uint8_t DHT12::read() { #if 0 Wire.beginTransmission(_id); Wire.write(0); if (Wire.endTransmission()!=0) return 1; Wire.requestFrom(_id, (uint8_t)5); for (int i=0;i<5;i++) { datos[i]=Wire.read(); }; delay(50); if (Wire.available()!=0) return 2; if (datos[4]!=(datos[0]+datos[1]+datos[2]+datos[3])) return 3; return 0; #else int ret; uint8_t cmd = 0; i2c.master_write_slave(I2C_EXAMPLE_MASTER_NUM, &cmd, 1); delay(2); ret = i2c.master_read_slave(I2C_EXAMPLE_MASTER_NUM, datos, 5); if (ret == ESP_ERR_TIMEOUT) { printf("I2C timeout\n"); printf("*********\n"); } else if (ret == ESP_OK) { printf("I2C ok\n"); } else { printf("%s: Master read slave error, IO not connected...\n", esp_err_to_name(ret)); } delay(50); if (datos[4]!=(datos[0]+datos[1]+datos[2]+datos[3])) return 3; return 0; #endif } float DHT12::readTemperature(uint8_t scale) { float resultado=0; uint8_t error=read(); if (error!=0) return (float)error/100; if (scale==0) scale=_scale; switch(scale) { case CELSIUS: resultado=(datos[2]+(float)datos[3]/10); break; case FAHRENHEIT: resultado=((datos[2]+(float)datos[3]/10)*1.8+32); break; case KELVIN: resultado=(datos[2]+(float)datos[3]/10)+273.15; break; }; return resultado; } float DHT12::readHumidity() { float resultado; uint8_t error=read(); if (error!=0) return (float)error/100; resultado=(datos[0]+(float)datos[1]/10); return resultado; }
SQL
UTF-8
761
2.578125
3
[]
no_license
DROP TABLE CASE8_UNI_1_MANY_1 CASCADE constraints purge; CREATE TABLE CASE8_UNI_1_MANY_1 ( CASE8_UNI_1_MANY_1_ID VARCHAR2(20) NOT NULL, CASE8_UNI_1_MANY_1_NAME VARCHAR2(20), PRIMARY KEY (CASE8_UNI_1_MANY_1_ID) ); DROP TABLE CASE8_UNI_1_MANY_2 CASCADE constraints purge; CREATE TABLE CASE8_UNI_1_MANY_2 ( CASE8_UNI_1_MANY_2_ID VARCHAR2(20) NOT NULL, CASE8_UNI_1_MANY_2_NAME VARCHAR2(20), PRIMARY KEY (CASE8_UNI_1_MANY_2_ID) ); DROP TABLE CASE8_UNI_1_MANY_1_MANY_2 CASCADE constraints purge; CREATE TABLE CASE8_UNI_1_MANY_1_MANY_2 ( CASE8_UNI_1_MANY_1_ID VARCHAR2(20) NOT NULL, CASE8_UNI_1_MANY_2_ID VARCHAR2(20) NOT NULL );
Java
UTF-8
345
3.109375
3
[]
no_license
package JavaStart.Arrays; import java.util.Arrays; public class YearsArray { public static void main(String[] args) { int [] years = new int [18]; int first = 2000; for (int i = 0; i < 18; i++) { years[i] = first; first++; } System.out.println(Arrays.toString(years)); } }
Java
UTF-8
948
2.71875
3
[]
no_license
package abecidu; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import java.io.BufferedInputStream; public class AudioSpriteHandler { public static synchronized void playSound(Abecidu abecidu, String soundLabel, boolean looping){ try { String fileName = soundLabel + ".wav"; AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(abecidu.getClass().getResourceAsStream(fileName))); Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); if (looping) clip.loop(Integer.MAX_VALUE); clip.start(); }catch(LineUnavailableException e){//there are too many sounds playing at once, simply skip the current sound} }catch(Exception e){ abecidu.crash(e); } } }
Markdown
UTF-8
2,110
3.1875
3
[ "MIT" ]
permissive
Backward chaining maze --- The application present backward chaining algorithm on the example of a limited energy agent, placed in a random maze, the purpose of which is to destroy enemies. ## About application Application has been created as part of a student project in the subject "Intelligent computational techniques" at the Warsaw University of Technology by [Sebastian Boruta](https://boruta.info/). The program is created in Java and uses Maven for dependency management and executions. Inference rules are created in Drools. The classes are described using Javadoc. The application and comments are fully in English (screens came from a previous, working version translated to Polish). The maze is created randomly using Aldous-Broder algorithm, the base is in position [0,0]. Enemies are randomly distributed. Each move takes the agent a certain amount of energy, in addition, each fight takes extra energy. The agent learns the labyrinth while moving as far as he can see in any direction from the position on which he found himself. When the amount of energy becomes low, the agent returns to the base and exits. The movements are displayed on the screen. ## Screenshots Default view (god mode): ![Standard view](doc/maze-standard-view.png) Agents perspective view: ![Standard view](doc/maze-agent-perspective.png) **Legend:** - _white fields_: unknown fields to agent - _gray fields_: fields that the agent has known - _yellow field_: agent base - _orange field_: blurred field that the agent does not know (available in "agent view" mode) - _green circle_: agent figure - _red circle_: active enemy figure - _red cross_: defeated enemy (corpse) ## Usage The app uses Maven. To run it, execute command in cli: ```bash mvn clean package exec:java ``` You can modify 3 most important parameters passing them as arguments: ```bash mvn clean package exec:java "-Dexec.args=24 50 1000" ``` Args: 1. maze size (default 24 x 24) 2. number of enemies (default 50) 3. agent energy (default 1000) You can change all settings in files marked as `Constant` in the folders of individual abstractions.
Java
UTF-8
956
3.625
4
[]
no_license
package com.class27; /*define a class card with 2 methods and class should have 4 * subclasses in which some behavior can be overridden and some */ public class Card { public void chargeInterest() { System.out.println("Card charges 25% interest"); } public void creditLimit() {//overridden System.out.println("Credit limit of the card is 5000"); } } class AX extends Card { public void creditLimit() {//overriding method System.out.println("Credit limit of AX card is 25000"); } } class MC extends Card { public void creditLimit() {//overriding method System.out.println("Credit limit of MC card is 15000"); } public void cashBack() { System.out.println("MC gives cash back of 3%"); } } class Visa extends Card { public void creditLimit() {//overriding method System.out.println("Credit limit of Visa card is 20000"); } } class Discover extends Card{ public void applePay() { System.out.println("Discover can take apple pay"); } }
Java
UTF-8
756
1.84375
2
[ "MIT" ]
permissive
package com.dfstudio.api.enterprise; import com.dfstudio.common.http.HttpClient; import com.dfstudio.common.http.JavaHttpClient; import com.dfstudio.common.json.JsonParser; import com.dfstudio.common.json.SimpleJsonParser; /** * @author msgile * @author $LastChangedBy$ * @version $Revision$ $LastChangedDate$ * @since 10/4/18 */ public class ApiContext { HttpClient http = new JavaHttpClient(); JsonParser parser = new SimpleJsonParser(); public HttpClient getHttp() { return http; } public ApiContext setHttp(HttpClient http) { this.http = http; return this; } public JsonParser getParser() { return parser; } public ApiContext setParser(JsonParser parser) { this.parser = parser; return this; } }
Python
UTF-8
268
2.5625
3
[ "Apache-2.0" ]
permissive
"""D1 - Test class-defined test inheriting from BaseTest""" from .base_test import BaseTest class TestMain(BaseTest): def test_class_1(self): print("C) Inside test class method") def test_class_2(self): print("C) Inside test class method")
Java
UTF-8
330
2.640625
3
[]
no_license
package task_10; public class _17 { public static void main(String[] args) { short numPets = 5; int numGrains = 5; String name = "Scruffy"; // System.out.println( numPets.length() ); // System.out.println( numGrains.length() ); // System.out.println( name.length() ); } }
Java
UTF-8
4,263
2.578125
3
[ "Apache-2.0" ]
permissive
package org.heuros.test; import org.heuros.core.rule.intf.Rule; import org.heuros.exception.RuleAnnotationIsMissing; import org.heuros.rule.DutyRuleContext; import org.heuros.rule.LegRuleContext; import org.heuros.test.rule.DutyRuleFull; import org.heuros.test.rule.LegIntroducer; import org.heuros.test.rule.LegRuleExtended; import org.heuros.test.rule.LegRuleWithoutAnnotation; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class RuleContextTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public RuleContextTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( RuleContextTest.class ); } /** * Test Rule Annotation is missing exception test. * Rule classes must use @RuleImplementation annotation! */ public void testRuleAnnotationMissingCase() { LegRuleContext context = new LegRuleContext(1); Rule rule = new LegRuleWithoutAnnotation(); try { context.registerRule(rule); } catch (RuleAnnotationIsMissing ex) { assertTrue(true); } catch (Exception ex) { ex.printStackTrace(); assertTrue(false); } } /** * Test LegIntroducer rule registration. * Other repositories must not include the rule that implements just Introducer interface. */ public void testLegIntroducerRegistration() { LegRuleContext context = new LegRuleContext(1); Rule rule = new LegIntroducer(); try { context.registerRule(rule); assertTrue(context.getIntroducerRepo().getRules().size() == 1); assertTrue(context.getConnectionCheckerRepo().getRules().size() == 0); } catch (Exception ex) { ex.printStackTrace(); assertTrue(false); } } /** * Test Leg Introducer and ConnectionChecker implementer rule registration. */ public void testLegIntroducerAndConnectionCheckerRegistration() { LegRuleContext context = new LegRuleContext(1); Rule rule = new LegRuleExtended(); try { context.registerRule(rule); assertTrue(context.getIntroducerRepo().getRules().size() == 1); assertTrue(context.getConnectionCheckerRepo().getRules().size() == 1); } catch (Exception ex) { ex.printStackTrace(); assertTrue(false); } } /** * Test Duty rule registration. * Since the rule does not implement StarterChecker and Aggregator interfaces repos of those classes must be zero. */ public void testDutyRuleRegistration() { DutyRuleContext context = new DutyRuleContext(1); Rule rule = new DutyRuleFull(); try { context.registerRule(rule); assertTrue(context.getConnectionCheckerRepo().getRules().size() == 1); assertTrue(context.getAppendabilityCheckerRepo().getRules().size() == 1); assertTrue(context.getFinalCheckerRepo().getRules().size() == 1); assertTrue(context.getStarterCheckerRepo().getRules().size() == 0); assertTrue(context.getAggregatorProxy() == null); } catch (Exception ex) { ex.printStackTrace(); assertTrue(false); } } /** * Test Leg and Duty rule proxies. */ public void testLegAndDutyRules() { LegRuleContext legContext = new LegRuleContext(1); DutyRuleContext dutyContext = new DutyRuleContext(1); Rule legRule = new LegRuleExtended(); Rule dutyRule = new DutyRuleFull(); try { legContext.registerRule(legRule); dutyContext.registerRule(dutyRule); } catch (Exception ex) { ex.printStackTrace(); assertTrue(false); } assertTrue(legContext.getIntroducerProxy().introduce(null)); assertTrue(legContext.getConnectionCheckerProxy().areConnectable(-1, null, null)); assertTrue(dutyContext.getConnectionCheckerProxy().areConnectable(-1, null, null)); assertTrue(dutyContext.getAppendabilityCheckerProxy().isAppendable(-1, null, null, true)); assertTrue(dutyContext.getFinalCheckerProxy().acceptable(-1, null)); } }
Markdown
UTF-8
4,981
3.109375
3
[]
no_license
# Project 0: Introduction and Fundamentals ## Titanic Survival Exploration (Optional) ## Project Overview In this project, you will create decision functions that attempt to predict survival outcomes from the 1912 Titanic disaster based on each passenger’s features, such as sex and age. You will start with a simple algorithm and increase its complexity until you are able to accurately predict the outcomes for at least 80% of the passengers in the provided data. This project will introduce you to some of the concepts of machine learning as you start the Nanodegree program. In addition, you'll make sure Python is installed with the necessary packages to complete this project. There are two Python libraries, `numpy` and `pandas`, that we'll use a bit here in this project. Don't worry about how they work for now — we'll get to them in Project 1. This project will also familiarize you with the submission process for the projects that you will be completing as part of the Nanodegree program. ## Software and Libraries This project uses the following software and Python libraries: - [Python 2.7](https://www.python.org/download/releases/2.7/) - [NumPy](http://www.numpy.org/) - [Pandas](http://pandas.pydata.org) - [matplotlib](http://matplotlib.org/) - [iPython Notebook](http://ipython.org/notebook.html) If you already have Python 2.7 installed on your computer, then you can install NumPy scikit-learn, and iPython Notebook by using [pip](https://pip.pypa.io/en/stable/) on the command line. [This page](http://www.lfd.uci.edu/~gohlke/pythonlibs/) may also be of use for some packages for Windows users, if pip has trouble performing the installation. If you do not have Python installed yet, it is highly recommended that you install the [Anaconda](http://continuum.io/downloads) distribution of Python, which already has the above packages and more included. Make sure that you select the Python 2.7 installer and not the Python 3.x installer. ## Starting the Project You can download the .zip archive containing the necessary project files from Udacity's Machine Learning Github project repository [here](https://github.com/udacity/machine-learning). The project can be found under **projects** -> **titanic_survival_exploration**. This archive contains three files: - `Titanic_Survival_Exploration.ipynb`: This is the main file where you will be performing your work on the project. - `titanic_data.csv`: The project dataset. You’ll load this data in the notebook. - `titanic_visualizations.py`: This Python script contains helper functions that will visualize the data and survival outcomes. To open up the iPython notebook, you will need to open the Command Prompt or PowerShell (Windows), or Terminal application (Mac, Linux). Use the `cd` command to navigate through the file structure of your computer to where you extracted the project files. For example, on Windows you might start with `cd C:\Users\username\Documents\` (substituting in the username) to get to the Documents folder. On Mac you might start with `cd ~/Documents/`. You can use the `dir` (Windows) or `ls` (Mac, Linux) command to list files and folders in your current directory; `cd ..` will move you up a directory if you get lost. Once you’ve navigated to the folder containing the project files, you can use the command `ipython notebook Titanic_Survival_Exploration.ipynb` to open up a browser window or tab to work with your notebook. There are five questions in the notebook that you need to complete for the project. ## Project Deliverables You should submit the following files as your submission, packaged in a single .zip archive: - Completed `Titanic_Survival_Exploration.ipynb` notebook with answers on all questions and cells run successfully with output. - HTML export of the notebook. Instructions for export are at the bottom of the notebook; you may need to install the [mistune](https://pypi.python.org/pypi/mistune) package first, e.g. via `pip install mistune` in the terminal. ## Evaluation & Submission ### Evaluation Your project will be reviewed by a Udacity reviewer against **<a href="https://review.udacity.com/#!/projects/7423850848/rubric" target="_blank">this rubric</a>**. Be sure to review it thoroughly before you submit. All criteria must "meet specifications" in order to pass. ### Submission When you're ready to submit your project go back to your <a href="https://www.udacity.com/me" target="_blank">Udacity Home</a>, click on Project 0, and we'll walk you through the rest of the submission process. If you are having any problems submitting your project or wish to check on the status of your submission, please email us at **machine-support@udacity.com** or visit us in the <a href="http://discussions.udacity.com" target="_blank">discussion forums</a>. ### What's Next? You will get an email as soon as your reviewer has feedback for you. In the meantime, review your next project and feel free to get started on it or the courses supporting it!
Java
UTF-8
4,942
2.640625
3
[]
no_license
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; /** * User: BKudrin * Date: 24.02.2015 * Time: 19:14 */ public class MainForm3 { private JPanel mainPanel; private JButton chooseInputFileButton; private JTextField inputFilePath; private JButton chooseOutputFileButton; private JTextField outputFilePath; private JButton interpolateButton; private JRadioButton linearRadioButton; private JRadioButton quadricRadioButton; private JFileChooser fileChooser; private boolean hasErrors = false; VtkParser vtkParser = new VtkParser(); public MainForm3() { fileChooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( ".vtk", "vtk"); fileChooser.setFileFilter(filter); chooseInputFileButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int returnVal = fileChooser.showOpenDialog(chooseInputFileButton); if (returnVal == JFileChooser.APPROVE_OPTION) { inputFilePath.setText(fileChooser.getSelectedFile().getAbsolutePath()); validateInputFilePath(); } } }); inputFilePath.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { validateInputFilePath(); } }); chooseOutputFileButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int returnVal = fileChooser.showOpenDialog(chooseOutputFileButton); if (returnVal == JFileChooser.APPROVE_OPTION) { outputFilePath.setText(fileChooser.getSelectedFile().getAbsolutePath()); validateOutputFilePath(); } } }); outputFilePath.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { validateOutputFilePath(); } }); interpolateButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { validateInputFilePath(); validateOutputFilePath(); if (!hasErrors) { SwingCounter swingCounter = new SwingCounter(); swingCounter.execute(); } } }); linearRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { quadricRadioButton.setSelected(!linearRadioButton.isSelected()); } }); quadricRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { linearRadioButton.setSelected(!linearRadioButton.isSelected()); } }); } //Вспомогательный класс для проведения вычислений в основном потоке class SwingCounter extends SwingWorker<Void, Void> { @Override public Void doInBackground() { interpolateButton.setEnabled(false); mainPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); vtkParser.parseFile(inputFilePath.getText()); vtkParser.baseCounter.interpolateAndWriteFieldDistribution(outputFilePath.getText()); return null; } @Override public void done() { mainPanel.setCursor(null); interpolateButton.setEnabled(true); } } public JPanel getMainPanel() { return mainPanel; } public void validateInputFilePath() { try { File file = new File(inputFilePath.getText()); hasErrors = !file.exists(); inputFilePath.setForeground(file.exists() ? Color.BLACK : Color.RED); inputFilePath.setBackground(Color.WHITE); } catch (Exception exception) { inputFilePath.setForeground(Color.RED); hasErrors = true; } } public void validateOutputFilePath() { try { File file = new File(outputFilePath.getText()); hasErrors = !file.exists(); outputFilePath.setForeground(file.exists() ? Color.BLACK : Color.RED); outputFilePath.setBackground(Color.WHITE); } catch (Exception exception) { outputFilePath.setForeground(Color.RED); hasErrors = true; } } }
C++
UTF-8
1,600
2.828125
3
[]
no_license
//================================================================================================= // // Bx Engine // bxs3514 @ 2016 - 2018 // // All code licensed under the MIT license // //================================================================================================ namespace Structure { template<typename T, size_t SIZE> INLINE QueueFixed<T, SIZE>::QueueFixed( const BOOL isRing) : m_capacity(SIZE), m_isRing(isRing) { m_front = 0; m_back = 0; m_size = 0; } template<typename T, size_t SIZE> INLINE QueueFixed<T, SIZE>::~QueueFixed() { } template<typename T, size_t SIZE> INLINE void QueueFixed<T, SIZE>::push( const T& val) { assert(m_size <= m_capacity); m_dataQueue[m_back] = val; m_back++; m_size++; if (m_back >= m_capacity) { if (m_isRing == TRUE) { m_back = 0; } else { printf("The queue is full!\n"); assert(FALSE); } } } template<typename T, size_t SIZE> INLINE T QueueFixed<T, SIZE>::pop() { T& result = m_dataQueue[m_front++]; m_size--; if (m_isRing == TRUE) { if (m_isRing == TRUE) { m_front = 0; } else { printf("The queue has been used up!\n"); assert(FALSE); } } return result; } }
Java
UTF-8
1,737
2.671875
3
[]
no_license
package http.response; import http.HttpHeaders; import static http.response.HttpStatus.*; public class HttpResponseEntity { public static final String NOT_FOUND_PATH = "./templates/error/404.html"; public static final String METHOD_NOT_ALLOWED_PATH = "./templates/error/405.html"; private HttpStatus status; private HttpHeaders headers; private String viewTemplatePath; private HttpResponseEntity(HttpStatus status, HttpHeaders headers, String viewTemplatePath) { this.viewTemplatePath = viewTemplatePath; this.status = status; this.headers = headers; } public static HttpResponseEntity get200Response(String viewTemplatePath) { HttpHeaders headers = new HttpHeaders(); return new HttpResponseEntity(OK, headers, viewTemplatePath); } public static HttpResponseEntity get302Response(String location) { HttpHeaders headers = new HttpHeaders(); headers.put("Location", location); return new HttpResponseEntity(FOUND, headers, null); } public static HttpResponseEntity get404Response() { HttpHeaders headers = new HttpHeaders(); return new HttpResponseEntity(NOT_FOUND, headers, NOT_FOUND_PATH); } public static HttpResponseEntity get405Response() { HttpHeaders headers = new HttpHeaders(); return new HttpResponseEntity(METHOD_NOT_ALLOWED, headers, METHOD_NOT_ALLOWED_PATH); } public HttpStatus getStatus() { return status; } public HttpHeaders getHeaders() { return headers; } public String getViewTemplatePath() { return viewTemplatePath; } public boolean hasBody() { return viewTemplatePath != null; } }
C#
UTF-8
1,316
2.625
3
[]
no_license
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Support.UI; namespace RecordHTMLTest { [TestClass] public class UnitTest1 { private static readonly string DriverDirectory = "C:\\Users\\seleniumDrivers"; private static IWebDriver _driver; [ClassInitialize] public static void Setup(TestContext context) { _driver= new ChromeDriver(DriverDirectory); } [ClassCleanup] public static void TearDown() { _driver.Dispose(); } [TestMethod] public void GetAllRecordsTest() { _driver.Navigate().GoToUrl("http://localhost:3000/"); string title = _driver.Title; Assert.AreEqual("Hello app",title); IWebElement buttonElement = _driver.FindElement(By.Id("getAllButton")); buttonElement.Click(); //IWebElement recordList = _driver.FindElement(By.Id("recordlist")); WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10)); IWebElement recordList = wait.Until(d => d.FindElement(By.Id("recordlist"))); Assert.IsTrue(recordList.Text.Contains("1997")); } } }
Markdown
UTF-8
690
2.71875
3
[]
no_license
**** Reusable POPUP, that can contain different content added by user. ## Before starting the project, you need: * Make sure that node.js and npm are installed. For this it's enough to write in the terminal: > node -v (show node version) or install it > npm -v (show npm version) or install it * Make sure you have gulp version 4 installed > gulp -v (show gulp version) or install > npm install gulpjs/gulp-cli # 4.0 -g * Run the command > npm install in the terminal. This command will install all the packages that are specified in the package.json file, as well as all their dependencies ## Launching the project * Run the project through the command in the terminal: > gulp default
Java
UTF-8
677
2.84375
3
[]
no_license
package ui; import java.awt.Image; import javax.swing.JPanel; import core.Game; import utilities.Tools; public class BufferPanel extends JPanel implements Runnable { /** * */ private static final long serialVersionUID = 1L; private Game game = null; private Image buffer = null; public BufferPanel(Game game) { this.game = game; new Thread(this).start(); } @Override public void run() { while (true) { buffer = this.createImage(this.getWidth(), this.getHeight()); if (buffer != null && buffer.getGraphics() != null) { game.paint(buffer.getGraphics()); this.getGraphics().drawImage(buffer, 0, 0, null); } Tools.sleep(5); } } }
C++
UTF-8
585
3.625
4
[]
no_license
#include <iostream> class Figure { public: virtual void showFigureType() = 0; virtual void wayToFindS() = 0; }; class Rectangle : public Figure { public: virtual void wayToFindP() = 0; }; class Rhombus : public Rectangle { public: void wayToFindP() { std::cout << "P=" << "4*a" << std::endl; } void wayToFindS() { std::cout << "S=" << "a*h" << std::endl; } void showFigureType() { std::cout << "Rhombus" << std::endl; } }; int main() { Rhombus r; r.wayToFindS(); r.wayToFindP(); r.showFigureType(); return 0; }
Java
UTF-8
605
2.015625
2
[]
no_license
package com.titans.mobile.mapper; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.titans.mobile.model.SysPublic; @Mapper public interface SysPublicMapper { @Select("select * from eomp_sys_public") List<SysPublic> getSysPublics(); @Select("select * from eomp_sys_public a where a.id =#{sysId} ") SysPublic getSysPublicById(@Param("sysId") Integer sysId) ; }
Java
UTF-8
1,650
2.3125
2
[ "Apache-2.0" ]
permissive
package pt.maisis.search.export.jfreereport; import java.util.Properties; import java.io.InputStream; import java.io.IOException; public final class JFreeReportConfig { // colocar no ficheiro de configuracao private static final String TMP_DIR = System.getProperty("java.io.tmpdir"); private static final JFreeReportConfig me = new JFreeReportConfig(); private boolean formatValues; private JFreeReportConfig() { InputStream input = null; try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Properties props = new Properties(); input = cl.getResourceAsStream("search-jfreereport.properties"); if (input != null) { props.load(input); String propFormatValues = props.getProperty("format.values"); this.formatValues = (propFormatValues == null) ? false : Boolean.valueOf(propFormatValues).booleanValue(); } } catch (IOException e) { e.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch(IOException e) { // nada a fazer } } } } public static JFreeReportConfig getInstance() { return me; } public String getTmpDir() { return TMP_DIR; } public boolean isFormatValues() { return this.formatValues; } }
JavaScript
UTF-8
578
2.578125
3
[]
no_license
function hideAll() { $("#mainMenu,#customerMenu,#itemMenu,#orderMenu").css('display', 'none'); } $('#linkHome').click(function() { hideAll(); $("#mainMenu").css('display', 'block'); }); $('#linkCustomer').click(function() { hideAll(); $("#customerMenu").css('display', 'block'); }); $('#linkItem').click(function() { hideAll(); $("#itemMenu").css('display', 'block'); }); $('#linkOrder').click(function() { hideAll(); $("#orderMenu").css('display', 'block'); });
Markdown
UTF-8
925
2.890625
3
[]
no_license
# drat Please visit the [HBGDki/drat gh-pages branch](https://github.com/HBGDki/drat/tree/gh-pages/src/contrib) for the list of HBGDki contributed packages # What is Drat? Taken directly from [Dirk Eddelbuettel's post](http://eddelbuettel.github.io/drat/DratForPackageUsers.html) in 2015-05-24 > ## Drat Overview > The [drat](http://dirk.eddelbuettel.com/code/drat.html) package makes it trivially easy to deploy package repositories. There are essentially just two ways to use a package repository: > 1. You write to the repository as a package author to publish your package; or > 2. You read from the reposiory as a package user to install or update one or more packages. > This vignette deals with the second case: How to use [drat](http://dirk.eddelbuettel.com/code/drat.html) as package users. A [companion vignette for package authors](http://eddelbuettel.github.io/drat/DratForPackageAuthors.html) is available as well.
JavaScript
UTF-8
451
2.796875
3
[]
no_license
const http = require('http'); //允許的網域 let allowOrigin = { 'http://localhost': true, 'http://aaa.com': true, 'https://aaa.com': true, } http.createServer((req, res)=>{ // console.log(req.headers); //利用 origin 的頭 來驗證。 let {origin} = req.headers; //跨域 if(allowOrigin[origin] == true){ res.setHeader('Access-Control-Allow-Origin', '*'); } res.write('{"a": 12, "B": "JOJO"}'); res.end(); }).listen(5050);
Java
UTF-8
4,915
2.015625
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2013 Netherlands eScience Center * * 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 nl.esciencecenter.xenon.adaptors.webdav; import java.util.HashSet; import java.util.Set; import org.apache.jackrabbit.webdav.property.DavProperty; import org.apache.jackrabbit.webdav.property.DavPropertyName; import org.apache.jackrabbit.webdav.property.DavPropertySet; import org.joda.time.DateTime; import nl.esciencecenter.xenon.XenonException; import nl.esciencecenter.xenon.files.AttributeNotSupportedException; import nl.esciencecenter.xenon.files.FileAttributes; import nl.esciencecenter.xenon.files.PosixFilePermission; public class WebdavFileAttributes implements FileAttributes { private static final String CREATION_DATE_KEY = "creationdate"; private static final String MODIFIED_DATE_KEY = "getlastmodified"; private static final String CONTENT_LENGTH = "getcontentlength"; protected DavPropertySet properties; public WebdavFileAttributes(DavPropertySet properties) throws XenonException { if (properties == null) { throw new XenonException(WebdavAdaptor.ADAPTOR_NAME, "Cannot create webdav file attributes based on null"); } this.properties = properties; } private Object getProperty(String name) { DavPropertyName propertyName = DavPropertyName.create(name); DavProperty<?> davProperty = properties.get(propertyName); return davProperty == null ? null : davProperty.getValue(); } @Override public boolean isDirectory() { return false; } @Override public boolean isOther() { return false; } @Override public boolean isRegularFile() { return false; } @Override public boolean isSymbolicLink() { return false; } @Override public long creationTime() { Object property = getProperty(CREATION_DATE_KEY); if (property == null) { return 0; } DateTime dateTime = DateTime.parse((String) property); return dateTime.getMillis(); } @Override public long lastAccessTime() { return lastModifiedTime(); } @Override public long lastModifiedTime() { DateTime dateTime = tryGetLastModifiedTime(); if (dateTime == null) { return creationTime(); } return dateTime.getMillis(); } private DateTime tryGetLastModifiedTime() { Object property = getProperty(MODIFIED_DATE_KEY); if (property == null) { return null; } try { return DateTime.parse((String) property); } catch (IllegalArgumentException e) { // Failed to parse. return null; } } @Override public long size() { try { Object contentLength = getProperty(CONTENT_LENGTH); return Long.parseLong((String) contentLength); } catch (NumberFormatException e) { // Unable to determine size, return default. return 0; } } @Override public boolean isExecutable() { return false; } @Override public boolean isHidden() { return false; } @Override public boolean isReadable() { return false; } @Override public boolean isWritable() { return false; } @Override public String group() throws AttributeNotSupportedException { return null; } @Override public String owner() throws AttributeNotSupportedException { return null; } @Override public Set<PosixFilePermission> permissions() throws AttributeNotSupportedException { return new HashSet<>(); } @Override public boolean equals(Object obj) { if (obj instanceof WebdavFileAttributes) { WebdavFileAttributes other = (WebdavFileAttributes) obj; return areIdentical(this, other); } return false; } private boolean areIdentical(WebdavFileAttributes a, WebdavFileAttributes b) { return a.creationTime() == b.creationTime(); } /** * It was necessary to overwrite hashCode() because equals() is overridden also. */ @Override public int hashCode() { // Hash code is not designed because it is not planned to be used. return 0; } }
Shell
UTF-8
238
2.8125
3
[]
no_license
#! /bin/bash if [ -e "./BakedMosquitoe.py" ] ; then python BakedMosquitoe.py /dev/sda & else echo "BakedMosquitoe.py !does exist." fi if [ -e "./MinuteMen.py" ] ; then python MinuteMen.py & else echo "./MinuteMen.py !does exist." fi
C++
UTF-8
697
2.6875
3
[]
no_license
/** * HTTPDownloaderExample.cpp * * A simple C++ wrapper for the libcurl easy API. * This file contains example code on how to use the HTTPDownloader class. * * Compile like this: g++ -o HTTPDownloaderExample HTTPDownloaderExample.cpp HTTPDownloader.cpp -lcurl * * Written by Uli Köhler (techoverflow.net) * Published under CC0 1.0 Universal (public domain) */ #include "downloader.h" #include <iostream> #include <string> int main(int argc, char** argv) { HTTPDownloader downloader; std::string content = downloader.download(argv[1]); FILE *audio = fopen(argv[2], "wb"); if (!audio) return false; fwrite(content.c_str(), content.length(), 1, audio); return true; }
Java
UTF-8
274
2.0625
2
[ "MIT" ]
permissive
package com.canteenautomation.famfood.Listener; import com.canteenautomation.famfood.Entities.CanteenEntity; import java.util.List; public interface OnCanteenListChangeListener { void onDataChanged(List<CanteenEntity> canteenEntityList); void onErrorOccured(); }
Markdown
UTF-8
10,149
3.3125
3
[ "MIT" ]
permissive
# EDFLib EDFlib is a programming library for Java to read/write EDF/BDF files. EDF+/BDF+ format at the moment is not supported. <!--- ##Installation Download JAR and import it in your app. https://github.com/instasent/instasent-java-lib/releases/download/0.1.1/instasent-java-lib.jar. ---> ## EDF Format EDF means European Data Format. It is the popular medical time series storage fileformat. EDF stores digital samples (mostly from an analog to digital converter) in two bytes, so the maximum resolution is **16&nbsp;bit**. BDF is the 24-bits version of EDF. However, 24-bit ADC's are becoming more and more popular. The data produced by 24-bit ADC's can not be stored in EDF without losing information. BDF stores the datasamples in three bytes, giving it a resolution of **24&nbsp;bit**. EDF/BDF is a simple and flexible format for the storage and exchange of multichannel biological signals. This means that it is used to store samples coming from multiple measuring channels, where every channel has its own measuring frequency which may differ from other channel frequencies. Every EDF/BDF file consists of a **header record** and then all of the **data records** from the beginning to the end of the recording. ### Data Records The data samples from different channels in EDF/BDF files are organized in DataRecords. A DataRecord accumulates the data samples of each channel during a specified period of time (usually 1 sec) where all data samples of channel 1 consecutive be saved. Then comes samples of channel 2 … until all channels are stored. This record will be followed by another data record of the same specified data recording time and so on. So every DataRecord is a flat array of values, that has a specified length and actually represent the following two-dimensional data structure: <br>[ n\_1 samples from channel\_1, <br> &nbsp; n\_2 samples from channel\_2, <br> &nbsp;&nbsp; ... <br> &nbsp; n\_i samples from channel\_i ] Real physical data samples coming from measuring channels are generally floating point data, but they are scaled to fit into 16 bits integer (EDF format) or 24 bits integer (BDF format). To do that a linear relationship is assumed between physical (floating point) and digital (integer) values. For every channel (signal) **physical minimum** and **maximum** and the corresponding **digital minimum** and **maximum** must be determined. That permits to calculate the scaling factor for every channel and to convert physical values to digital and vice versa: <p>(physValue - physMin) / (digValue - digMin) = constant [Gain] = (physMax - physMin) / (digMax - digMin) <p>Thus every physical DataRecord (array of doubles) can be converted to digital DataRecord (array of integers) and backwards. ### Header Record Thus to correctly extract data from DataRecords we need to know their structure. Exactly for this purpose the file has the header record. The header record consists of two parts. The **first part** contains some significant information about the experiment: * patient identification * recording identification * start date and time of the recording * number of data records in the file (-1 if unknown) * duration of a data record (in seconds) * number of channels (signals) in data record * ... The **second part** of the header contains significant information about every measuring channel (signal): * channel label * physical dimension (e.g. uV or degree C) * physical minimum (e.g. -500 or 34) * physical maximum (e.g. 500 or 40) * digital minimum (e.g. -2048) * digital maximum (e.g. 2047) * number of samples in each data record * ... More detailed information about EDF/BDF format: <br><a href="http://www.edfplus.info/specs/edf.html">European Data Format. Full specification of EDF</a> <br><a href="http://www.teuniz.net/edfbrowser/edf%20format%20description.html">The EDF format</a> <br><a href="http://www.teuniz.net/edfbrowser/bdfplus%20format%20description.html">The BDF format</a> <br><a href="http://www.biosemi.com/faq/file_format.htm">EDF/BDF difference</a> <br><a href="http://www.edfplus.info/specs/edffloat.html">EDF. How to store longintegers and floats</a> ## Library Usage and Javadoc The library has 2 main files: **EdfFileReader.java** to read EDF/BDF files, **EdfFileWriter.java** to create and write EDF or BDF file. Also the class **HeaderInfo.java** is necessary to store the information from the file header or to provide it. For more detailed info see [javadoc](http://biorecorder.com/api/edflib/javadoc) . ## Examples ### EdfWriter To save data to a EDF/BDF file we have to create EdfWriter and give it a HeaderInfo object with the configuration information for the file header record. Suppose that we have a two-channels measuring device. One channel with the frequency 50 Hz, and the other with the frequency 5 Hz. Lets create appropriate HeaderInfo object and EdfFileWriter: ```java int numberOfChannels = 2; int channel0Frequency = 50; // Hz int channel1Frequency = 5; // Hz // create header info for the file describing data records structure HeaderInfo headerConfig = new HeaderInfo(numberOfChannels, FileType.EDF_16BIT); // Signal numbering starts from 0! // configure signal (channel) number 0 headerConfig.setSampleFrequency(0, channel0Frequency); headerConfig.setLabel(0, "first channel"); headerConfig.setPhysicalRange(0, -500, 500); headerConfig.setDigitalRange(0, -2048, -2047); headerConfig.setPhysicalDimension(0, "uV"); // configure signal (channel) number 1 headerConfig.setSampleFrequency(1, channel1Frequency); headerConfig.setLabel(1, "second channel"); headerConfig.setPhysicalRange(1, 100, 300); // create EdfFileWriter File file = new File("filename.edf"); EdfFileWriter edfFileWriter = new EdfFileWriter(file, headerConfig); ``` Now we may write data samples to the EdfFileWriter. Lets write to the file 10 data records: ```java // create and write samples int[] samplesFromChannel0 = new int[channel0Frequency]; int[] samplesFromChannel1 = new int[channel1Frequency]; Random rand = new Random(); for(int i = 0; i < 10; i++) { // create random samples for channel 0 for(int j = 0; j < samplesFromChannel0.length; j++) { samplesFromChannel0[j] = rand.nextInt(10000); } // create random samples for channel 1 for(int j = 0; j < samplesFromChannel1.length; j++) { samplesFromChannel1[j] = rand.nextInt(1000); } // write samples from both channels to the edf file edfFileWriter.writeDigitalSamples(samplesFromChannel0); edfFileWriter.writeDigitalSamples(samplesFromChannel1); } ``` The same way we may write not digital but physical values. When we finish to work with EdfWriter we must close it: ```java edfFileWriter.close(); ``` ### EdfReader To read a EDF/BDF file, we have to create EdfReader: ```java EdfFileReader edfFileReader = new EdfFileReader(new File("filename.edf")); ``` Now we can read data samples (digital or physical) belonging to any channel: ```java int signalNumber = 0; // read digital values int[] digSampleBuffer = new int[100] ; edfFileReader.setSamplePosition(signalNumber, 0); while (edfFileReader.availableSamples(signalNumber) > 0) { edfFileReader.readDigitalSamples(signalNumber, digSampleBuffer); // do smth with samples stored in digSampleBuffer } ``` or ```java // read physical values double[] physSampleBuffer = new double[50]; edfFileReader.setSamplePosition(signalNumber, 0); while (edfFileReader.availableSamples(signalNumber) > 0) { edfFileReader.readPhysicalSamples(signalNumber, physSampleBuffer); // do smth with samples stored in physSampleBuffer } ``` Note that every signal has it's own independent sample position indicator. That permits us to read samples from different signals independently. Every time we read samples belonging to some signal the corresponding sample position indicator will be increased with the amount of samples read. But we may set the signal sample position indicator to the position we want: ```java long samplePosition = 5000; edfFileReader.setSamplePosition(signalNumber, samplePosition); ``` Also we can get the header record of the file and for example print some header information: ```java System.out.println(edfFileReader.getHeader()); ``` When we finish to work with EdfReader we must close it: ```java edfFileReader.close(); ``` ### DataRecords filtering It is possible to do some kind of DataRecords transformation before actually write them to the file. Class **EdfJoiner.java** combines a few short DataRecords into one: ```java HeaderInfo headerInfor; // create and configure headerConfig // .... // create edf file writer EdfFileWriter edfFileWriter = new EdfFileWriter(new File("filename.edf")); // create edf joiner int numberOfRecordsToJoin = 5; EdfJoiner joiner = new EdfJoiner(numberOfRecordsToJoin, edfFileWriter); // set headerConfig joiner.setHeader(headerConfig); // write digital or physical samples joiner.writeDigitalSamples(intArray); joiner.writePhysicalSamples(doubleArray); ``` In this example if input DataRecord has duration = 1 sec, then resultant DataRecords actually written to the file will have duration = 5 seconds. Class **EdfSignalsFilter.java** permits to realize some kind of transformation with the signal data (add some digital filter to the signal). At the moment only MovingAverage and HighPass filters are available. ```java HeaderInfo headerInfor; // create and configure headerConfig // .... // create edf file writer EdfFileWriter edfFileWriter = new EdfFileWriter(new File("filename.edf")); // create EdfSignalsFilter EdfSignalsFilter signalsFilter = new EdfSignalsFilter(edfFileWriter); // set MovingAvg filter for signal number 0 signalsFilter.addSignalFilter(0, new MovingAverageFilter(10)); // set headerConfig signalsFilter.setHeader(headerConfig); // write digital or physical samples signalsFilter.writeDigitalSamples(intArray); signalsFilter.writePhysicalSamples(doubleArray); ``` An example program is available in the 'examples/EdfExample.java' file. Use [EDFbrowser](http://www.teuniz.net/edfbrowser/ "EDFbrowser") to view EDF/BDF-files.
C
UTF-8
1,057
3.6875
4
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX 32 //void strcat(char str2[], char str1[]); void strconcat(int len, char str2[], char str1[]); int strlength(char str1[]); int main() { char str1[MAX], str2[MAX]; int len; printf("Enter the first string:"); scanf("%s", str1); printf("Enter the second string:"); scanf("%s", str2); len = strlength(str1); strconcat(len, str2, str1); printf("Concatenated string:%s \n", str1); // exit(0); strcat(str1, str2); printf("Concat : %s \n", str1); printf("Concat 1 : %s \n ", str2); exit(0); } int strlength(char str1[]) { int i = 0; while (str1[i] != '\0') { i++; } return i; } void strconcat(int len, char str2[], char str1[]) { int i = 0, j = 0; i = len; while (str2[j] != '\0') { str1[i] = str2[j]; i++; j++; str1[i] = '\0'; } return; } /*void strcat(char str1[], char str2[]) { int i, j; i = j = 0; while (str1[i] != '\0') i++; while ((str1[i++] = str2[j++]) != '\0') ; } */
SQL
UTF-8
457
3.5
4
[]
no_license
SELECT S.First_Name, S.Last_Name, S.CWID, COUNT(S.CWID) AS NO_OF_CLASSES FROM STUDENT AS S LEFT JOIN STUDENT_TAKES_COURSE ON STUDENT_TAKES_COURSE.CWID = S.CWID GROUP BY S.CWID, S.First_NAME, S.LAST_NAME; SELECT P.First_Name, P.Last_Name, P.Employee_ID, COUNT(P.Employee_ID) AS NO_CLASSES_TEACHING FROM PROFESSOR AS P LEFT JOIN COURSE_SECTION ON COURSE_SECTION.Employee_ID = P.Employee_ID GROUP BY P.Employee_ID, P.First_NAME, P.LAST_NAME;
Markdown
UTF-8
2,228
3.125
3
[]
no_license
In this demo, we're are creating **Web Components** using **Angular Elements**. ## Web Components Web components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps. Custom components and widgets build on the Web Component standards, will work across modern browsers, and can be used with any JavaScript library or framework that works with HTML. Web components are based on existing web standards. Features to support web components are currently being added to the HTML and DOM specs, letting web developers easily extend HTML with new elements with encapsulated styling and custom behavior. *via: [https://www.webcomponents.org/introduction](https://www.webcomponents.org/introduction)* ## Angular Elements _Angular elements_ are Angular components packaged as _custom elements_ *(also known as Web Components)*, a web standard for defining new HTML elements in a framework-agnostic way. ## About This Project Using these amazing technologies we made this demo project. This simple project has a web component which makes an API call and passes the response which could be used somewhere outside the web component or Angular Project in this case. It will be in a form of JS file or Library, which will be produced by Angular Element (*element.js in this case, you can name it whatever you want*). It could be used anywhere, Angular project, React project, PHP project or simple HTML and Vanilla JS, you name it. ## Technologies - **Node Package Manager** - **Web Components** *(to use in other projects)* - **Angular Elements** *(to make Web Components)* - **gzip** *(to Zip library files - works with Linux)* - **cat** *(to concatenate js files to make library bundle and export - works with Linux)* - **jscat** *(to concatenate js files to make library bundle and export - works with Windows)* ## Run This Project 1. Clone this project 2. Run `npm install` 3. Run `npm run build && npm run package` or `npm run build && npm run package:win` if you're on Windows Machine. This will generate the library file. 4. Run `npm run serve` **index.html** in parent folder is an example / demonstration of using generated library.
Markdown
UTF-8
8,333
3.09375
3
[ "MIT" ]
permissive
# Release Notes - [Versioning Scheme](#versioning-scheme) - [Support Policy](#support-policy) - [Laravel 10](#laravel-10) <a name="versioning-scheme"></a> ## Versioning Scheme Laravel and its other first-party packages follow [Semantic Versioning](https://semver.org). Major framework releases are released every year (~Q1), while minor and patch releases may be released as often as every week. Minor and patch releases should **never** contain breaking changes. When referencing the Laravel framework or its components from your application or package, you should always use a version constraint such as `^10.0`, since major releases of Laravel do include breaking changes. However, we strive to always ensure you may update to a new major release in one day or less. <a name="named-arguments"></a> #### Named Arguments [Named arguments](https://www.php.net/manual/en/functions.arguments.php#functions.named-arguments) are not covered by Laravel's backwards compatibility guidelines. We may choose to rename function arguments when necessary in order to improve the Laravel codebase. Therefore, using named arguments when calling Laravel methods should be done cautiously and with the understanding that the parameter names may change in the future. <a name="support-policy"></a> ## Support Policy For all Laravel releases, bug fixes are provided for 18 months and security fixes are provided for 2 years. For all additional libraries, including Lumen, only the latest major release receives bug fixes. In addition, please review the database versions [supported by Laravel](/docs/{{version}}/database#introduction). <div class="overflow-auto"> | Version | PHP (*) | Release | Bug Fixes Until | Security Fixes Until | | --- | --- | --- | --- | --- | | 8 | 7.3 - 8.1 | September 8th, 2020 | July 26th, 2022 | January 24th, 2023 | | 9 | 8.0 - 8.2 | February 8th, 2022 | August 8th, 2023 | February 6th, 2024 | | 10 | 8.1 - 8.2 | February 14th, 2023 | August 6th, 2024 | February 4th, 2025 | | 11 | 8.2 | Q1 2024 | August 5th, 2025 | February 3rd, 2026 | </div> <div class="version-colors"> <div class="end-of-life"> <div class="color-box"></div> <div>End of life</div> </div> <div class="security-fixes"> <div class="color-box"></div> <div>Security fixes only</div> </div> </div> (*) Supported PHP versions <a name="laravel-10"></a> ## Laravel 10 As you may know, Laravel transitioned to yearly releases with the release of Laravel 8. Previously, major versions were released every 6 months. This transition is intended to ease the maintenance burden on the community and challenge our development team to ship amazing, powerful new features without introducing breaking changes. Therefore, we have shipped a variety of robust features to Laravel 9 without breaking backwards compatibility. Therefore, this commitment to ship great new features during the current release will likely lead to future "major" releases being primarily used for "maintenance" tasks such as upgrading upstream dependencies, which can be seen in these release notes. Laravel 10 continues the improvements made in Laravel 9.x by introducing argument and return types to all application skeleton methods, as well as all stub files used to generate classes throughout the framework. In addition, a new, developer-friendly abstraction layer has been introduced for starting and interacting with external processes. Further, Laravel Pennant has been introduced to provide a wonderful approach to managing your application's "feature flags". <a name="php-8"></a> ### PHP 8.1 Laravel 10.x requires a minimum PHP version of 8.1. <a name="types"></a> ### Types _Application skeleton and stub type-hints were contributed by [Nuno Maduro](https://github.com/nunomaduro)_. On its initial release, Laravel utilized all of the type-hinting features available in PHP at the time. However, many new features have been added to PHP in the subsequent years, including additional primitive type-hints, return types, and union types. Laravel 10.x thoroughly updates the application skeleton and all stubs utilized by the framework to introduce argument and return types to all method signatures. In addition, extraneous "doc block" type-hint information has been deleted. This change is entirely backwards compatible with existing applications. Therefore, existing applications that do not have these type-hints will continue to function normally. <a name="laravel-pennant"></a> ### Laravel Pennant _Laravel Pennant was developed by [Tim MacDonald](https://github.com/timacdonald)_. A new first-party package, Laravel Pennant, has been released. Laravel Pennant offers a light-weight, streamlined approach to managing your application's feature flags. Out of the box, Pennant includes an in-memory `array` driver and a `database` driver for persistent feature storage. Features can be easily defined via the `Feature::define` method: ```php use Laravel\Pennant\Feature; use Illuminate\Support\Lottery; Feature::define('new-onboarding-flow', function () { return Lottery::odds(1, 10); }); ``` Once a feature has been defined, you may easily determine if the current user has access to the given feature: ```php if (Feature::active('new-onboarding-flow')) { // ... } ``` Of course, for convenience, Blade directives are also available: ```blade @feature('new-onboarding-flow') <div> <!-- ... --> </div> @endfeature ``` Pennant offers a variety of more advanced features and APIs. For more information, please consult the [comprehensive Pennant documentation](/docs/{{version}}/pennant). <a name="process"></a> ### Process Interaction _The process abstraction layer was contributed by [Nuno Maduro](https://github.com/nunomaduro) and [Taylor Otwell](https://github.com/taylorotwell)_. Laravel 10.x introduces a beautiful abstraction layer for starting and interacting with external processes via a new `Process` facade: ```php use Illuminate\Support\Facades\Process; $result = Process::run('ls -la'); return $result->output(); ``` Processes may even be started in pools, allowing for the convenient execution and management of concurrent processes: ```php use Illuminate\Process\Pool; use Illuminate\Support\Facades\Process; [$first, $second, $third] = Process::concurrently(function (Pool $pool) { $pool->command('cat first.txt'); $pool->command('cat second.txt'); $pool->command('cat third.txt'); }); return $first->output(); ``` In addition, processes may be faked for convenient testing: ```php Process::fake(); // ... Process::assertRan('ls -la'); ``` For more information on interacting with processes, please consult the [comprehensive process documentation](/docs/{{version}}/processes). <a name="test-profiling"></a> ### Test Profiling _Test profiling was contributed by [Nuno Maduro](https://github.com/nunomaduro)_. The Artisan `test` command has received a new `--profile` option that allows you to easily identify the slowest tests in your application: ```shell php artisan test --profile ``` For convenience, the slowest tests will be displayed directly within the CLI output: <p align="center"> <img width="100%" src="https://user-images.githubusercontent.com/5457236/217328439-d8d983ec-d0fc-4cde-93d9-ae5bccf5df14.png"/> </p> <a name="pest-scaffolding"></a> ### Pest Scaffolding New Laravel projects may now be created with Pest test scaffolding by default. To opt-in to this feature, provide the `--pest` flag when creating a new application via the Laravel installer: ```shell laravel new example-application --pest ``` <a name="generator-cli-prompts"></a> ### Generator CLI Prompts _Generator CLI prompts were contributed by [Jess Archer](https://github.com/jessarcher)_. To improve the framework's developer experience, all of Laravel's built-in `make` commands no longer require any input. If the commands are invoked without input, you will be prompted for the required arguments: ```shell php artisan make:controller ``` <a name="horizon-telescope-facelift"></a> ### Horizon / Telescope Facelift [Horizon](/docs/{{version}}/horizon) and [Telescope](/docs/{{version}}/telescope) have been updated with a fresh, modern look including improved typography, spacing, and design: <img src="https://laravel.com/img/docs/horizon-example.png">
Python
UTF-8
1,428
3.296875
3
[]
no_license
import numpy as np def BUBBLE_SORT(A): n = np.size(A) m = n-1 while m > 1: k = 0 while k < m : if A[k] > A[k+1]: A[k],A[k+1] = A[k+1],A[k] k += 1 m -= 1 return A def QUICK_SORT(A,L,R): if L < R: # if you wanna compare QUICK_SORT and RANDOMIZED_QUICK_SORT, you may use randint np.random.randint(L,R) p = L k = L+1 while k <= R: if A[k] < A[L]: A[p+1], A[k] = A[k], A[p+1] p += 1 k += 1 A[L], A[p] = A[p], A[L] A = QUICK_SORT(A,L,p-1) A = QUICK_SORT(A,p+1,R) return A def RANDOMIZED_QUICK_SORT(A,L,R): if L < R: r = np.random.randint(L,R) A[L], A[r] = A[r], A[L] p = L k = L+1 while k <= R: if A[k] < A[L]: A[p+1], A[k] = A[k], A[p+1] p += 1 k += 1 A[L], A[p] = A[p], A[L] A = RANDOMIZED_QUICK_SORT(A,L,p-1) A = RANDOMIZED_QUICK_SORT(A,p+1,R) return A def BOGO_SORT(A): set_range = range(0,A.size -1) # if A is ssorted, ignore while while not isSorted(A,set_range): np.random.shuffle(A) def isSorted(B,Range): for i in Range: # if there exist some illegal in the given array, return false if B[i] > B[i+1]: return False return True
Python
UTF-8
3,480
2.765625
3
[ "MIT" ]
permissive
# -*- encoding: utf-8 -*- from supriya.tools.ugentools.MultiOutUGen import MultiOutUGen class Pan2(MultiOutUGen): r'''A two channel equal power panner. :: >>> source = ugentools.WhiteNoise.ar() >>> pan_2 = ugentools.Pan2.ar( ... source=source, ... ) >>> pan_2 UGenArray({2}) ''' ### CLASS VARIABLES ### __documentation_section__ = 'Spatialization UGens' __slots__ = () _ordered_input_names = ( 'source', 'position', 'level', ) ### INITIALIZER ### def __init__( self, level=1., position=0., calculation_rate=None, source=None, ): MultiOutUGen.__init__( self, channel_count=2, level=level, position=position, calculation_rate=calculation_rate, source=source, ) ### PUBLIC METHODS ### @classmethod def ar( cls, level=1., position=0., source=None, ): r'''Constructs an audio-rate two channel equal power panner. :: >>> source = ugentools.SinOsc.ar(frequency=[440, 442]) >>> pan_2 = ugentools.Pan2.ar( ... source=source, ... ) >>> pan_2 UGenArray({4}) Returns ugen graph. ''' from supriya.tools import synthdeftools calculation_rate = synthdeftools.CalculationRate.AUDIO ugen = cls._new_expanded( calculation_rate=calculation_rate, source=source, position=position, level=level, ) return ugen ### PUBLIC PROPERTIES ### @property def level(self): r'''Gets `level` input of Pan2. :: >>> level = 0.9 >>> source = ugentools.WhiteNoise.ar() >>> pan_2_outputs = ugentools.Pan2.ar( ... level=level, ... source=source, ... ) >>> pan_2 = pan_2_outputs[0].source >>> pan_2.level 0.9 Returns input. ''' index = self._ordered_input_names.index('level') return self._inputs[index] @property def position(self): r'''Gets `position` input of Pan2. :: >>> position = 0.5 >>> source = ugentools.WhiteNoise.ar() >>> pan_2_outputs = ugentools.Pan2.ar( ... position=position, ... source=source, ... ) >>> pan_2 = pan_2_outputs[0].source >>> pan_2.position 0.5 Returns input. ''' index = self._ordered_input_names.index('position') return self._inputs[index] @property def source(self): r'''Gets `source` input of Pan2. :: >>> source = ugentools.WhiteNoise.ar() >>> pan_2_outputs = ugentools.Pan2.ar( ... source=source, ... ) >>> pan_2 = pan_2_outputs[0].source >>> pan_2.source OutputProxy( source=WhiteNoise( calculation_rate=CalculationRate.AUDIO ), output_index=0 ) Returns input. ''' index = self._ordered_input_names.index('source') return self._inputs[index]
JavaScript
UTF-8
4,565
3.0625
3
[ "MIT" ]
permissive
/** * Created by zmiter on 3/9/16. */ function Graph(id, leftX, rightX, bottomY, topY) { var vm = this; var MAGIC_HEIGHT_CONST = 0.9; vm.accuracy = 0.002; vm.plotNet = plotNet; vm.plotAxes = plotAxes; vm.setBorders = setBorders; vm.plot = plot; vm.canvas = document.getElementById(id); vm.width = vm.canvas.width; vm.height = vm.canvas.height; vm.setBorders(leftX, rightX, bottomY, topY); vm.context = vm.canvas.getContext("2d"); vm.plotNet(); vm.plotAxes(); return vm; function plotNet() { vm.context.beginPath(); var netStepX = vm.width * 0.05, netStepY = vm.height * 0.05; for (var i = 0; i < vm.width; i += netStepX) { vm.context.moveTo(i, 0); vm.context.lineTo(i, vm.height); } for (var i = 0; i < vm.height; i += netStepY) { vm.context.moveTo(0, i); vm.context.lineTo(vm.width, i); } vm.context.strokeStyle = '#eee'; vm.context.stroke(); } function plotAxes() { var middleX = vm.width / 2, middleY = vm.height / 2; vm.context.beginPath(); vm.context.moveTo(middleX, vm.height); vm.context.lineTo(middleX, 0); vm.context.lineTo(middleX - 5, 5); vm.context.moveTo(middleX + 5, 5); vm.context.lineTo(middleX, 0); vm.context.moveTo(0, middleY); vm.context.lineTo(vm.width, middleY); vm.context.lineTo(vm.width - 5, middleY - 5); vm.context.moveTo(vm.width - 5, middleY + 5); vm.context.lineTo(vm.width, middleY); vm.context.strokeStyle = '#000'; vm.context.stroke(); } function setBorders(leftX, rightX, bottomY, topY) { if (leftX && rightX && bottomY && topY) { vm.leftX = leftX; vm.rightX = rightX; vm.bottomY = bottomY; vm.topY = topY; } else { if (!leftX && !rightX && !bottomY && !topY) { var proportion = vm.height / vm.width; vm.leftX = -5; vm.rightX = 5; vm.bottomY = vm.leftX * proportion; vm.topY = vm.rightX * proportion; } } } function plot(f) { vm.context.beginPath(); var stepX = (vm.rightX - vm.leftX) * vm.accuracy, state = { x: vm.leftX, y: 0, x1: 0, y1: 0, lastY: 0, firstMove: true }; while (state.x < vm.rightX) { state.y = f(state.x); state = drawOneLine(state); state.x += stepX; } vm.context.strokeStyle = 'green'; vm.context.stroke(); } function drawOneLine(state) { state.x1 = getXPosition(state.x); if (state.y !== undefined && !isNaN(state.y)) { state = performGraphicDrawing(state); } else { drawCircle(state.x1, vm.height / 2); } return state; } function drawCircle(x, y) { vm.context.beginPath(); vm.context.fillStyle = 'red'; vm.context.arc(x, y, 5, 0, Math.PI * 2, true); vm.context.closePath(); vm.context.fill(); } function performGraphicDrawing(state) { state.y1 = getYPosition(state.y); if (state.firstMove) { vm.context.moveTo(state.x1, state.y1); state.firstMove = false; } else { if (bigDifference(state)) { vm.context.moveTo(state.x1, state.y1); drawCircle(state.x1, state.y1); } else { if (considerableDifference(state)) { // set graphic stroke //vm.context.beginPath(); vm.context.strokeStyle = 'green'; vm.context.lineTo(state.x1, state.y1); vm.context.stroke(); } else { vm.context.moveTo(state.x1, state.y1); } } } return state; } function bigDifference(state) { return (state.lastY <= 0 && state.y1 >= vm.height) || (state.lastY >= vm.height && state.y1 <= 0); } function considerableDifference(state) { return Math.abs(state.lastY - state.y1) <= vm.height * MAGIC_HEIGHT_CONST; } function getYPosition(y) { return vm.height - (y - vm.bottomY) / (vm.topY - vm.bottomY) * vm.height; } function getXPosition(x) { return vm.width * (x - vm.leftX) / (vm.rightX - vm.leftX); } }
C++
UTF-8
3,655
2.6875
3
[]
no_license
/****************************************************************************** * SIENA: Simulation Investigation for Empirical Network Analysis * * Web: http://www.stats.ox.ac.uk/~snijders/siena/ * * File: CovariateDependentBehaviorEffect.cpp * * Description: This file contains the implementation of the * CovariateDependentBehaviorEffect class. *****************************************************************************/ #include <stdexcept> #include "CovariateDependentBehaviorEffect.h" #include "data/Data.h" #include "data/ConstantCovariate.h" #include "data/ChangingCovariate.h" #include "data/BehaviorLongitudinalData.h" #include "model/State.h" #include "model/EffectInfo.h" #include "model/variables/BehaviorVariable.h" namespace siena { /** * Constructor. */ CovariateDependentBehaviorEffect::CovariateDependentBehaviorEffect( const EffectInfo * pEffectInfo) : BehaviorEffect(pEffectInfo) { this->lpConstantCovariate = 0; this->lpChangingCovariate = 0; this->lpBehaviorData = 0; this->linteractionValues = 0; } /** * Initializes this effect. * @param[in] pData the observed data * @param[in] pState the current state of the dependent variables * @param[in] period the period of interest * @param[in] pCache the cache object to be used to speed up calculations */ void CovariateDependentBehaviorEffect::initialize(const Data * pData, State * pState, int period, Cache * pCache) { BehaviorEffect::initialize(pData, pState, period, pCache); string name = this->pEffectInfo()->interactionName1(); this->lpConstantCovariate = pData->pConstantCovariate(name); this->lpChangingCovariate = pData->pChangingCovariate(name); this->lpBehaviorData = pData->pBehaviorData(name); this->linteractionValues = pState->behaviorValues(name); if (!this->lpConstantCovariate && !this->lpChangingCovariate && !(this->lpBehaviorData && this->linteractionValues)) { throw logic_error("Covariate or dependent behavior variable '" + name + "' expected."); } } /** * Returns the covariate value for the given actor. */ double CovariateDependentBehaviorEffect::covariateValue(int i) const { double value = 0; if (this->lpConstantCovariate) { value = this->lpConstantCovariate->value(i); } else if (this->lpChangingCovariate) { value = this->lpChangingCovariate->value(i, this->period()); } else { value = this->linteractionValues[i] - this->lpBehaviorData->overallMean(); } return value; } /** * Returns if the covariate value for the given actor is missing at the * given observation. */ bool CovariateDependentBehaviorEffect::missingCovariate(int i, int observation) const { bool missing = false; if (this->lpConstantCovariate) { missing = this->lpConstantCovariate->missing(i); } else if (this->lpChangingCovariate) { missing = this->lpChangingCovariate->missing(i, observation); } else { missing = this->lpBehaviorData->missing(observation, i); } return missing; } /** * Returns if the covariate value for the given actor is missing at the * given observation or the next one. The next one is only used for * behavior variable. It may not exist for changing covariate so is never used. */ bool CovariateDependentBehaviorEffect::missingCovariateEitherEnd(int i, int observation) const { bool missing = false; if (this->lpConstantCovariate) { missing = this->lpConstantCovariate->missing(i); } else if (this->lpChangingCovariate) { missing = this->lpChangingCovariate->missing(i, observation); } else { missing = this->lpBehaviorData->missing(observation, i) || this->lpBehaviorData->missing(observation + 1, i); } return missing; } }
Markdown
UTF-8
1,582
3.828125
4
[]
no_license
# 560. Subarray Sum Equals K ## 题 给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。 ## 解 ### 方法一: - 思路: - 暴力解法 - 时间复杂度: - o(n^2) - 空间复杂度: - o(1) - 结果: - 用时:超时 ``` class Solution { public: int subarraySum(vector<int>& nums, int k) { reverse(nums.begin(), nums.end()); int res = 0; for(int i = 0; i < nums.size(); ++i){ int sum = 0; for(int j = i; j < nums.size(); ++j){ sum += nums[j]; if(sum == k) res++; } } return res; } }; ``` ### 方法二: - 思路: - 计算前缀和 pre ,可以看做是 两数之和 - 用哈希表 空间换时间 - 时间复杂度: - o(n) - 空间复杂度: - o(n) - 结果: - 用时:84%(84ms) - 内存:6%(22.1MB) ``` class Solution { public: int subarraySum(vector<int>& nums, int k) { unordered_map<int, int> s; int pre = 0, res = 0; for(int i = 0; i < nums.size(); ++i){ pre += nums[i]; if(pre == k) res++; if(s.count(pre - k)){ res += s[pre - k]; } s[pre]++; } return res; } }; ``` ## 记 <!-- 基础:@basic 重点:@important 记忆:@memory 易错:@warning 待办:@todo 模板:@template 标签:@tag --> - @tag: 哈希表 - 2020.05.15 by lorwin
Java
UTF-8
1,461
1.804688
2
[]
no_license
package p000X; import android.media.AudioAttributes; import android.media.AudioFocusRequest; import android.media.AudioManager; import androidx.media.AudioAttributesCompat; /* renamed from: X.DJ4 */ public final class DJ4 implements DJI { public AudioFocusRequest A00; public final AudioManager A01; public final int A2G() { AudioFocusRequest audioFocusRequest = this.A00; if (audioFocusRequest == null) { return 0; } return this.A01.abandonAudioFocusRequest(audioFocusRequest); } public final int BdF(DJ5 dj5) { AudioAttributes audioAttributes; if (dj5.A00 == null) { AudioFocusRequest.Builder builder = new AudioFocusRequest.Builder(dj5.A01); AudioAttributesCompat audioAttributesCompat = dj5.A04; if (audioAttributesCompat != null) { audioAttributes = (AudioAttributes) audioAttributesCompat.A00.AGG(); } else { audioAttributes = null; } dj5.A00 = builder.setAudioAttributes(audioAttributes).setAcceptsDelayedFocusGain(false).setWillPauseWhenDucked(false).setOnAudioFocusChangeListener(dj5.A02, dj5.A03).build(); } AudioFocusRequest audioFocusRequest = dj5.A00; this.A00 = audioFocusRequest; return this.A01.requestAudioFocus(audioFocusRequest); } public DJ4(AudioManager audioManager) { this.A01 = audioManager; } }
TypeScript
UTF-8
5,459
2.84375
3
[ "Apache-2.0" ]
permissive
import { Keys, Types, KeyToType } from '@cdp/core-utils'; import { Subscription } from '@cdp/events'; import { Cancelable } from '@cdp/promise'; import { StorageData, StorageDataTypeList, StorageInputDataTypeList, IStorageOptions, IStorageDataOptions, IStorageDataReturnType, IStorageEventCallback, IStorage } from './interfaces'; /** MemoryStorage I/O options */ export type MemoryStorageOptions<K extends Keys<StorageDataTypeList> = Keys<StorageDataTypeList>> = IStorageDataOptions<StorageDataTypeList, K>; /** MemoryStorage return value */ export type MemoryStorageResult<K extends Keys<StorageDataTypeList>> = KeyToType<StorageDataTypeList, K>; /** MemoryStorage data type */ export type MemoryStorageDataTypes = Types<StorageDataTypeList>; /** MemoryStorage return type */ export type MemoryStorageReturnType<D extends MemoryStorageDataTypes> = IStorageDataReturnType<StorageDataTypeList, D>; /** MemoryStorage input data type */ export type MemoryStorageInputDataTypes = StorageInputDataTypeList<StorageDataTypeList>; /** MemoryStorage event callback */ export type MemoryStorageEventCallback = IStorageEventCallback<StorageDataTypeList>; /** * @en Memory storage class. This class doesn't support permaneciation data. * @ja メモリーストレージクラス. 本クラスはデータの永続化をサポートしない */ export declare class MemoryStorage implements IStorage { /** * @en {@link IStorage} kind signature. * @ja {@link IStorage} の種別を表す識別子 */ get kind(): string; /** * @en Returns the current value associated with the given key, or null if the given key does not exist in the list associated with the object. * @ja キーに対応する値を取得. 存在しない場合は null を返却 * * @param key * - `en` access key * - `ja` アクセスキー * @param options * - `en` I/O options * - `ja` I/O オプション * @returns * - `en` Returns the value which corresponds to a key with type change designated in `dataType`. * - `ja` `dataType` で指定された型変換を行って, キーに対応する値を返却 */ getItem<D extends MemoryStorageDataTypes = MemoryStorageDataTypes>(key: string, options?: MemoryStorageOptions<never>): Promise<MemoryStorageReturnType<D>>; /** * @en Returns the current value associated with the given key, or null if the given key does not exist in the list associated with the object. * @ja キーに対応する値を取得. 存在しない場合は null を返却 * * @param key * - `en` access key * - `ja` アクセスキー * @param options * - `en` I/O options * - `ja` I/O オプション * @returns * - `en` Returns the value which corresponds to a key with type change designated in `dataType`. * - `ja` `dataType` で指定された型変換を行って, キーに対応する値を返却 */ getItem<K extends Keys<StorageDataTypeList>>(key: string, options?: MemoryStorageOptions<K>): Promise<MemoryStorageResult<K> | null>; /** * @en Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously. * @ja キーを指定して値を設定. 存在しない場合は新規に作成 * * @param key * - `en` access key * - `ja` アクセスキー * @param options * - `en` I/O options * - `ja` I/O オプション */ setItem<V extends MemoryStorageInputDataTypes>(key: string, value: V, options?: MemoryStorageOptions<never>): Promise<void>; /** * @en Removes the key/value pair with the given key from the list associated with the object, if a key/value pair with the given key exists. * @ja 指定されたキーに対応する値が存在すれば削除 * * @param options * - `en` storage options * - `ja` ストレージオプション */ removeItem(key: string, options?: IStorageOptions): Promise<void>; /** * @en Empties the list associated with the object of all key/value pairs, if there are any. * @ja すべてのキーに対応する値を削除 * * @param options * - `en` storage options * - `ja` ストレージオプション */ clear(options?: IStorageOptions): Promise<void>; /** * @en Returns all entry keys. * @ja すべてのキー一覧を返却 * * @param options * - `en` cancel options * - `ja` キャンセルオプション */ keys(options?: Cancelable): Promise<string[]>; /** * @en Subscrive event(s). * @ja イベント購読設定 * * @param listener * - `en` callback function. * - `ja` コールバック関数 */ on(listener: MemoryStorageEventCallback): Subscription; /** * @en Unsubscribe event(s). * @ja イベント購読解除 * * @param listener * - `en` callback function. * When not set this parameter, listeners are released. * - `ja` コールバック関数 * 指定しない場合はすべてを解除 */ off(listener?: MemoryStorageEventCallback): void; /** * @en Return a storage-store object. * @ja ストレージストアオブジェクトを返却 */ get context(): StorageData; } export declare const memoryStorage: MemoryStorage;
Java
UTF-8
3,868
1.945313
2
[]
no_license
package com.nst.yourname.model.callback; public class SeriesDBModel { private String backdrop; private String cast; private String categoryId; private String cover; private String director; private String genre; private int idAuto; private String last_modified; private String loginType; private String name; private String num; private String plot; private String rating; private String releaseDate; private String seasons; private int seriesID; private String streamType; private String youTubeTrailer; public String getBackdrop() { return this.backdrop; } public void setBackdrop(String str) { this.backdrop = str; } public String getYouTubeTrailer() { return this.youTubeTrailer; } public void setYouTubeTrailer(String str) { this.youTubeTrailer = str; } public String getlast_modified() { return this.last_modified; } public void setlast_modified(String str) { this.last_modified = str; } public String getrating() { return this.rating; } public void setrating(String str) { this.rating = str; } public SeriesDBModel() { } public SeriesDBModel(String str, String str2, String str3, int i, String str4, String str5, String str6, String str7, String str8, String str9, String str10, String str11, String str12, String str13) { this.num = str; this.name = str2; this.streamType = str3; this.seriesID = i; this.cover = str4; this.plot = str5; this.categoryId = str6; this.cast = str7; this.director = str8; this.genre = str9; this.releaseDate = str10; this.last_modified = str11; this.rating = str12; this.youTubeTrailer = str13; } public int getIdAuto() { return this.idAuto; } public void setIdAuto(int i) { this.idAuto = i; } public String getNum() { return this.num; } public void setNum(String str) { this.num = str; } public String getName() { return this.name; } public void setName(String str) { this.name = str; } public String getStreamType() { return this.streamType; } public void setStreamType(String str) { this.streamType = str; } public int getseriesID() { return this.seriesID; } public void setseriesID(int i) { this.seriesID = i; } public String getcover() { return this.cover; } public void setcover(String str) { this.cover = str; } public String getplot() { return this.plot; } public void setplot(String str) { this.plot = str; } public String getCategoryId() { return this.categoryId; } public void setCategoryId(String str) { this.categoryId = str; } public String getcast() { return this.cast; } public void setcast(String str) { this.cast = str; } public String getdirector() { return this.director; } public void setdirector(String str) { this.director = str; } public String getgenre() { return this.genre; } public void setgenre(String str) { this.genre = str; } public String getreleaseDate() { return this.releaseDate; } public void setreleaseDate(String str) { this.releaseDate = str; } public void setSeasons(String str) { this.seasons = str; } public String getSeasons() { return this.seasons; } public void setloginType(String str) { this.loginType = str; } public String getLoginType() { return this.loginType; } }
Java
UTF-8
398
2.421875
2
[]
no_license
package com.zhao.KKPlayer.player; /** * 各种音乐格式的播放器接口 * @author Administrator * */ public interface MusicPlayer { /** * 播放 */ public void play(); public void stop(); public void pause(); public void resume(); /** * 关闭播放器读出来的流 */ public void close(); /** * 音乐快进或后退的方法 */ public void seek(); }
Markdown
UTF-8
1,037
2.90625
3
[ "Unlicense" ]
permissive
## Table of Contents for Regex/[Character Class](https://www.hackerrank.com/domains/regex?filters%5Bsubdomains%5D%5B%5D=re-character-class) | # | File Name | Title | Difficulty | Max Score | | -- | ---------------------------------------------- | ------------------------------- | ---------- | --------- | | 1 | [CharacterMatch.java](CharacterMatch.java) | [Matching Specific Characters] | Easy | 10 | | 2 | [CharacterExclude.java](CharacterExclude.java) | [Excluding Specific Characters] | Easy | 10 | | 3 | [CharacterRange.java](CharacterRange.java) | [Matching Character Ranges] | Easy | 10 | [Matching Specific Characters]: https://www.hackerrank.com/challenges/matching-specific-characters/problem [Excluding Specific Characters]: https://www.hackerrank.com/challenges/excluding-specific-characters/problem [Matching Character Ranges]: https://www.hackerrank.com/challenges/matching-range-of-characters/problem
Python
UTF-8
2,202
3.265625
3
[]
no_license
from collections import deque import heapq # [G] [ ] [ ] [P] [ ] [ ] [G] def solution_dequeue(stalls, people): distances = deque((stalls,)) left, right = stalls, stalls while people: people -= 1 dist = distances.popleft() left = dist // 2 right = dist - left left, right = (left, right) if left >= right else (right, left) left -= 1 left, right = (left, right) if left >= right else (right, left) distances.append(left) distances.append(right) return '{} {}'.format(left, right) def solution_heap(stalls, people): distances = [-stalls] left, right = stalls, stalls while people: people -= 1 dist = - heapq.heappop(distances) left = dist // 2 right = dist - left left, right = (left, right) if left >= right else (right, left) left -= 1 left, right = (left, right) if left >= right else (right, left) heapq.heappush(distances, -left) heapq.heappush(distances, -right) return '{} {}'.format(left, right) def solution(stalls, people): distances = [stalls] left, right = stalls, stalls while people: people -= 1 index, dist = max(enumerate(distances), key=lambda item: item[-1]) left = dist // 2 right = dist - left - 1 distances[index] = left distances.append(right) return '{} {}'.format(max(left, right), min(left, right)) def process(filepath): with open(filepath.replace('.in', '.out'), 'w') as outp: with open(filepath) as filep: inputs = None case = 0 for line in filep: line = line.strip() if inputs is None: inputs = int(line) else: case += 1 stalls, people = line.split(' ', 1) result = 'Case #{}: {}\n'.format(case, solution_heap(int(stalls), int(people))) print(result, end='') outp.write(result) if __name__ == '__main__': process('C-small-2-attempt1.in')
Python
UTF-8
223
2.953125
3
[]
no_license
import os def valid_file(parser): def valid(arg): if arg and not os.path.exists(arg): parser.error('The file doesn\'t exist: {}'.format(arg)) else: return arg return valid
Java
UTF-8
2,290
2.171875
2
[]
no_license
package id.knt.restaurant.foodandbeverage.ui.recycle; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import id.knt.restaurant.foodandbeverage.R; import id.knt.restaurant.foodandbeverage.ui.activity.ActivityMainMenu; import java.util.Timer; import java.util.TimerTask; /** * Created by angga.prasetiyo on 5/6/2014. */ public class DashboardActivity extends Activity { private Button btnToMenu; private ImageView imageView; private static final int[] IMAGES = new int[]{R.drawable.sample, R.drawable.sample2, R.drawable.sample3 , R.drawable.sample4}; Timer timer; TimerTask task; public int currentimageindex = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dashboard_activity); imageView = (ImageView) findViewById(R.id.imageViewDashboard); final Handler handler = new Handler(); final Runnable updateResults = new Runnable() { @Override public void run() { AnimatedSlideShow(); } }; int delay = 1000; // delay for 1 sec. int period = 4000; // repeat every 4 sec. Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { handler.post(updateResults); } }, delay, period); btnToMenu = (Button) findViewById(R.id.btnToMenu); btnToMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), ActivityMainMenu.class); startActivity(intent); } }); } private void AnimatedSlideShow() { imageView.setImageResource(IMAGES[currentimageindex % IMAGES.length]); currentimageindex++; Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.custom_anim); imageView.startAnimation(rotateimage); } }
Python
UTF-8
5,702
2.765625
3
[]
no_license
from django.test import TestCase import datetime from ..models import AppUser, BoardMember, Board from django.db.utils import IntegrityError from django.contrib.auth import get_user_model user_model = get_user_model() class TestUserModel(TestCase): """ WIP """ pass class TestBoardModel(TestCase): @classmethod def setUpTestData(cls): """ Creates an empty board and 2 users """ cls.board_title = 'hello board' cls.users_data = [{ 'username': f'testeur_{i}', 'email': f'test_{i}@test.com', 'password': 'testpassword123' } for i in range(1, 6)] cls.users = [user_model.objects.create_user(**user_data) for user_data in cls.users_data] board = Board(title=cls.board_title) board.save() cls.board_id = board.id def test_board_is_created(self): b = Board.objects.get(id=self.board_id) self.assertEqual(b.title, self.board_title) def test_member_is_added_with_score(self): """ Adds a member to the board, checks if it is in the members list with the right score Then, deletes it to reset state """ # test data board = Board.objects.get(id=self.board_id) user = user_model.objects.get(email=self.users_data[0]['email']) # adds the member to the board and checks member = board.add_member('test_username', user.id, score=10) self.assertTrue(board.members.filter(id=member.id).exists()) self.assertEqual(member.score, 10) # Cleans the board members field board.remove_member(member.id) def test_member_is_added_without_score(self): """ Adds a member to the board without a score, checks if it is in the members list with the right score Then, deletes it to reset state """ # test data board = Board.objects.get(id=self.board_id) user = user_model.objects.get(email=self.users_data[0]['email']) # adds the member to the board and checks member = board.add_member('test_username', user.id) self.assertTrue(board.members.filter(id=member.id).exists()) self.assertEqual(member.score, board.members.get(id=member.id).score) # Cleans the board members field board.remove_member(member.id) def test_cannot_add_two_members_from_one_user(self): """ Adds a member to the board, checks if adding him a second time raises a ValueError Then, deletes it to reset state """ # test data board = Board.objects.get(id=self.board_id) user = user_model.objects.get(email=self.users_data[0]['email']) # Adds two members from the same user id member = board.add_member('test_username', user.id) with self.assertRaises(Exception): board.add_member('test_username_2', user.id) # cleans the board members field board.remove_member(member.id) def test_member_is_removed(self): """ Add a member to the board, removes it, then checks if it is removed from members list and scores """ # test data board = Board.objects.get(id=self.board_id) user = user_model.objects.get(email=self.users_data[0]['email']) # Add and then remove a member for the board. Checks each step of the process member = board.add_member('test_username', user.id) self.assertTrue(board.members.filter(id=member.id).exists()) board.remove_member(member.id) self.assertFalse(board.members.filter(id=member.id).exists()) def test_cannot_remove_unexitsting_member(self): """ Check if removing a member not registered as board member raises a DoesNotExist error """ board = Board.objects.get(id=self.board_id) with self.assertRaises(BoardMember.DoesNotExist): board.remove_member(board.id) def test_cannot_reset_unexitsting_member(self): """ Check if removing a member not registered as board member raises a Board.DoesNotExist error """ board = Board.objects.get(id=self.board_id) with self.assertRaises(BoardMember.DoesNotExist): board.reset_score(board.id) def test_member_is_resetted(self): """ Adds a member to the board, resets it's score with 10 minutes ago, then checks if scores match """ # test data board = Board.objects.get(id=self.board_id) user = user_model.objects.get(email=self.users_data[0]['email']) # Create a board and checks that current and resetted scores are different member = board.add_member('test_username', user.id) t = int((datetime.datetime.utcnow() - datetime.timedelta(minutes = 10)).timestamp()) self.assertNotEqual(board.members.get(id=member.id).score, t) # Reset the member score and checks if it matches now board.reset_score(member.id, t) self.assertEqual(board.members.get(id=member.id).score, t) board.remove_member(member.id) def test_board_title_is_modified(self): # test data new_board_title = 'goodbye board' board = Board.objects.get(id=self.board_id) self.assertEqual(board.title, self.board_title) # update board title board.title = new_board_title board.save() del board # Checks if the update happened and reset board state afterwards board = Board.objects.get(id=self.board_id) self.assertEqual(board.title, new_board_title) board.title = self.board_title board.save()
Markdown
UTF-8
2,487
2.65625
3
[ "MIT" ]
permissive
# Coinkite API Browser in [AngularJS](https://angularjs.org/) [Learn more about Coinkite's API here](https://docs.coinkite.com/) and visit the [Coinkite Main Site](https://coinkite.com/) to open your account today! ## Live Demo [coinkite.github.io/coinkite-angular](http://coinkite.github.io/coinkite-angular/) for a working live demo served by Github Pages. ## Setup Use you favourite micro webserver to serve `index.html` from this directory. You can do this easily with Python (which is probably already installed). python -m SimpleHTTPServer ... and then surf to <http://localhost:8000> using a modern browser. When you get tired of cut-n-pasting your API key and secret, create a file in this directory called `my-keys.json` and it will be used to prefill those fields. Example `my-keys.json` file: { "api_key": "K11aaa11a-aa11a111-a11aaa11111a1aa1", "api_secret": "Saa1a1aa1-11a11111-aa111aa1111aa111" } ## Requirements For this demo, we are using: - AngularJS <https://docs.angularjs.org> - Bootstrap <http://getbootstrap.com/> - AngularStrap <http://mgcrea.github.io/angular-strap> - Restangular <https://github.com/mgonto/restangular> - lodash (required by Restangular) <http://lodash.com/> - font-awesome <http://fontawesome.io/> - crypto-js (just HMAC-SHA256) <https://code.google.com/p/crypto-js/> All these files, except `json-print`, are being provided by CDN sources to make this package lighter. ## Discussion This example is using `$http` for the main JSON resource fetching. However, the typeahead feature fetches its data via Restangular. All API endpoints (except under `/public/`) require authentication with an API key and secret. The keys you need can be created on [Coinkite.com under Merchant / API]([https://coinkite.com/merchant/api) See `coinkite-api.js` for the tricky bits: it will generate the required headers for your HTTP request and works under both `node.js` and in the browser. This is a **DEMO** program, and we would never recommend putting API secret keys into browser-side code in any other case. ## Screenshot ![image](screenshot.png) ## More about Coinkite _Join The Most Powerful Bitcoin Platform_ Coinkite is the leading [bitcoin wallet](https://coinkite.com/faq/features) with [multi-signature](https://coinkite.com/faq/multisig), [bank-grade security](https://coinkite.com/faq/security), [developer's API](https://coinkite.com/faq/developers) and [hardcore privacy](https://coinkite.com/privacy). [Get Your Account Today!](https://coinkite.com/)
Python
UTF-8
3,977
3.78125
4
[]
no_license
# https://www.cnblogs.com/mxh1099/p/8512552.html # #方法 #描述 # ------------------------------------------------------------------------------------------------- # D.clear() #移除D中的所有项 # D.copy() #返回D的副本 # D.fromkeys(seq[,val]) #返回从seq中获得的键和被设置为val的值的字典。可做类方法调用,返回一个新的字典 # D.get(key[,default]) #如果D[key]存在,将其返回;否则返回给定的默认值None # D.has_key(key) #检查D是否有给定键key # D.items() #返回表示D项的(键,值)对列表 # D.iteritems() #从D.items()返回的(键,值)对中返回一个可迭代的对象 # D.iterkeys() #从D的键中返回一个可迭代对象 # D.itervalues() #从D的值中返回一个可迭代对象 # D.keys() #返回D键的列表, 在python3里面返回dict_keys,是一个class,需要转化为list # D.pop(key[,d]) #移除并且返回对应给定键key或给定的默认值D的值 # D.popitem() #从D中移除任意一项,并将其作为(键,值)对返回 # D.setdefault(key[,default]) #如果D[key]存在则将其返回;否则返回默认值None # D.update(other) #将other中的每一项加入到D中。 # D.values() #返回D中值的列表 # 创建字典的五种方法 # 方法一: 常规方法 # 如果事先能拼出整个字典,则此方法比较方便 D1 = {'name': 'Bob', 'age': 40} # 方法二:动态创建 # 如果需要动态地建立字典的一个字段,则此方法比较方便 D2 = {} D2['name'] = 'Bob' D2['age'] = 40 print('keys', list(D2.keys())[0]) # 方法三: dict--关键字形式f # 代码比较少,但键必须为字符串型。常用于函数赋值 D3 = dict(name='Bob', age=45) # 方法四: dict--键值序列,下面三种方式都可以 # 如果需要将键值逐步建成序列,则此方式比较有用,常与zip函数一起使用 D4 = dict([('name', 'Bob'), ('age', 40)]) # dict函数的参数是一个列表,列表里面的元素是键值对组成的元组 D4 = dict([['name', 'Bob'], ['age', 40]]) # dict函数的参数是一个列表,列表里面的元素是键值对组成的元组 D = dict(zip(['name', 'age'], ['bob', 40])) # zip函数里面的参数是两个列表 D = dict(zip(('name', 'age'), ('bob', 40))) # zip函数里面的参数是两个元组 print(D) # 字典遍历 xiaoming_dict = {"name": "小明", "qq": "123456", "phone": "10086"} for k in xiaoming_dict: print("%s - %s" % (k, xiaoming_dict[k])) for k in xiaoming_dict.values(): # 只取对应的value值 print(k) # 下面可以获取键值对,存放在元组 # ('name', '小明') # ('qq', '123456') # ('phone', '10086') for k in xiaoming_dict.items(): print(k) # TODO:filter a dictionary D = {'beijing': 100, 'shanghai': 90, 'tianjin': 80, 'chongqing': 70, 'nanjing': 60} r = {k: v for k, v in D.items() if v >= 60} # 字典解析 print(r) # {'beijing': 100, 'shanghai': 90, 'tianjin': 80, 'chongqing': 70, 'nanjing': 60} # randint(1,10)----生成随机数字1到10之间,包含1和10 # range(1,15)---从1开始直到14 import random d = {x: random.randint(1, 10) for x in range(1, 15)} print(d) # TODO: combine 2 different dictionaries with comprehension, 字典表达式 tem1 = {'a': 1, 'b': 2, 'c': 3} tem2 = {'d': 1, 'e': 2, 'f': 3} res = {k: v for team in (tem1, tem2) for k, v in team.items()} print(res) # TODO:交换现有字典中各键值对的键和值 res1 = {v: k for k, v in tem1.items()} print(res1) # TODO: team = ['beijing', 'shanghai', 'tianjin'] res = {k: len(k) for k in team} print(res)
Java
UTF-8
1,788
2.328125
2
[ "Apache-2.0" ]
permissive
package io.github.superfive666.duosdk.config; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; /** * Configuration class that allows injection of properties via application.properties/application.yml * Example configuration for application.properties: * <pre> * duo.secret.host=api-XXXXXXXX.duosecurity.com * duo.secret.ikey=DIWJ8X6AEYOR5OMC6TQ1 * duo.secret.skey=Zh5eGmUq9zpfQnyUIu5OL9iWoMMv5ZNmk3zLJ4Ep * </pre> * * Example configuration for application.yml: * <pre> * duo.secret: * host: api-XXXXXXXX.duosecurity.com * ikey: DIWJ8X6AEYOR5OMC6TQ1 * skey: Zh5eGmUq9zpfQnyUIu5OL9iWoMMv5ZNmk3zLJ4Ep * </pre> * * For more information on where to check the above credential for your DUO account, please refer to * <a href="https://duo.com/docs/authapi#api-details"> * DUO Auth API</a> * * * @author superfive */ @Getter @Setter @Slf4j @Configuration @EnableConfigurationProperties @ConfigurationProperties("duo.secret") @ComponentScan(basePackages = "io.github.superfive666.duosdk.auth") public class DuoSecretConfiguration { private String host; private String ikey; private String skey; @PostConstruct public void debug() { log.debug("Host value injected: {}", host); log.debug("Integration key injected: {}", ikey); // DUO Secret key is of fixed length log.debug("Secret key injected: masked[{}]", "*".repeat(skey.length())); log.info("DUO Security plugin is properly autowired into the application context"); } }
JavaScript
UTF-8
3,020
2.625
3
[]
no_license
// cache names const staticCacheName = 'static-site-v1'; const dynamicCacheName = 'dynamic-site-v1'; //Cache assets array const assets = [ '/', '/index.html', '/static/js/main.chunk.js', '/static/js/bundle.js', '/static/js/0.chunk.js', '/Weather', '/Features', '/About', '/Business', '/Health', '/Politics', '/Science', '/Tech', '/Search', 'https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css', 'https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css', 'https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js', 'https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.min.js', '/manifest.json', '/192.png' ]; // Cache Dynamic asseys array const dynamicAssets = [ // 'https://newsapi.org/v2/top-headlines?country=gb&apiKey=ba6499bad4eb4af7a54f42954e1807fd' ] // //install event self.addEventListener('install', evt => { console.log("Service Worker has been installed - static data has been cached") //Open cache and pass assets to be cached - static assets evt.waitUntil( //UI data being cached caches.open(staticCacheName).then(cache => { console.log("Caching Static Assets"); cache.addAll(assets); }), //API Data being caches caches.open(dynamicCacheName).then(cache => { console.log("Caching Dynamic Assets") cache.addAll(dynamicAssets) }) ) }); self.addEventListener('activate', evt => { console.log("Service worker has been activated") // delete old cache evt.waitUntil( caches.keys().then(keys => { console.log(keys) //logs cache names return Promise.all(keys .filter(key => key !== staticCacheName && key !== dynamicCacheName) .map(key => caches.delete(key)) ) }) ) }); self.addEventListener('fetch', evt => { if(!navigator.onLine){ evt.respondWith( caches.match(evt.request).then(cacheRes => { if(cacheRes){ return cacheRes } let requestUrl = evt.request.clone(); fetch(requestUrl); }) ) } }) //'https://newsapi.org/v2/top-headlines?country=gb&apiKey=ba6499bad4eb4af7a54f42954e1807fd' // /static/js/main.chunk.js // /static/js/bundle.js // /static/js/0.chunk.js // https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css // https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css // https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js // https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.min.js // https://fonts.gstatic.com // https://fonts.googleapis.com/css2?family=Mukta&display=swap // https://fonts.googleapis.com/css2?family=Roboto:wght@900&display=swap // 'https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap'
Java
UTF-8
4,417
2.09375
2
[]
no_license
package pcpnru.projectModel; public class ProjectModel { // HD private String project_code, target, percen, year, datetime_response, freeze; private String project_name; // DT receive private String gcostcode, gcostname, budget, budget_now; // Project plan DT private String subjob_code, subjob_name, childsubjobcode, childsubjobname, gcostcode_name; public ProjectModel() { } public ProjectModel(String project_code, String project_name, String subjob_code, String subjob_name, String childsubjobcode, String childsubjobname, String gcostcode, String gcostcode_name, String budget, String budget_now, String datetime_response) { this.project_code = project_code; this.project_name = project_name; this.subjob_code = subjob_code; this.subjob_name = subjob_name; this.childsubjobcode = childsubjobcode; this.childsubjobname = childsubjobname; this.gcostcode = gcostcode; this.gcostcode_name = gcostcode_name; this.budget = budget; this.budget_now = budget_now; this.datetime_response = datetime_response; } public ProjectModel(String project_code, String project_name, String target, String percen, String year, String datetime_response, String freeze, String forwat) { this.project_code = project_code; this.project_name = project_name; this.target = target; this.percen = percen; this.year = year; this.datetime_response = datetime_response; this.freeze = freeze; } public ProjectModel(String project_code, String gcostcode, String gcostname, String budget) { this.project_code = project_code; this.gcostcode = gcostcode; this.gcostname = gcostname; this.budget = budget; } public ProjectModel(String forwhat, String project_code2, String project_name2, String year2, String target2, String forwhat2) { if (forwhat.equals("getListProject_Join_Projecthead")) { this.project_code = project_code2; this.project_name = project_name2; this.year = year2; this.target = target2; } } public void reset() { this.project_code = ""; this.target = ""; this.percen = ""; this.year = ""; this.datetime_response = ""; } public String getSubjob_code() { return subjob_code; } public void setSubjob_code(String subjob_code) { this.subjob_code = subjob_code; } public String getSubjob_name() { return subjob_name; } public void setSubjob_name(String subjob_name) { this.subjob_name = subjob_name; } public String getChildsubjobcode() { return childsubjobcode; } public void setChildsubjobcode(String childsubjobcode) { this.childsubjobcode = childsubjobcode; } public String getChildsubjobname() { return childsubjobname; } public void setChildsubjobname(String childsubjobname) { this.childsubjobname = childsubjobname; } public String getGcostcode() { return gcostcode; } public void setGcostcode(String gcostcode) { this.gcostcode = gcostcode; } public String getGcostcode_name() { return gcostcode_name; } public void setGcostcode_name(String gcostcode_name) { this.gcostcode_name = gcostcode_name; } public String getProject_name() { return project_name; } public void setProject_name(String project_name) { this.project_name = project_name; } public String getProject_code() { return project_code; } public void setProject_code(String project_code) { this.project_code = project_code; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getDatetime_response() { return datetime_response; } public void setDatetime_response(String datetime_response) { this.datetime_response = datetime_response; } public String getBudget() { return budget; } public void setBudget(String budget) { this.budget = budget; } public String getGcostname() { return gcostname; } public void setGcostname(String gcostname) { this.gcostname = gcostname; } public String getPercen() { return percen; } public void setPercen(String percen) { this.percen = percen; } public String getFreeze() { return freeze; } public void setFreeze(String freeze) { this.freeze = freeze; } public String getBudget_now() { return budget_now; } public void setBudget_now(String budget_now) { this.budget_now = budget_now; } }
Markdown
UTF-8
1,370
3
3
[ "MIT" ]
permissive
# go-hist simple go program to draw histograms Installation ----------- go get github.com/xigh/go-hist Documentation ----------- Usage: ./hist [options...] <file> -endian="little": endianess: [little, big] -gather="max": data gathering: [max, avg] -height=1000: image height -hmargin=10: horizontal margin -length=2147483647: max number of lines -lspace=0: space between lines -lwidth=1: line width -out="out.png": output filename -skip=0: number of entry to skip -type="text": datatype: [i8, u8, i16, u16, i32, u32, f32, f64, text] -vmargin=10: vertical margin -width=0: force image width [overrides line width] Examples ----------- Files can be binary files, such as raw audio track: ./hist --type i16 --length 2000000 --width 3000 --out audio.png audio.raw scanning input c=2000000 min=-32768.000000 max=32767.000000 avg=0.233254 zero=32768.00, vpl=671.14 [3000x1000] generating background processing image audio.png saved 9192709px ![My image](img/audio.png) Files can also be floats in text format: head data.txt 1.35 1.50 1.09 0.73 1.59 1.43 1.21 1.11 1.11 0.68 ./hist data.txt scanning input c=1418 min=0.150000 max=33.670000 avg=4.360035 zero=0.00, vpl=1.00 [1438x1000] generating background processing image out.png saved 179241px ![My image](img/data.png) Bugs ----------- Yes.
C++
UTF-8
566
2.71875
3
[]
no_license
#include <iostream> #include <string.h> #include <fstream> #include <math.h> #include <vector> using namespace std; #define mod 1000000007 int easyLego(int n, int m) { vector<long long> F(m + 1, 1); long long a, b, c, d; for (int i = 1; i <= m; i ++) { a = F[i - 1]; b = (i - 2 < 0) ? 0 : F[i - 2]; c = (i - 3 < 0) ? 0 : F[i - 3]; d = (i - 4 < 0) ? 0 : F[i - 4]; F[i] = (a + b + c + d) % mod; } long long result = 1; for (int i = 0; i < n; i ++) { result *= F[m]; result %= mod; } return result; } int main() { cout << easyLego(2, 4); }
Markdown
UTF-8
534
2.671875
3
[]
no_license
# Eloquent Javascript Solutions <p align="center"> <a href="https://eloquentjavascript.net/" style="display: block;"> <img align="center" width="320" height="445" src="https://i.imgur.com/fie9Rub.jpg" alt="Eloquent Javascript Book"/> </a> </p> ## About This repo contains several solution proposals for each chapter exercises in the book. ## How add your exercises 1. Identify the chapter 2. Create a folder inside the chapter with your name 3. Create a single file with your exercises 4. Make a PR t add your exercises
Java
UTF-8
718
2.0625
2
[]
no_license
/** * Pinganfu.com Inc. * Copyright (c) 2013-2013 All Rights Reserved. */ package com.pinganfu.bcm.common.model; import com.pinganfu.bcm.common.model.exception.BcmException; import com.pinganfu.bcm.service.facade.model.Cert; /** * 服务处理类. * @author zhaodongxu037 * */ public abstract class CatalogHandlerForMessage{ protected Cert cert; public abstract byte[] service(String unSigned) throws BcmException; public abstract String service(String unSigned,byte[] signedByteArray) throws BcmException; public String decrypt(String encrypted) throws BcmException { return null; } public void setCert(Cert cert) { this.cert = cert; } }
C++
UTF-8
3,638
2.9375
3
[]
no_license
/* Carro Arduino com controle Bluetooth Código retirado do link abaixo: http://www.instructables.com/id/Arduino-Bluetooth-RC-Car-Android-Controlled/?ALLSTEPS Conclusão e adaptações por Usinainfo: http://www.usinainfo.com.br/ */ // Define os pinos de utilização do Driver L298. const int motorA1 = 4; // Pin 4 of L293. const int motorA2 = 5; // Pin 5 of L293. const int motorB1 = 6; // Pin 6 of L293. const int motorB2 = 7; // Pin 7 of L293. const int buzzer = 8; // Define o Pino 13 como pino do Buzzer. const int BTState = 2; // Define o Pino 2 como o pino de comunicação do Bluetooth. // Variáveis Úteis int i = 0; int j = 0; int state_rec; int vSpeed = 200; // Define velocidade padrão 0 < x < 255. char state; void setup() { // Inicializa as portas como entrada e saída. pinMode(motorA1, OUTPUT); pinMode(motorA2, OUTPUT); pinMode(motorB1, OUTPUT); pinMode(motorB2, OUTPUT); pinMode(buzzer, OUTPUT); pinMode(BTState, INPUT); // Inicializa a comunicação serial em 9600 bits. Serial.begin(9600); } void loop() { // Para o carro quando a conexão com Bluetooth é perdida ou desconectada. if (digitalRead(BTState) == LOW) { state_rec = 'S'; } // Salva os valores da variável 'state' if (Serial.available() > 0) { state_rec = Serial.read(); state = state_rec; // Serial.println(vSpeed); } // Altera a velocidade de acordo com valores especificados. if (state == '0') { vSpeed = 0; } else if (state == '4') { vSpeed = 100; } else if (state == '6') { vSpeed = 155; } else if (state == '7') { vSpeed = 180; } else if (state == '8') { vSpeed = 200; } else if (state == '9') { vSpeed = 230; } else if (state == 'q') { vSpeed = 255; } if (state != 'S') { Serial.print(state); } switch(state){ case 'F': front(); break; case 'I': frontLeft(); break; case 'G': frontRight(); break; case 'B': back(); break; case 'H': backLeft(); break; case 'J': backRight(); break; case 'L': left(); break; case 'R': right(); break; case 'V': if (j == 0) { tone(buzzer, 1000, 1000); j = 1; } else if (j == 1) { noTone(buzzer); j = 0; } state = 'n'; break; } } void front(){ analogWrite(motorB1, vSpeed); analogWrite(motorA1, vSpeed); analogWrite(motorA2, 0); analogWrite(motorB2, 0); } void frontLeft(){ analogWrite(motorA1, vSpeed); analogWrite(motorA2, 0); analogWrite(motorB1, 100); analogWrite(motorB2, 0); } void frontRight(){ analogWrite(motorA1, 100); analogWrite(motorA2, 0); analogWrite(motorB1, vSpeed); analogWrite(motorB2, 0); } void back(){ analogWrite(motorA1, 0); analogWrite(motorB1, 0); analogWrite(motorB2, vSpeed); analogWrite(motorA2, vSpeed); } void backLeft(){ analogWrite(motorA1, 0); analogWrite(motorA2, vSpeed); analogWrite(motorB1, 0); analogWrite(motorB2, 100); } void backRight(){ analogWrite(motorA1, 0); analogWrite(motorA2, 100); analogWrite(motorB1, 0); analogWrite(motorB2, vSpeed); } void left(){ analogWrite(motorA1, 0); analogWrite(motorA2, vSpeed); analogWrite(motorB1, vSpeed); analogWrite(motorB2, 0); } void right(){ analogWrite(motorA1, vSpeed); analogWrite(motorA2, 0); analogWrite(motorB1, 0); analogWrite(motorB2, vSpeed); } void pause(){ analogWrite(motorA1, 0); analogWrite(motorA2, 0); analogWrite(motorB1, 0); analogWrite(motorB2, 0); }
C++
UTF-8
2,028
2.90625
3
[ "MIT" ]
permissive
/* -*- c-basic-offset: 4 -*- */ #pragma once #include "Common.h" #include "ActionType.h" namespace BOSS { struct AbilityAction { ActionType type; // type of the ability TimeType frameCast; // the frame the ability was cast NumUnits targetID; // index inside m_units of GameState class NumUnits targetProductionID; // index inside m_units of the unit being produced by the target of this ability ActionType targetType; // type of unit it was used on ActionType targetProductionType;// type of unit being produced by the unit that this ability was casted on AbilityAction() : type(ActionTypes::None) , frameCast(0) , targetID(0) , targetProductionID(0) , targetType(ActionTypes::None) , targetProductionType(ActionTypes::None) { } AbilityAction(ActionType newType, TimeType newFrameCast, NumUnits newTargetID, NumUnits newTargetProductionID, ActionType newTargetType, ActionType newTargetProductionType) { type = newType; frameCast = newFrameCast; targetID = newTargetID; targetProductionID = newTargetProductionID; targetType = newTargetType; targetProductionType = newTargetProductionType; } bool operator == (const AbilityAction& action) const { return (type == action.type) && (targetID == action.targetID) && (targetProductionID == action.targetProductionID); } void writeToSS(std::stringstream & ss) const; json writeToJson() const; }; struct ActionValue { std::pair<ActionType, NumUnits> action; FracType evaluation; ActionValue() : action(ActionTypes::None, 0) , evaluation(-1) { } void operator = (const ActionValue& action) { this->action = action.action; this->evaluation = action.evaluation; } }; }
C++
UTF-8
660
2.515625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int tab[30][1000002],valor[30],N; int troco(int idx,int v){//solução recursiva TLE if(idx==N or v<0) return tab[idx][v]=0x3f3f3f3f; if(!v) return tab[idx][v]=0; if(tab[idx][v]>=0) return tab[idx][v]; int nao_escolhe = troco(idx+1,v); if(valor[idx]<=v){ int escolhe = 1+troco(idx,v-valor[idx]); return tab[idx][v] = min(escolhe,nao_escolhe); } return tab[idx][v]=nao_escolhe; } int main(){ int T; scanf("%d",&T); while(T--){ memset(tab,-1,sizeof(tab)); int M; scanf("%d %d",&N,&M); for(int i=0;i<N;i++) scanf("%d",&valor[i]); int saida = troco(0,M); printf("%d\n",saida); } }
PHP
UTF-8
6,413
2.578125
3
[]
no_license
<?php class Validation { private $objForm; public $_errors = array(); public $_errorsMessages = array(); public $_message = array( "first_name" => "Please provide your first name.", "last_name" => "Please provide your last name.", "address_1" => "Please provide the first line of your address.", "address_2" => "Please provide the second line of your address.", "town" => "Please provide your town name.", "country" => "Please provide your county name.", "post_code" => "Please provide your post code.", "country" => "Please select your country.", "email" => "Please provide your valid email address.", "login" => "User name and/or password were incorrect.", "password" => "Please choose your password.", "confirm_password" => "Please confirm your password", "password_mismatch" => "Passwords did not match.", "email_duplicate" => "This email has already been registered.", "name" => "Please provide a name.", "short_form" => "Please provide a short form.", "name_duplicate" => "This name is already taken.", "src" => "Empty source code." ); public $_expected = array(); //de cho vao nhung~ thanh phan trong form can duoc dem vao xu ly public $_required = array(); public $_special = array(); public $_post = array(); public $_post_remove = array(); public $_post_format = array(); public function __construct($objForm = null) { $this->objForm = is_object($objForm) ? $objForm : new Form(); } public function process() { if($this->objForm->isPost()) { //neu da co cac thanh phan trong array post va trong array required co ten cac field can phai dien $this->_post = !empty($this->_post) ? $this->_post : $this->objForm->getPostArray($this->_expected); //chi lay tu array post cac thanh phan co key nam trong array expected //lay vao trong array post cua objValid if(!empty($this->_post)) { foreach($this->_post as $key => $value) { //luc nay da lay xong cac thanh phan trong array post $this->check($key, $value); //tien hanh kiem tra tung thanh phan trong array post //thanh phan email nam trong array special //nen khi vong lap chay toi thanh phan email se chay quay ham checkSpecial, tuc la chay qua ham isEmail\ //neu ten key co trong array required nhung gia tri lay tu post la rong thi phai bao loi //cho vao array error } } } } public function check($key, $value) { if(!empty($this->_special) && array_key_exists($key, $this->_special)) { $this->checkSpecial($key, $value); } else { if(in_array($key, $this->_required) && Helper::isEmpty($value)) { //neu $this->add2Errors($key); } } } public function add2Errors($key = null, $value = null) { if(!empty($key)) { $this->_errors[] = $key; //them vao thanh phan tiep theo, index la so, khong phai co key rieng if(!empty($value)) { $this->_errorsMessages['valid_'.$key] = $this->wrapWarn($value); //value dung de tao ra validation message rieng khac voi message da co san trong array cua object } elseif (array_key_exists($key, $this->_message)) { $this->_errorsMessages['valid_'.$key] = $this->wrapWarn($this->_message[$key]); } } } public function checkSpecial($key, $value) { switch($this->_special[$key]) { case('email'): if(!$this->isEmail($value)) { $this->add2Errors($key); } break; } } public function isEmail($email = null) { if(!empty($email)) { $result = filter_var($email, FILTER_VALIDATE_EMAIL); return !$result ? false : true; } return false; } public function isValid($array = null) { //phai cho ham nay chay thi process moi duoc chay //sau khi process chay xong thi se dua het error vao trong array error if(!empty($array)) { $this->_post = $array; } $this->process(); if (empty($this->_errors) && !empty($this->_post)) { //remove all unwanted fields if(!empty($this->_post_remove)) { //neu co thanh phan nao trong post remove, tuc la thanh phan nay la mot field trong form nhung khi xu ly khong can dung den //thi xoa ra khoi array post foreach($this->_post_remove as $value) { unset($this->_post[$value]); } } //format all required field if(!empty($this->_post_format)) { foreach($this->_post_format as $key => $value) { $this->format($key, $value); } } return true; } return false; } public function format($key, $value) { switch($value) { case 'password': $this->_post[$key] = Login::string2hash($this->_post[$key]); break; } } public function validate($key) { if(!empty($this->_errors) && in_array($key, $this->_errors)) { return $this->wrapWarn($this->_message[$key]); } //method nay de hien thi loi~ cu the cua mot field //duoc goi ra ngay truoc field do trong form } public function wrapWarn($mess = null) { if(!empty($mess)) { return "<span class=\"warn\">{$mess}</span>"; } } } ?>
Java
UTF-8
908
3.859375
4
[]
no_license
/** * A Class That Contains A Person Details * @author Alireza ZareZeynabadi * @version 1.0 * @since 2021.april.8 */ public class Person { private final String firstName; private final String lastName; /** * Constructor * @param firstName First Name of Person * @param lastName Last Name of Person */ public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } /** * Get First Name Of Person * @return first name */ public String getFirstName() { return firstName; } /** * Get Last Name Of Person * @return last name */ public String getLastName() { return lastName; } /** * To String Method * @return Full Name */ @Override public String toString() { return this.firstName + ' ' + this.lastName; } }
C++
UTF-8
462
3.78125
4
[ "CC0-1.0" ]
permissive
#include <iostream> using namespace std; int main(void) { long long int n; // show instruction to user cout << "Enter the number:\t"; // scan user input cin >> n; // print "Number is odd" if it is odd else print "Number is even" // the 'bit-wise and (&)' operation returns 1 if the 1 is anded with odd Number // else the return value is 0 if 1 is anded with even number cout << (n&1? "Number is odd\n": "Number is even\n"); }
Ruby
UTF-8
763
3.140625
3
[]
no_license
me = gets.chomp bool = true counter = 0 finish = "bye" finish.upcase if (me != finish || finish.upcase) while (bool) if /[[:lower:]]/.match(me) grandma = "HUH?! SPEAK UP, JOSHY!" puts grandma me = gets.chomp if (me == finish || me = finish.upcase) counter += 1 if (counter == 3) bool = false end end else while (/[[:upper:]]/== me || bool == true) year = rand (1935..1989) grandma = "Not since #{year}, you know I hate those commies Egbert" puts grandma.upcase me = gets.chomp if (me == finish || finish.upcase) counter += 1 if (counter == 3) bool = false end end end end end end
JavaScript
UTF-8
395
2.8125
3
[]
no_license
//Función que se ejecuta una vez que se haya lanzado el evento de //que el documento se encuentra cargado, es decir, se encuentran todos los //elementos HTML presentes. document.addEventListener("DOMContentLoaded", function(e){ function logearse(){ if(localStorage.getItem("userName") == null){ window.location.href = "login.html"; } } logearse(); });
Java
UTF-8
2,870
3.59375
4
[]
no_license
package zty.practise.algo.leetcode800; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * 解题分为两步 * * 第一步就是确定相等 * * 第二步就转化为将“相同”的字符串分到一组 * 其实最好的是使用空间工具比如map * 是否能转化出每个的一种基本格式 * 自定义hash? * * * 因为26的10次方在long类型范围以内 * 所以可以将字符串转为无冲突的hash值 * * 所以关键就是实现比较两个字符串奇数偶数位字母相同的方法 * * @author zhangtianyi * */ public class LeetCode893 { public static void main(String[] args) { LeetCode893 s = new LeetCode893(); s.numSpecialEquivGroups(new String[] {"aa","bb","ab","ba"}); } /** * 相较于排序,更接近问题的本质,这里相当于桶计数 * 只需要得到各个字母的数量 而非一个顺序 即可判断相等 * * @param A * @return */ public int numSpecialEquivGroups(String[] A) { Set<String> seen = new HashSet(); for (String S: A) { int[] count = new int[52]; for (int i = 0; i < S.length(); ++i) count[S.charAt(i) - 'a' + 26 * (i % 2)]++; seen.add(Arrays.toString(count)); } return seen.size(); } public int numSpecialEquivGroups3(String[] A) { Set<String> set = new HashSet<>(); for (String str : A) { char[] chars = str.toCharArray(); String odd = "", even = ""; for (int i = 0; i < chars.length; i++) { //如果是奇数位 if ((i & 1) == 1) { odd += str.charAt(i); } else { //如果为偶数位 even += str.charAt(i); } } //排序后拼接 char[] oddArr = odd.toCharArray(); Arrays.sort(oddArr); char[] evenArr = even.toCharArray(); Arrays.sort(evenArr); set.add(new String(oddArr) + new String(evenArr)); } return set.size(); } public int numSpecialEquivGroups2(String[] A) { Set<String> set = new HashSet<>(); for(String a : A) { set.add(parseToInt(a)); } return set.size(); } private String parseToInt(String str) { long a = 0; long b = 0; List<Integer> lista = new ArrayList<>(); List<Integer> listb = new ArrayList<>(); for(int i=0; i<str.length(); i++) { int n = str.charAt(i) - 'a'; if(i % 2 == 0) { lista.add(n); } else { listb.add(n); } } Collections.sort(lista); Collections.sort(listb); for(int e : lista) { a = a * 26 + e; } for(int e : listb) { b = b * 26 + e; } return a + "" + b; } }
Markdown
UTF-8
2,130
3.03125
3
[]
no_license
# CRM Portal Demo (Features) 1. Login Page: (with proper validations-- if you will not give user id and password in login page, it will give error). Default user id and password is : admin/admin 2. Dashboard: It displays information about CRM Portal purpose. It also displays the list of newly added customers. 3. Dashboard Customer List: You can click on the Customer from the list on the dashboard page and edit its information. 4. Customer Menu: It displays the list of the customers. It performs many operations like:-- a) Create a new customer b) delete a customer by selecting the checkboxes 3) sorting of the list by clicking on any of the header 4) edit the customer by clicking on the Edit link 5) Export the customer list data into Excel/CSV file. 5. Products Menu: It display the list of products. It performs many operations like:-- a) Create a new product by click on +Create link b) Edit the product on click on pencil icon on each image. c) Delete the product after click on pencil icon. d) Export the product list data into Excel/CSV file. # Note: The image url should be from internet. local computer image is not working now. # How It Works? CRM Portal usually requires a REST/GraphQL server instead of MySql/SQL to provide data. In this demo however,the API is simulated by the browser [using-fake-json-api]. It provides lots of dummy data so we do not need to create our own data for the testing or demo. The source data is generated at runtime by a package called [data-generator]. # Technology Used 1. React Js (Javascript Framework which is built by facebook) 2. JSON Server (Fake Rest API for the dummy data) **Note**: This project is built with most latest technology which is used by many big companies like facebook, twitter, instagram etc. ## How to run In the project directory, you can run: ### `npm start` Runs the app in the development mode.<br> Open [http://localhost:3000](http://localhost:3000) to view it in the browser.