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 |
|---|---|---|---|---|---|---|---|
Markdown | UTF-8 | 7,204 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | # Integrate Exemplars with Metrics
This OTEP adds exemplar support to aggregations defined in the Metrics SDK.
## Definition
Exemplars are example data points for aggregated data. They provide specific context to otherwise general aggregations. For histogram-type metrics, exemplars are points associated with each bucket in the histogram giving an example of what was aggregated into the bucket. Exemplars are augmented beyond just measurements with references to the sampled trace where the measurement was recorded and labels that were attached to the measurement.
## Motivation
Defining exemplar behaviour for aggregations allows OpenTelemetry to support exemplars in Google Cloud Monitoring.
Exemplars provide a link between metrics and traces. Consider a user using a Histogram aggregation to track response latencies over time for a high QPS server. The histogram is composed of buckets based on the speed of the request, for example, "there were 55 requests that took 400-500 milliseconds". The user wants to troubleshoot slow requests, so they would need to find a trace where the latency was high. With exemplars, the user is able to get an exemplar trace from a high latency bucket, an exemplar trace from a low latency bucket, and compare them to figure out the reason for the high latency.
Exemplars are meaningful for all aggregations where relevant traces can provide more context to the aggregation, as well as when exemplars can display specific information not otherwise shown in the aggregation (for example, the full set of labels where they otherwise might be aggregated away).
## Internal details
An exemplar is a `RawValue`, which is defined as:
```
message RawValue {
// Numerical value of the measurement that was recorded. Only one of these two fields is
// used for the data, depending on its type
double double_value = 0;
int64 int64_value = 1;
// Exact time that the measurement was recorded
fixed64 time_unix_nano = 2;
// 'label:value' map of all labels that were provided by the user recording the measurement
repeated opentelemetry.proto.common.v1.StringKeyValue labels = 3;
// Span ID of the current trace
optional bytes span_id = 4;
// Trace ID of the current trace
optional bytes trace_id = 5;
// When sample_count is non-zero, this exemplar has been chosen in a statistically
// unbiased way such that the exemplar is representative of `sample_count` individual events
optional double sample_count = 6;
}
```
Exemplar collection should be enabled through an optional parameter (disabled by default), and when not enabled, there should be no collection/logic performed related to exemplars. This is to ensure that when necessary, aggregators are as high performance as possible. Aggregators should also have a parameter to determine whether exemplars should only be collected if they are recorded during a sampled trace, or if tracing should have no effect on which exemplars are sampled. This allows aggregations to prioritize either the link between metrics and traces or the statistical significance of exemplars, when necessary.
[#347](https://github.com/open-telemetry/opentelemetry-specification/pull/347) describes a set of standard aggregators in the metrics SDK. Here we describe how exemplars could be implemented for each aggregator.
### Exemplar behaviour for standard aggregators
#### HistogramAggregator
The HistogramAggregator MUST (when enabled) maintain a list of exemplars whose values are distributed across all buckets of the histogram (there should be one or more exemplars in every bucket that has a population of at least one sample-able measurement). Implementations SHOULD NOT retain an unbounded number of exemplars.
#### Sketch
A Sketch aggregator SHOULD maintain a list of exemplars whose values are spaced out across the distribution. There is no specific number of exemplars that should be retained (although the amount SHOULD NOT be unbounded), but the implementation SHOULD pick exemplars that represent as much of the distribution as possible. (Specific details not defined, see open questions.)
#### Last-Value
Most (if not all) Last-Value aggregators operate asynchronously and do not ever interact with context. Since the value of a Last-Value is the last measurement (essentially the other parts of an exemplar), exemplars are not worth implementing for Last-Value.
#### Exact
The Exact aggregator will function by maintaining a list of `RawValue`s, which contain all of the information exemplars would carry. Therefore the Exact aggregator will not need to maintain any exemplars.
#### Counter
Exemplars give value to counter aggregations in two ways: One, by tying metric and trace data together, and two, by providing necessary information to re-create the input distribution. When enabled, the aggregator will retain a bounded list of exemplars at each checkpoint, sampled from across the distribution of the data. Exemplars should be sampled in a statistically significant way.
#### MinMaxSumCount
Similar to Counter, MinMaxSumCount should retain a bounded list of exemplars that were sampled from across the input distribution in a statistically significant way.
#### Custom Aggregators
Custom aggregators MAY support exemplars by maintaining a list of exemplars that can be retrieved by exporters. Custom aggregators should select exemplars based on their usage by the connected exporter (for example, exemplars recorded for Google Cloud Monitoring should only be retained if they were recorded within a sampled trace).
Exemplars will always be retrieved from aggregations (by the exporter) as a list of RawValue objects. They will be communicated via a
```
optional repeated RawValue exemplars = 6
```
attribute on the `Metric` object.
## Trade-offs and mitigations
Performance (in terms of memory usage and to some extent time complexity) is the main concern of implementing exemplars. However, by making recording exemplars optional, there should be minimal overhead when exemplars are not enabled.
## Prior art and alternatives
Exemplars are implemented in [OpenCensus](https://github.com/census-instrumentation/opencensus-specs/blob/master/stats/Exemplars.md#exemplars), but only for HistogramAggregator. This OTEP is largely a port from the OpenCensus definition of exemplars, but it also adds exemplar support to other aggregators.
[Cloud monitoring API doc for exemplars](https://cloud.google.com/monitoring/api/ref_v3/rpc/google.api#google.api.Distribution.Exemplar)
## Open questions
- Exemplars usually refer to a span in a sampled trace. While using the collector to perform tail-sampling, the sampling decision may be deferred until after the metric would be exported. How do we create exemplars in this case?
- We don’t have a strong grasp on how the sketch aggregator works in terms of implementation - so we don’t have enough information to design how exemplars should work properly.
- The spec doesn't yet define a standard set of aggregations, just default aggregations for standard metric instruments. Since exemplars are always attached to particular aggregations, it's impossible to fully specify the behavior of exemplars.
|
C++ | UTF-8 | 7,243 | 3 | 3 | [
"MIT"
] | permissive | #include "interfazCursos.h"
#include "interfazPrincipal.h"
#include "contenedorEscuelas.h"
#include "grupoProfesores.h"
#include "contenedorCursos.h"
#include "curso.h"
#include <iostream>
#include <conio.h>
#include <Windows.h>
using namespace std;
char Interfaz_Cursos::vMenuCursos()
{
char ans;
cout << "**************MENU CURSOS**************" << endl;
cout << "(1)--Consultar curso" << endl;
cout << "(2)--Consultar lista de cursos de una Escuela" << endl;
cout << "(3)--Ajustes" << endl;
cout << "(4)--Salir" << endl;
cout << "********************************************" << endl;
Interfaz_Principal::msjIngreseOpcion();
ans = _getch();
while (ans < '1' || ans > '4') {
cout << "Opcion Incorrecta. Intente de nuevo. " << endl;
ans = _getch();
}
system("cls");
return ans;
}
char Interfaz_Cursos::vAjustesCursos()
{
char ans;
cout << "***************AJUSTES CURSOS***************" << endl;
cout << "-(1)-Ingresar Curso" << endl;
cout << "-(2)-Editar Curso" << endl;
cout << "-(3)-Eliminar Curso" << endl;
cout << "-(4)-Salir" << endl;
Interfaz_Principal::msjIngreseOpcion();
ans = _getch();
while (ans < '1' || ans > '4')
{
cout << "Opcion Incorrecta. Try again " << endl;
ans = _getch();
}
system("cls");
return ans;
}
void Interfaz_Cursos::vIngresaCurso(Universidad* U)
{
cout << "Nombre de la Universidad: " << U->getNombre() << endl << endl;
cout << U->getContenedorEscuelas()->toString('1') << endl;
cout << "Digite las siglas de la Escuela a la que desea ingresar el curso -> ";
string sigla; cin >> sigla; cin.ignore();
sigla = Interfaz_Principal::convierteMayuscula(sigla);
if (!U->getContenedorEscuelas()->retornaEscuela(sigla))
cout << "No se ha encontrado la Escuela..." << endl;
else {
system("cls");
string nombre;
cout << "Ingrese el nombre del curso -> "; getline(cin, nombre); cout << endl;
cout << "Curso: " << "\"" << nombre << "\" "; cout << "| es esta informacion correcta? ";
char ans = Interfaz_Principal::vInfoConfirmacion();
while (nombre == "Undefined" || nombre == " " || nombre == "") {
cout << "Nombre Invalido. Intente de nuevo -> ";
Sleep(800);
system("cls");
cout << "Ingrese el nombre del curso -> "; std::getline(std::cin, nombre); cout << endl << endl;
}
cout << "Ingrese la cantidad de creditos del Curso -> (1 - 5) -> "; int creditos; cin >> creditos; cin.ignore();
Curso* cur = new Curso(nombre, sigla);
cur->setCantidadCreditos(creditos);
U->getContenedorEscuelas()->retornaEscuela(sigla)->getContenedorCursos()->insertaInicio(cur);
Interfaz_Principal::msjPerfecto();
}
Interfaz_Principal::msjPausa();
system("cls");
}
void Interfaz_Cursos::vEditarCurso(Universidad *U)
{
cout << U->getContenedorEscuelas()->toString('2');
cout << "Ingrese el codigo del curso que desea editar -> ";
string codigo, sigla;
cin >> codigo; cin.ignore();
codigo = Interfaz_Principal::convierteMayuscula(codigo);
sigla = codigo.substr(0, 3);
if (U->getContenedorEscuelas() == nullptr || U->getContenedorEscuelas()->retornaEscuela(sigla)->getContenedorCursos() == nullptr)
cout << "No existe ningun curso con esa sigla..." << endl;
else
if (!U->getContenedorEscuelas()->retornaEscuela(sigla)->getContenedorCursos()->retornaCursoEspecifico(codigo))
cout << "El curso no ha sido encontrado..." << endl;
else {
string nombre;
cout << "Ingrese el nuevo nombre del curso -> "; getline(cin, nombre); cout << endl;
cout << "Curso: " << "\"" << nombre << "\" "; cout << "| es esta informacion correcta? ";
char ans = Interfaz_Principal::vInfoConfirmacion();
while (nombre == "Undefined" || nombre == " " || nombre == "") {
cout << "Nombre Invalido. Intente de nuevo -> ";
Sleep(800);
system("cls");
cout << "Ingrese el nuevo nombre del curso -> "; std::getline(std::cin, nombre); cout << endl << endl;
}
U->getContenedorEscuelas()->retornaEscuela(sigla)->getContenedorCursos()->
retornaCursoEspecifico(codigo)->setNombre(nombre);
cout << "Ingrese la cantidad de creditos del Curso -> (1 - 5) -> "; int creditos; cin >> creditos; cin.ignore();
U->getContenedorEscuelas()->retornaEscuela(sigla)->getContenedorCursos()->
retornaCursoEspecifico(codigo)->setCantidadCreditos(creditos);
Interfaz_Principal::msjPerfecto();
}
Interfaz_Principal::msjPausa();
system("cls");
}
void Interfaz_Cursos::vEliminaCurso(Universidad *U) //debe implementarse mejor
{
cout << U->getContenedorEscuelas()->toString('2') << endl;
cout << "Ingrese el codigo del curso que desea eliminar -> ";
string codigo, sigla, aux;
cin >> aux; cin.ignore();
codigo = Interfaz_Principal::convierteMayuscula(aux);
sigla = codigo.substr(0, 3);
try {
Escuela *Esc = U->getContenedorEscuelas()->retornaEscuela(sigla);
if (Esc == nullptr) throw 1;
if (Esc->getContenedorCursos()->eliminaCursoEspecifico(codigo))
cout << "Curso eliminado con exito" << endl;
else
cout << "No se ha podido eliminar el curso." << endl;
Interfaz_Principal::msjPausa();
system("cls");
}
catch (int e) {
if (e == 1)
cout << "No existe ningun curso con ese codigo" << endl;
}
}
void Interfaz_Cursos::vInfoCurso(Universidad *U) //necesita ser optimizado
{
string codigo, sigla;
cout << "Ingrese el codigo del curso que desea consultar -> ";
cin >> codigo; cin.ignore();
codigo = Interfaz_Principal::convierteMayuscula(codigo);
sigla = codigo.substr(0, 3);
if (U->getContenedorEscuelas()->retornaEscuela(sigla) == nullptr)
cout << "No existe ningun curso perteneciente a esa sigla..." << endl;
else
if (U->getContenedorEscuelas()->retornaEscuela(sigla)->getContenedorCursos()->retornaCursoEspecifico(codigo) == NULL)
cout << "El curso no ha sido encontrado..." << endl;
else
cout << *(U->getContenedorEscuelas()->retornaEscuela(sigla)->getContenedorCursos()->retornaCursoEspecifico(codigo)) << endl;
Interfaz_Principal::msjPausa();
system("cls");
}
void Interfaz_Cursos::vListaCursosEscuelaParticular(Universidad *U) {
cout << U->getContenedorEscuelas()->toString('1'); //Imprime lista de Escuelas con sus codigos
string sigla;
cout << "Ingrese la sigla de la escuela que desea consultar la lista de cursos -> ";
cin >> sigla; cin.ignore();
sigla = Interfaz_Principal::convierteMayuscula(sigla);
if (!U->getContenedorEscuelas()->retornaEscuela(sigla))
cout << "La escuela no ha sido encontrada..." << endl;
else {
Escuela *EE = U->getContenedorEscuelas()->retornaEscuela(sigla);
if (EE->getContenedorCursos()->getCantidad() == 0)
cout << "No existen cursos aun en esta Escuela..." << endl;
else
for (int i = 0; i < EE->getContenedorCursos()->getCantidad(); i++) { //algoritmo mortal xxxxxx
cout << "Curso: " << EE->getContenedorCursos()->getCursoporPos(i)->getNombre() << endl;
cout << "Profesores:" << endl;
for (int x = 0; x < EE->getContenedorCursos()->getCursoporPos(i)->getGrupoProfesores()->getCantidadProfesores(); x++) {
int cedulaProfe = EE->getContenedorCursos()->getCursoporPos(i)->getGrupoProfesores()->getProfesor(x)->getNumCedula();
cout << U->getContenedorEscuelas()->retornaProfesor(cedulaProfe)->getNombreCompleto() << endl;
}
}
}
Interfaz_Principal::msjPausa();
system("cls");
} |
Markdown | UTF-8 | 561 | 2.546875 | 3 | [] | no_license | # iTerm-ssh
iTerm 2 Plugin for Colouring SSH Connections
## Usage
This plugin must be put into the plugin directory with `oh-my-zsh`, this can either be the default one or the custom defined one.
Once it's been put into the correct directory add the plugin name into the **plugin array** in your `.zshrc`. The following are examples of where the files *might* live.
```
ZSH_CUSTOM=~/dotfiles/zsh/custom
plugins=(iTerm-ssh)
```
The above assumes the plugin exists in the following directory: `~/dotfiles/zsh/custom/plugins/iTerm-ssh/iTerm-ssh.plugin.zsh`
|
Python | UTF-8 | 1,364 | 2.640625 | 3 | [] | no_license | #!/usr/bin/env python
import random
from slackclient import SlackClient
import time
from supporting_functions import parseInput, rollSomeDie, getDieResult,\
buildWeaponDictFromFile, getAllWeaponTypes
# Insert slack token
slack_token = ""
slack_conn = SlackClient(slack_token)
# Insert bot ID
at_bot = ""
def parse_slack_output(slack_rtm_output):
output_list = slack_rtm_output
if output_list and len(output_list) > 0:
for output in output_list:
if output and 'text' in output and at_bot in output['text']:
# return text after the @ mention, whitespace removed
return output['text'].split(at_bot)[1].strip().lower(), \
output['channel']
return None, None
if __name__ == "__main__":
cache = redis.Redis(unix_socket_path='/tmp/redis.sock')
if slack_conn.rtm_connect():
backoff_time = 1
while True:
command, channel = parse_slack_output(slack_conn.rtm_read())
if command and channel:
# DEBUG
# print(command)
response = parseInput(command, cache)
slack_conn.api_call("chat.postMessage", channel=channel,
text = response, as_user=True)
time.sleep(backoff_time)
else:
print("Unable to connect")
|
Java | UTF-8 | 473 | 1.757813 | 2 | [] | no_license | package com.tenone.gamebox.mode.able;
import android.content.Context;
import android.content.Intent;
import com.tenone.gamebox.mode.mode.OpenServiceNotificationMode;
import java.util.List;
public interface NotificationDetailsAble {
String getTitle(Intent intent);
List<OpenServiceNotificationMode> getContent(Context context);
void deleteItem(Context context, OpenServiceNotificationMode notificationMode);
void deleteAll(Context context);
}
|
Go | UTF-8 | 399 | 3.0625 | 3 | [] | no_license | package uuid
import (
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
const Base62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
// UniqueFilename 文件名唯一表示 len:字符串长度
func UniqueFilename(length int) string {
vb := make([]byte, length)
for i, _ := range vb {
n := rand.Intn(62)
vb[i] = Base62[n]
}
return string(vb)
}
|
PHP | UTF-8 | 3,054 | 2.625 | 3 | [] | no_license | <?php
namespace App\Model;
use App\Model\Conexao;
use PDO;
class Usuario
{
function __construct()
{
$this->connection = new Conexao();
}
public function add($request)
{
$usuario = $request->getParam('usuario');
$email = $request->getParam('email');
$senha = $request->getParam('senha');
$status = $request->getParam('status');
$sql = "INSERT INTO usuario (usuario,email,senha,status) VALUES
(:usuario,:email,:senha,:status)";
try{
$connection = $this->connection->PDOConnect();
$stmt = $connection->prepare($sql);
$stmt->bindParam(':usuario', $usuario);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':senha', $senha);
$stmt->bindParam(':status', $status);
$stmt->execute();
echo json_encode('{"success": "Usuario Adicionado"}');
} catch(PDOException $e){
echo json_encode('{"error": '.$e->getMessage().'}');
}
}
public function validateSenha($senha)
{
$sql = "SELECT * FROM usuario WHERE senha = '$senha'";
try{
$connection = $this->connection->PDOConnect();
$stmt = $connection->query($sql);
$usuario = $stmt->fetchAll(PDO::FETCH_OBJ);
echo json_encode($usuario);
$connection = null;
}catch(PDOException $e){
echo json_encode('{"error": '.$e->getMessage().'}');
}
}
public function validateLogin($login)
{
$sql = "SELECT * FROM usuario WHERE (email = '$login')";
try{
$connection = $this->connection->PDOConnect();
$stmt = $connection->query($sql);
$usuario = $stmt->fetchAll(PDO::FETCH_OBJ);
echo json_encode($usuario);
$connection = null;
}catch(PDOException $e){
echo json_encode('{"error": '.$e->getMessage().'}');
}
}
public function logar($login, $senha){
$sql = "SELECT * FROM usuario WHERE senha = '$senha' AND
( usuario = '$login' OR email = '".$login."' )";
try{
$connection = $this->connection->PDOConnect();
$stmt = $connection->query($sql);
$usuario = $stmt->fetchAll(PDO::FETCH_ASSOC);
return($usuario);
$connection = null;
}catch(PDOException $e){
echo json_encode('{"error": '.$e->getMessage().'}');
}
}
public function logout()
{
session_start();
if( isset( $_SESSION['logado']) )
unset($_SESSION['logado']);
if( isset( $_SESSION['id']) )
unset($_SESSION['id']);
if( isset( $_SESSION['usuario']) )
unset($_SESSION['usuario']);
session_destroy();
/* header("location:http://localhost/geradorXml/App/View/Login/Login.php"); */
/* exit; */
}
}
|
JavaScript | UTF-8 | 5,877 | 2.859375 | 3 | [] | no_license | "use strict";
import * as itbooks from "./itbookapi.js";
import * as db from "./datastore.js";
function writeBookElement(book, target) {
let bookElement = document.createElement("div");
bookElement.classList.add("book", "grid");
let bookCover = document.createElement("img");
bookCover.setAttribute("src", book["image"]);
let title = document.createElement("h2");
title.textContent = book["title"];
let subtitle = document.createElement("p");
subtitle.textContent = book["subtitle"];
let buttonsContainer = document.createElement("div");
buttonsContainer.classList.add("buttons");
let infoButton = document.createElement("button");
infoButton.classList.add("btn", "info-button");
infoButton.dataset["isbn"] = book["isbn13"];
infoButton.textContent = "More Info";
let borrowButton = document.createElement("button");
borrowButton.classList.add("btn", "borrow-button");
borrowButton.dataset["isbn"] = book["isbn13"];
borrowButton.textContent = "Borrow";
buttonsContainer.appendChild(infoButton);
buttonsContainer.appendChild(borrowButton);
bookElement.appendChild(bookCover);
bookElement.appendChild(title);
bookElement.appendChild(subtitle);
bookElement.appendChild(buttonsContainer);
target.appendChild(bookElement);
}
let searchForm = document.querySelector("form.search-form");
searchForm.addEventListener("submit", (e) => {
e.preventDefault();
let q = searchForm.elements.q.value;
itbooks.search(q).then((results) => {
let msg = "";
if (results["total"] == 0) {
msg = "No results Found";
} else {
msg = "10 / " + results["total"] + " results showing";
}
document.querySelector("#book-list").innerHTML = "";
document.querySelector("#status").textContent = msg;
let count = results["total"] > 10 ? 10 : results["total"];
for (let i = 0; i < count; i++) {
writeBookElement(
results.books[i],
document.querySelector("#book-list")
);
}
});
});
document.querySelector(".books").addEventListener("click", (e) => {
if (e.target.classList.contains("info-button")) {
let isbn = e.target.dataset["isbn"];
itbooks.getBookDetails(isbn).then((book) => {
document.querySelector(".book-info .title").textContent =
book["title"];
document.querySelector(".book-info .subtitle").textContent =
book["subtitle"];
document.querySelector(".book-info .author").textContent =
book["authors"];
document.querySelector(".book-info .description").textContent =
book["desc"];
document
.querySelector(".book-info img")
.setAttribute("src", book["image"]);
document.querySelector(".book-info").classList.add("shown");
});
} else if (e.target.classList.contains("borrow-button")) {
let isbn = e.target.dataset["isbn"];
itbooks.getBookDetails(isbn).then((book) => {
document.querySelector(".book-borrow .title").textContent =
book["title"];
document.querySelector(".book-borrow .author").textContent =
book["authors"];
document.querySelector("#borrow-form").elements.isbn.value = isbn;
document.querySelector(".book-borrow").classList.add("shown");
});
}
});
document
.querySelector(".book-info .card-title i")
.addEventListener("click", (_) => {
document.querySelector(".book-info").classList.remove("shown");
});
document
.querySelector(".book-borrow .card-title i")
.addEventListener("click", (_) => {
document.querySelector(".book-borrow").classList.remove("shown");
});
document.querySelector("#borrow-form").addEventListener("submit", (e) => {
e.preventDefault();
let userId = e.target.elements.accountNumber.value;
let isbn = e.target.elements.isbn.value;
db.get("users", userId).then((user) => {
if (user) {
if (user.borrowed.some((x) => x.isbn == isbn)) {
alert("You've already borrowed this book");
} else {
if (user.borrowed.length < 5) {
itbooks.getBookDetails(isbn).then((book) => {
fetch(
"https://tgrp-cxany.herokuapp.com/" + book["image"]
).then((resp) =>
resp.blob().then((cover) => {
db.add("books", {
isbn: book["isbn13"],
title: book["title"],
author: book["authors"],
subtitle: book["subtitle"],
description: book["desc"],
cover: cover,
});
})
);
let date = new Date(Date.now());
let due = new Date();
due.setDate(date.getDate() + 30);
user.borrowed.push({
isbn: isbn,
date: date,
due: due,
});
db.update("users", user);
document
.querySelector(".book-borrow")
.classList.remove("shown");
});
} else {
alert("You've already borrowed 5 books.");
}
}
} else {
alert("Invalid User Id");
}
});
});
|
JavaScript | UTF-8 | 881 | 3.09375 | 3 | [] | no_license |
const app = {
title:'Indecision App',
subTitle:'This is a demo test',
options:['one','two','three']
};
// console.log("App.js is running")
const template=(
<div>
<h1>{app.title}</h1>
{app.subTitle && <p>Subtitle : {app.subTitle}</p>}
{app.options && app.options.length > 0 ? "Here are your options" : "No options"}
<ol>
<li>item one.</li>
<li>item two.</li>
</ol>
</div>
);
const user={
name:'Ghanashyam',
Age:23,
Location:'Kottakkal'
}
function getLocation(location){
if(location){
return <p>Location : {location}</p>;
}
}
const templateTwo=(
<div>
<h1>{user.name ? user.name : 'Anonymous'}</h1>
{(user.Age && user.Age >= 18) && <p>Age : {user.Age}</p>}
{getLocation(user.Location)}
</div>
);
const appRoot= document.getElementById('demo');
ReactDOM.render(template,appRoot);
|
Markdown | UTF-8 | 1,137 | 2.625 | 3 | [] | no_license | # Memoire-M2
Ce repository contient tous les documents en relation avec mon mémoire de stage de deuxième de master "Technologies numériques appliquées à l'histoire" à l'École nationale des Chartes.
En plus du README, le repository contient deux dossiers et un PDF :
* Le dossier "Livrable technique" contient différents dossiers avec des documents en lien avec le stage et le projet développé, tels que des scripts, des graphiques ou des tableaux en CSV. En plus de ces dossiers, il y a un fichier texte qui détaille le contenu du livrable technique.
* Le dossier "Mémoire Stage M2" contient la version LateX du mémoire telle qu'elle a été réalisée et produit par le site Overleaf. Ce dossier est lui-même découpé en dossier qui forme la structure du mémoire.
* "Mémoire Stage M2" est la production PDF du mémoire.
# En plus
Ce repository peut être mis en lien avec le repository du projet MetaLEX, qui contient les différents scripts réalisés pour le projet (et également présents dans le dossier "Livrable technique") : [PSIG-EHESS/metalex](https://github.com/PSIG-EHESS/metalex "Repository MetaLEX") |
C | UTF-8 | 8,768 | 2.875 | 3 | [] | no_license | #include "Origa_Nvm.h"
const ULONG g_culNvmTimeout = System_CyclesToNvmOut(System_MicrosToCycles(20000u)); /* 20ms */
/* ****************************************************************************
name: Nvm_ProgramData()
function: program desired data values into ORIGA NVM address space.
the option b_VerifyData can be used to re-read the programmed
data to be sure that the data was written correct.
input: IN: b_WaitForFinish
if 'true', then the host waits for the NVM state-mashine to
finish before returning from that function.
IN: b_VerifyData
if 'true', then the written data is cross-checked with the
content of the write buffer.
IN: uw_Address
start address within NVM to program data beginning from.
IN: ub_BytesToProgram
number of bytes to program.
IN: * ubp_Data
pointer to buffer holding values to program into NVM.
output: bool
return: 'true', if write access was executed without any problems.
'false', if failures happened
date: 2010-03-04: time out added.
************************************************************************* */
BOOL Nvm_ProgramData( BOOL b_WaitForFinish, BOOL b_VerifyData, UWORD uw_Address, UBYTE ub_BytesToProgram, UBYTE * ubp_Data )
{
BOOL bResult;
UBYTE ubData;
UWORD uwDataCount;
UWORD uwAddress;
UBYTE ubAddressH;
UBYTE ubAddressL;
ULONG ulNvmTimeOut;
/* check not allowed settings */
if( (b_WaitForFinish == FALSE) && (b_VerifyData == TRUE) )
{
return FALSE;
}
/* remove NVM offset */
uw_Address &= 0x00FFu;
for( uwDataCount = 0u; uwDataCount < ub_BytesToProgram; uwDataCount++ )
{
uwAddress = uw_Address + uwDataCount;
ubAddressH = (UBYTE)((uwAddress >> 3u) & 0x1Fu);
ubAddressH |= 0xC0u;
ubAddressL = (UBYTE)(uwAddress & 0x07u);
/* wait for NVM state-machine to be ready for a new command */
ulNvmTimeOut = g_culNvmTimeout;
do
{
if( Swi_ReadRegisterSpace( SWI_ORIGA_CTRL2_NVM, &ubData ) == FALSE )
{
return FALSE;
}
/* check for timeout */
if( ulNvmTimeOut == 0u )
{
return FALSE;
}
ulNvmTimeOut--;
}while( (ubData & 0x80u) != 0u );
/* functions return always true, if mask is set to 0xFF */
(void)Swi_WriteRegisterSpaceNoIrq( SWI_NVM_WIP0 | ubAddressL, ubp_Data[uwDataCount], 0xFFu );
(void)Swi_WriteRegisterSpaceNoIrq( SWI_ORIGA_NVM_ADDR, ubAddressL, 0xFFu );
(void)Swi_WriteRegisterSpaceNoIrq( SWI_ORIGA_CTRL2_NVM, ubAddressH, 0xFFu );
}
/* if user wants to wait until write is done, then poll as long as programming requires */
if( b_WaitForFinish == TRUE )
{
ulNvmTimeOut = g_culNvmTimeout;
do
{
if( Swi_ReadRegisterSpace( SWI_ORIGA_CTRL2_NVM, &ubData ) == FALSE )
{
return FALSE;
}
/* check for timeout */
if( ulNvmTimeOut == 0u )
{
return FALSE;
}
ulNvmTimeOut--;
}while( (ubData & 0x80u) != 0u );
}
if( b_VerifyData == TRUE )
{
for( uwDataCount = 0u; uwDataCount < ub_BytesToProgram; uwDataCount++ )
{
bResult = Nvm_ReadData( uw_Address + uwDataCount, 1u, &ubData );
if( (bResult == FALSE) || (ubData != ubp_Data[uwDataCount]) )
{
return FALSE;
}
}
}
/* all ok */
return TRUE;
}
/* ****************************************************************************
name: Nvm_ReadData()
function: read data from requested NVM address and store data into
provided buffer.
input: IN: uw_Address
start address to read data from NVM.
IN: ub_BytesToRead
number of bytes to read from NVM.
OUT: * ubp_Data
pointer to buffer to store read data into.
output: bool
return: 'true', if reading was ok .
'false', if reading failed.
date: 2010-03-04: time out added.
************************************************************************* */
BOOL Nvm_ReadData( UWORD uw_Address, UBYTE ub_BytesToRead, UBYTE * ubp_Data )
{
UWORD uwDataCount;
UBYTE ubData;
UWORD uwAddress;
UBYTE ubAddressH;
UBYTE ubAddressL;
ULONG ulNvmTimeOut;
/* remove NVM offset */
uw_Address &= 0x00FFu;
for( uwDataCount = 0u; uwDataCount < ub_BytesToRead; uwDataCount++ )
{
uwAddress = uw_Address + uwDataCount;
ubAddressH = (UBYTE)((uwAddress >> 3u) & 0x1Fu);
ubAddressH |= 0x80u;
ubAddressL = (UBYTE)(uwAddress & 0x07u);
ulNvmTimeOut = g_culNvmTimeout;
do
{
if( Swi_ReadRegisterSpace( SWI_ORIGA_CTRL2_NVM, &ubData ) == FALSE )
{
return FALSE;
}
/* check for timeout */
if( ulNvmTimeOut == 0u )
{
return FALSE;
}
ulNvmTimeOut--;
}while( (ubData & 0x80u) != 0u );
/* functions return always true, if mask is set to 0xFF */
(void)Swi_WriteRegisterSpaceNoIrq( SWI_ORIGA_NVM_ADDR, ubAddressL, 0xFFu );
(void)Swi_WriteRegisterSpaceNoIrq( SWI_ORIGA_CTRL2_NVM, ubAddressH, 0xFFu );
ulNvmTimeOut = g_culNvmTimeout;
do
{
if( Swi_ReadRegisterSpace(SWI_ORIGA_CTRL2_NVM, &ubData) == FALSE )
{
return FALSE;
}
/* check for timeout */
if( ulNvmTimeOut == 0u )
{
return FALSE;
}
ulNvmTimeOut--;
}while( (ubData & 0x80u) != 0u );
if( Swi_ReadRegisterSpace( SWI_NVM_WIP2 | ubAddressL, &ubData ) == FALSE )
{
return FALSE;
}
ubp_Data[uwDataCount] = ubData;
}
/* all ok */
return TRUE;
}
/* ****************************************************************************
name: Nvm_DecreaseLifeSpanCounter()
function: try to decrease LifeSpanCounter by one.
input: -
output: bool
return: 'true', if decrease was triggered.
'false', if decrease failed.
date: 2010-03-04: time out added.
************************************************************************* */
BOOL Nvm_DecreaseLifeSpanCounter( void )
{
UBYTE ubData;
ULONG ulNvmTimeOut;
/* wait for NVM state-machine to be ready for a new command */
ulNvmTimeOut = g_culNvmTimeout;
do
{
if( Swi_ReadRegisterSpace( SWI_ORIGA_CTRL2_NVM, &ubData ) == FALSE )
{
return FALSE;
}
/* check for timeout */
if( ulNvmTimeOut == 0u )
{
return FALSE;
}
ulNvmTimeOut--;
}while( (ubData & 0x80u) != 0u );
/* function returns always true, if mask is set to 0xFF */
(void)Swi_WriteRegisterSpaceNoIrq( SWI_ORIGA_NVM_ADDR, 0x20u, 0xFFu );
return TRUE;
}
/* ****************************************************************************
name: Nvm_VerifyLifeSpanCounter()
function: check that the LifeSpanCounter is within a valid nuber range
input: OUT: * bp_IsValid
pointer to bool to store verification state of the
LifeSpanCounter into.
output: bool
return: 'true', if read access was ok.
'false', if read access failed.
date: .
************************************************************************* */
BOOL Nvm_VerifyLifeSpanCounter( BOOL * bp_IsValid )
{
ULONG ulLifeSpanCount;
/* for case of fail, the LSP also will set to false */
*bp_IsValid = FALSE;
if( Nvm_ReadLifeSpanCounter( &ulLifeSpanCount ) == TRUE )
{
if( ulLifeSpanCount <= 100000u )
{
*bp_IsValid = TRUE;
}
return TRUE;
}
else
{
return FALSE;
}
}
/* ****************************************************************************
name: Nvm_ReadLifeSpanCounter()
function: read current setting of the LifeSpanCounter.
input: OUT: * ulp_LifeSpanCounter
pointer to ULONG to store current LifeSpanCounter state
into.
output: bool
return: 'true', if LifeSpanCounter reading was ok.
'false', if LifeSpanCounter reading failed.
date: v0.93; 2009-05-25: size optimized
************************************************************************* */
BOOL Nvm_ReadLifeSpanCounter( ULONG * ulp_LifeSpanCounter )
{
UBYTE ubCount;
UBYTE ubData[ 4 ];
ULONG ulResult = 0UL;
/* read data from NVM */
if( Nvm_ReadData( 0x148u, 4u, ubData ) == FALSE )
{
return FALSE;
}
/* create result */
ubCount = 4;
do
{
ubCount--; /* NOTE: prevent MISRA-C rule 12.13 violation. */
ulResult = (ulResult << 8u) | ubData[ubCount];
}while( ubCount != 0u );
*ulp_LifeSpanCounter = ulResult;
/* all done well */
return TRUE;
}
|
PHP | UTF-8 | 3,798 | 2.625 | 3 | [] | no_license | <?php
include("login.php");
if(isset($_SESSION['login_user']))
{
header("Location: usuario.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<?php
include("template.php");
?>
</head>
<body>
<div>
<h1 class="mb-3">Sign up</h1>
<form name="signup" action="signup.php" method="post" onsubmit="return(validatesu());">
<div class="form-group">
<input type="text" class="form-control" name="nombre" placeholder="Nombre" style="width: 250px;">
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" placeholder="Correo" style="width: 250px;">
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" maxlength="20" placeholder="Contrasena" style="width: 250px;">
</div>
<div class="form-group">
<div class="form-check">
<input type="radio" name="genero" value="hombre">
<label for="Hombre">Hombre</label>
</div>
<div class="form-check">
<input type="radio" name="genero" value="mujer">
<label for="Mujer">Mujer</label>
</div>
<div class="form-check">
<input type="radio" name="genero" value="otro">
<label for="Otro">Otro</label>
</div>
</div>
<button class="btn btn-primary" type="submit" name="submit">Sign up</button>
</form>
<a href="/ingreso.php">Ya tienes cueta? Ingresa aqui</a>
</div>
</body>
<script type="text/javascript">
function validatesu()
{
if(document.signup.nombre.value == "")
{
alert("Por favor escriba su nombre");
document.signup.nombre.focus();
return false;
}
if(document.signup.email.value == "")
{
alert("Por favor escriba su e-mail");
document.signup.email.focus();
return false;
}
else
{
correo = document.signup.email.value;
validate = validateEmail(correo);
if(validate == false)
return validate;
}
if(document.signup.password.value == "")
{
alert("Por favor escriba una contrasena");
document.signup.password.focus();
return false;
}
if(document.signup.genero.value == "")
{
alert("Por favor escoja un genero");
return false;
}
//alert("Registro exitoso!");
return true;
}
function validateEmail(correo)
{
email = correo;
at = correo.indexOf("@");
dot = correo.lastIndexOf(".");
var v;
if(at < 1 || (dot - at < 2))
{
alert("Por favor introduce un correo valido");
return false;
}
return true;
}
</script>
</html>
|
Markdown | UTF-8 | 1,120 | 2.625 | 3 | [] | no_license |
## Table of contents
* [General info](#general-info)
* [Technologies](#technologies)
* [Libraries](#libraries)
* [Setup](#setup)
## General info
This project is based on Netmiko and Jinja ,this programme will build a configuration file from Jinja Template and pushes that file inividualy to each Devices.
When the programme is first executed it does SSH to Terminal-Server/Intermediate-Server(Linux) and after getting access ,another command is executed from here
to SSH login on remote Network Devices, Then after this Configuration files are pushed and saved on Network Devices
## Technologies
Project is created with:
* Python 3.6.9
Network Device from Cisco Sandbox
* GNS3 IOU and IOS Routers
## Libraries
* [Netmiko](https://github.com/ktbyers/netmiko/blob/develop/README.md)
* [Jinja2](https://jinja2docs.readthedocs.io/en/stable/)
* [Rich](https://rich.readthedocs.io/en/latest/)
## Setup
To run this project, clone this to your local Folder using 'git clone'
```
$ git clone https://github.com/shebin7/Netmiko_Jinja
```
Then run it from IDE or from Terminal
```
$ python3 Netmiko_Jinja.py
```
|
JavaScript | UTF-8 | 1,839 | 3.59375 | 4 | [] | no_license | for(var index = 0; index < 5; index++) {
setTimeout(() => {
console.log("After Seconds "+ (index+1)); //3- "1 second, 3rd second, 5 second"
}, 1000);
}
// console.log("File Name", __filename);
// console.log("Directory Name", __dirname);
// global.persons = [
// {id : 1, name : "John", savedby : "CaptainAmerica"},
// {id : 2, name : "Alice", savedby : "IronMan"},
// {id : 3, name : "Roger", savedby : "CaptainAmerica"},
// {id : 4, name : "Adam", savedby : "IronMan"},
// {id : 5, name : "Alex", savedby : "SpiderMan"}
// ];
// console.log(global.persons);
// let fs = require("fs"),
// data = `Read, Write, Duplex and Transform Streams
// is used to read write data into a file
// updated`,
// // Create a writable stream
// writerStream = fs.createWriteStream('output.txt');
// // Write the data to stream with encoding to be utf8
// writerStream.write(data,'UTF8');
// // Mark the end of file
// writerStream.end();
// // Handle stream events --> finish, and error
// writerStream.on('finish', function(err, data) { console.log("Write completed."); });
// writerStream.on('error', function(err, data) {
// console.log(err.stack);
// });
// console.log("Program Ended To Write Through Stream");
// //Lets write a code for read through stream
// // Create a readable stream
// let readerStream = fs.createReadStream('output.txt');
// // Set the encoding to be utf8.
// readerStream.setEncoding('UTF8');
// // Handle stream events --> data, end, and error
// readerStream.on('data', function(chunk) { data += chunk; });
// readerStream.on('end',function() { console.log("read data ends over here : ", data); });
// readerStream.on('error', function(err) { console.log(err.stack); });
// console.log("Program Read Ended"); |
C++ | UTF-8 | 1,612 | 3.0625 | 3 | [] | no_license |
//
// myString.cpp
// Hw5
//
// Created by Emil Iliev on 1/13/16.
// Copyright © 2016 Emil Iliev. All rights reserved.
//
#include "myString.hpp"
#include <string.h>
#include <iostream>
MyString::MyString(){
setLength(0);
allocatedLength = 1;
this->data = new char[allocatedLength];
data[0] = '\0';
}
MyString::MyString(char* _data){
setData(_data);
}
MyString::~MyString(){
del();
}
MyString::MyString(MyString const &other){
copyFrom(other);
}
MyString& MyString::operator=(MyString const &other){
if(this != &other){
del();
copyFrom(other);
}
return *this;
}
void MyString::setData(char* _data){
del();
size_t newLength = strlen(_data) + 1;
setLength(newLength);
this->data = new char[newLength];
strcpy(data, _data);
allocatedLength = newLength;
}
void MyString::setLength(size_t _length){
this->length = _length;
}
size_t MyString::getLength(){
return this->length;
}
void MyString::append(char* symbol){
if(allocatedLength <= length) {
resize();
}
data[length++] = *symbol;
}
char* MyString::getData(){
return this->data;
}
void MyString::copyFrom(MyString const &other){
setLength(other.length);
setData(other.data);
}
void MyString::del(){
delete [] data;
data = NULL;
length = 0;
}
void MyString::resize(){
allocatedLength *= 2;
char* buffer = new char[allocatedLength];
strcat(buffer, data);
delete [] data;
data = buffer;
}
|
Java | UTF-8 | 4,688 | 3.09375 | 3 | [] | no_license | package ArvoreBinaria;
public class Tree {
private No root;
public Tree() {
this.root = null;
}
public void insert (double value) {
No neww = new No();
neww.item = value;
neww.right = null;
neww.left = null;
if(root == null)
root = neww;
else {
No current = root;
No previos;
while(true) {
previos = current;
if(value <= current.item) {
current = current.left;
if(current == null) {
previos.left = neww;
return;
}
}else {
current = current.right;
if(current == null) {
previos.right = neww;
return;
}
}
}
}
}
public No seach (double key) {
if(root == null)
return null;
No current = root;
while(current.item != key) {
if(key < current.item)
current = current.left;
else
current = current.right;
if(current == null)
return null;
}
return current;
}
public int grauNo (No current) {
if(current == null)
return 0;
if((current.left != null && current.right == null) || current.left == null && current.right != null)
return 1;
if(current.left != null && current.right != null)
return 2;
return 0;
}
public int depth (double key) {
int value = 0;
if(root == null)
return -1;
No current = root;
while(current.item != key) {
if(key < current.item) {
current = current.left;
value ++;
}
else {
current = current.right;
value ++;
}
}
return value;
}
public int levels (double key) {
int value = 0;
if(root == null)
return -1;
No current = root;
while(current.item != key) {
if(key < current.item) {
current = current.left;
value ++;
}
else {
current = current.right;
value ++;
}
}
return value;
}
public No inversor () {
return root;
}
public boolean remove (double value) {
if(root == null)
return false;
No current = root;
No dad = root;
boolean son_left = true;
while(current.item != value ) {
dad = current;
if(value < current.item) {
current = current.left;
son_left = true;
}else {
current = current.right;
son_left = false;
}
if(current == null)
return false;
}
if(current.left == null && current.right == null) {
if(current == root)
root = null;
else if (son_left)
dad.left = null;
else dad.right = null;
}
else if (current.left == null ) {
if(current == root)
root = current.right;
else if(son_left)
dad.left = current.right;
else
dad.right = current.right;
}else {
No successor = no_successor(current);
if(current == root)
root = successor;
else if (son_left)
dad.left = successor;
else
dad.right = successor;
successor.left = current.left;
}
return true;
}
// Metodo para ajudar na remoção
public No no_successor(No delete) {
No dadSuccessor = delete;
No successor = delete;
No current = delete.right;
while (current != null) {
dadSuccessor = successor;
successor = current;
current = current.left;
}
if (successor != delete.right) {
dadSuccessor.left = successor.right;
successor.right = delete.right;
}
return successor;
}
public int height (No current) {
if(current == null || (current.left == null && current.right == null))
return 0;
else {
if(height(current.left)> height(current.right))
return (1 + height(current.left));
else
return (1 + height(current.right));
}
}
public int sheets(No current) {
if(current == null)
return 0;
if(current.left == null && current.right == null)
return 1;
return sheets(current.left) + sheets(current.right);
}
public int countNo(No current) {
if(current == null)
return 0;
else
return(1 + countNo(current.left) + countNo(current.right));
}
// Navegar pela arvore
public void inOrdem(No current) {
if(current != null) {
inOrdem(current.left);
System.out.println(current.item + "");
inOrdem(current.right);
}
}
public void preOrdem(No current) {
if(current != null) {
System.out.println(current.item + "");
preOrdem(current.left);
preOrdem(current.right);
}
}
public void posOrdem(No current) {
if(current != null) {
posOrdem(current.left);
posOrdem(current.right);
System.out.println(current.item + "");
}
}
public void walk () {
System.out.println("Em Ordem: ");
inOrdem(root);
System.out.println("Pre-Ordem: ");
preOrdem(root);
System.out.println("Pos-Ordem: ");
posOrdem(root);
}
}
|
TypeScript | UTF-8 | 1,035 | 2.6875 | 3 | [] | no_license | import { Song } from './Song';
export class Album {
private _songs: Song[];
public get songs(): Song[] {
return this._songs;
}
private _name: string;
public get name(): string {
return this._name;
}
public set name(v: string) {
this._name = v;
}
private _author: string;
public get author(): string {
return this._author;
}
public set author(v: string) {
this._author = v;
}
private _grade: number;
public get grade(): number {
return this._grade;
}
public set grade(v: number) {
this._grade = v;
}
private _src : string;
public get src() : string {
return this._src;
}
public set src(v : string) {
this._src = v;
}
constructor(name: string, author: string, grade: number, songs: Song[], src: string) {
this._name = name;
this._author = author;
this._grade = grade;
this._songs = songs;
this._src = src
}
} |
Java | UTF-8 | 672 | 3.640625 | 4 | [] | no_license | package com.techlab.unittesting;
import java.lang.reflect.Type;
public class UnitTestingExample {
public int cubeOfEven(int number) throws Exception {
int cubeOfEvenNumber;
if (number % 2 == 1) {
throw new Exception("Dont pass odd numbers");
}
if (number == (double) number) {
throw new Exception("Dont pass numbers of type Double");
}
if (number == (float) number) {
throw new Exception("Dont pass numbers of type Float");
}
if (number < 0) {
throw new Exception("Dont pass negative numbers");
}
if (number % 2 == 1 && number < 0) {
throw new Exception("Dont enter negative odd numbers");
}
return number * number * number;
}
}
|
PHP | UTF-8 | 4,762 | 2.65625 | 3 | [] | no_license | <?php
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Copyright: Mathijs Baaijens, Iris Bekker, Renze Droog,
* Maarten van Duren, Jeroen Hanselman, Bert Massop, Robin van der Ploeg,
* Tom Tervoort, Gerben van Veenendaal, Tom Wennink.
*/
require_once 'controllers/controllerbase.php';
require_once 'models/scan/scanlist.php';
require_once 'models/upload/upload.php';
require_once 'models/binding/binding.php';
require_once 'util/authentication.php';
require_once 'models/scan/scan.php';
/**
* Scan controller class.
*/
class ScanController extends ControllerBase
{
/**
* Loads scans.
*/
public function actionLoad($data)
{
// Handle load.
$defaultSorters = array(
array('column' => 'page', 'direction' => 'ASC'),
array('column' => 'scanId', 'direction' => 'ASC')
);
$result = $this->handleLoad($data, 'Scan', 'scanId', array(
'scanId',
'bindingId',
'page',
'status',
'width',
'height',
'zoomLevel',
'scanName',
'bookTitle'
), $defaultSorters);
foreach ($result['records'] as $id => $scan)
{
$result['records'][$id]['location'] = Scan::getLocation($scan['scanId']);
}
return $result;
}
/**
* Reorders the scans of a binding
*/
public function actionReorder($data)
{
// Assert the user has permission to upload bindings.
Authentication::assertPermissionTo('upload-bindings');
Database::getInstance()->doTransaction(function() use ($data)
{
// Collect the binding id and ordered scans from the request.
$inputBindingId = Controller::getInteger($data, 'bindingId');
$inputOrderedScans = Controller::getArray($data, 'orderedScans');
$inputDeletedScans = Controller::getArray($data, 'deletedScans');
// Load the binding to be modified from the database.
$binding = new Binding($inputBindingId);
$binding->load(true);
$binding->loadDetails(true);
$page = 0;
$deleteBookPageNumbers = false;
// Iterate over all scans in the provided new order.
foreach ($inputOrderedScans as $key => $scanId)
{
$page++;
$scan = $binding->getScanList()->getByKeyValue('scanId', $scanId);
// Determine if the page number changed for this scan. If this is the case update
// the scan in the database.
if ($scan != null && $page != $scan->getPage())
{
$scan->setPage($page);
$scan->setMarkedAsUpdated(true);
$deleteBookPageNumbers = true;
}
}
// Iterate over all scans to be deleted.
foreach ($inputDeletedScans as $key => $scanId)
{
// Get the scan from the binding and mark it as deleted.
$scan = $binding->getScanList()->getByKeyValue('scanId', $scanId);
$scan->setStatus(Scan::STATUS_DELETED);
$scan->setUploadId(null);
$scan->save();
$deleteBookPageNumbers = true;
// Deleted any associated uploads.
if ($scan->getUploadId() !== null)
{
$upload = new Upload($scan->getUploadId());
$upload->load(true);
$upload->delete();
}
}
// Determine if the order of scans has changed. If this is the case clear the starting page
// and ending page for all books in this binding.
if ($deleteBookPageNumbers === true)
{
foreach ($binding->getBookList() as $book)
{
$book->setFirstPage(null);
$book->setLastPage(null);
$book->setMarkedAsUpdated(true);
}
}
// Update the binding status/
$binding->setStatus(Binding::STATUS_REORDERED);
$binding->saveWithDetails();
});
}
}
|
Java | UTF-8 | 653 | 2.25 | 2 | [] | no_license | package com.it.SpringPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
@Component
public class SpringServer1 {
private SpringServer1() {
// TODO Auto-generated method stub
System.out.println("SpringServer1 init...");
}
@Autowired
private ApplicationEventPublisher eventPublisher;
public void push() {
//创建事件
MyEvent e = new MyEvent();
e.setFlage(true);
//发布事件,然后触发监听
eventPublisher.publishEvent(e);
}
}
|
PHP | UTF-8 | 5,559 | 2.59375 | 3 | [] | no_license | <?php
session_start();
require_once '../../model/connection.php';
require_once '../../model/usersModel.php';
require_once '../../model/categoriesModel.php';
require_once '../../model/orderModel.php';
require_once '../../model/pagesModel.php';
$categories = getAllCategoriesForNavigation($connection);
$pagesNavigation = getAllPages($connection);
$defaultFormData = array(
);
$pageTitle = "Checkout";
//ovde se smestaju greske koje imaju polja u formi
$formErrors = array();
//u promenljivu $formData stavljate $_GET ili $_POST u zavisnosti od forme
$formData = $_POST; // $_GET ili $_POST
//uvek se prosledjuje jedno polje koje je indikator da su podaci poslati sa forme
//odnosno da je korisnik pokrenuo neku akciju
//kod nas to polje ce biti SUBMIT dugme
if (isset($formData["click"]) && $formData["click"] == "Finish Order") {
/* * ********* filtriranje i validacija polja *************** */
if (isset($formData["name"])) {
//Filtering 1
$formData["name"] = trim($formData["name"]);
$formData["name"] = strip_tags($formData["name"]);
//Validation - if required
if ($formData["name"] === "") {
$formErrors["name"][] = "Polje name ne sme biti prazno";
} else {
if (mb_strlen($formData["name"]) <= 3 || mb_strlen($formData["name"]) > 50) {
$formErrors["name"][] = "Polje name mora imati vise od 3 a manje od 50 karaktera";
}
}
} else {
//if required
$formErrors["name"][] = "Polje name mora biti prosledjeno";
}
/* * ********* filtriranje i validacija polja *************** */
if (isset($formData["surname"])) {
//Filtering 1
$formData["surname"] = trim($formData["surname"]);
$formData["surname"] = strip_tags($formData["surname"]);
//Validation - if required
if ($formData["surname"] === "") {
$formErrors["surname"][] = "Polje surname ne sme biti prazno";
} else {
if (mb_strlen($formData["surname"]) <= 3 || mb_strlen($formData["name"]) > 50) {
$formErrors["surname"][] = "Polje surname mora imati vise od 3 a manje od 50 karaktera";
}
}
} else {
//if required
$formErrors["name"][] = "Polje name mora biti prosledjeno";
}
/* * ********* filtriranje i validacija polja *************** */
if (isset($formData["email"])) {
//Filtering 1
$formData["email"] = trim($formData["email"]);
$formData["email"] = strip_tags($formData["email"]);
//Validation - if required
if ($formData["email"] === "") {
$formErrors["email"][] = "Polje email ne sme biti prazno";
} else {
if (filter_var($formData["email"], FILTER_VALIDATE_EMAIL) === false) {
$formErrors["email"][] = "Email nije u validnom formatu";
} else {
// check is product title is unique (already exists in database)
if (!checkEmailIsUnique($formData['email'], $connection)) {
$formErrors["email"][] = "User with this email already exists!!! Choose another email for user!!!";
}
}
}
} else {
//if required
$formErrors["email"][] = "Polje email mora biti prosledjeno";
}
/* * ********* filtriranje i validacija polja *************** */
if (isset($formData["phone"])) {
//Filtering 1
$formData["phone"] = trim($formData["phone"]);
$formData["phone"] = strip_tags($formData["phone"]);
//Validation - if required
if ($formData["phone"] === "") {
$formErrors["phone"][] = "Polje password ne sme biti prazno";
} else {
if (mb_strlen($formData["phone"]) <= 4 || mb_strlen($formData["phone"]) > 50) {
$formErrors["phone"][] = "Polje password mora imati vise od 4 a manje od 50 karaktera";
}
}
} else {
//if required
$formErrors["phone"][] = "Polje password mora biti prosledjeno";
}
/* * ********* filtriranje i validacija polja *************** */
if (isset($formData["address"])) {
//Filtering 1
$formData["address"] = trim($formData["address"]);
$formData["address"] = strip_tags($formData["address"]);
//Validation - if required
if ($formData["address"] === "") {
$formErrors["address"][] = "Polje address ne sme biti prazno";
} else {
if (mb_strlen($formData["address"]) <= 10 || mb_strlen($formData["address"]) > 200) {
$formErrors["address"][] = "Polje address mora imati vise od 10 a manje od 200 karaktera";
}
}
} else {
//if required
$formErrors["address"][] = "Polje address mora biti prosledjeno";
}
//Ukoliko nema gresaka
if (empty($formErrors)) {
$lastID = insertOrder($connection, $formData);
if (isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
foreach ($cart as $product) {
insertOrderProduct($connection, $lastID, $product);
$_SESSION[systemMessage] = "Order was successful";
header('Location:/shopping-cart/success-order.php');
}
}
}
}
require_once '../../view/headerView.php';
require_once '../../view/navigationView.php';
require_once '../../view/shopping-cart/checkoutView.php';
require_once '../../view/footerView.php';
|
C# | UTF-8 | 632 | 2.828125 | 3 | [
"MIT"
] | permissive | using System;
using System.Reflection;
namespace ObservableComputations.ExtentionMethods
{
internal static partial class ExtensionMethods
{
public static bool IsReadOnly(this MemberInfo memberInfo)
{
PropertyInfo propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != null)
{
return !propertyInfo.CanWrite;
}
else
{
FieldInfo fieldInfo = memberInfo as FieldInfo;
if (fieldInfo != null)
{
return fieldInfo.IsInitOnly;
}
else
{
throw new Exception("Неизвестный наследник MemberInfo");
}
}
}
}
} |
PHP | UTF-8 | 1,103 | 2.78125 | 3 | [] | no_license | <?php
namespace RateHub\NewRelic\Exceptions;
use RateHub\NewRelic\Contracts\Exceptions\ExceptionFilter;
final class AggregateExceptionFilter implements ExceptionFilter
{
/**
* @var ExceptionFilter[]
*/
private $exceptionFilters;
/**
* @param ExceptionFilter[] $exceptionFilters
*/
public function __construct(array $exceptionFilters)
{
if (count($exceptionFilters) === 0) {
throw new \InvalidArgumentException('You must provide at least one exception filter');
}
foreach ($exceptionFilters as $exceptionFilter) {
if (!$exceptionFilter instanceof ExceptionFilter) {
throw new \InvalidArgumentException('Invalid exception filter');
}
}
$this->exceptionFilters = $exceptionFilters;
}
public function shouldReport(\Throwable $exception): bool
{
foreach ($this->exceptionFilters as $exceptionFilter) {
if (!$exceptionFilter->shouldReport($exception)) {
return false;
}
}
return true;
}
}
|
Java | UTF-8 | 794 | 2.109375 | 2 | [] | no_license | package com.cts.training.SeriesModelService.controller;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import com.cts.training.SeriesModelService.model.ModelModel;
import com.cts.training.SeriesModelService.model.SeriesModel;
import io.swagger.annotations.Api;
@Api(value = "series-model controller",description = "for accessing series and models of cars available")
public interface ISeriesModelController {
public ResponseEntity<List<SeriesModel>> getAllSeries();
public ResponseEntity<List<ModelModel>> getModelBySeriesId(@PathVariable Integer seriesId);
public ResponseEntity<ModelModel> getModelById(@PathVariable Integer modelId);
public ResponseEntity<List<ModelModel>> getAllModels();
}
|
Python | UTF-8 | 460 | 3.65625 | 4 | [] | no_license | def printSubSequences(STR, subSTR=""):
"""
function:
To print all subsequences of string
concept:
Pick and Don’t Pick
variables:
STR = string
subSTR = to store subsequence
"""
if len(STR) == 0:
print(subSTR, end=" ")
return
printSubSequences(STR[:-1], subSTR + STR[-1])
printSubSequences(STR[:-1], subSTR)
return
S = "bcade"
K = 3
printSubSequences(S) |
Ruby | UTF-8 | 1,534 | 3.328125 | 3 | [] | no_license | require './test/test_helper'
require './lib/writer'
class WriterTest < Minitest::Test
def test_it_is_a_thing
write = Writer.new
assert_instance_of(Writer, write)
end
def test_can_convert_single_letter_to_array_of_braille
writer = Writer.new
assert_equal(["0.", "..", ".."], writer.convert("a"))
end
def test_can_convert_and_return_two_letters
write = Writer.new
assert_equal(["0.0.", "..0.", "...."], write.convert("ab"))
end
def test_can_convert_uppercase_letters
write = Writer.new
assert_equal(["..0.", "....", ".0.."], write.convert("A"))
end
def test_can_convert_two_uppercase_letters
write = Writer.new
assert_equal(["..0...0.", "..0.....", ".0...0.."], write.convert("BA"))
end
def test_can_convert_one_uppercase_and_one_lowercase
write = Writer.new
assert_equal(["..0.0.", "..0...", ".0...."], write.convert("Ba"))
end
def test_constrains_to_80_characters
write = Writer.new
actual_string = "a" * 40 + "z"
assert_equal(41, actual_string.length)
assert_equal(actual_string, actual_string.downcase)
expected = ["0." * 40, ".." * 40, ".." * 40, "0.", ".0", "00"]
assert_equal(expected, write.convert(actual_string))
end
def test_constrains_to_80_characters_from_78_to_82_points
write = Writer.new
actual_string = "a" * 39 + "A"
assert_equal(40, actual_string.length)
expected = ["0." * 39, ".." * 39, ".." * 39, "..0.", "....", ".0.."]
assert_equal(expected, write.convert(actual_string))
end
end
|
Rust | UTF-8 | 9,815 | 2.640625 | 3 | [
"MIT"
] | permissive | // Copyright (c) 2018 10X Genomics, Inc. All rights reserved.
// This file contains an equivalence relation struct. There is a literature on
// this and multiple rust implementations of sophisticated algorithms, see:
//
// 1. https://en.wikipedia.org/wiki/Disjoint-set_data_structure
// 2. https://crates.io/crates/union-find
// 3. https://crates.io/crates/disjoint-sets
// 4. https://crates.io/crates/disjoint-set [seems defunct]
// 5. https://crates.io/crates/fera-unionfind
//
// The code here is an optimized and rustified version of the code in the 10X
// supernova codebase, which was adopted from the BroadCRD codebase. The code here
// uses a very naive algorithm that should not be competitive with the sophisticated
// algorithms, but for unknown reasons, it is. There are some comparisons to the
// disjoint-sets crate at the end of this file. The implementations in other
// crates were not tested.
use std::mem::swap;
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// EQUIVALENCE RELATION
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// Computational performance of EquivRel:
// - storage = 3N bytes, where N is the set size; storage is flat
// - initialization time = O(N)
// - time to make n joins = O( n * log(N) )
// - time to find all orbit reps = O(N)
// - time to find an orbit = O(size of orbit)
// - time to find the size of an orbit = O(1)
// - time to find the class id of an element = O(1).
pub struct EquivRel {
x: Vec<i32>, // next element in orbit
y: Vec<i32>, // orbit class id
z: Vec<i32>, // orbit size
}
impl EquivRel {
pub fn new(n: i32) -> EquivRel {
let mut xx: Vec<i32> = Vec::with_capacity(n as usize);
let mut yy: Vec<i32> = Vec::with_capacity(n as usize);
let mut zz: Vec<i32> = Vec::with_capacity(n as usize);
for i in 0..n {
xx.push(i);
yy.push(i);
zz.push(1);
}
EquivRel {
x: xx,
y: yy,
z: zz,
}
}
pub fn from_raw(xx: Vec<i32>, yy: Vec<i32>, zz: Vec<i32>) -> EquivRel {
EquivRel {
x: xx,
y: yy,
z: zz,
}
}
pub fn join(&mut self, a: i32, b: i32) {
let mut ax = a;
let mut bx = b;
if self.y[ax as usize] != self.y[bx as usize] {
// Always move the smaller orbit. This is critical as otherwise
// complexity of join would be O( n * N ) and not O( n * log(N) ).
if self.orbit_size(ax) < self.orbit_size(bx) {
swap(&mut ax, &mut bx);
}
// Now do the move.
let new_size = self.orbit_size(ax) + self.orbit_size(bx);
self.x.swap(ax as usize, bx as usize);
let mut n = self.x[ax as usize];
loop {
if self.y[n as usize] == self.y[ax as usize] {
break;
}
self.y[n as usize] = self.y[ax as usize];
n = self.x[n as usize];
}
// Update orbit size.
self.z[self.y[bx as usize] as usize] = new_size;
}
}
pub fn orbit_reps(&self, reps: &mut Vec<i32>) {
reps.clear();
for i in 0..self.x.len() {
if i == self.y[i] as usize {
reps.push(i as i32);
}
}
}
pub fn norbits(&self) -> usize {
let mut n = 0;
for i in 0..self.x.len() {
if i == self.y[i] as usize {
n += 1;
}
}
n
}
pub fn orbit_size(&self, a: i32) -> i32 {
self.z[self.y[a as usize] as usize]
}
// orbit: compute the orbit o of an element. The simplest thing is for o
// to be a Vec<i32>, but often it is convenient to instead have it be a
// Vec<usize>.
pub fn orbit<T: From<i32>>(&self, a: i32, o: &mut Vec<T>) {
o.clear();
// o.reserve( self.orbit_size(a) as usize ); // weirdly slower
o.push(T::from(a));
let mut b = a;
loop {
b = self.x[b as usize];
if b == a {
break;
}
o.push(T::from(b));
}
}
pub fn class_id(&self, a: i32) -> i32 {
self.y[a as usize]
}
}
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// PERFORMANCE COMPARISONS
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// Comparison to the disjoint-sets crate. Note that with disjoint sets, it is not
// clear how to find just one orbit, or the size of one orbit. Two comparisons
// were carried out. The first comparison follows. Briefly, it shows that
// disjoint-sets is faster for this use case, but uses more memory, and in short,
// the conclusion is a "toss-up".
/*
// Setup.
const N : usize = 10_000_000;
const L : usize = 20_000_000;
let mut x : Vec<i64> = vec![ 0; L ];
make_random_vec( &mut x, L );
for i in 0..L { x[i] = x[i].abs() % (N as i64); }
let peak = peak_mem_usage_bytes();
let t = Instant::now( );
// EquivRel version (use this or the following)
// there are 1618950 orbits
// 2.6 seconds, delta peak mem = 137 Mb
let mut e = EquivRel::new(N as i32);
for j in 0..L/2 { e.join( x[j] as i32, x[j+L/2] as i32 ); }
let mut reps = Vec::<i32>::new();
e.orbit_reps( &mut reps );
println!( "there are {} orbits", reps.len() );
let mut o = Vec::<i32>::new();
for i in 0..reps.len() { e.orbit( reps[i] as i32, &mut o ); }
// UnionFind version (use this or the previous);
// there are 1618950 orbits
// 1.5 seconds, delta peak mem = 258 Mb
// disjoint-sets = "0.4.2"
// extern crate disjoint_sets;
use disjoint_sets::UnionFind;
let mut uf = UnionFind::<u32>::new(N as usize);
for j in 0..L/2 { uf.union( x[j] as u32, x[j+L/2] as u32 ); }
let reps = uf.to_vec();
let mut repsx = Vec::<(u32,u32)>::new();
for i in 0..reps.len() { repsx.push( (reps[i],i as u32) ); }
repsx.sort();
let mut o = Vec::<u32>::new();
let mut orbits = Vec::<Vec<u32>>::new();
for i in 0..repsx.len() {
if i > 0 && repsx[i].0 != repsx[i-1].0 {
orbits.push( o.clone() );
o.clear();
}
o.push( repsx[i].1 );
}
orbits.push( o.clone() );
println!( "there are {} orbits", orbits.len() );
// Summarize.
let delta_peak = peak_mem_usage_bytes() - peak;
println!(
"{} seconds used, delta peak mem = {} bytes", elapsed(&t), delta_peak );
*/
// The second comparison involves a change to the code in hyper.rs. Here is the
// relevant chunk of code, using EquivRel:
/*
// Find nodes in the transformed graph. They are orbits of edge ends under
// the natural equivalence relation.
let mut eq : EquivRel = EquivRel::new( 2 * edges.len() as i32 );
for i in 0..adj.len() {
let left = adj[i].0;
let right = adj[i].1;
eq.join( 2*left + 1, 2*right );
}
let mut reps = Vec::<i32>::new();
eq.orbit_reps( &mut reps );
// Now actually create the transformed graph.
g_out.clear();
g_out.reserve_exact_nodes( reps.len() );
g_out.reserve_exact_edges( edges.len() );
for i in 0..reps.len() { g_out.add_node(i as u32); }
for e in 0..edges.len() {
let v = bin_position( &reps, &eq.class_id((2*e) as i32) );
let w = bin_position( &reps, &eq.class_id((2*e+1) as i32) );
g_out.add_edge( NodeIndex::<u32>::new(v as usize),
NodeIndex::<u32>::new(w as usize), edges[e].2.clone() );
}
}
*/
// and here is the relevant chunk of code using disjoint-sets:
/*
use disjoint_sets::UnionFind;
// Find nodes in the transformed graph. They are orbits of edge ends under
// the natural equivalence relation.
let mut eq = UnionFind::<u32>::new( 2 * edges.len() );
for i in 0..adj.len() {
let left = adj[i].0 as u32;
let right = adj[i].1 as u32;
eq.union( 2*left + 1, 2*right );
}
let mut reps = eq.to_vec(); // list of orbit representatives
reps.sort();
// Now actually create the transformed graph.
g_out.clear();
g_out.reserve_exact_nodes( reps.len() );
g_out.reserve_exact_edges( edges.len() );
for i in 0..reps.len() { g_out.add_node(i as u32); }
for e in 0..edges.len() {
let v = bin_position( &reps, &eq.find( (2*e) as u32) );
let w = bin_position( &reps, &eq.find( (2*e+1) as u32) );
g_out.add_edge( NodeIndex::<u32>::new(v as usize),
NodeIndex::<u32>::new(w as usize), edges[e].2.clone() );
*/
// Performance comparison: the test consisted of running the assemblies for
// 14 VDJ samples. The actual test is not described here, but the results are
// as follows:
//
// version server seconds peak mem GB
// EquivRel 1366.10 7.65
// disjoint-sets 1570.20 13.45
//
// Of course one ought to be able to define a reproducible test that exhibits this
// performance difference.
|
Java | UTF-8 | 3,266 | 3.046875 | 3 | [] | no_license | package Parser;
import java.io.*;
import java.util.ArrayList;
import Compile.Translator;
import DataTypes.Token;
import Errors.InvalidSyntaxException;
import SharedResources.InputType;
public class Lexer {
private static String buffer = "";
private static ArrayList<Token> tokens = new ArrayList<>();
private static InputType m = InputType.NORMAL;
private static int lineNumber = 0;
public static void read(String filename) throws IOException, InvalidSyntaxException
{
File file = new File(filename);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = bufferedReader.readLine();
while (line != null)
{
lineNumber++;
tokenizeString(line);
clearBlankTokens();
Translator.handleLine(tokens);
line = bufferedReader.readLine();
tokens.clear();
m = InputType.NORMAL;
}
fileReader.close();
}
private static void tokenizeString(String line)
{
for (char c : line.toCharArray())
{
// NORMAL MODE
if (m == InputType.NORMAL)
readInputNormal(c);
// ARGUMENT MODE
else if (m == InputType.ARGUMENTS)
readInputArgument(c);
// STRING MODE
else if (m == InputType.STRING)
readInputString(c);
}
endTokenAndSwitchType(InputType.NORMAL);
}
private static void readInputNormal(char c) {
if ( c == ' ' || c == '\n' || c == ';' || c == '\t')
endTokenAndSwitchType(InputType.NORMAL);
// SYMBOLS
else if ( c == '+' || c == '-' || c == '/' || c == '*'
|| c == '&' || c == '|'
|| c == '(' || c == ')'
|| c == '{' || c == '}'
|| c == '!' || c == ','
|| c == '[' || c == ']')
{
endTokenAndSwitchType(InputType.NORMAL);
buffer += c;
endTokenAndSwitchType(InputType.NORMAL);
}
else if (c == '=' && buffer.equals("="))
{
buffer += c;
endTokenAndSwitchType(InputType.NORMAL);
}
else if (c == '"')
endTokenAndSwitchType(InputType.STRING);
else
buffer += c;
}
private static void readInputArgument(char c) {
if ( c == ',' && m == InputType.ARGUMENTS )
endTokenAndSwitchType(InputType.ARGUMENTS);
}
private static void readInputString(char c) {
if (c == '"')
endTokenAndSwitchType(InputType.NORMAL);
else
buffer += c;
}
private static void clearBlankTokens()
{
int i = 0;
while ( i < tokens.size() )
{
if (tokens.get(i).getContent().equals(""))
tokens.remove(i);
else
i++;
}
}
private static void endTokenAndSwitchType(InputType it)
{
tokens.add( new Token(buffer, m) );
buffer = "";
m = it;
}
public static int getLineNumber()
{
return lineNumber;
}
}
|
Java | UTF-8 | 258 | 1.515625 | 2 | [] | no_license | package com.ms.test.repository;
import org.springframework.data.repository.CrudRepository;
import com.ms.test.beans.Message;
/**
* MessageRepository
* @author Manish
*
*/
public interface MessageRepository extends CrudRepository<Message, Integer> {
} |
C# | UTF-8 | 1,404 | 2.625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TrustyLadder.Models.DataGridModels
{
public class InMemoryServicesDataGridContext
{
const string SessionKey = "8c6f2106-d4fA-4057-b267-55afa3cf3890";
public ICollection<ServicesDataGrid> Services
{
get
{
TLDBEntities _context = new TLDBEntities();
var session = HttpContext.Current.Session;
if (session[SessionKey] == null)
{
session[SessionKey] = _context.tl_services.Select(i => new ServicesDataGrid
{
id = i.id,
description = i.description,
rate = i.rate,
})
.ToList();
}
var tl_services = _context.tl_services.Select(i => new ServicesDataGrid{
id = i.id,
description = i.description,
rate = i.rate,
})
.ToList();
return (ICollection<ServicesDataGrid>)session[SessionKey];
}
}
public void SaveChanges()
{
foreach (var service in Services.Where(a => a.id == 0))
{
service.id = Services.Max(a => a.id) + 1;
}
}
}
} |
Java | UTF-8 | 986 | 2.109375 | 2 | [] | no_license | package entidades;
public class reclaTecniProce {
private String car_proc_pendiente;
private int plazo;
private String cod_agrupacion;
private int plazo_adic1;
private int plazo_adic2;
public void setCarProcPendiente(String car_proc_pendiente) {
this.car_proc_pendiente = car_proc_pendiente;
}
public String getCarProcPendiente() {
return car_proc_pendiente;
}
public void setPlazo(int plazo) {
this.plazo=plazo;
}
public int getPlazo() {
return plazo;
}
public void setCodAgrupacion(String cod_agrupacion) {
this.cod_agrupacion = cod_agrupacion;
}
public String getCodAgrupacion() {
return cod_agrupacion;
}
public void setPlazoAdic1(int plazo_adic1) {
this.plazo_adic1 = plazo_adic1;
}
public int getPlazoAdic1() {
return plazo_adic1;
}
public void setPlazoAdic2(int plazo_adic2) {
this.plazo_adic2 = plazo_adic2;
}
public int getPlazoAdic2() {
return plazo_adic2;
}
}
|
JavaScript | UTF-8 | 291 | 3.03125 | 3 | [] | no_license | var d = new Date();
var dob = new Date("September 12, 2019");
var dtime = d.getTime();
var dobtime = dob.getTime();
var msDiff = dobtime - dtime;
console.log(msDiff);
var dateDiff = msDiff/(1000*60*60*24);
console.log(dateDiff);
dateDiff = Math.floor(dateDiff);
console.log(dateDiff);
|
C | UTF-8 | 11,287 | 3.046875 | 3 | [] | no_license | #include <geekos/fmt.h>
#include <math.h>
/* HELPER FUNCTIONS */
int minimum(int a, int b){
if(a < b)
return a;
return b;
}
//gets the block number for a <inode index>
int getBlockForIndex(int index){
int number_of_i_node_per_block = BLOCK_SIZE/sizeof(Inode);
return i_node_manager->start_i_node_block + index/number_of_i_node_per_block;
}
//gets the first empty inode position
int getFirstEmpty(char[] bitmap, int max_bitmap_size){
//bitmap : 1 block
//max_bitmap_size : max bitmaps allowed in that block(or overflow)
int i,pos_in_char;
for(i = 0 ; i < BLOCK_SIZE; i++){
int current_location_max = max_bitmap_size - i*8;
//Might have to use "unsigned int" conversion of char
int power_of_2 = 0x80;
for(pos_in_char = 0; pos_in_char < 8; pos_in_char++){
if(current_location_max > pos_in_char && (bitmap[i] & power_of_2 == 0))
return i*8 + pos_in_char;
power_of_2 /= 2;
}
if(current_location_max <= 8)
return -1;
}
return -1;
}
//assigns an Inode into the buffer
void writeInodeIntoBuffer(char[] buffer, int i_node_index; Inode* data){
int i_node_index_in_buffer = i_node_index%(BUFFER_SIZE/sizeof(Inode));
int start_location = i_node_index_in_buffer*sizeof(Inode);
memcpy(&(buffer[start_location]),data,sizeof(Inode));
}
//loads an inode from the buffer
int loadInodeFromBuffer(char[] i_node_block_buffer,int new_i_node_index,Inode* i_node){
int i_node_index_in_buffer = i_node_index%(BUFFER_SIZE/sizeof(Inode));
int start_location = i_node_index_in_buffer*sizeof(Inode);
memcpy(i_node,&(buffer[start_location]),sizeof(Inode));
return 0;
}
//initialises a new inode item
int initInodeItem(InodeItem* i_node_item,Inode* i_node, int i_node_index, int user_count){
i_node_item->i_node = *i_node;
i_node_item->i_node_index = i_node_index;
i_node_item->prev = NULL;
i_node_item->next = NULL;
i_node_item->user_count = user_count;
i_node_item->dirty = 0;
return 0;
}
void removeInodeItem (InodeItem* i_node_item){
if(i_node_item->prev != NULL){
i_node_item->prev->next = i_node_item->next;
}if(i_node_item->next != NULL){
i_node_item->next->prev = i_node_item->prev;
}
if(i_node_item->dirty == 1)
writeBackIntoBlock(&i_node_item->i_node, i_node_item->i_node_index);
// delete(i_node_item);
i_node_manager->cache_size--;
}
int swapOutFromCache(InodeItem** i_node_item_pointer){
//POSSIBLE BETTER CODE
InodeItem* current_i_node_item = i_node_manager->cache;
InodeItem* swappable = NULL;
while(current_i_node_item != NULL){
if(current_i_node_item->user_count == 0)
swappable = current_i_node_item;
current_i_node_item = current_i_node_item->next;
}
if(swappable == NULL)
return 0;
removeInodeItem(swappable);
(*i_node_item_pointer) = swappable;
return 1;
}
InodeItem* searchInCache(int i_node_index){
InodeItem* current_i_node_item = i_node_manager->cache;
while(current_i_node_item != NULL){
if(current_i_node_item->i_node_index == i_node_index){
return current_i_node_item;
}
}
return NULL;
}
int releaseInCache(int i_node_index){
InodeItem* current_i_node_item = i_node_manager->cache;
while(current_i_node_item != NULL){
if(current_i_node_item->i_node_index == i_node_index){
if(current_i_node_item->user_count == 0)
return -1;
current_i_node_item->user_count--;
return 1;
}
}
return 0;
}
void addToCache(Inode* i_node, int i_node_index, int increment=0){
if(i_node_manager->cache == NULL){
InodeItem* i_node_item = (InodeItem*) malloc(sizeof(InodeItem));
initInodeItem(i_node_item,i_node,i_node_index,increment);
i_node_manager->cache = i_node_item;
i_node_manager->cache_size++;
}
else if(i_node_manager->cache_size < i_node_manager->max_cache_size){
InodeItem* i_node_item = (InodeItem*) malloc(sizeof(InodeItem));
initInodeItem(i_node_item,i_node,i_node_index,increment);
i_node_manager->cache->prev = i_node_item;
i_node_item->next = i_node_manager->cache;
i_node_manager->cache = i_node_item;
cache_size++;
}else{
InodeItem* i_node_item;
int swapped_something = swapOutFromCache(&i_node_item);
if(swapped_something == 1){
initInodeItem(i_node_item,i_node,i_node_index,increment);
i_node_manager->cache->prev = i_node_item;
i_node_item->next = i_node_manager->cache;
i_node_manager->cache = i_node_item;
cache_size++;
}else{
//make the thing wait
}
}
}
void writeBackIntoBlock(Inode* i_node, int i_node_index){
char i_node_block_buffer[BLOCK_SIZE];
//Fetch that Inode
int i_node_block = getBlockForIndex(i_node_manager,i_node_index);
Fegade_getBlock(i_node_block,&i_node_block_buffer);
writeInodeIntoBuffer(i_node_block_buffer,new_i_node_index,i_node);
//Write Back
// Fegade_setDirtyBlock(i_node_block);
Fegade_writeIntoBlock(i_node_block,i_node_block_buffer);
}
int getNextBlock(int *i_1,int *i_2,int *i_3){
int &index_1 = *i_1;
int &index_2 = *i_2;
int &index_3 = *i_3;
if(index_1 <= 11){
index_1 = 12; index_2 = -1; index_3 = -1;
}else if(index_1 == 12 && index_2 == (BLOCK_SIZE/sizeof(int))-1){
index_1 = 13; index_2 = -1; index_3 = -1;
}else if(index_1 == 12){
index_2++;
}else if(index_1 == 13 && index_3 == (BLOCK_SIZE/sizeof(int))-1){
index_2++; index_3 = -1;
}else if(index_1 == 13){
index_3++;
}
}
int addBlockAt(Inode* i_node, int index_1, int index_2, int index_3, int block_address){
int int_size = sizeof(int);
int new_block_address;
Fegade_allocateNewBlock(&new_block_address);
if(index_2 == -1){
i_node->entries[index_1] = new_block_address;
return new_block_address;
}else{
int index = index_2;
if(index_1 == 12 || index_3 == -1)
index = index_2;
else if(index_1 == 13)
index = index_3;
char buffer[BLOCK_SIZE];
Fegade_getBlock(block_address,buffer);
memcpy(&buffer[index_2*int_size],&new_block_address,int_size);
Fegade_writeIntoBlock(block_address,buffer);
return new_block_address;
}else{
Fegade_releaseBlock(new_block_address);
return -1;
}
}
int getEntryFromBlock(int block_address,int index){
char buffer[BLOCK_SIZE];
Fegade_getBlock(block_address,buffer);
int new_block_address = ((int) buffer)[index];
// memcpy(&new_block_address,&buffer[index*sizeof(int)],sizeof(int));
return new_block_address;
}
int getBlockAddressForIndex(Inode* i_node,int index_1,int index_2,int index_3){
if(index_1 < 12)
return i_node->entries[index_1];
else if(index_1 == 12){
return getEntryFromBlock(i_node->entries[index_1],index_2);
}
else if(index_1 == 13){
int block_address = getEntryFromBlock(i_node->entries[index_1],index_2);
return getEntryFromBlock(block_address,index_3);
}
}
int getLocationOfByteAddress(int byte_address,int &index_1, int &index_2, int &index_3){
int int_size = sizeof(int);
int level_1_size = 12*BLOCK_SIZE;
int level_2_size = (BLOCK_SIZE/int_size)*BLOCK_SIZE;
int level_3_size = (BLOCK_SIZE/int_size)*(BLOCK_SIZE/int_size)*BLOCK_SIZE;
if(byte_address < 0){
return -1;
}else if(byte_address < level_1_size){
index_1 = byte_address/BLOCK_SIZE;
}else if(byte_address < level_1_size + level_2_size){
index_1 = 12;
index_2 = (byte_address - level_1_size)/BLOCK_SIZE;
}else if(byte_address < level_1_size + level_2_size + level_3_size){
index_1 = 13;
index_2 = (byte_address - level_1_size - level_2_size)/level_2_size;
index_3 = (byte_address - level_1_size - level_2_size - index_2*level_2_size)/BLOCK_SIZE;
}else{
return -1;
}
return 1;
}
/* API */
int Init_Inode_Manager(int bitmap_start_block, int bitmap_number_of_blocks,
int i_node_start_block, int i_node_number_of_blocks){
//CHANGE FROM HERE
i_node_manager->bitmap_start_block = bitmap_start_block;
i_node_manager->bitmap_number_of_blocks = bitmap_number_of_blocks;
i_node_manager->i_node_start_block = i_node_start_block;
i_node_manager->i_node_number_of_blocks = i_node_number_of_blocks;
//CHANGE TILL HERE
i_node_manager->max_cache_size = (int) CACHE_SIZE/sizeof(InodeItem);
i_node_manager->cache_size = 0;
i_node_manager->max_bitmap_size =
minimum(i_node_manager->i_node_number_of_blocks/sizeof(Inode),
i_node_manager->bitmap_number_of_blocks*BLOCK_SIZE*8);
i_node_manager->cache = NULL;
return 1;
}
void Format_Inode_Blocks(){
;//TODO: If Fegade already formats the kernel space this is not necessary
}
int Create_New_Inode(MetaData meta_data){
//Fetch the array of bitmaps
int current_block = i_node_manager->bitmap_start_block;
int bitmap_block_count = 1;
int new_i_node_index = -1;
int max_bitmap_size = i_node_manager->max_bitmap_size;
char bitmap_block_buffer[BLOCK_SIZE];
//CLEANER CODE POSSIBLE
while(new_i_node_index == -1 && bitmap_block_count <= i_node_manager->bitmap_number_of_blocks){
Fegade_getBlock(&bitmap_block_buffer);
if(max_bitmap_size > BLOCK_SIZE*8)
new_i_node_index = getFirstEmpty(bitmap_block_buffer,BLOCK_SIZE*8);
else
new_i_node_index = getFirstEmpty(bitmap_block_buffer,max_bitmap_size);
max_bitmap_size -= BLOCK_SIZE;
}
if(new_i_node_index == -1)
return -1;
//Create the I_Node
Inode i_node;
i_node.meta_data = meta_data;
writeBackIntoBlock(&i_node,new_i_node_index);
//Add to cache
addToCache(i_node);
//Return
return new_i_node_index;
}
int Load_Inode(int i_node_index, Inode** i_node){
InodeItem* searched = searchInCache(i_node_index);
if(searched != NULL){
searched->user_count++;
(*i_node) = &(searched->i_node);
return 1;
}else{
//Fetch and Initialise
char i_node_block_buffer[BLOCK_SIZE];
int i_node_block = getBlockForIndex(i_node_index);
Fegade_getBlock(i_node_block,&i_node_block_buffer);
Inode new_i_node;
loadInodeFromBuffer(i_node_block_buffer,i_node_index,&new_i_node);
addToCache(new_i_node,i_node_index,1);
(*i_node) = new_i_node;
return 1;
}
}
int Release_Inode(int i_node_index){
return releaseInCache(i_node_index);
}
int Allocate_Upto(Inode* i_node, int allocate_size){
if(allocate_size > i_node->meta_data.file_size){
i_node->meta_data.file_size = allocate_size;
}
if((int)(allocate_size/BLOCK_SIZE) <= (int)(i_node->meta_data.file_size/BLOCK_SIZE)){
return 1;
}
int start_index_1 = -1, start_index_2 = -1, start_index_3 = -1;
getLocationOfByteAddress(i_node->meta_data.file_size-1,
start_index_1,start_index_2,start_index_3);
int index_1 = -1,index_2 = -1,index_3 = -1;
int rc = getLocationOfByteAddress(allocate_size-1,index_1,index_2,index_3);
if(rc == -1)
return rc;
int next_block;
int loop_condition = true;
while(loop_condition){
loop_condition = !(start_index_1 == index_1 && start_index_2 == index_2 && start_index_3 == index_3);
getNextBlock(&start_index_1,&start_index_2,&start_index_3);
next_block = addBlockAt(i_node,start_index_1,start_index_2,start_index_3,next_block);
}
return 1;
}
int Get_Block_For_Byte_Address(Inode* i_node, int byte_address){
int index_1 = -1,index_2 = -1,index_3 = -1;
getLocationOfByteAddress(byte_address,index_1,index_2,index_3);
return getBlockAddressForIndex(i_node,index_1,index_2,index_3);
}
|
Java | UTF-8 | 16,149 | 3.421875 | 3 | [] | no_license | package fr.istic.prg1.tp6;
import java.util.Scanner;
import fr.istic.prg1.tp6.util.AbstractImage;
import fr.istic.prg1.tp6.util.Iterator;
import fr.istic.prg1.tp6.util.Node;
import fr.istic.prg1.tp6.util.NodeType;
/**
* @author Juvenal Attoumbre && Emilie DaConceicao
* @version 5.0
* @since 2021-11-22
*
* Classe décrivant les images en noir et blanc de 256 sur 256 pixels
* sous forme d'arbres binaires.
*
*/
public class Image extends AbstractImage {
private static final Scanner standardInput = new Scanner(System.in);
public Image() {
super();
}
public static void closeAll() {
standardInput.close();
}
/**
* @param x
* abscisse du point
* @param y
* ordonnée du point
* @pre !this.isEmpty()
* @return true, si le point (x, y) est allumé dans this, false sinon
*/
@Override
public boolean isPixelOn(int x, int y) {
int prof = 0;
int upperX = 0, upperY = 0;
int largeur = 256;
int hauteur;
Iterator<Node> it = this.iterator();
while (it.nodeType() != NodeType.LEAF) {
hauteur = largeur / 2;
if (prof % 2 == 0) {
if (y < hauteur + upperY) {
it.goLeft();
} else {
upperY += hauteur;
it.goRight();
}
} else {
largeur = hauteur;
if (x < upperX + largeur) {
it.goLeft();
} else {
upperX += largeur;
it.goRight();
}
}
++prof;
}
return it.getValue().state == 1;
}
/**
* this devient identique à image2.
*
* @param image2
* image à copier
*
* @pre !image2.isEmpty()
*/
@Override
public void affect(AbstractImage image2) {
Iterator <Node> it2 = image2.iterator();
Iterator <Node> it = this.iterator();
it.clear();
this.affectAux(it, it2);
}
private void affectAux(Iterator<Node> it, Iterator<Node> it2) {
it.addValue(Node.valueOf(it2.getValue().state));
if(it2.nodeType() != NodeType.LEAF){
it.goLeft();
it2.goLeft();
this.affectAux(it,it2);
it.goUp();
it2.goUp();
it.goRight();
it2.goRight();
this.affectAux(it,it2);
it.goUp();
it2.goUp();
}
}
/**
* this devient rotation de image2 à 180 degrés.
*
* @param image2
* image pour rotation
* @pre !image2.isEmpty()
*/
@Override
public void rotate180(AbstractImage image2) {
Iterator<Node> it2 = image2.iterator();
Iterator<Node> it1 = this.iterator();
//Clear this image
it1.clear();
rotate180Aux(it2, it1);
}
private void rotate180Aux(Iterator<Node> it2, Iterator<Node> it1) {
if (!it2.isEmpty()) {
it1.addValue(Node.valueOf(it2.getValue().state));
it2.goLeft();
it1.goRight();
rotate180Aux(it2, it1);
it2.goUp();
it1.goUp();
it2.goRight();
it1.goLeft();
rotate180Aux(it2, it1);
it2.goUp();
it1.goUp();
}
}
/**
* this devient rotation de image2 à 90 degrés dans le sens des aiguilles
* d'une montre.
*
* @param image2
* image pour rotation
* @pre !image2.isEmpty()
*/
@Override
public void rotate90(AbstractImage image2) {
System.out.println();
System.out.println("-------------------------------------------------");
System.out.println("Fonction non demeandée");
System.out.println("-------------------------------------------------");
System.out.println();
}
/**
* this devient inverse vidéo de this, pixel par pixel.
*
* @pre !image.isEmpty()
*/
@Override
public void videoInverse() {
Iterator<Node> it = this.iterator();
//inverse tous les nodes et ses fils
inverseAux(it);
}
private void inverseAux(Iterator<Node> it) {
if (!it.isEmpty()) {
//Process this one
if (it.getValue().state == 1) {
it.setValue(Node.valueOf(0));
}
else if (it.getValue().state == 0) {
it.setValue(Node.valueOf(1));
}
//Process the sons
it.goLeft();
inverseAux(it);
it.goUp();
it.goRight();
inverseAux(it);
it.goUp();
}
}
/**
* this devient image miroir verticale de image2.
*
* @param image2
* image à agrandir
* @pre !image2.isEmpty()
*/
@Override
public void mirrorV(AbstractImage image2) {
Iterator<Node> it = this.iterator();
it.clear();
int prof = 0;
this.mirrorVAux(it, image2.iterator(), prof);
}
private void mirrorVAux(Iterator<Node> it1, Iterator<Node> it2, int prof) {
it1.addValue(Node.valueOf(it2.getValue().state));
if(it2.nodeType() != NodeType.LEAF){
it2.goLeft();
if(prof % 2== 1) {
it1.goLeft();
} else {
it1.goRight();
}
this.mirrorVAux(it1, it2, ++prof);
it2.goUp();
it1.goUp();
--prof;
it2.goRight();
if(prof % 2 == 1) {
it1.goRight();
}else {
it1.goLeft();
}
this.mirrorVAux(it1,it2,++prof);
it1.goUp();
it2.goUp();
--prof;
}
}
/**
* this devient image miroir horizontale de image2.
*
* @param image2
* image à agrandir
* @pre !image2.isEmpty()
*/
@Override
public void mirrorH(AbstractImage image2) {
Iterator<Node> it = this.iterator();
it.clear();
int prof = 0;
this.mirrorHAux(it, image2.iterator(), prof);
}
private void mirrorHAux(Iterator<Node> it1, Iterator<Node> it2, int prof) {
it1.addValue(Node.valueOf(it2.getValue().state));
if(it2.nodeType() != NodeType.LEAF ){
it2.goLeft();
if(prof % 2 ==0){
it1.goLeft();
}else{
it1.goRight();
}
++prof;
this.mirrorHAux(it1, it2,prof);
it2.goUp();
it1.goUp();
--prof;
it2.goRight();
if(prof % 2 == 0){
it1.goRight();
}else{
it1.goLeft();
}
++prof;
this.mirrorHAux(it1, it2, prof);
it2.goUp();
it1.goUp();
--prof;
}
}
/**
* this devient quart supérieur gauche de image2.
*
* @param image2
* image à agrandir
*
* @pre !image2.isEmpty()
*/
@Override
public void zoomIn(AbstractImage image2) {
Iterator<Node> it = this.iterator();
it.clear();
int prof =0;
this.zoomInAux(it, image2.iterator(),prof);
}
private void zoomInAux(Iterator<Node> it1, Iterator<Node> it2,int prof) {
if(prof < 2){
if(it2.nodeType() != NodeType.LEAF){
it2.goLeft();
++prof;
this.zoomInAux(it1,it2,prof);
}else{
this.affectAux(it1,it2);
}
}else{
this.affectAux(it1,it2);
}
}
/**
* Le quart supérieur gauche de this devient image2, le reste de this
* devient éteint.
*
* @param image2
* image à réduire
* @pre !image2.isEmpty()
*/
@Override
public void zoomOut(AbstractImage image2) {
Iterator<Node> it1 = iterator();
it1.clear();
Iterator<Node> it2 = image2.iterator();
// si l'image à dézoomer est totalement noire
if (it2.getValue().state == 0) {
it1.addValue(Node.valueOf(0));
} else {
// Ajouter 2 au parent
it1.addValue(Node.valueOf(2));
// ajouter 0 sur la moitié droite
it1.goRight();
it1.addValue(Node.valueOf(0));
// ajouter 2 sur la moitié gauche
it1.goUp();
it1.goLeft();
it1.addValue(Node.valueOf(2));
// ajouter 0 sur le quart haut & droit
it1.goRight();
it1.addValue(Node.valueOf(0));
// Copier l'image sur le quart haut & gauche
it1.goUp();
it1.goLeft();
ZoomOutAux(it1, it2, 2);
// Remonter à la racine
it1.goRoot();
affectVal(it1);
}
}
/**
* Fonction de zoom avec les itérateurs
*
* @param it1
* @param it2
* @return false si le dernier élément parcouru était un noeud
*/
private void ZoomOutAux(Iterator<Node> it1, Iterator<Node> it2, int prof) {
if (it2.nodeType() != NodeType.SENTINEL) {
if (prof < 16) {
// affecter
it1.addValue(it2.getValue());
++prof;
// aller à gauche
it1.goLeft();
it2.goLeft();
ZoomOutAux(it1, it2, prof); // parcourir le préfixe du sous-arbre gauche
it1.goUp();
it2.goUp();
it1.goRight();
it2.goRight();
ZoomOutAux(it1, it2, prof); // parcourir le préfixe du sous-arbre droit
it1.goUp(); // replacer l'itérateur là où il était à l'appel de la méthode
it2.goUp();
} else {
// tableau =>
// 0 : somme des pixels
int[] tableau = new int[]{0}; // 0
// pixel 0 => somme -1
// pixel 1 => somme + 1
// som > -1 => 1
if (it2.nodeType() == NodeType.DOUBLE) {
majorite(it2, tableau);
} else {
tableau[0] = it2.getValue().state == 0 ? -1 : 1;
}
it1.addValue(Node.valueOf(tableau[0] > -1 ? 1 : 0));
}
}
}
/**
* Méthode pour trouver la majorité
* entre le nombre de pixels blancs & noirs
*
* @param it
* @param tableau
*/
private void majorite(Iterator<Node> it, int[] tableau) {
if (it.nodeType() != NodeType.SENTINEL) {
if (it.nodeType() == NodeType.LEAF) {
tableau[0] += it.getValue().state == 0 ? -1 : 1;
}
// aller à gauche
it.goLeft();
majorite(it, tableau); // parcourir le préfixe du sous-arbre gauche
it.goUp();
it.goRight();
majorite(it, tableau); // parcourir le préfixe du sous-arbre gauche
it.goUp(); // replacer l'itérateur là où il était à l'appel de la méthode
}
}
/**
* Méthode pour corriger un arbre
*
* @param it
*/
public void affectVal(Iterator<Node> it) {
if (it.nodeType() != NodeType.SENTINEL) {
// affecter
it.goLeft();
affectVal(it); // parcourir le préfixe du sous-arbre gauche
// Récupérer la valeur à gauche
// Avant de remonter
int left = it.nodeType() != NodeType.SENTINEL ? it.getValue().state : 0;
it.goUp();
it.goRight();
affectVal(it); // parcourir le préfixe du sous-arbre droit
// Récupérer la valeur à droite
// Avant de remonter
int right = it.nodeType() != NodeType.SENTINEL ? it.getValue().state : 1;
it.goUp(); // replacer l'itérateur là où il était à l'appel de la méthode
// Corriger l'arbre
if (it.nodeType() == NodeType.DOUBLE && left == right && left != 2) {
// retirer le noeud
it.clear();
// Remplacer par un noeud simple
it.addValue(Node.valueOf(left));
}
}
}
/**
* this devient l'intersection de image1 et image2 au sens des pixels
* allumés.
*
* @pre !image1.isEmpty() && !image2.isEmpty()
*
* @param image1 premiere image
* @param image2 seconde image
*/
@Override
public void intersection(AbstractImage image1, AbstractImage image2) {
Iterator<Node> it = this.iterator();
it.clear();
this.IntersectionAux(it, image1.iterator(), image2.iterator());
}
private void IntersectionAux(Iterator<Node> it1, Iterator<Node> it2, Iterator<Node> it3) {
if(it2.getValue().state == 0 || it3.getValue().state==0 ){
it1.addValue(Node.valueOf(0));
} else if (it2.getValue().state == it3.getValue().state) {
switch (it2.getValue().state) {
case 1 : it1.addValue(Node.valueOf(1));
break;
case 2 : it1.addValue(Node.valueOf(2));
it1.goLeft();
it2.goLeft();
it3.goLeft();
this.IntersectionAux(it1,it2, it3);
int state1 = it1.getValue().state;
it1.goUp();
it2.goUp();
it3.goUp();
it1.goRight();
it2.goRight();
it3.goRight();
this.IntersectionAux(it1,it2, it3);
int state2 = it1.getValue().state;
it1.goUp();
it2.goUp();
it3.goUp();
if(state1 == state2 && state1 != 2) {
it1.clear();
it1.addValue(Node.valueOf(state1));
}
break;
}
}else {
if(it2.getValue().state == 2){
this.affectAux(it1,it2);
}else{
this.affectAux(it1, it3);
}
}
}
/**
* this devient l'union de image1 et image2 au sens des pixels allumés.
*
* @pre !image1.isEmpty() && !image2.isEmpty()
*
* @param image1 premiere image
* @param image2 seconde image
*/
@Override
public void union(AbstractImage image1, AbstractImage image2) {
Iterator <Node> it = this.iterator();
it.clear();
this.unionAux(it, image1.iterator(),image2.iterator());
}
private void unionAux(Iterator<Node> it1, Iterator<Node> it2, Iterator<Node> it3) {
if (it2.getValue().state == 1 || it3.getValue().state == 1) {
it1.addValue(Node.valueOf(1));
} else if (it2.getValue().state == it3.getValue().state) {
switch (it2.getValue().state) {
case 0:
it1.addValue(Node.valueOf(0));
break;
case 2:
it1.addValue(Node.valueOf(2));
it1.goLeft();
it2.goLeft();
it3.goLeft();
this.unionAux(it1, it2, it3);
int state1 = it1.getValue().state;
it1.goUp();
it2.goUp();
it3.goUp();
it1.goRight();
it2.goRight();
it3.goRight();
this.unionAux(it1, it2, it3);
int state2 = it1.getValue().state;
it1.goUp();
it2.goUp();
it3.goUp();
if (state1 == state2 && state1 != 2) {
it1.clear();
it1.addValue(Node.valueOf(state1));
}
break;
}
} else {
if (it2.getValue().state == 2) {
this.affectAux(it1, it2);
} else {
this.affectAux(it1, it3);
}
}
}
/**
* Attention : cette fonction ne doit pas utiliser la commande isPixelOn
*
* @return true si tous les points de la forme (x, x) (avec 0 <= x <= 255)
* sont allumés dans this, false sinon
*/
@Override
public boolean testDiagonal() {
/*
2
/\
2 2
/\ /\
2 0 2 1
/\ /\
0 0 0 1
2
/\
1 2
/\
0 1
2
/\
2 2
/\ /\
0 1 0 1
*/
boolean isRigth = true;
int prof= 0;
Iterator<Node>it = this.iterator();
return this.testDiagonalAux(it, prof,isRigth);
}
private boolean testDiagonalAux(Iterator<Node> it, int prof, boolean isRigth) {
if(it.getValue().state==1){
return true;
}
if(it.getValue().state == 0){
return false;
}
if (prof % 2 == 0) {
it.goLeft();
++prof;
boolean gauche = this.testDiagonalAux(it, prof,false);
it.goUp();
it.goRight();
boolean droit = this.testDiagonalAux(it, prof, true);
it.goUp();
--prof;
return gauche && droit;
} else {
if (isRigth) {
it.goRight();
++prof;
boolean droit = this.testDiagonalAux(it, prof,true);
it.goUp();
--prof;
return droit;
} else {
it.goLeft();
++prof;
boolean gauche = this.testDiagonalAux(it, prof,false);
it.goUp();
--prof;
return gauche ;
}
}
}
/**
* @param x1
* abscisse du premier point
* @param y1
* ordonnée du premier point
* @param x2
* abscisse du deuxième point
* @param y2
* ordonnée du deuxième point
* @pre !this.isEmpty()
* @return true si les deux points (x1, y1) et (x2, y2) sont représentés par
* la même feuille de this, false sinon
*/
@Override
public boolean sameLeaf(int x1, int y1, int x2, int y2) {
System.out.println();
System.out.println("-------------------------------------------------");
System.out.println("Fonction à écrire");
System.out.println("-------------------------------------------------");
System.out.println();
return false;
}
/**
* @param image2
* autre image
* @pre !this.isEmpty() && !image2.isEmpty()
* @return true si this est incluse dans image2 au sens des pixels allumés
* false sinon
*/
@Override
public boolean isIncludedIn(AbstractImage image2) {
Iterator<Node> itThis = this.iterator();
Iterator<Node> it2 = image2.iterator();
if (it2.isEmpty()) {
return false; // car vide
} else {
return isIncludeNodeByNode(itThis, it2);
}
}
private boolean isIncludeNodeByNode (Iterator<Node> itThis, Iterator<Node> it2) {
boolean result = true;
if (!itThis.isEmpty() && !it2.isEmpty()) {
//Arriver au bout de la branche
if (it2.getValue().equals(Node.valueOf(0)) || itThis.getValue().equals(Node.valueOf(1))) {
result = false;
// Descendants existent
} else {
itThis.goLeft();
it2.goLeft();
if (isIncludeNodeByNode(itThis, it2)) {
itThis.goUp();
it2.goUp();
itThis.goRight();
it2.goRight();
result = isIncludeNodeByNode(itThis, it2);
} else {
result = false;
}
itThis.goUp();
it2.goUp();
}
}
//fin exploration de l'arbre
return result;
}
}
|
C++ | UTF-8 | 671 | 2.734375 | 3 | [
"MIT"
] | permissive | /*
* test.cpp
*
* Created on: 2017/03/09
* Author: tkato
*/
#include <stdio.h>
#include <stdlib.h>
#include "mmult_accel.h"
int main(void) {
int *x, *w, *y;
#define N_X 32
#define N_H 32
int n_x[] = {256,32,32};
int n_h[] = {32,32,10};
for (int i = 0; i < 3; i++) {
x = (int *) malloc(n_x[i] * sizeof(int));
w = (int *) malloc(n_x[i] * n_h[i] * sizeof(int));
y = (int *) malloc(n_h[i] * sizeof(int));
printf("test start\n");
fflush(stdout);
binary_connect(0, x, w, y, i);
printf("weight initialized.\n");
fflush(stdout);
binary_connect(1, x, w, y, i);
printf("test end\n");
free(x);
free(y);
free(w);
}
return 0;
}
|
Go | UTF-8 | 3,201 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | package couch
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/go-kivik/kivik"
)
type statusErr interface {
StatusCode() int
}
func (d *DataService) CopyRoom(ctx context.Context, src, dst string) error {
rooms := d.client.DB(ctx, "rooms")
uiConfigs := d.client.DB(ctx, "ui-configuration")
devices := d.client.DB(ctx, d.database)
// make sure all of the dst docs don't exist
exists, err := docExists(ctx, rooms, dst)
switch {
case err != nil:
return err
case exists:
return fmt.Errorf("%q already exists", dst)
}
exists, err = docExists(ctx, uiConfigs, dst)
switch {
case err != nil:
return err
case exists:
return fmt.Errorf("%q already exists", dst)
}
deviceIDs := make(map[string]string)
query := map[string]interface{}{
"selector": map[string]interface{}{
"_id": map[string]interface{}{
"$regex": src,
},
},
}
rows, err := devices.Find(ctx, query)
if err != nil {
return err
}
for rows.Next() {
srcDoc := struct {
ID string `json:"_id"`
}{}
if err := rows.ScanDoc(&srcDoc); err != nil {
return err
}
deviceIDs[srcDoc.ID] = strings.ReplaceAll(srcDoc.ID, src, dst)
exists, err = docExists(ctx, devices, deviceIDs[srcDoc.ID])
switch {
case err != nil:
return err
case exists:
return fmt.Errorf("%q already exists", deviceIDs[srcDoc.ID])
}
}
replacements := []replacement{
{
old: []byte(src),
new: []byte(dst),
},
{
// TODO should this logic be somewhere else?
old: []byte(strings.Replace(src, "-", " ", 1)),
new: []byte(strings.Replace(dst, "-", " ", 1)),
},
}
if err := copyDoc(ctx, rooms, src, dst, replacements...); err != nil {
return err
}
if err := copyDoc(ctx, uiConfigs, src, dst, replacements...); err != nil {
return err
}
for srcID, dstID := range deviceIDs {
if err := copyDoc(ctx, devices, srcID, dstID, replacements...); err != nil {
return err
}
}
return nil
}
type replacement struct {
old []byte
new []byte
}
func docExists(ctx context.Context, db *kivik.DB, id string) (bool, error) {
row := db.Get(ctx, id)
if statusErr, ok := row.Err.(statusErr); ok && statusErr.StatusCode() == http.StatusNotFound {
return false, nil
} else if row.Err != nil {
return false, row.Err
}
return true, nil
}
func copyDoc(ctx context.Context, db *kivik.DB, srcID, dstID string, replacements ...replacement) error {
row := db.Get(ctx, dstID)
if statusErr, ok := row.Err.(statusErr); ok && statusErr.StatusCode() == http.StatusNotFound {
} else if row.Err != nil {
return row.Err
}
/* this updates a previously existing document
dst := dstID
if row.Rev != "" {
dst = dstID + "?rev=" + row.Rev
}
*/
if _, err := db.Copy(ctx, dstID, srcID); err != nil {
return err
}
// make the replacements to the doc
row = db.Get(ctx, dstID)
if row.Err != nil {
return row.Err
}
doc, err := ioutil.ReadAll(db.Get(ctx, dstID).Body)
if err != nil {
return err
}
for _, replace := range replacements {
doc = bytes.ReplaceAll(doc, replace.old, replace.new)
}
// upload the replaced doc
if _, err := db.Put(ctx, dstID, doc); err != nil {
return err
}
return nil
}
// TODO change to Copy()
|
Java | UTF-8 | 7,000 | 1.914063 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.ext.wires.core.grids.client.widget.grid.selections.impl;
import java.util.List;
import org.junit.Test;
import org.uberfire.ext.wires.core.grids.client.model.GridData.SelectedCell;
import org.uberfire.ext.wires.core.grids.client.widget.grid.selections.CellSelectionStrategy;
import static org.junit.Assert.*;
public class RowSelectionStrategyMergedDataTest extends BaseCellSelectionStrategyTest {
@Override
protected CellSelectionStrategy getStrategy() {
return new RowSelectionStrategy();
}
@Test
public void singleCellSelection() {
strategy.handleSelection(uiModel,
0,
0,
false,
false);
final List<SelectedCell> selectedCells = uiModel.getSelectedCells();
assertEquals(4,
selectedCells.size());
assertTrue(selectedCells.contains(new SelectedCell(0,
0)));
assertTrue(selectedCells.contains(new SelectedCell(1,
0)));
assertTrue(selectedCells.contains(new SelectedCell(1,
1)));
assertTrue(selectedCells.contains(new SelectedCell(1,
1)));
}
@Test
public void extendSelectionWithShiftKey() {
strategy.handleSelection(uiModel,
0,
0,
false,
false);
strategy.handleSelection(uiModel,
2,
1,
true,
false);
final List<SelectedCell> selectedCells = uiModel.getSelectedCells();
assertEquals(8,
selectedCells.size());
assertTrue(selectedCells.contains(new SelectedCell(0,
0)));
assertTrue(selectedCells.contains(new SelectedCell(1,
0)));
assertTrue(selectedCells.contains(new SelectedCell(2,
0)));
assertTrue(selectedCells.contains(new SelectedCell(3,
0)));
assertTrue(selectedCells.contains(new SelectedCell(0,
1)));
assertTrue(selectedCells.contains(new SelectedCell(1,
1)));
assertTrue(selectedCells.contains(new SelectedCell(2,
1)));
assertTrue(selectedCells.contains(new SelectedCell(3,
1)));
}
@Test
public void extendSelectionWithControlKey() {
strategy.handleSelection(uiModel,
0,
0,
false,
false);
strategy.handleSelection(uiModel,
2,
1,
false,
true);
final List<SelectedCell> selectedCells = uiModel.getSelectedCells();
assertEquals(8,
selectedCells.size());
assertTrue(selectedCells.contains(new SelectedCell(0,
0)));
assertTrue(selectedCells.contains(new SelectedCell(1,
0)));
assertTrue(selectedCells.contains(new SelectedCell(2,
0)));
assertTrue(selectedCells.contains(new SelectedCell(3,
0)));
assertTrue(selectedCells.contains(new SelectedCell(0,
1)));
assertTrue(selectedCells.contains(new SelectedCell(1,
1)));
assertTrue(selectedCells.contains(new SelectedCell(2,
1)));
assertTrue(selectedCells.contains(new SelectedCell(3,
1)));
}
@Test
public void extendSelectionWithColumnMovedWithShiftKey() {
uiModel.moveColumnTo(0,
gc2);
strategy.handleSelection(uiModel,
0,
0,
false,
false);
strategy.handleSelection(uiModel,
2,
1,
true,
false);
final List<SelectedCell> selectedCells = uiModel.getSelectedCells();
assertEquals(8,
selectedCells.size());
assertTrue(selectedCells.contains(new SelectedCell(0,
0)));
assertTrue(selectedCells.contains(new SelectedCell(1,
0)));
assertTrue(selectedCells.contains(new SelectedCell(2,
0)));
assertTrue(selectedCells.contains(new SelectedCell(3,
0)));
assertTrue(selectedCells.contains(new SelectedCell(0,
1)));
assertTrue(selectedCells.contains(new SelectedCell(1,
1)));
assertTrue(selectedCells.contains(new SelectedCell(2,
1)));
assertTrue(selectedCells.contains(new SelectedCell(3,
1)));
}
}
|
PHP | UTF-8 | 1,805 | 2.84375 | 3 | [] | no_license | <?php
/**
* This is a generated class based on the schema.org type catalog.
*
* @license MIT
*/
declare(strict_types=1);
namespace EFrane\SchemaObjects;
/**
* A short TV or radio program or a segment/part of a program.
*/
class Clip extends CreativeWork
{
/**
* Position of the clip within an ordered group of clips.
*/
private $clipNumber;
/**
* The episode to which this clip belongs.
*/
private $partOfEpisode;
/**
* The start time of the clip expressed as the number of seconds from the beginning
* of the work.
*/
private $startOffset;
/**
* The season to which this episode belongs.
*/
private $partOfSeason;
/**
* The end time of the clip expressed as the number of seconds from the beginning
* of the work.
*/
private $endOffset;
public function getClipNumber()
{
return $this->clipNumber;
}
public function setClipNumber($clipNumber)
{
$this->clipNumber = $clipNumber;
}
public function getPartOfEpisode()
{
return $this->partOfEpisode;
}
public function setPartOfEpisode($partOfEpisode)
{
$this->partOfEpisode = $partOfEpisode;
}
public function getStartOffset()
{
return $this->startOffset;
}
public function setStartOffset($startOffset)
{
$this->startOffset = $startOffset;
}
public function getPartOfSeason()
{
return $this->partOfSeason;
}
public function setPartOfSeason($partOfSeason)
{
$this->partOfSeason = $partOfSeason;
}
public function getEndOffset()
{
return $this->endOffset;
}
public function setEndOffset($endOffset)
{
$this->endOffset = $endOffset;
}
}
|
C++ | UTF-8 | 10,965 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "sling/nlp/kb/calendar.h"
#include <stdio.h>
#include "sling/base/logging.h"
#include "sling/frame/object.h"
#include "sling/frame/store.h"
#include "sling/string/strcat.h"
#include "sling/string/text.h"
namespace sling {
namespace nlp {
static const char *parse_number(const char *p, const char *end, int *value) {
int n = 0;
while (p < end && *p >= '0' && *p <= '9') {
n = n * 10 + (*p++ - '0');
}
*value = n;
return p;
}
void Date::Init(const Object &object) {
year = month = day = 0;
precision = NONE;
if (object.IsInt()) {
int num = object.AsInt();
CHECK(num >= 0);
ParseFromNumber(num);
} else if (object.IsString()) {
Text datestr = object.AsString().text();
ParseFromString(datestr);
} else if (object.IsFrame()) {
Frame frame = object.AsFrame();
ParseFromFrame(frame);
}
}
void Date::ParseFromNumber(int num) {
if (num >= 1000000) {
// YYYYMMDD
year = num / 10000;
month = (num % 10000) / 100;
day = num % 100;
precision = DAY;
} else if (num >= 10000) {
// YYYYMM
year = num / 100;
month = num % 100;
precision = MONTH;
} else if (num >= 1000) {
// YYYY
year = num;
precision = YEAR;
} else if (num >= 100) {
// YYY*
year = num * 10;
precision = DECADE;
} else if (num >= 10) {
// YY**
year = num * 100 + 1;
precision = CENTURY;
} else if (num >= 0) {
// Y***
year = num * 1000 + 1;
precision = MILLENNIUM;
}
}
void Date::ParseFromString(Text str) {
const char *p = str.data();
const char *end = p + str.size();
// Parse + and - for AD and BC.
bool bc = false;
if (p < end && *p == '+') {
p++;
} else if (p < end && *p == '-') {
bc = true;
p++;
}
// Parse year, which can have trailing *s to indicate precision.
p = parse_number(p, end, &year);
int stars = 0;
while (p < end && *p == '*') {
p++;
stars++;
}
switch (stars) {
case 0: precision = YEAR; break;
case 1: precision = DECADE; year = year * 10; break;
case 2: precision = CENTURY; year = year * 100 + 1; break;
case 3: precision = MILLENNIUM; year = year * 1000 + 1; break;
}
if (bc) year = -year;
// Parse day and month.
if (p < end && *p == '-') {
p++;
p = parse_number(p, end, &month);
if (month != 0) precision = MONTH;
if (p < end && *p == '-') {
p++;
p = parse_number(p, end, &day);
if (day != 0) precision = DAY;
}
}
}
void Date::ParseFromFrame(const Frame &frame) {
// Try to get the 'point in time' property from frame and parse it.
Store *store = frame.store();
Object time(store, store->Resolve(frame.GetHandle("P585")));
if (time.invalid()) return;
if (time.IsInt()) {
int num = time.AsInt();
CHECK(num > 0);
ParseFromNumber(num);
} else if (time.IsString()) {
Text datestr = time.AsString().text();
ParseFromString(datestr);
}
}
string Date::ISO8601() const {
char str[32];
*str = 0;
switch (precision) {
case Date::NONE: break;
case Date::MILLENNIUM:
case Date::CENTURY:
case Date::DECADE:
case Date::YEAR:
sprintf(str, "%+05d-00-00T00:00:00Z", year);
break;
case Date::MONTH:
sprintf(str, "%+05d-%02d-00T00:00:00Z", year, month);
break;
case Date::DAY:
sprintf(str, "%+05d-%02d-%02dT00:00:00Z", year, month, day);
break;
}
return str;
}
int Date::AsNumber() const {
if (year < 1000 || year > 9999) return -1;
switch (precision) {
case NONE:
return -1;
case MILLENNIUM: {
int mille = year > 0 ? (year - 1) / 1000 : (year + 1) / 1000;
if (mille < 0) return -1;
return mille;
}
case CENTURY: {
int cent = (year - 1) / 100;
if (cent < 10) return -1;
return cent;
}
case DECADE:
return year / 10;
case YEAR:
return year;
case MONTH:
return year * 100 + month;
case DAY:
return year * 10000 + month * 100 + day;
}
return -1;
}
string Date::AsString() const {
char str[16];
*str = 0;
if (year >= -9999 && year <= 9999 && year != 0) {
switch (precision) {
case NONE: break;
case MILLENNIUM:
if (year > 0) {
int mille = (year - 1) / 1000;
CHECK_GE(mille, 0) << year;
CHECK_LE(mille, 9) << year;
sprintf(str, "+%01d***", mille);
} else {
int mille = (year + 1) / -1000;
CHECK_GE(mille, 0) << year;
CHECK_LE(mille, 9) << year;
sprintf(str, "-%01d***", mille);
}
break;
case CENTURY:
if (year > 0) {
int cent = (year - 1) / 100;
CHECK_GE(cent, 0) << year;
CHECK_LE(cent, 99) << year;
sprintf(str, "+%02d**", cent);
} else {
int cent = (year + 1) / -100;
CHECK_GE(cent, 0) << year;
CHECK_LE(cent, 99) << year;
sprintf(str, "-%02d**", cent);
}
break;
case DECADE:
sprintf(str, "%+04d*", year / 10);
break;
case YEAR:
sprintf(str, "%+05d", year);
break;
case MONTH:
sprintf(str, "%+05d-%02d", year, month);
break;
case DAY:
sprintf(str, "%+05d-%02d-%02d", year, month, day);
break;
}
}
return str;
}
void Calendar::Init(Store *store) {
// Get symbols.
store_ = store;
n_name_ = store->Lookup("name");
// Get calendar from store.
Frame cal(store, "/w/calendar");
if (!cal.valid()) return;
// Build calendar mappings.
BuildCalendarMapping(&weekdays_, cal.GetFrame("/w/weekdays"));
BuildCalendarMapping(&months_, cal.GetFrame("/w/months"));
BuildCalendarMapping(&days_, cal.GetFrame("/w/days"));
BuildCalendarMapping(&years_, cal.GetFrame("/w/years"));
BuildCalendarMapping(&decades_, cal.GetFrame("/w/decades"));
BuildCalendarMapping(¢uries_, cal.GetFrame("/w/centuries"));
BuildCalendarMapping(&millennia_, cal.GetFrame("/w/millennia"));
};
bool Calendar::BuildCalendarMapping(CalendarMap *mapping, const Frame &source) {
if (!source.valid()) return false;
for (const Slot &s : source) {
(*mapping)[s.name.AsInt()] = s.value;
}
return true;
}
string Calendar::DateAsString(const Date &date) const {
// Parse date.
Text year = YearName(date.year);
switch (date.precision) {
case Date::NONE:
return "";
case Date::MILLENNIUM: {
Text millennium = MillenniumName(date.year);
if (!millennium.empty()) {
return millennium.str();
} else if (date.year > 0) {
return StrCat((date.year - 1) / 1000 + 1, ". millennium AD");
} else {
return StrCat(-((date.year + 1) / 1000 - 1), ". millennium BC");
}
}
case Date::CENTURY: {
Text century = CenturyName(date.year);
if (!century.empty()) {
return century.str();
} else if (date.year > 0) {
return StrCat((date.year - 1) / 100 + 1, ". century AD");
} else {
return StrCat(-((date.year + 1) / 100 - 1), ". century BC");
}
}
case Date::DECADE: {
Text decade = DecadeName(date.year);
if (!decade.empty()) {
return decade.str();
} else {
return StrCat(year, "s");
}
}
case Date::YEAR: {
if (!year.empty()) {
return year.str();
} else if (date.year > 0) {
return StrCat(date.year);
} else {
return StrCat(-date.year, " BC");
}
}
case Date::MONTH: {
Text month = MonthName(date.month);
if (!month.empty()) {
if (!year.empty()) {
return StrCat(month, " ", year);
} else {
return StrCat(month, " ", date.year);
}
} else {
return StrCat(date.year, "-", date.month);
}
}
case Date::DAY: {
Text day = DayName(date.month, date.day);
if (!day.empty()) {
if (!year.empty()) {
return StrCat(day, ", ", year);
} else {
return StrCat(day, ", ", date.year);
}
} else {
return StrCat(date.year, "-", date.month, "-", date.day);
}
}
}
return "???";
}
Handle Calendar::Day(const Date &date) const {
if (date.precision < Date::DAY) return Handle::nil();
return Day(date.month, date.day);
}
Handle Calendar::Day(int month, int day) const {
auto f = days_.find(month * 100 + day);
return f != days_.end() ? f->second : Handle::nil();
}
Handle Calendar::Month(const Date &date) const {
if (date.precision < Date::MONTH) return Handle::nil();
return Month(date.month);
}
Handle Calendar::Month(int month) const {
auto f = months_.find(month);
return f != months_.end() ? f->second : Handle::nil();
}
Handle Calendar::Year(const Date &date) const {
if (date.precision < Date::YEAR) return Handle::nil();
return Year(date.year);
}
Handle Calendar::Year(int year) const {
auto f = years_.find(year);
return f != years_.end() ? f->second : Handle::nil();
}
Handle Calendar::Decade(const Date &date) const {
if (date.precision < Date::DECADE) return Handle::nil();
return Decade(date.year);
}
Handle Calendar::Decade(int year) const {
int decade = year / 10;
if (year < 0) decade--;
auto f = decades_.find(decade);
return f != decades_.end() ? f->second : Handle::nil();
}
Handle Calendar::Century(const Date &date) const {
if (date.precision < Date::CENTURY) return Handle::nil();
return Century(date.year);
}
Handle Calendar::Century(int year) const {
int century = year > 0 ? (year - 1) / 100 + 1 : (year + 1) / 100 - 1;
auto f = centuries_.find(century);
return f != centuries_.end() ? f->second : Handle::nil();
}
Handle Calendar::Millennium(const Date &date) const {
if (date.precision < Date::MILLENNIUM) return Handle::nil();
return Millennium(date.year);
}
Handle Calendar::Millennium(int year) const {
int millennium = year > 0 ? (year - 1) / 1000 + 1 : (year + 1) / 1000 - 1;
auto f = millennia_.find(millennium);
return f != millennia_.end() ? f->second : Handle::nil();
}
Text Calendar::ItemName(Handle item) const {
if (!store_->IsFrame(item)) return "";
FrameDatum *frame = store_->GetFrame(item);
Handle name = frame->get(n_name_);
if (!store_->IsString(name)) return "";
StringDatum *str = store_->GetString(name);
return str->str();
}
} // namespace nlp
} // namespace sling
|
Python | UTF-8 | 1,266 | 2.84375 | 3 | [
"MIT"
] | permissive | """
Utility functions.
"""
from uuid import UUID
from functools import singledispatch
from .models import FeedbackForm, Placement
class dotdict(dict):
"""
dot.access to dict attributes, even across nested dictionaries.
"""
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def __getattr__(self, key):
_val = self.get(key)
if isinstance(_val, dict):
return dotdict(_val)
elif isinstance(_val, list):
return list(map(lambda x: dotdict(x) if isinstance(x, dict) else x, _val))
return self.get(key)
@singledispatch
def get_form(form):
return form
@get_form.register(dict)
def _(form): # noqa
return dotdict(form)
@get_form.register(UUID)
def _(form): # noqa
return FeedbackForm.objects.get(id=form)
@get_form.register(str)
def _(form): # noqa
return FeedbackForm.objects.by_key(form)
@singledispatch
def get_placement(placement):
return placement
@get_placement.register(str)
def _(placement): # noqa
return Placement.objects.get(id=placement)
def is_uuid(value):
"""
Validate a value to be or not to be a UUID4
"""
try:
UUID(value, version=4)
return True
except ValueError:
return False
|
JavaScript | UTF-8 | 2,048 | 2.59375 | 3 | [] | no_license | (function(){
/* Global YUITest, CSSLint */
var Assert = YUITest.Assert;
YUITest.TestRunner.add(
new YUITest.TestCase({
name: "A-To-Z Property Order Errors",
"Properties that are not ordered alphabetically (excluding vendor-specific) should result in a warning (simple)": function() {
var result = CSSLint.verify(
"h1 { color: red; background-color: green; }",
{ "a-to-z-property-order": 1 });
Assert.areEqual(1, result.messages.length);
Assert.areEqual("warning", result.messages[0].type);
Assert.areEqual("The property 'background-color' should be placed above 'color'", result.messages[0].message);
},
"Properties that are not ordered alphabetically (excluding vendor-specific) should result in a warning (complex)": function() {
var result = CSSLint.verify(
"h1 {background-color: green; color: blue; } p { z-order: 0; transition: opacity 3s ease 1s; -webkit-transition: opacity 3s ease 1s; background-color: red; border: 1px solid black; }",
{ "a-to-z-property-order": 1 });
Assert.areEqual(2, result.messages.length);
Assert.areEqual("warning", result.messages[0].type);
Assert.areEqual("warning", result.messages[1].type);
Assert.areEqual("The property 'transition' should be placed above 'z-order'", result.messages[0].message);
Assert.areEqual("The property 'background-color' should be placed above 'transition'", result.messages[1].message);
},
"Alphabetically ordered properties should not result in a warning": function() {
var result = CSSLint.verify(
"p { background-color: red; border: 1px solid black; transition: opacity 3s ease 1s; -webkit-transition: opacity 3s ease 1s; z-order: 0; }",
{ "a-to-z-property-order": 1 });
Assert.areEqual(0, result.messages.length);
}
})
);
})(); |
Ruby | UTF-8 | 1,475 | 3.765625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class Pokemon
attr_accessor :id, :name, :type, :db
def initialize(args)
@name = args[:name]
@type = args[:type]
@db = args[:db]
@id = args[:id]
end
def self.save(name, type, db)
sql = "INSERT INTO pokemon (name, type) VALUES (?, ?)"
db.execute(sql, name, type)
end
def self.find(id, db)
sql = "SELECT * FROM pokemon WHERE id = ?"
result = db.execute(sql, id).flatten #flatten returns array w/o nested arrays.
Pokemon.new(id: result[0], name: result[1], type: result[2], db:db)
end
end
# Pokemon.reify_from_row(row).flatten
# finds based on id, returns a new Pokemon object, selects their row from the db, using the id number
# def alter(new_health, db)
# sql = "UPDATE pokemon SET hp = ? WHERE id = ?"
# db.execute(sql, new_health, self.id)
# end
#
# def self.find(id_num, db)
# pokemon_info = db.execute("SELECT * FROM pokemon WHERE id=?", id_num).flatten
# Pokemon.new(id: pokemon_info[0], name: pokemon_info[1], type: pokemon_info[2], db: db)
# end
# def self.reify_from_row(rows)
# rows.collect{|r| reify_from_row(r) }
# end
# save, add, remove, change
#
# def self.save(nam, type, db)# called from scraper class to save the newly scraped instance
# database_connection.execute ("INSERT INTO pokemon (name, type) VALUES (?, ?)", name, type)
# end
# s
#
# def self.find(id=nil, db)
# database_connection.execute #find in database
# end
|
C++ | UTF-8 | 958 | 2.796875 | 3 | [] | no_license | #include <cstdlib>
#include <string>
#include "DVD.h"
using namespace std;
DVD::DVD(string Title,string Category,string Runtime,string Studio,string releaseDate){
this->Title = Title;
this->Category = Category;
this->Runtime = Runtime;
this->Studio = Studio;
this->releaseDate = releaseDate;
}
void DVD::SetTitle(string Title){
this->Title = Title;
}
string DVD::GetTitle() const{
return Title;
}
void DVD::SetCategory(string Category){
this->Category = Category;
}
string DVD::GetCategory() const{
return Category;
}
void DVD::SetRuntime(string Runtime){
this->Runtime;
}
string DVD::GetRuntime() const{
return Runtime;
}
void DVD::SetStudio(string Studio){
this->Studio = Studio;
}
string DVD::GetStudio() const{
return Studio;
}
void DVD::SetReleaseDate(string releaseDate){
this->releaseDate = releaseDate;
}
string DVD::GetReleaseDate() const{
return releaseDate;
}
|
Shell | UTF-8 | 420 | 3.28125 | 3 | [
"MIT"
] | permissive | #!/bin/bash
set -e
# parse command line arguments
cuda=false
for key in "$@"; do
case $key in
--cuda)
cuda=true
;;
esac
done
# install requirements
./tensorflow_cc/ubuntu-requirements.sh
if $cuda; then
# install libcupti
apt-get -y install cuda-command-line-tools-11-6
fi
apt-get -y clean
# build and install tensorflow_cc
./tensorflow_cc/Dockerfiles/install-common.sh "$@"
|
Java | UTF-8 | 550 | 1.859375 | 2 | [] | no_license | package com.ebizprise.das.form.base;
import java.util.List;
public class DvdForm {
private String currency;
private List dividends;
private String assetId;
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public List getDividends() {
return dividends;
}
public void setDividends(List dividends) {
this.dividends = dividends;
}
public String getAssetId() {
return assetId;
}
public void setAssetId(String assetId) {
this.assetId = assetId;
}
}
|
Java | UTF-8 | 876 | 1.742188 | 2 | [] | no_license | package com.jjxt.ssm.service;
import java.util.List;
import java.util.Map;
import com.jjxt.ssm.entity.SignMatchExt;
import com.jjxt.ssm.utils.DataSource;
public interface SignMatchExtService {
@DataSource("master")
public List<SignMatchExt> findPageList(Map<String, Object> map) throws Exception;
@DataSource("master")
public Integer findTotal(Map<String, Object> map) throws Exception;
@DataSource("master")
public Integer findMaxExtByAppIdAndExtLength(SignMatchExt signMExt) throws Exception;
@DataSource("master")
public Integer addSignMatchExt(SignMatchExt signMExt) throws Exception;
@DataSource("master")
public int deleteSignMatchExt(String id) throws Exception;
@DataSource("master")
public SignMatchExt findListById(String id) throws Exception;
@DataSource("master")
public List<SignMatchExt> findAllList(Map<String, Object> map) throws Exception;
}
|
C# | UTF-8 | 3,021 | 3.421875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace LazyLoading
{
public class LazyLoadingCalculator
{
string inputPath;
string outputPath;
const int minimumApparentWeight = 50;
public void Dispose()
{
GC.SuppressFinalize(this);
}
public LazyLoadingCalculator()
{
}
public void Init(string inputPath, string outputPath)
{
this.inputPath = inputPath;
this.outputPath = outputPath;
}
public void startComputing()
{
ReadInputFileAndWriteAnswerToFile();
}
private void ReadInputFileAndWriteAnswerToFile()
{
StreamReader reader = new StreamReader(inputPath);
StreamWriter writer = new StreamWriter(outputPath);
int numberOfWorkingDays = Convert.ToInt32(reader.ReadLine());
int optimalRoundTripsForCurrentDay = 0;
List<int> itemsWeights = new List<int>();
int linenumber = 1;
for (int i = 1; i <= numberOfWorkingDays; i++)
{
int numberOfItemsForCurrentDay = Convert.ToInt32(reader.ReadLine());
itemsWeights.Clear();
linenumber++;
for (int j = 0; j < numberOfItemsForCurrentDay; j++)
{
linenumber++;
itemsWeights.Add(Convert.ToInt32(reader.ReadLine()));
}
optimalRoundTripsForCurrentDay = ComputeMaximumRoundTrips(itemsWeights);
writer.Write(string.Format("Case #{0}: {1}\n", i, optimalRoundTripsForCurrentDay));
}
reader.Close();
writer.Flush();
writer.Close();
}
public int ComputeMaximumRoundTrips(List<int> itemsWeights)
{
if (itemsWeights.Count == 1)
return 1;
int amountOfTrips = 0;
itemsWeights.Sort();
int topItem;
int numberOfItemsNeededToFakeHeavyLifting = 0;
while (itemsWeights.Count > 0)
{
topItem = itemsWeights.Last();
itemsWeights.Remove(topItem);
numberOfItemsNeededToFakeHeavyLifting = (int)Math.Ceiling((double)minimumApparentWeight / (double)topItem);
if (itemsWeights.Count >= (numberOfItemsNeededToFakeHeavyLifting - 1))
{
itemsWeights.RemoveRange(0, numberOfItemsNeededToFakeHeavyLifting - 1);
amountOfTrips++;
}
else
{
//There are not enough items to fake the last trip - Asuming they go into other trips
// Discard rest of list
itemsWeights.Clear();
}
}
return amountOfTrips;
}
}
} |
Markdown | UTF-8 | 2,045 | 3.390625 | 3 | [] | no_license | # Promise
Promise is a async program solution, it is a contructor.It has three status: Pending, Resolved, Rejected.
### base demo 1
```javascript
var _promise = new Promise(function(resolve, reject) {
if(/* finish async operation */) {
resolve(value);//The params will be passed to callback func
} else {
reject(error);
}
});
_promise.then(function(value) {
//success
}, function(err) {//This error func is option
//failure
});
```
### base demo 2
The param of resolve func can be a Promise object.
```javascript
var p1 = new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error('fail')), 3000)
});
var p2 = new Promise(function (resolve, reject) {
setTimeout(() => resolve(p1), 1000)
});
p2.then(result => console.log(result))
.catch(error => console.log(error))
//output=> Error: fail
```
p1's status will passed to p2.
### base demo 3
invoking resolve and reject func will not end Promise's param func to run continue program lines.
for example:
```javascript
new Promise((resolve, reject) => {
resolve(1);
console.log(2);
}).then(r => {
console.log(r);
});
//output:
//2
//1
```
**better write**
```javascript
new Promise((resolve,reject) => {
return resolve(1);//return directly
});
```
### advanced demo 1
then func's return is a Promise object. so we can use chain invoke.
```javascript
getJSON("/posts.json").then(function(json) {
return json.post;//result will passed to next then func
}).then(function(post) {
// ...
});
```
### advanced demo 2
catch func will be invoked when error happend.
```javascript
getJSON('/posts.json').then(function(posts) {
// ...
}).catch(function(error) {
console.log('error happend!', error);
});
```
**better write**
using catch func, not error callback way.
```javascript
// bad
promise
.then(function(data) {
// success
}, function(err) {
// error
});
// good
promise
.then(function(data) { //cb
// success
})
.catch(function(err) {
// error
});
```
|
Python | UTF-8 | 207 | 3.046875 | 3 | [] | no_license | import numpy as np
from matplotlib.pyplot import plot, show, xlabel, ylabel
def f(x, t):
return np.exp(-(x-3*t)**2)*np.sin(3*np.pi*(x-t))
t = 0
x = np.linspace(-4, 4, 41)
y = f(x, t)
plot(x, y)
show() |
Python | UTF-8 | 3,517 | 2.515625 | 3 | [] | no_license | #!/usr/bin/python
#
# Copyright (c) 2015 EMC Corporation
# All Rights Reserved
#
# This software contains the intellectual property of EMC Corporation
# or is licensed to EMC Corporation from third parties. Use of this
# software and the intellectual property contained therein is expressly
# limited to the terms and conditions of the License Agreement under which
# it is provided by or on behalf of EMC.
#
import argparse
import sys
import os
from bourne import Bourne
#----------------------------------------------------------------------
# backup cli functions
#----------------------------------------------------------------------
def create_backup(args):
bourne.connect(args.ip)
bourne.create_backup(args.name)
def delete_backup(args):
bourne.connect(args.ip)
bourne.delete_backup(args.name)
def list_backup(args):
bourne.connect(args.ip)
backuparray = bourne.list_backup()
if backuparray is None:
print None
elif backuparray['backupsets_info'] is None:
print None
else:
for backup in backuparray['backupsets_info']:
if(backup['name'] == args.name):
print backup['name']
def download_backup(args):
bourne.connect(args.ip)
if (args.filepath.endswith(".zip") is False):
args.filepath += ".zip"
response=bourne.download_backup(args.name)
filename=args.filepath
if (filename):
with open(filename, 'wb') as fp:
fp.write(str(response))
#----------------------------------------------------------------------
# command-line parsing
#----------------------------------------------------------------------
try:
bourne_ip = os.environ['BOURNE_IPADDR']
except:
bourne_ip = 'localhost'
# backup [--ip ipaddr]
parser = argparse.ArgumentParser(description = 'Bourne tenant cli usage.')
parser.add_argument('cmd', help = 'cmd = (create | list | delete | download)')
parser.add_argument('--ip', metavar = 'ipaddr', help = 'IP address of bourne', default=bourne_ip)
# create backup
backupcreate = argparse.ArgumentParser(parents = [parser], conflict_handler='resolve')
backupcreate.add_argument('name', help = 'name of backup file', type=str)
# list backup
backuplist = argparse.ArgumentParser(parents = [parser], conflict_handler='resolve')
backuplist.add_argument('name', help = 'name of backup file', type=str)
# delete backup
backupdelete = argparse.ArgumentParser(parents = [parser], conflict_handler='resolve')
backupdelete.add_argument('name', help = 'name of backup file', type=str)
# download backup
backupdownload = argparse.ArgumentParser(parents = [parser], conflict_handler='resolve')
backupdownload.add_argument('name', help = 'name of backup file', type=str)
backupdownload.add_argument('filepath', help= 'path of target file', type=str)
#----------------------------------------------------------------------
# Main script
#----------------------------------------------------------------------
try:
if (len(sys.argv) > 1):
cmd = sys.argv[1]
else:
cmd = None
bourne = Bourne()
if (cmd == "create"):
args = backupcreate.parse_args()
create_backup(args)
elif (cmd == "list"):
args = backuplist.parse_args()
list_backup(args)
elif (cmd == "delete"):
args = backupdelete.parse_args()
delete_backup(args)
elif (cmd == "download"):
args = backupdownload.parse_args()
download_backup(args)
else:
parser.print_help()
except:
raise
|
Java | UTF-8 | 2,428 | 2.140625 | 2 | [] | no_license | package com.course22056.sherlock4;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MAIN";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navbar_layout);
Log.d(TAG, "onCreate: navbar_layout");
getSupportFragmentManager().beginTransaction().replace(R.id.fragContainer,new homeFragment()).commit();
Log.d(TAG, "Replace container with homeFragment()");
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNav);
bottomNavigationView.setSelectedItemId(R.id.Navhome);
bottomNavigationView.setOnNavigationItemSelectedListener(bottomNavMethod);
}
private BottomNavigationView.OnNavigationItemSelectedListener bottomNavMethod =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
if(item.getItemId() == R.id.Navhome){
selectedFragment = new homeFragment();
Log.d(TAG, "onNavigationItemSelected: NavHome");
}else if(item.getItemId() == R.id.Navstats){
selectedFragment = new statsFragment();
Log.d(TAG, "onNavigationItemSelected: NavStats");
}else if (item.getItemId() == R.id.Navinfo){
selectedFragment = new infoFragment();
Log.d(TAG, "onNavigationItemSelected: NavInfo");
}
assert selectedFragment != null;
getSupportFragmentManager().beginTransaction().replace(R.id.fragContainer,selectedFragment).commit();
return true;
}
};
} |
Python | UTF-8 | 1,350 | 3.296875 | 3 | [] | no_license | import multiprocessing as mp
import random
import string
# Define an output queue
output = mp.Queue()
# define a example function
def rand_string(length, pos, output):
""" Generates a random string of numbers, lower- and uppercase chars. """
rand_str = ''.join( random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for i in range(length) )
output.put( (pos, rand_str) )
# Setup a list of processes that we want to run
processes = [mp.Process(target=rand_string, args=(5, x, output)) for x in range(4)]
# Run processes
for p in processes:
p.start()
# Exit the completed processes
for p in processes:
p.join()
# Get process results from the output queue
results = [output.get() for p in processes]
print(results)
xs = [results[i][1] for i in range(len(results))]
xs
''.join( random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for i in range(8) )
random.seed(1)
import random
print ("Random number with seed 30")
random.seed( 10 )
print ("first - ", random.randint(25,50))
#will generate a same random number as previous
random.seed( 10 )
print ("Second - ", random.randint(25,50))
#will generate a same random number as previous
random.seed( 10 )
print ("Third - ", random.randint(25,50))
random()
from matplotlib.pylab import * # for random()
random()
rr
##
|
Python | UTF-8 | 1,185 | 3.8125 | 4 | [] | no_license | class Account:
def __init__(self,name,balance,min_balance):
self.name=name
self.balance=balance
self.min_balance=min_balance
def deposite(self,amount):
self.balance+=amount
def withdraw(self,amount):
if self.balance-amount >= self.min_balance:
self.balance-=amount
else:
print("Sorry Insufficient Funds")
def printStatement(self):
print("Account Balance:-",self.balance)
class Current(Account):
def __init__(self,name,balance):
super().__init__(name, balance, min_balance=-1000)
def __str__(self):
return "{}'s Current Account with Balance :{}".format(self.name,self.balance)
class Saving(Account):
def __init__(self,name,balance):
super().__init__(name, balance, min_balance=0)
def __str__(self):
return "{}'s Current Account with Balance :{}".format(self.name,self.balance)
c=Saving("ASHISH",10000)
print(c)
c.deposite(5000)
c.printStatement()
c.withdraw(2000)
c.withdraw(500)
print(c)
c2=Current("AJIT",50000)
c2.deposite(10000)
print(c2)
c2.withdraw(27000)
print(c2)
|
C# | UTF-8 | 873 | 2.859375 | 3 | [] | no_license | using Logistics.DB;
using System.Collections.Generic;
using System.Linq;
namespace Logistics.Core
{
public class LogisticsServices : ILogisticsServices
{
private LogisticsContext _context;
public LogisticsServices(LogisticsContext context)
{
_context = context;
}
public Parcel CreateParcel(Parcel order)
{
_context.Add(order);
_context.SaveChanges();
return order;
}
public Letter CreateLetter(Letter order)
{
_context.Add(order);
_context.SaveChanges();
return order;
}
public List<Parcel> GetParcels()
{
return _context.Parcels.ToList();
}
public List<Letter> GetLetters()
{
return _context.Letters.ToList();
}
}
}
|
C# | UTF-8 | 6,208 | 2.59375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
namespace Graphics3D
{
class ParticleEmitter
{
private Vector3 position;
private Texture2D particleTexture;
private int maxParticles;
private float maxParticleAge;
private int numActiveParticles;
private List<Particle> activeParticles;
private ParticleEmitterUpdater particleUpdater;
private BillboardRenderer billboardRenderer;
private GraphicsDevice device;
private Random rand;
public ParticleEmitter(GraphicsDevice device, ContentManager content,
Vector3 position, Texture2D particleTexture,
ParticleEmitterUpdater particleUpdater,
int maxParticles, float maxParticleAge)
{
this.device = device;
this.position = position;
this.particleTexture = particleTexture;
this.particleUpdater = particleUpdater;
this.maxParticles = maxParticles;
this.maxParticleAge = maxParticleAge;
rand = new Random();
billboardRenderer = new BillboardRenderer(device, content.Load<Effect>(@"Effects\Billboard"));
// Create particle list
Reset();
}
public void EmitParticles(int numParticles, Vector3 direction, Vector2 size, float speed)
{
for (int i = 0; i < numParticles; i++)
{
EmitParticle(direction, size, speed);
}
}
public void EmitParticle(Vector3 direction, Vector2 size, float speed)
{
// Find 'dead' particle to emit
Particle p = null;
for (int i = 0; i < activeParticles.Count; i++)
{
if (!activeParticles[i].IsAlive)
{
p = activeParticles[i];
break;
}
}
// Emit a new particle
if (p != null)
{
// Set this particle's data
p.IsAlive = true;
p.Position = position;
p.Direction = direction;
p.Size = size;
p.Speed = speed;
p.Age = 0.0f;
}
}
public void EmitRandomParticles(int numParticles, Vector3 direction, Vector2 size, float speed)
{
for (int i = 0; i < numParticles; i++)
{
// Emit a new particle with random changes
Vector3 randDirection = direction;
randDirection.X += (float)(rand.NextDouble()) - 0.5f;
randDirection.Y += (float)(rand.NextDouble()) - 0.5f;
randDirection.Z += (float)(rand.NextDouble()) - 0.5f;
Vector2 randSize = Vector2.One;
randSize.X = (float)(rand.NextDouble() * size.X) + size.X * 0.25f;
randSize.Y = (float)(rand.NextDouble() * size.Y) + size.Y * 0.25f;
float randSpeed = speed;
randSpeed += (float)(rand.NextDouble()) - (speed * 0.25f);
EmitParticle(randDirection, randSize, randSpeed);
}
}
public void Reset()
{
// Create list if needed
if (activeParticles == null)
{
activeParticles = new List<Particle>(maxParticles);
for (int i = 0; i < maxParticles; i++)
{
// Create particle
activeParticles.Add(new Particle(device, Vector3.Zero, Vector3.Zero,
Vector2.Zero, 0.0f, ParticleTexture));
}
}
else
{
// Set all particles to 'dead'
foreach (Particle p in activeParticles)
{
p.IsAlive = false;
}
}
}
public void Update(float dt)
{
numActiveParticles = 0;
// Update all particles with particle updater
foreach (Particle p in activeParticles)
{
if (p.IsAlive)
{
particleUpdater.UpdateParticle(p, dt);
if (p.Age > maxParticleAge)
{
// Mark this particle as 'dead'
p.IsAlive = false;
}
else
{
numActiveParticles++;
}
}
}
billboardRenderer.UpdateEffectVariables();
}
public void DrawParticles(FirstPersonCamera camera)
{
// Draw each particle
foreach (Particle p in activeParticles)
{
if (p.IsAlive)
{
// Draw the particle's billboard
if(camera.ViewFrustum.Intersects(p.ParticleBillboard.AABB))
{
billboardRenderer.DrawParticle(p.ParticleBillboard, Vector3.Up, camera.Look);
}
}
}
}
// PROPERTIES
public Vector3 Position
{
get { return position; }
set { position = value; }
}
public Texture2D ParticleTexture
{
get { return particleTexture; }
}
public int MaxParticles
{
get { return maxParticles; }
set
{
maxParticles = value;
// Build new list of particles
activeParticles = null;
Reset();
}
}
public float MaxParticleAge
{
get { return maxParticleAge; }
set { maxParticleAge = value; }
}
public int NumActiveParticles
{
get { return numActiveParticles; }
}
}
} |
Python | UTF-8 | 316 | 3.328125 | 3 | [] | no_license |
# coding: utf-8
# In[1]:
i=2000
x=''
while i<=3000:
#print (i)
if i%7==0 and i%5!=0:
x=x+','+str(i)
i=i+1
print (x[1:len(x)])
# In[3]:
print("Enter FirstName:")
x=input()
print("Enter LastName:")
y=input()
print(y+' '+x)
# In[10]:
d=12
r=12/2
pi=3.14
V=4/3*pi*r**3
print(V)
|
TypeScript | UTF-8 | 2,860 | 2.734375 | 3 | [
"MIT"
] | permissive | import suite, { fixture } from "../test-suite";
import { join } from "path";
import * as tmp from "tmp";
import { EventEmitter } from "events";
import * as sf from "./sf";
suite(__filename, s => {
s.case("exists", async t => {
t.true(await sf.exists(fixture.path("empty")));
t.false(await sf.exists(fixture.path("a-classic-cake-song")));
});
s.case("readFile", async t => {
t.same(
await sf.readFile(fixture.path("txt"), { encoding: "utf8" }),
"Hello there, just writing a bit of text for the sniffer specs\n",
);
});
s.case("writeFile", async t => {
const contents = "What is head may never dye";
let readContents: string;
let err: Error;
const tmpObj = tmp.fileSync();
try {
await sf.writeFile(tmpObj.name, contents, { encoding: "utf8" });
readContents = await sf.readFile(tmpObj.name, { encoding: "utf8" });
} catch (e) {
err = e;
} finally {
tmpObj.removeCallback();
}
if (err) {
throw err;
}
t.same(readContents, contents);
});
s.case("appendFile", async t => {
const contentsA = "What is head";
const contentsB = " may never dye";
let readContents: string;
let err: Error;
const tmpObj = tmp.fileSync();
try {
await sf.writeFile(tmpObj.name, contentsA, { encoding: "utf8" });
await sf.appendFile(tmpObj.name, contentsB, { encoding: "utf8" });
readContents = await sf.readFile(tmpObj.name, { encoding: "utf8" });
} catch (e) {
err = e;
} finally {
tmpObj.removeCallback();
}
if (err) {
throw err;
}
t.same(readContents, contentsA + contentsB);
});
s.case("wipe", async t => {
let err: Error;
const tmpObj = tmp.dirSync();
const touch = async function(name: string) {
const path = join(tmpObj.name, name);
await sf.writeFile(path, name, { encoding: "utf8" });
};
try {
await touch("hello.txt");
await touch("super/deep/hello.txt");
await touch("super/deep/hella.txt");
await touch("super/cavernous/and/deep/into/the/temple/of/no.txt");
await sf.wipe(tmpObj.name);
} catch (e) {
err = e;
}
if (err) {
throw err;
}
t.false(await sf.exists(tmpObj.name));
});
s.case("promised (resolve 1)", async t => {
const stream = new EventEmitter();
const p = sf.promised(stream);
setTimeout(() => stream.emit("close"), 0);
await p;
});
s.case("promised (resolve 2)", async t => {
const stream = new EventEmitter();
const p = sf.promised(stream);
setTimeout(() => stream.emit("end"), 0);
await p;
});
s.case("promised (rejects)", async t => {
const stream = new EventEmitter();
const p = sf.promised(stream);
setTimeout(() => stream.emit("error", new Error()), 0);
await t.rejects(p);
});
});
|
JavaScript | UTF-8 | 9,595 | 3.140625 | 3 | [] | no_license | /**
* Class to create Comparison Country/Region input field + tags
*/
class ComparisonWidget {
/**
* Class constructor
* @param {Selected} _selected
* @param {Object} _constants = {regionMapper, countries, regions, dispatcherEvents}
* @param {Object} _dispatcher : d3 dispatcher
*/
constructor(_selected, _constants, _dispatcher) {
this.selected = _selected;
this.regionMapper = _constants.regionMapper;
this.countries = _constants.countries;
this.regions = _constants.regions;
this.dispatcherEvents = _constants.dispatcherEvents;
this.dispatcher = _dispatcher;
this.inputSanitizer = new InputSanitizer();
this.warningType = _constants.warningType ? _constants.warningType : new WarningType();
this.autocompleteCreator = new AutocompleteCreator();
}
/**
* Purpose: Initailizes or Updates Comparison Country/Region Input field, Submit Button, and tags
*/
updateComparisonSection() {
this.createTitleSection();
this.createInputSection();
this.updateTags();
}
// --------------------------- Helper Functions ----------------------------------- //
/**
* Purpose: Creates a title for the comparison section
*/
createTitleSection() {
let parent = document.getElementById('select-comparison');
// Remove any previous titles
let titleElem = document.getElementById('comparison-title');
if (titleElem) parent.removeChild(titleElem);
let title = 'Compare ' + this.selected.indicator;
titleElem = document.createElement('h6');
titleElem.id = 'comparison-title';
titleElem.className = 'sub-title';
titleElem.innerText = title;
parent.prepend(titleElem);
}
/**
* Purpose: Creates input section for comparison countries
*/
createInputSection() {
let parent = document.getElementById('comparison-selector-container');
// Clear previously created inputs
this.clearChildNodes(parent);
// Create container div
let div = document.createElement('div');
div.className = 'container';
// Create autocomplete div
let autocompleteContainer = document.createElement('div');
autocompleteContainer.className = 'autocomplete';
// Create input field & submit button
let input = this.createInputElem();
let submitButton = this.createSubmitButton();
autocompleteContainer.appendChild(input);
// Autocomplete dropdown functionality
this.autocompleteCreator.setInputOrSubmit({inputElem: input, submitButton});
this.autocompleteCreator.autocomplete(this.regionMapper.getCountriesOfRegion(this.regions.WORLD))
div.appendChild(autocompleteContainer);
div.appendChild(submitButton);
parent.appendChild(div);
}
/**
* Purpose: Creates a "submit" button
* @returns {Node} : DOM element of tag type 'button'
*/
createSubmitButton() {
let submitButton = document.createElement('button');
submitButton.innerHTML = 'Submit';
submitButton.type = 'button';
submitButton.className = 'button';
submitButton.name = 'comparison-submit-button';
submitButton.id = submitButton.name;
submitButton.addEventListener('click', e => this.handleSubmitInput(e));
return submitButton;
}
/**
* Purpose: Creates an input field with default autocomplete turned off
* @returns {Node} : DOM element of type 'input'
*/
createInputElem() {
let input = document.createElement('input');
input.placeholder = 'Add country to compare...';
input.autocomplete = 'off';
input.id = 'comparison-input';
return input;
}
/**
* Purpose: Adds comparison area to selected and updates view if valid input
* @param {Event} event : Native JS event
*/
handleSubmitInput(event) {
let inputValue = this.getInputValue();
let isCountry = this.regionMapper.doesRegionContainCountry(this.regions.WORLD, inputValue);
if (isCountry) {
this.clearWarning();
this.dispatcher.call(this.dispatcherEvents.SELECT_COMPARISON_ITEM, event, inputValue);
} else if (inputValue) {
this.displayWarning(this.warningType.INVALID_INPUT);
}
this.clearInputValue();
}
/**
* Purpose: Retrieves value in input field
* @returns {string} : value in text field
*/
getInputValue() {
let input = document.getElementById('comparison-input');
return input.value;
}
/**
* Purpose: Clears input field
*/
clearInputValue() {
let input = document.getElementById('comparison-input');
input.value = '';
}
/**
* Purpose: Displays a warning message to user depending on type of error
* @param {WarningType} warningType
*/
displayWarning(warningType) {
let parent = document.getElementById('warning-container');
this.clearWarning(parent);
this.createWarningContents(warningType, parent);
// Show warning box
parent.style.visibility = 'visible';
}
/**
* Purpose: Appends the contents of the warning box to the box element
* @param {WarningType} warningType
* @param {Node} warningBox : DOM node of warning box
*/
createWarningContents(warningType, warningBox) {
const warningIcon = `<i class="material-icons"></i> `;
const warningMsg = `<text>${this.getWarningMessage(warningType)}</text>`;
warningBox.innerHTML += warningIcon + warningMsg;
this.createCloseButton(warningBox, this.handleCloseWarning);
}
/**
* Purpose: Clears contents of warning box and hides the box
* @param {Node} parent : DOM node of warning box
*/
clearWarning(parent) {
if (!parent) {
parent = document.getElementById('warning-container');
}
this.clearChildNodes(parent);
// Hide warning box
parent.style.visibility = 'hidden';
}
/**
* Purpose: Returns appropriate warning message to the user
* @param {WarningType} warningType
* @returns {String} : warning message
*/
getWarningMessage(warningType) {
const {TOO_MANY_SELECTED, INVALID_INPUT} = this.warningType;
switch (warningType) {
case TOO_MANY_SELECTED:
return 'Only 4 comparison countries can be selected at a time.';
case INVALID_INPUT:
return 'Invalid country name. Please try again.'
default:
return 'An Error has occurred';
}
}
/**
* Purpose: Updates tags to display tags
* of selected focused area and selected comparison countries
*/
updateTags() {
// Clear previous tags
let parent = document.getElementById('tag-container');
this.clearChildNodes(parent);
let {area, comparisonAreas} = this.selected;
// Create tag for focused country
this.createTag(area.country, true);
// Create tag for each comparison area
for (let i = 0; i < comparisonAreas.length; i++) {
this.createTag(comparisonAreas[i], false);
}
}
/**
* Purpose: Creates individual tag (div element) and appends it to parent
* @param {string} countryOrRegion
* @param {Boolean} : true if given country/region is the currently selected focusArea
*/
createTag(countryOrRegion, isFocusedArea) {
let parent = document.getElementById('tag-container');
// Add attributes
let tag = document.createElement('div');
tag.className = isFocusedArea ?
'tag chip tag-focusedArea' :
'tag chip';
tag.innerText = countryOrRegion;
tag.value = countryOrRegion;
tag.id = `tag-${countryOrRegion.toLowerCase()}`
if (!isFocusedArea) {
// Create delete button for tag
this.createCloseButton(tag, this.handleCloseTag);
}
parent.appendChild(tag);
}
/**
* Purpose: Creates the "x" (i.e. close) button for each tag item or warning box
* @param {Node} container : div element representing a tag or warning box
* @param {Function} fn : callback to attach to addEventListener, which takes 'event' as an argument
*/
createCloseButton(container, fn) {
let closeBtn = document.createElement('span');
closeBtn.className = 'close-button';
closeBtn.innerHTML = '×';
closeBtn.value = container.value;
closeBtn.addEventListener('click', e => fn.call(this, e));
container.appendChild(closeBtn);
};
/**
* Purpose: Removes all child nodes from given parentNode
* @param {Node} parentNode
*/
clearChildNodes(parentNode) {
while (parentNode.firstChild) {
parentNode.firstChild.remove();
}
}
/**
* Purpose: Handles close tag
* @param {Event} e : Native JS event (e.g. "mouseover", "click", etc.)
*/
handleCloseTag(e) {
this.dispatcher.call(this.dispatcherEvents.DELETE_COMPARISON_ITEM, e, e.target.value);
}
/**
* Purpose: Closes warning box
*/
handleCloseWarning() {
this.clearWarning();
}
} |
PHP | UTF-8 | 704 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
namespace Bermuda\Validation\Rules;
use Bermuda\Validation\NullValidationDataException;
/**
* @method string|bool validate
*/
final class Required implements RuleInterface, ValidationDataAwareInterface
{
use RuleTrait, ValidationDataTrait;
public function __construct(private string $columnName, ?string $message = null)
{
$this->messages[] = $message === null ? "$columnName is required" : $message;
}
protected function doValidate($var): bool
{
if ($this->data === null) throw new NullValidationDataException;
return isset($this->data[$this->columnName]);
}
public function getName(): string
{
return 'required';
}
}
|
Python | UTF-8 | 3,178 | 2.65625 | 3 | [] | no_license | import pandas as pd
import csv
import os
import json
import sys
from Models.Auction import *
from Models.Time import *
from decimal import Decimal
import pyodbc
import requests
from bs4 import BeautifulSoup
import numpy as np
import urllib.request
class Surplus(object):
_instance = None
auctionList = []
auctionDict = {}
URL = 'https://www.publicsurplus.com/sms/calpoly,ca/list/current?orgid=3013'
def __new__(cls):
if cls._instance is None:
cls._instance = super(Surplus, cls).__new__(cls)
return cls._instance
def isInt(self, s):
try:
int(s)
return True
except ValueError:
return False
def loadSrc(self, url):
src = urllib.request.urlopen(url).read()
bs = BeautifulSoup(src, "html.parser")
return bs
def parseTime(self, timeString):
timeStringList = list(timeString.split(" "))
splitTime =[]
lst=[]
timelist=[0] * 4
for i in timeStringList:
lst.append(i)
if(not self.isInt(i)):
splitTime.append(lst)
lst = []
for j in splitTime:
if j[1] == 'days':
timelist[0] = j[0]
if j[1] == 'hours':
timelist[1] = j[0]
if j[1] == 'min':
timelist[2] = j[0]
if j[1] == 'seconds':
timelist[3] = j[0]
return Time(timelist[0], timelist[1], timelist[2], timelist[3])
def toCSV(self):
if not os.path.exists('out'):
os.makedirs('out')
with open(os.path.join(os.getcwd(), 'out', 'auctions.csv'), mode='w+') as auctions:
csvwriter = csv.writer(auctions, delimiter = ',', quotechar = '"', quoting=csv.QUOTE_MINIMAL)
csvwriter.writerow(["Auction Number", "Title", "Time Remaining", "Current Price"])
for key, val in self.auctionDict.items():
csvwriter.writerow([key, val.auctionTitle, val.auctionTime.toEndDateStamp(), val.auctionCurrentPrice])
def processAuctions(self):
allAuctions = self.loadSrc(self.URL).findAll('tr')
for auctionRecord in allAuctions:
auctionInfo = [i for i in [td.get_text().strip() for td in auctionRecord.findAll('td') if td] if i]
if(len(auctionInfo) == 4):
auctionInfo[0] = int(auctionInfo[0])
auctionInfo[3] = auctionInfo[3].strip('$')
time = self.parseTime(auctionInfo[2])
if "," in auctionInfo[3]:
auctionInfo[3] = auctionInfo[3].replace(",", "")
currentAuction = Auction(auctionInfo[0], auctionInfo[1], time, auctionInfo[3])
self.auctionList.append(currentAuction)
self.auctionDict[auctionInfo[0]] = currentAuction
def writeToSQL(self):
with open('db.json') as json_file:
db_info = json.load(json_file)
conn = pyodbc.connect('DRIVER='+db_info['drvr']+';SERVER='+db_info["server"]+';DATABASE='+db_info["database"]+';UID='+db_info["user"]+';PWD='+db_info["password"])
cursor = conn.cursor()
|
Markdown | UTF-8 | 7,733 | 2.765625 | 3 | [
"MIT"
] | permissive | # 브라우저 탐지
브라우저 탐지 방법은 웹 개발에서 항상 뜨거움 쟁점입니다. 이 논쟁은 특히 과거에 가장 인기 있었떤 넷스케이프 내비게이터의 등장으로 더 일찌감치 시작되었습니다. 당시 넷스케이프2.0은 다른 웹 브라우저보다 훨씬 발달하여 웹사이트가 사용자에게 정보를 보내기 전에 사용자 에이전트 문자열을 확인하는 것도 가능했습니다. 이 때문에 많은 브라우저 공급사, 특히 마이크로소프트에서는 어쩔 수 없이 당시 쓰였던 브라우저 탐지 방법에 맞춰 사용자 에이전트 문자열을 넣게 되었습니다.
## 6.1 사용자 에이전트 탐지
요즘에는 클라이언트에서 브라우저를 주로 탐지하지만, 초기에는 서버에서 사용자 에이전트 문자열을 기준으로 서버에서 특정 브라우저의 접속을 막아 사이트의 내용을 아예 보여주지 않았습니다. 이때 가장 큰 혜택을 본 건 넷스케이프였습니다. 넷스케이프는 당시 가장 성능이 뛰어는 브라우저였고 그래서 많은 웹 사이트가 넷스케이프를 기준으로 제작되었습니다. 당시의 넷스케이프의 사용자 에이전트 문자열은 다음과 같습니다.
```javascript
Mozilla/2.0 (Win95; I)
```
최초의 IE는 서버의 내용을 정상적으로 볼 수 있또록 넷스케이프의 사용자 에이전트 문자열을 많은 부분 따라 했습니다. 당시 사용자 에이전트 탐지는 'Mozilla'라는 단어와 슬래시로 버전을 표기했는지를 확인했기에 IE는 다음처럼 사용자 에이전트 문자열을 추가했습니다.
```javascript
Mozilla/2.0 (compatible; MSIE 3.0; Windows 95)
```
IE의 등장으로 모든 사람이 쓰던 사용자 에이전트 문자열 탐지는 이 새로운 브라우저를 넷스케이프로 인지하게 되었습니다. 이때부터 새로운 브라우저는 기존 브라우저의 사용자 에이전트 문자열을 따라하는 게 유행이 되었고 이 유행은 크롬까지 이어져 크롬의 사용자 에이전트 문자열은 사파리의 문자열을 포함하고 있습니다. 여기서 계속 따라가 보면 사파리의 문자열은 파이어폭스의 문자열을, 파이어폭스의 문자열은 넷스케이프 문자열을 포함합니다.
## 6.2 기능 탐지
개발자들은 더 괜찮은 브라우저 탐지 방법이 있는지 알아보다가 기능 탐지라 불리는 테크닉에 주목했습니다. 기능 탐지는 특정 브라우저의 기능이 있는지 확인하는 방법을 이용합니다.
```javascript
// 나쁜 예
if (navigatot.userAgent.indexOf('MSIE 7') > -1) {
// 실행할 코드
}
```
따라서 기능 탐지는 위 예제 코드 대신 다음 코드를 사용합니다.
```javascript
if (document.getElementById) {
// 실행할 코드
}
```
위 두 가지 접근법에는 차이가 있습니다. 첫 번째 예제는 이름과 버전으로 특정 브라우저인지 확인하고, 두 번째 예제는 document.getElementById라는 특정 기능으로 확인합니다. 따라서 사용자 에이전트 탐지는 브라우저와 버전을 정확하게 알 수 있지만 기능 탐지는 검사에 사용한 객체나 메서드가 사용 가능한지만 확인할 수 있습니다. 이로 인해 결과는 완전히 다르게 나타납니다.
기능 탐지는 어떤 브라우저를 사용하는지에 상관없이 특정 기능을 사용할 수 있는지만 확인하는 방법이라 새로운 브라우저가 나와도 별 문제가 없습니다. 예를 들어 DOM이 갓 나왔을 때 document.getElementById()를 지원하는 브라우저가 많지 않아 다음과 같은 코드를 작성할 수 있었습니다.
```javascript
// 좋은 예
function getById(id) {
var element = null;
if (document.getElementById) { // DOM
element = document.getElementById(id);
} else if (document.all) { // IE
element = document.all[id];
} else if (document.layers) { // Netscape <= 4
element = document.layers[id];
}
return element;
}
```
이 코드는 기능이 있는지 확인한 후 있으면 사용하도록 기능 탐지를 적절히 설정하고 있습니다. 함수를 보면 document.getElementById는 표준 메서드이므로 제일 처음 확인하고 그 다음에 특정 브라우저의 메서드를 검사합니다. 만약 이러한 기능이 아무 것도 없으면 메서드는 null을 반환합니다. 초기 IE와 넷스케이프는 document.getElementById()를 지원하지 않았지만 IE5와 넷스케이프6가 출시되며 이 메서드를 지원하기 시작했습니다.
위 예제는 기능 탐지의 중요한 세 가지를 잘 보여주고 있습니다.
**1. 표준 솔루션을 확인한다.**
**2. 브라우저 기반 솔루션을 검사한다.**
**3. 기능 탐지에 실패하면 적절하게 처리한다.**
## 6.3 기능 추론 금지
기능 탐지를 부적절하게 사용하면 기능 탐지가 아닌 기능 추론이 됩니다. 기능 추론은 어느 기능이 있는지 확인하고 그 외 다른 기능까지 사용하는 것을 말합니다. 한 가지 기능이 있으므로 다른 기능이 있으리라고 생각하는 겁니다. 당연히 추론은 사실보다는 추측에 기반을 두므로 유지보수에 문제가 생길 수 있습니다. 다음 예제는 기능 추론을 사용한 다소 오래된 코드입니다.
```javascript
// 나쁜 예 - 기능 추론을 사용함
function getById(id) {
var element = null;
if (document.getElementByTagName) { // DOM
element = document.getElementById(id);
} else if (window.ActiveXObject) { // IE
element = document.all[id];
} else { // Netscape <= 4
element = document.layers[id];
}
return element;
}
```
이 함수는 기능 추론을 사용하는 나쁜 예 입니다. 이런 추론은 다음과 같은 색각에 기반을 둡니다.
- **document.getElementsByTagName()가 있으면 document.getElementById()도 있다.**
이 추측은 DOM 메서드 하나가 있다고 모든 DOM 메서드가 있으리라고 생각하는 것 입니다.
- **window.ActiveXObject가 있으면 document.all도 있다.**
이 추론은 window.ActiveXObject와 document.all은 IE에만 존재하므로 둘 중 하나가 있는지만 알면 다른 것도 있을 것이라 생각하는 것 입니다. 실제로 오페라7에서는 document.all을 지원하기도 합니다.
- **이들 조건에 맞지 않으면 분명 넷스케이프4 이전 버전임이 확실하다**
정확히 말하면 이건 사실이 아닙니다.
한 기능이 있다고 다른 기능도 있으리라 생각하면 안 됩니다. 실제로는 두 기능이 거의 관계가 없거나 중요하지 않은 관계인 경우가 많습니다. 이는 마치 오리처럼 보인다고 오리처럼 꽤꽥 울거라 단정 짓는 것과 같습니다.
## 6.4 무엇을 사용해야 할까?
기능 추론과 브라우저 탐지는 매우 안 좋은 습관이고 반드시 피해야 합니다. 어떤 상황이든 기능 탐지를 사용하는 것이 가장 좋습니다. 일반적으로 어떤 기능을 사용하기 전에는 그 기능이 이미 있는지 부터 알아야 합니다. 하지만 기능 간에 관계로 추측하면 잘못된 판단을 할 수도 있습니다.
저는 기능 탐지를 사용할 것을 권장합니다. 기능 탐지를 사용할 수 없을 때에는 대신 사용자 에이전트 탐지를 사용하십시오. 하지만 브라우저 추론은 유지보수에 좋지도 않고 브라우저가 새로 배포될 때마다 업데이트해야 하므로 코드에서 벗어날 수 없게 될지도 모릅니다. |
PHP | UTF-8 | 4,793 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
class extension_reflecteduploadfield extends Extension
{
/*------------------------------------------------------------------------*/
/* DEFINITION & SETTINGS
/*------------------------------------------------------------------------*/
/**
* Name of the extension field table
* @var string
*
* @since version 1.3.0
*/
const FIELD_TBL_NAME = 'tbl_fields_reflectedupload';
/**
* Holds the fields that need post-save treatment
* @static
* @var array
*
* @since version 1.0.0
*/
protected static $fields = array();
/**
* Add field to the $fields array for post save treatment
* @static
* @param $field
* @return void
*
* @since version 1.0.0
*/
public static function registerField($field)
{
self::$fields[] = $field;
}
/**
* GET SUBSCRIBES DELEGATES
*
* http://www.getsymphony.com/learn/api/2.4/toolkit/extension/#getSubscribedDelegates
*
* @since version 1.0.0
*/
public function getSubscribedDelegates()
{
return array(
array(
'page' => '/publish/new/' ,
'delegate' => 'EntryPostCreate' ,
'callback' => 'compileFields'
),
array(
'page' => '/publish/edit/' ,
'delegate' => 'EntryPostEdit' ,
'callback' => 'compileFields'
),
array(
'page' => '/frontend/' ,
'delegate' => 'EventPostSaveFilter' ,
'callback' => 'compileFields'
)
);
}
/**
* COMPILE FIELDS (delegate callback)
*
* @param $context
* @return void
* @since version 1.0.0
*/
public function compileFields($context)
{
foreach (self::$fields as $field) {
if (!$field->compile($context['entry'])) {
// TODO:ERROR
}
}
}
/*------------------------------------------------------------------------*/
/* INSTALL / UPDATE / UNINSTALL
/*------------------------------------------------------------------------*/
/**
* INSTALL
*
* http://www.getsymphony.com/learn/api/2.4/toolkit/extension/#install
*
* @since version 1.0.0
*/
public function install()
{
return self::createFieldTable();
}
/**
* CREATE FIELD TABLE
*
* @since version 1.3.0
*/
public static function createFieldTable()
{
$tbl = self::FIELD_TBL_NAME;
return Symphony::Database()->query("
CREATE TABLE IF NOT EXISTS `$tbl` (
`id` int(11) unsigned NOT NULL auto_increment,
`field_id` int(11) unsigned NOT NULL,
`destination` varchar(255) NOT NULL,
`validator` varchar(50),
`expression` VARCHAR(255) DEFAULT NULL,
`unique` tinyint(1) default '0',
PRIMARY KEY (`id`),
KEY `field_id` (`field_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
");
}
/**
* UPDATE
*
* http://www.getsymphony.com/learn/api/2.4/toolkit/extension/#update
*
* @since version 1.0.0
*/
public function update($previousVersion = false)
{
// updating from versions prior to 1.0
if(version_compare($previousVersion, '1.0','<=')) {
Symphony::Database()->query("ALTER TABLE `tbl_fields_reflectedupload` ADD `unique` tinyint(1) default '0'");
}
// updating from versions prior to 1.2
if (version_compare($previous_version, '1.2', '<')) {
// Remove directory from the upload fields, fixes Symphony Issue #1719
$upload_tables = Symphony::Database()->fetchCol("field_id", "SELECT `field_id` FROM `tbl_fields_reflectedupload`");
if(is_array($upload_tables) && !empty($upload_tables)) foreach($upload_tables as $field) {
Symphony::Database()->query(sprintf(
"UPDATE tbl_entries_data_%d SET file = substring_index(file, '/', -1)",
$field
));
}
}
}
/**
* UNINSTALL
*
* http://www.getsymphony.com/learn/api/2.4/toolkit/extension/#uninstall
*
* @since version 1.0.0
*/
public function uninstall()
{
return self::deleteFieldTable();
}
/**
* DELETE FIELD TABLE
*
* @since version 1.3.0
*/
public static function deleteFieldTable()
{
$tbl = self::FIELD_TBL_NAME;
return Symphony::Database()->query("
DROP TABLE IF EXISTS `$tbl`
");
}
}
|
Swift | UTF-8 | 1,958 | 3.125 | 3 | [] | no_license | //
// DailyLogView.swift
// WaterApp
//
// Created by Aiur on 15.11.2020.
//
import SwiftUI
private struct LogItem: View {
@State var day: DailyLog
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 25)
.fill(Color.white)
.shadow(color: .gray, radius: 3, x: 0, y: 2)
// .overlay(
// RoundedRectangle(cornerRadius: 25)
// .stroke(Color.black, lineWidth: 1)
// )
HStack {
Spacer()
Text("\(day.capacity)ml")
Spacer()
Spacer()
Text(convertTime(date: day.time))
Spacer()
}
}
.frame(height: 80)
.padding([.leading, .trailing])
}
private func convertTime(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
return dateFormatter.string(from: date)
}
}
struct DailyLogView: View {
var dailyDrink: DailyDrink
var body: some View {
VStack(spacing: 16) {
ForEach(dailyDrink.log, id: \.id) { (day: DailyLog) in
LogItem(day: day)
}
}
}
}
struct DailyLogView_Previews: PreviewProvider {
static var previews: some View {
DailyLogView(dailyDrink: DailyDrink(
date: Date(),
currentCapacityMl: 1600,
totalCapacityMl: 3000,
log: [
DailyLog(time: Date(), capacity: 250),
DailyLog(time: Date(), capacity: 250),
DailyLog(time: Date(), capacity: 250),
DailyLog(time: Date(), capacity: 250),
DailyLog(time: Date(), capacity: 250)
])
)
}
}
|
Markdown | UTF-8 | 1,552 | 3.828125 | 4 | [] | no_license | # Burger Town
### Problem the app addresses
This app allows you to enter a hamburger name and update the database to store that new name. It then allows you to change the status of that hamburger to devoured and change it to a separate list on the webpage.
### How the app is layed out
The app has essentially three separate functionalities to it. It has a create functionality where the user can input a new hamburger name. It has a read functionality where the user can see which hamburger names have been created. The third functionality is an update. The user can select the "Devour It" button and it will update the database to show that the hamburger has been devoured.
### Instructions on running the app
1. The user can click on the create a burger name box and type whatever name they would like. They can then select the create button to add it to the list of burgers created.
2. The user can then select the devour button by any of the listed names to move it over to the devoured list on the right.
### Technologies used
* Node.js used to test server connection and install packages.
* MVC to organize the files.
* Express.js to set up the different routes
* MySql to set up a database to store and update the information inputted.
* Handlebars used to render the html page.
### Link to Github and Heroku Links
* https://github.com/mattwhittle10/burger
* https://limitless-sands-50340.herokuapp.com/burgers
#### My Role
I created this from start to finish. I used past examples of code from our class and researched a lot on my own. |
Java | UTF-8 | 290 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | package com.example;
public class ChatBotLogic {
public String chatBotProcess(String message) {
if( "do-not-reply".equals(message) ) {
return null; // no response in the chat
}
return "echo from the bot: " + message; // echoes the message
}
} |
Markdown | UTF-8 | 2,525 | 2.65625 | 3 | [] | no_license | # GitHub action for WordPress.org Plugin Deployment
This actions uses the content in the latest pushed tag, runs the build process inside the repository root and copies latest files excluding specified files and commits to WP.org plugin directory.
If an assets directory is provide it will be used to update assets directory of the plugin at WP.org
## Configuration
### Required secrets
* `WORDPRESS_USERNAME`
* `WORDPRESS_PASSWORD`
### Optional environment variables
* `SLUG` - Defaults to the respository name, customizable in case your WordPress repository has a different slug
* `ASSETS_DIR` - If assets directory is provided then it's content will be used to update `assets` direct at plugin svn repository.
* `CUSTOM_COMMAND` - This can be used to pass custom command which can be used to build plugin assets before files are copied to plugin `trunk`. Eg `gulp build`
* `CUSTOM_PATH` - Some plugins tend to have a different folder inside git repository where the source files are kept aside from development files. If provided files will be copied from `CUSTOM_PATH` to plugin `trunk`.
* `EXCLUDE_LIST`
* Add file / folders that you wish to exclude from final list of files to be sent to plugin `trunk`. Eg development files. By default the script will exclude `.git .github` and `assets` if provided.
* Final value of the above var is expected to be a string delimited with spaces. Eg: '.gitignore package.json README.md'
* Please Note excluded file/folder path is considered from the root of repository unless `CUSTOM_PATH` is provided, in which case excluded file/folder path should be relative to the final source of files.
## Example Workflow File
```
workflow "Deploy" {
resolves = ["WordPress Plugin Deploy"]
on = "push"
}
# Filter for tag
action "tag" {
uses = "actions/bin/filter@master"
args = "tag"
}
action "WordPress Plugin Deploy" {
needs = ["tag"]
uses = "rtCamp/github-actions-library/wp-plugin-deploy@master"
secrets = ["WORDPRESS_USERNAME", "WORDPRESS_PASSWORD"]
env = {
SLUG = "plugin-slug"
CUSTOM_COMMAND = "gulp build"
CUSTOM_PATH = "post-contributor"
EXCLUDE_LIST = "asset_sources/"
}
}
```
## Credits
* Github action bootstrapped from - [10up/actions-wordpress/dotorg-plugin-deploy](https://github.com/10up/actions-wordpress/tree/master/dotorg-plugin-deploy)
* Deployment Docker Image - [awhalen/docker-php-composer-node](https://github.com/amwhalen/docker-php-composer-node)
|
C# | UTF-8 | 1,378 | 3.328125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab2
{
public enum Material
{
PINE = 0,
OAK = 1,
STEEL = 2,
SILVER = 3,
GOLD = 4
}
public enum Style
{
SIMPLE = 0,
MODERN = 1,
ANTIQUE = 2,
VINTAGE = 3,
ECLECTIC = 4
}
public class FramedPhoto : Photo
{
protected Material _material;
protected Style _style;
public FramedPhoto(float width, float height, Material material, Style style) : base(width, height)
{
_material = material;
_style = style;
}
public Material Material
{
set { _material = value; }
get { return _material; }
}
public Style Style
{
set { _style = value; }
get { return _style; }
}
public override string ToString()
{
return $"{_width}x{_height}, {Price}, {_material}, {_style}";
}
public override double Price { get => base.Price + 25; }
}
}
|
Python | UTF-8 | 1,429 | 4.34375 | 4 | [] | no_license | # 正则表达式
# 给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '*' 的正则表达式匹配。
#
# '.' 匹配任意单个字符
# '*' 匹配零个或多个前面的那一个元素
# 所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。
#
# 说明:
# s 可能为空,且只包含从 a-z 的小写字母。
# p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
# 示例 1:
# 输入:
# s = "aa"
# p = "a"
# 输出: false
# 解释: "a" 无法匹配 "aa" 整个字符串。
# 示例 2:
# 输入:
# s = "aa"
# p = "a*"
# 输出: true
# 解释: 因为 '*' 代表可以匹配零个或多个前面的那一个元素, 在这里前面的元素就是 'a'。因此,字符串 "aa" 可被视为 'a' 重复了一次。
# 示例 3:
# 输入:
# s = "ab"
# p = ".*"
# 输出: true
# 解释: ".*" 表示可匹配零个或多个('*')任意字符('.')。
# 示例 4:
# 输入:
# s = "aab"
# p = "c*a*b"
# 输出: true
# 解释: 因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 "aab"。
# 示例 5:
# 输入:
# s = "mississippi"
# p = "mis*is*p*."
# 输出: false
class Solution:
def isMatch(self, s: str, p: str) -> bool:
return False
if __name__ == '__main__':
sol = Solution()
s = "ab"
p = "a"
r1 = sol.isMatch(s, p)
print(r1)
|
C# | UTF-8 | 1,176 | 2.921875 | 3 | [] | no_license | ////////////////////////////////////////////////////////////
///// WatchedObject.cs
///// James McNeil - 2020
////////////////////////////////////////////////////////////
using System.Collections.Generic;
using UnityEngine;
namespace PersonalFramework
{
public class WatchedObject : MonoBehaviour
{
private const int k_startingObserverCapacity = 5;
private List<Observer> m_observers = new List<Observer>(k_startingObserverCapacity);
public void AddObserver(Observer observer)
{
if(!m_observers.Contains(observer))
{
m_observers.Add(observer);
}
}
public void RemoveObserver(Observer observer)
{
if(m_observers.Contains(observer))
{
m_observers.Remove(observer);
}
}
public void ClearAllObservers()
{
m_observers.Clear();
}
public void NotifyObservers(object objectToNotify)
{
for(int i = 0; i < m_observers.Count; i++)
{
m_observers[i]?.ObserveMessage(objectToNotify);
}
}
}
} |
C# | UTF-8 | 2,451 | 2.828125 | 3 | [] | no_license | using System.Collections;
using UnityEngine;
namespace TimeOfTheDay
{
public class GameTimeHandler : MonoBehaviour
{
public int DayLengthInSeconds;
public bool isEnabled;
public delegate void GameTimeEventHandler();
public event GameTimeEventHandler OnAfterValueChangedEvent;
private int currentDay;
private int currentHour;
private int currentMinute;
private int currentSecond;
private float processFrequencyInSeconds = 1;
public long RealGameSecondsPast;
private float currentTimeOfDay;
void Start()
{
if (isEnabled)
{
Init();
StartCoroutine(Process());
}
}
internal void SetCurrentTime(long realGameSecondsPast)
{
RealGameSecondsPast = realGameSecondsPast;
}
private void Init()
{
RealGameSecondsPast = 0;
}
public CurrentTimePastModel GetGameTime()
{
return new CurrentTimePastModel(currentDay, currentHour, currentMinute, currentSecond);
}
private IEnumerator Process()
{
while (isEnabled)
{
yield return new WaitForSeconds((float)processFrequencyInSeconds);
CalculateTimeOfTheDay();
RealGameSecondsPast++;
}
}
public void CalculateTimeOfTheDay()
{
if (RealGameSecondsPast > 0)
{
var ratio = DayLengthInSeconds / 86400f;
//how many seconds past according to game time.
var secondsPastInGame = RealGameSecondsPast / ratio;
var dayx = secondsPastInGame / (24 * 3600);
secondsPastInGame = secondsPastInGame % (24 * 3600);
var hourx = secondsPastInGame / 3600;
secondsPastInGame %= 3600;
var minutesx = secondsPastInGame / 60;
secondsPastInGame %= 60;
var secondsx = secondsPastInGame;
currentDay = (int)dayx;
currentHour = (int)hourx;
currentMinute = (int)minutesx;
currentSecond = (int)secondsx;
if (OnAfterValueChangedEvent != null)
{
OnAfterValueChangedEvent();
}
}
}
}
} |
Python | UTF-8 | 810 | 3.609375 | 4 | [] | no_license | #python3
import sys
def fibonacci_number_naive(num):
f_1, f_2 = 0,1
temp = 0
for _ in range(0, num):
temp = f_1 + f_2
f_1 = f_2
f_2 = temp
return f_1
def fibonacci_number_reccursive(num):
if((num == 0) or (num == 1)):
return num
else:
return fibonacci_number_reccursive(num-1)+fibonacci_number_reccursive(num-2)
if __name__ == "__main__":
# test trigger
if(len(sys.argv) == 2):
if(sys.argv[1] == '-t'):
from Stress_Test import Test
test = Test(test_func = fibonacci_number_reccursive,
solution_func = fibonacci_number_naive,
iterations = 100)
test.run()
else:
num = int(input())
print(fibonacci_number_naive(num)) |
PHP | UTF-8 | 1,137 | 2.703125 | 3 | [] | no_license | <?php
// report all errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
// include the class file
require_once '../Contact/Vcard/Build.php';
// instantiate a builder object
// (defaults to version 3.0)
$vcard = new Contact_Vcard_Build();
// set a formatted name
$vcard->setFormattedName('Brandon McCarthy');
// set the structured name parts
$vcard->setName('McCarthy', 'Brandon', 'Christopher',
'Mr.', 'II');
// add a work email. note that we add the value
// first and the param after -- Contact_Vcard_Build
// is smart enough to add the param in the correct
// place.
$vcard->addEmail('mccarthyhe@gmail.com.com');
$vcard->addParam('TYPE', 'WORK');
// add a home/preferred email
$vcard->addEmail('mccarthyhe@gmail.com.com');
$vcard->addParam('TYPE', 'HOME');
$vcard->addParam('TYPE', 'PREF');
// add a work address
$vcard->addAddress('POB 101', 'Suite 202', '123 Main',
'Beverly Hills', 'CA', '90210', 'US');
$vcard->addParam('TYPE', 'WORK');
// set the title (checks for colon-escaping)
$vcard->setTitle('The Title: The Subtitle');
// send the vcard
header('Content-Type: text/plain');
echo $vcard->fetch();
?> |
C | UTF-8 | 815 | 3.65625 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int gen_array(int *arr, int n) {
int i = 0;
while (n) {
arr = realloc(arr, (i + 1) * sizeof(int));
int d = n % 10;
n /= 10;
arr[i] = d;
++i;
}
int l = i;
for (int j = 0; j< l/2; ++j){
int t = arr[j];
arr[j] = arr[l-j-1];
arr[l-j-1] = t;
}
return i;
}
int digits_sum(int n, int sum) {
if (n) {
int d = n % 10;
n /= 10;
sum += d;
digits_sum(n, sum);
} else {
return sum;
}
}
int main() {
int number = 561310;
int *arr = calloc(0, sizeof(int));
int len = gen_array(arr, number);
for (int i = 0; i < len; ++i) {
printf("%d\t", arr[i]);
}
printf("\n%d\n", digits_sum(number, 0));
return 0;
} |
C# | UTF-8 | 160 | 2.625 | 3 | [] | no_license | using System;
using System.Linq;
class P
{
static void Main()
{
Console.WriteLine(Console.ReadLine().Split().Select(int.Parse).Min());
}
}
|
Java | GB18030 | 7,544 | 2.40625 | 2 | [
"Apache-2.0"
] | permissive | package com.cloudfire.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.cloudfire.dao.OperationDao;
import com.cloudfire.db.DBConnectionManager;
import com.cloudfire.entity.Operation;
import com.cloudfire.entity.OperationQuery;
import com.cloudfire.entity.OperationType;
public class OperationDaoImpl implements OperationDao{
@Override
public int saveOperationRecord(int optype, String active, String passive,
String time, int status) {
String sql = " insert into operation_record(optype,active,passive,time,status) values(?,?,?,?,?) ";
Connection conn = DBConnectionManager.getConnection();
PreparedStatement ppst = DBConnectionManager.prepare(conn, sql);
int result = 0;
try {
ppst.setInt(1, optype);
ppst.setString(2, active);
ppst.setString(3, passive);
ppst.setString(4, time);
ppst.setInt(5, status);
result = ppst.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBConnectionManager.close(ppst);
DBConnectionManager.close(conn);
}
return result;
}
@Override
public List<OperationType> getAllType() {
String sql = "select optid,optype from operationtype where optid != 0";
Connection conn = DBConnectionManager.getConnection();
PreparedStatement ps = DBConnectionManager.prepare(conn, sql);
ResultSet rs = null;
List<OperationType> lstop = new ArrayList<OperationType>();
try {
rs = ps.executeQuery();
while (rs.next()){
OperationType op =new OperationType();
op.setOptid(rs.getInt("optid"));
op.setTypeName(rs.getString("optype"));
lstop.add(op);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DBConnectionManager.close(rs);
DBConnectionManager.close(ps);
DBConnectionManager.close(conn);
}
return lstop;
}
@Override
public int getOperationCount(OperationQuery query) {
String sql = " select count(*) from operation_record where 1=1 ";
if (StringUtils.isNotBlank(query.getOperator())){
sql+= " and active = '"+query.getOperator()+"'";
}
if (StringUtils.isNotBlank(query.getObject())){
sql+= " and passive = '"+query.getObject()+"'";
}
if (StringUtils.isNotBlank(query.getOpt())){
sql+= " and optype = "+query.getOpt();
}
if (StringUtils.isNotBlank(query.getStartTime())){
sql+= " and time > '"+query.getStartTime()+"'";
}
if (StringUtils.isNotBlank(query.getEndTime())){
sql+= " and time < '"+query.getEndTime()+"'";
}
Connection conn = DBConnectionManager.getConnection();
PreparedStatement ps = DBConnectionManager.prepare(conn, sql);
ResultSet rs = null;
int total = 0;
try {
rs = ps.executeQuery();
while(rs.next()) {
total = rs.getInt(1);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBConnectionManager.close(rs);
DBConnectionManager.close(ps);
DBConnectionManager.close(conn);
}
return total;
}
@Override
public List<Operation> getOperations(OperationQuery query) {
String sql = "select op.active,op.passive,op.time,op.status,opt.optid,opt.optype from operation_record op,operationType opt where op.optype = opt.optid ";
if (StringUtils.isNotBlank(query.getOperator())){
sql+= " and active = '"+query.getOperator()+"'";
}
if (StringUtils.isNotBlank(query.getObject())){
sql+= " and passive = '"+query.getObject()+"'";
}
if (StringUtils.isNotBlank(query.getOpt())){
sql+= " and op.optype = "+query.getOpt();
}
if (StringUtils.isNotBlank(query.getStartTime())){
sql+= " and time > '"+query.getStartTime()+"'";
}
if (StringUtils.isNotBlank(query.getEndTime())){
sql+= " and time < '"+query.getEndTime()+"'";
}
sql += " order by time desc ";
// sql += " limit "+query.getStartRow() + ","
// + query.getPageSize();
Connection conn = DBConnectionManager.getConnection();
PreparedStatement ps = DBConnectionManager.prepare(conn, sql);
ResultSet rs = null;
List<Operation> lstOp = new ArrayList<Operation>();
try {
rs = ps.executeQuery();
while(rs.next()) {
Operation op = new Operation();
op.setOperator(rs.getString("active"));
op.setObject(rs.getString("passive"));
op.setOptype(rs.getInt("optid"));
op.setTypeName(rs.getString("optype"));
String result = "";
switch(rs.getInt("status")){
case 0:
result= "";
break;
case 1:
result= "ɹ";
break;
case 2:
result= "ʧ";
break;
default:
result = "ʧ";
break;
}
op.setResult(result);
// op.setState(rs.getInt("state"));
op.setTime(rs.getString("time"));
// op.setContent(rs.getString("content"));
lstOp.add(op);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBConnectionManager.close(rs);
DBConnectionManager.close(ps);
DBConnectionManager.close(conn);
}
return lstOp;
}
@Override
public int saveOperation(Operation operation) {
String sql ="";
switch(operation.getOptype()){
case 2: //øֵ
case 3: //õֵ
case 4: //òɼʱ
case 5://ϱʱ
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
sql = "insert into operation(operator,object,opt,time,content) values(?,?,?,?,?)";
break;
default:
sql = "insert into operation(operator,object,opt,time,content,state) values(?,?,?,?,?,1)";
}
int rs = 0;
Connection conn = DBConnectionManager.getConnection();
PreparedStatement ps = DBConnectionManager.prepare(conn, sql);
try {
ps.setString(1, operation.getOperator());
ps.setString(2, operation.getObject());
ps.setInt(3, operation.getOptype());
ps.setString(4, operation.getTime());
ps.setString(5, operation.getContent());
rs = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBConnectionManager.close(ps);
DBConnectionManager.close(conn);
}
return rs;
}
@Override
public int getState(String waterMac, int optType) {
String sql = "select state from operation where object = ? and opt = ? order by time desc limit 1";
Connection conn = DBConnectionManager.getConnection();
PreparedStatement ps = DBConnectionManager.prepare(conn, sql);
ResultSet rs = null;
int result = 0;
try {
ps.setString(1, waterMac);
ps.setInt(2, optType);
rs = ps.executeQuery();
while(rs.next()) {
result =rs.getInt(1);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DBConnectionManager.close(rs);
DBConnectionManager.close(ps);
DBConnectionManager.close(conn);
}
return result;
}
@Override
public int updateOperationState(String smokeMac, int state) {
String sql = "update operation set state = ? where object = ? and state = 0";
Connection conn = DBConnectionManager.getConnection();
PreparedStatement ps = DBConnectionManager.prepare(conn, sql);
int rs = 0;
try {
ps.setInt(1, state);
ps.setString(2, smokeMac);
rs = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBConnectionManager.close(ps);
DBConnectionManager.close(conn);
}
return rs;
}
}
|
Python | UTF-8 | 1,159 | 3.015625 | 3 | [] | no_license | #!/usr/bin/python
# epivot.py - calculate the pivot energy from PL2 fit parameters
# See: http://tinyurl.com/epivot for further details
# Stephen Fegan - sfegan@llr.in2p3.fr - 2011-03-31
# $Id$
import math
import sys
if len(sys.argv) != 7:
print """Usage %s K g CKg Cgg E1 E2
Calculate the pivot energy from the parameters of a PowerLaw2 and
elements of the error matrix. See Jean Ballet's memo:
http://tinyurl.com/epivot for further details
for futher details. This program implements Eqns 7 and 7bis.
Required parameters:
K - Integral flux from PL2
g - Spectral index (defined in the sense of the ST, i.e. less than zero)
CKg - Covarience between K and g
Cgg - Varience of g
E1 - Low energy bound of PL2 energy range
E2 - High energy bound of PL2 energy range"""%sys.argv[0]
sys.exit(1)
K = float(sys.argv[1])
g = float(sys.argv[2])
CKg = float(sys.argv[3])
Cgg = float(sys.argv[4])
E1 = float(sys.argv[5])
E2 = float(sys.argv[6])
if g == -1:
loge = (math.log(E1)+math.log(E2))/2-CKg/K/Cgg;
else:
epsilon=(E2/E1)**(1+g);
loge=(math.log(E1)-epsilon*math.log(E2))/(1-epsilon)-1/(g+1)-CKg/K/Cgg;
e=math.exp(loge);
print e
|
Java | UTF-8 | 4,716 | 2.4375 | 2 | [] | no_license | package org.serger.servlets;
import org.serger.controller.ActionRest;
import org.serger.controller.ActionResult;
import org.serger.controller.ControllerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
/**
* Created by galichanin on 02.03.2017.
*/
@WebServlet("/*")
public class BooksRestServlet extends HttpServlet {
final Logger log = LoggerFactory.getLogger(BooksRestServlet.class);
private ApplicationContext applicationContext;
@Override
public void init() {
applicationContext = new AnnotationConfigApplicationContext("org.serger");
}
@Override
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try {
String path = req.getPathInfo();
log.info("Book servlet path = "+path);
if (path == null)
throw new ControllerException("Path not found", HttpServletResponse.SC_BAD_REQUEST);
String method = req.getMethod();
log.info("Method = "+method);
String[] paths = path.split("/");
// TODO: check URL
// if (paths.length < 2 && paths.length > 3) {
// throw new ServletException("Bad URL");
// }
String reqBody = readRequestBody(req);
log.info("reqBody = "+reqBody);
String controllerBeanName = prepareControllerBeanName(paths[1]);
log.info("Try find bean:"+controllerBeanName);
Object controller = applicationContext.getBean(controllerBeanName);
log.info("Check ActionRest...");
if (!(controller instanceof ActionRest)) {
throw new ControllerException("Wrong action!", HttpServletResponse.SC_BAD_REQUEST);
}
ActionRest actionRest = ((ActionRest) controller);
ActionResult rest;
switch (method) {
case "PUT":
rest = actionRest.put(paths, req.getParameterMap(), reqBody);
break;
case "POST":
rest = actionRest.post(paths, req.getParameterMap(), reqBody);
break;
case "DELETE":
rest = actionRest.delete(paths, req.getParameterMap());
break;
case "GET":
rest = actionRest.get(paths, req.getParameterMap());
break;
default:
throw new ControllerException("Method "+method+" is not supported!", HttpServletResponse.SC_BAD_REQUEST);
}
makeResponse(rest, res);
} catch (ControllerException e) {
String se = "{\"error\":\""+e.getLocalizedMessage()+"\"}";
res.setContentType("application/json; charset=UTF-8");
res.setHeader("Access-Control-Allow-Origin", "*");
res.getOutputStream().write( se.getBytes("UTF-8") );
res.setStatus(e.getStatus());
}
log.info("Query ok!");
}
private void makeResponse(ActionResult rest, HttpServletResponse res) throws IOException {
// Standart REST response
res.setContentType("application/json; charset=UTF-8");
res.setHeader("Access-Control-Allow-Origin", "*");
res.getOutputStream().write( rest.body.getBytes("UTF-8") );
res.setStatus( (rest.status == 0) ? HttpServletResponse.SC_OK : rest.status);
}
/**
* Name controller
* XXX: Camel case!!! Define in Controller @Qualifier annotation
* @param path
* @return
*/
private String prepareControllerBeanName(String path) {
String s = path.substring(0,1).toLowerCase() + path.substring(1);
return s+"Controller";
}
private String readRequestBody(HttpServletRequest request) {
try {
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (Exception e) {
log.warn("Failed to read the request body from the request.");
}
return null;
}
}
|
Markdown | UTF-8 | 9,505 | 2.96875 | 3 | [
"MIT"
] | permissive | # Dynamic Django Forms
## Looking for Maintainer
I haven't used Django in years, and am not actively maintaining this package.
If anyone is interested in maintaining this package, either on this repo or
as a fork, please let me know in a new issue!
## Anyways...
**dynamic-django-forms** is a simple, reusable app that allows you to build (and respond to) dynamic forms, i.e. forms that have variable numbers and types of fields. A few examples of uses include:
1. Building and sending out surveys
2. Job applications where each job might have a different application forms
## Installation
Install via pip:
`pip install dynamic-django-forms`
Add to settings.INSTALLED_APPS:
``` python
INSTALLED_APPS = {
"...",
"dynamic_forms",
"..."
}
```
## Components
The main functionality of `dynamic-django-forms` is contained within 2 model fields:
### Form Builder
`dynamic_forms.models.FormField` allows you to build and edit forms via a convenient UI, and stores them in JSON-Schema form. It is easy to use both through the admin panel and in any custom template webpage.
Example Setup:
``` python
from dynamic_forms.models import FormField
class Survey:
# Other Fields Here
form = FormField()
```
Please note that JSON data can saved into the model field as a python `dict` or a valid JSON string. When the value is retrieved from the database, it will be provided as a `list` containing `dict`s for each dynamic form field.
### Form Response
`dynamic_forms.models.ResponseField` allows you to render, and collect responses to, forms built with the Form Builder. It is currently only supported through custom views. All form responses are stored as a dict where the key is the question label, and the value is the user's input.
Example Setup:
Model Config:
``` python
from django.db import models
from dynamic_forms.models import ResponseField
from otherapp.models import Survey
class SurveyResponse:
# Other Fields Here
survey = models.ForeignKey(Survey, on_delete=models.CASCADE) # Optional
response = ResponseField()
```
Please note that including a ForeignKey link from the model containing responses to the model containing forms isnt technically required; however, it is highly recommended and will make linking the two much easier
### Configuring ResponseFields with forms
You must provide a valid JSON Schema to ResponseField's associated FormField at runtime. This is best done in the view where the dynamic form will be used. Generally speaking, this means you should:
1. Obtain the JSON Schema Form Data
* Get an instance of a model containing a FormField that has already been built OR
* Provide the form data as a constant
2. Intercept the Form instance used in the view where the dynamic form will be shown. This could be an automatically generated ModelForm (via a generic Class Based View), or a form instance you have made yourself.
3. Provide the JSON form data to the form field:
* form_instance.fields['response_field_name_in_form'].add_fields(JSON_DATA) will add the fields in JSON_DATA to the existing fields in the dynamic form.
* form_instance.fields['response_field_name_in_form].replace_fields(JSON_DATA) will remove any fields currently in the dynamic form and replace the with the fields in JSON_DATA
An example of how to do this can be found in the DynamicFormMixin explained in the next section:
``` python
from django.views.generic.edit import FormMixin
class DynamicFormMixin(FormMixin):
form_field = "form"
form_pk_url_kwarg = "pk"
response_form_fk_field = None
response_field = "response"
def _get_object_containing_form(self, pk):
return self.form_model.objects.get(pk=pk)
def get_form(self, *args, **kwargs):
form = super().get_form(*args, **kwargs)
# Get instance of model containing form used for this response. Save this object as an instance variable for use in form_valid method
form_instance_pk = self.kwargs[self.form_pk_url_kwarg]
self.form_instance = self._get_object_containing_form(form_instance_pk)
# Get json form configuration from form-containing object
json_data = getattr(self.form_instance, self.form_field)
# Add fields in JSON to dynamic form rendering field.
form.fields[self.response_field].add_fields(json_data)
return form
def form_valid(self, form):
action = form.save(commit=False)
action.survey = self.form_instance
action.save()
return super().form_valid(form)
```
#### Configuration Shortcut
The process of configuring ResponseFields with forms is somewhat complicated, so a shortcut is provided.
`dynamic_forms.views.DynamicFormMixin` can be added to Class Based Views extending from `django.views.generic.edit.CreateView` and `django.views.generic.edit.UpdateView`, and will automatically complete configure the dynamic form provided that:
1. The model containing the ResponseField has a ForeignKey link to a model containing the FormField.
2. The following attributes are provided:
1. `form_model`: The relevant model (not instance) containing a FormField with the wanted dynamic form configuration. I.e. which model is the survey defined in? Default: `None`
2. `form_field`: The attribute of `form_model` that contains the FormField. I.e. Which field in the Survey model contains the form? Default: `form`
3. `form_pk_url_kwarg` The [URL Keyword Argument](https://docs.djangoproject.com/en/2.2/topics/http/urls/#passing-extra-options-to-view-functions) containing the primary key of the instance of `form_model` that contains the dynamic form we want? I.e. Which survey are we responding to? Default: `pk`
4. `response_form_fk_field` The attribute of the model which contains the ResponseField that links via ForeignKey to the model containing the FormField. I.e. Which attribute of the Survey Response model links to the Survey model? Default: `None`
5. `response_field` The attribute of the Response model which contains the ResponseField. I.e. which attribute of the Survey Response model contains the actual responses? Default: `response`
Example:
``` python
class RespondView(DynamicFormMixin, CreateView):
model = SurveyResponse
fields = ['response']
template_name = "example/respond.html"
form_model = Survey
form_field = "form"
form_pk_url_kwarg = "survey_id"
response_form_fk_field = "survey"
response_field = "response"
def get_success_url(self):
return reverse('survey_detail', kwargs={"survey_id": self.form_instance.pk})
```
### Django Crispy Forms Support
If you are using [Django Crispy Forms](https://github.com/django-crispy-forms/django-crispy-forms) to make your forms look awesome, set use the following setting:
`USE_CRISPY = True` (false by default)
Please note that you are responsible for importing any CSS/JS libraries needed by your chosen crispy template pack into the templates where (e.x. bootstrap, uni-form, foundation).
## Fields Supported and Limitations
`dynamic-django-forms` currently supports the following field types:
| Description | JSON |
|----------------|----------------|
| Checkbox Group | checkbox-group |
| Date Field | date |
| Hidden Input | hidden |
| Number | number |
| Radio Group | radio-group |
| Select | select |
| Text Field | text |
| Email Field | email |
| Text Area | textarea |
The only major limitation of `dynamic-django-forms`, which is also one of its major features, is the dissociation of dynamic form questions and responses.
Pros:
* Responses cannot be changed after submission
* Dynamic forms can be edited, removing, changing, or adding questions, without affecting prior responses
Cons:
* Responses cannot be changed after submission
## Custom JS for FormBuilder
On `settings.py` you can use a variable to inject custom JS code before the form builder is initialized. Note that the `options` variable. Note that when this custom JS runs, the following variables are available:
- `textArea`: This is a hidden textarea input used to submit the JSON form schema.
- `options`: This is a [FormBuilder Options object](https://formbuilder.online/docs/) that you can override and modify to change how the form is displayed.
```
DYNAMIC_FORMS_CUSTOM_JS = 'console.log(1)'
```
## Example Site
To run an example site, run `cd example && docker-compose up`. If you do not use docker, you can manually install the requirements with `pip install -r example/requirements.txt` and run the site with `python example/manage.py runserver`.
## Planned Improvements
* Support for some HTML Elements
* Headers
* Paragraph Text
* Dividers
* Support for the following fields:
* Color Field
* Telephone Field
* Star Rating
* Support for "Other" option on radio groups, checkbox groups, and select dropdowns
* User can select "other", at which point an inline text-type input will appear where they can put a custom choice
* Ability to provide default JSON form config via:
* String
* Dict
* File
* Remote URL
* DynamicFormMixin should support slugs
* Ability to customize JSONBuilder settings through Django settings
* Extensive Automated Testing
### Possible Improvements
* Support File Upload Field
## Credits
Huge thanks to Kevin Chappell & Team for developing the awesome open source [Form Builder UI](https://github.com/kevinchappell/formBuilder)!
|
Python | UTF-8 | 2,489 | 2.71875 | 3 | [] | no_license | #!/usr/bin/env python
#
# server-version.py: print a Subversion server's version number
#
# USAGE: server-version.py URL
#
# The URL can contain any path on the server, as we are simply looking
# for Apache's response to OPTIONS, and its Server: header.
#
# EXAMPLE:
#
# $ ./server-version.py http://svn.collab.net/
# or
# $ ./server-version.py https://svn.collab.net/
#
import sys
import re
try:
# Python >=3.0
from http.client import HTTPConnection as http_client_HTTPConnection
from http.client import HTTPSConnection as http_client_HTTPSConnection
from urllib.parse import urlparse as urllib_parse_urlparse
except ImportError:
# Python <3.0
from httplib import HTTPConnection as http_client_HTTPConnection
from httplib import HTTPSConnection as http_client_HTTPSConnection
from urlparse import urlparse as urllib_parse_urlparse
def print_version(url):
scheme, netloc, path, params, query, fragment = urllib_parse_urlparse(url)
if scheme == 'http':
conn = http_client_HTTPConnection(netloc)
elif scheme == 'https':
conn = http_client_HTTPSConnection(netloc)
else:
print('ERROR: this script only supports "http" and "https" URLs')
sys.exit(1)
conn.putrequest('OPTIONS', path)
conn.putheader('Host', netloc)
conn.endheaders()
resp = conn.getresponse()
status, msg, server = (resp.status, resp.msg, resp.getheader('Server'))
conn.close()
# Handle "OK" and Handle redirect requests, if requested resource
# resides temporarily under a different URL
if not server:
print('ERROR: could not determine version - missing Server header')
else:
res = re.search('.*(SVN/[\d.]+).*', server)
if res != None:
print('Possible version: %s' % res.group(1))
else:
print('NOTICE: version unknown')
# if status != 200 and status != 302:
# print('ERROR: bad status response: %s %s' % (status, msg))
# sys.exit(1)
# if not server:
# # a missing Server: header. Bad, bad server! Go sit in the corner!
# print('WARNING: missing header')
# else:
# for part in server.split(' '):
# if part[:4] == 'SVN/':
# print(part[4:])
# break
# else:
# # the server might be configured to hide this information, or it
# # might not have mod_dav_svn loaded into it.
# print('NOTICE: version unknown')
if __name__ == '__main__':
if len(sys.argv) != 2:
print('USAGE: %s URL' % sys.argv[0])
sys.exit(1)
print_version(sys.argv[1])
|
Markdown | UTF-8 | 1,362 | 2.734375 | 3 | [
"MIT"
] | permissive | # Gradiance
**ATENÇÃO**: Tente fazer e entender as questões do Gradiance antes de ler esse documento.
Nessa página você irá encontrar as respostas com explicações delas
Esse github não providência as respostas sem explicações[.](https://github.com/thiagola92/PUC-INF1015/tree/0a21d31cd10dd1b2e7df2e0877fe30bb70401440/Gradiance)
---

Para descobrir as erradas basta usar essas duas informações:
**1)** Essa máquina substitui 1 por 0 e 0 por 0, ou seja, deixa 0 por onde passa
**2)** Da Halt se encontra 11
Utilizando a primeira informação você elimina qualquer alternativa que tiver 1 atrás do estado atual
Utilizando a segunda informação você sabe que essa máquina não tem como passar da parte que tem "11", então se alguma delas passou dessa parte então você pode eliminar
101q0110 - tem 1 antes do q, elimina por causa da informação **1**
0000000qB - passou de onde 11, elimina por causa da informação **2**
10q10110 - tem 1 antes do q, elimina por causa da informação **1**
---

Troca 0 por 1
Troca 1 por 0
Acaba escrevendo B e estado final no fim da string
---

Em 5 passos pode acabar em qualquer um desses 4 mostrados na imagem

---

Para(halt) quando encontra dois 1 seguidos (ou seja quando encontra "11")
|
Python | UTF-8 | 4,267 | 2.5625 | 3 | [
"MIT"
] | permissive | # PyTorch Lightning Imports
import pytorch_lightning as pl
from pytorch_lightning.metrics.functional import accuracy
from pytorch_lightning.loggers import TensorBoardLogger
# PyTorch Imports
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.functional import cross_entropy
from torch.utils.data import Dataset, DataLoader
import torchvision as tv
from torch.optim import Adam, AdamW
import torchvision.models as models
# Python Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Default Python
import os
from PIL import Image
cat_to_idx = {'Cassava bacterial blight (cbb)': 0,
'Cassava brown streak disease (cbsd)': 1,
'Cassava green mottle (cgm)': 2,
'Cassava mosaic disease (cmd)': 3,
'Healthy': 4}
class CustomDataset(Dataset):
def __init__(self, data_path, transforms, mapping = cat_to_idx):
self.data_path = data_path
self.transforms = transforms
self.mapping = cat_to_idx
def __len__(self):
return len(self.data_path)
def __getitem__(self, idx):
im = Image.open(self.data_path.loc[idx, 'file_name'])
label = int(self.mapping[self.data_path.loc[idx, 'classes']])
if self.transforms:
im = self.transforms(im)
return im, label
train_data = pd.read_csv('../remo_train.csv')
validation_data = pd.read_csv('../remo_valid.csv')
means = [0.485, 0.456, 0.406]
stds = [0.229, 0.224, 0.225]
tv_transforms = tv.transforms.Compose([
tv.transforms.RandomRotation(30),
tv.transforms.RandomResizedCrop(400),
tv.transforms.RandomHorizontalFlip(p=0.5),
tv.transforms.ToTensor(),
tv.transforms.Normalize(means, stds)])
val_transforms = tv.transforms.Compose([ tv.transforms.Resize((400, 400), Image.BICUBIC),
tv.transforms.ToTensor(),
tv.transforms.Normalize(means, stds)])
train_dl = DataLoader(CustomDataset(data_path=train_data, transforms=tv_transforms), batch_size=128, num_workers=4, pin_memory=True)
val_dl = DataLoader(CustomDataset(data_path=validation_data, transforms=val_transforms), batch_size = 10, num_workers=4, pin_memory=True)
class ResNetTransferLearning(pl.LightningModule):
def __init__(self, num_classes, model):
super().__init__()
self.num_classes = num_classes
self.backbone = model
for param in self.backbone.parameters():
param.required_grad = False
self.backbone.fc = nn.Sequential(nn.Linear(512, 256),
nn.ReLU(),
nn.Dropout(p=0.5),
nn.Linear(256, self.num_classes),
nn.LogSoftmax(dim=1))
def training_step(self, batch, batch_idx):
x, y = batch
preds = self.backbone(x)
loss = cross_entropy(preds, y)
self.log('train_loss', loss)
self.log('train_acc', accuracy(preds, y))
return loss
def validation_step(self, batch, batch_idx):
x, y = batch
preds = self.backbone(x)
loss = cross_entropy(preds, y)
self.log('valid_loss', loss)
self.log('valid_acc', accuracy(preds, y))
def forward(self, x):
with torch.no_grad():
out = self.backbone(x)
return out
def configure_optimizers(self):
optimizer = AdamW(self.parameters(), lr = 0.001)
scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, 5)
return [optimizer], [scheduler]
num_classes = 5
model = models.resnet18(pretrained=True)
#model = models.resnet34(pretrained=True)
resnet_model = ResNetTransferLearning(num_classes= num_classes,
model = model)
trainer = pl.Trainer(max_epochs=128, gpus=2, flush_logs_every_n_steps = 100, accelerator='ddp', plugins='ddp_sharded', resume_from_checkpoint='lightning_logs/version_7/checkpoints/epoch=107-step=7235.ckpt', check_val_every_n_epoch=5)
trainer.fit(resnet_model, train_dl, val_dl)
|
C | UTF-8 | 9,914 | 2.5625 | 3 | [] | no_license |
#include "axdr.h"
#include <stdio.h>
#include <string.h>
#include <assert.h>
typedef enum
{
DLMS_null_data = 0,
DLMS_array = 1,
DLMS_structure = 2,
DLMS_boolean = 3,
DLMS_bit_string = 4,
DLMS_integer32 = 5,
DLMS_unsigned32 = 6,
DLMS_octet_string = 9,
DLMS_visible_string = 10,
DLMS_bcd = 13,
DLMS_integer8 = 15,
DLMS_integer16 = 16,
DLMS_unsigned8 = 17,
DLMS_unsigned16 = 18,
DLMS_compact_array = 19,
DLMS_integer64 = 20,
DLMS_unsigned64 = 21,
DLMS_enumerate = 22,
DLMS_float32 = 23,
DLMS_float64 = 24,
DLMS_date_time = 25,
DLMS_date = 26,
DLMS_time = 27,
DLMS_dont_care = 255
} PrimitiveTypeTag;
//----------------------------------------------------------------------
// low-level buufer operations.
bool axdrStreamFromBytes( AXDRStream* stream, uint8_t* data, uint8_t numberOfBytes )
{
stream->data = data;
stream->dataEnd = data + numberOfBytes;
return true;
}
bool axdrGetByte( AXDRStream* stream, uint8_t* byte )
{
*byte = *stream->data;
stream->data++;
return true;
}
bool axdrGetByteAndCheck( AXDRStream* stream, uint8_t* byte, uint8_t expectedByte )
{
uint8_t value = *stream->data;
if(byte != NULL) {
*byte = value;
}
if( value != expectedByte ) {
return false;
}
stream->data++;
return true;
}
bool axdrSetByte( AXDRStream* stream, uint8_t byte )
{
*stream->data = byte;
stream->data++;
return true;
}
bool axdrSetBytes( AXDRStream* stream, uint8_t* bytes, uint32_t numberOfBytes )
{
memcpy(stream->data, bytes, numberOfBytes);
stream->data+=numberOfBytes;
return true;
}
bool axdrGetBytes( AXDRStream* stream, uint8_t* bytes, uint32_t numberOfBytes )
{
memcpy(bytes, stream->data, numberOfBytes);
stream->data += numberOfBytes;
return true;
}
//----------------------------------------------------------------------
// primitive types.
bool axdrSetUint8( AXDRStream* stream, uint8_t value )
{
axdrSetByte( stream, DLMS_unsigned8 );
axdrSetByte( stream, (value&0xff)>>0 );
return true;
}
bool axdrGetUint8( AXDRStream* stream, uint8_t* value )
{
axdrGetByteAndCheck( stream, NULL, DLMS_unsigned8 );
axdrGetByte( stream, value );
return true;
}
bool axdrSetUint16( AXDRStream* stream, uint16_t value )
{
axdrSetByte( stream, DLMS_unsigned16 );
axdrSetByte( stream, (value&0xff00)>>8 );
axdrSetByte( stream, (value&0xff)>>0 );
return true;
}
bool axdrGetUint16( AXDRStream* stream, uint16_t* value )
{
uint8_t byte;
axdrGetByteAndCheck( stream, NULL, DLMS_unsigned16 );
axdrGetByte( stream, &byte );
*value = (*value << 8) | (uint16_t)byte;
axdrGetByte( stream, &byte );
*value = (*value << 8) | (uint16_t)byte;
return true;
}
bool axdrSetUint32( AXDRStream* stream, uint32_t value )
{
axdrSetByte( stream, DLMS_unsigned32 );
axdrSetByte( stream, (value&0xff000000)>>24 );
axdrSetByte( stream, (value&0xff0000)>>16 );
axdrSetByte( stream, (value&0xff00)>>8 );
axdrSetByte( stream, (value&0xff)>>0 );
return true;
}
bool axdrGetUint32( AXDRStream* stream, uint32_t* value )
{
uint8_t byte;
axdrGetByteAndCheck( stream, NULL, DLMS_unsigned32 );
axdrGetByte( stream, &byte );
*value = (*value << 8) | (uint32_t)byte;
axdrGetByte( stream, &byte );
*value = (*value << 8) | (uint32_t)byte;
axdrGetByte( stream, &byte );
*value = (*value << 8) | (uint32_t)byte;
axdrGetByte( stream, &byte );
*value = (*value << 8) | (uint32_t)byte;
return true;
}
//----------------------------------------------------------------------
bool axdrSetLength( AXDRStream* stream, uint32_t length )
{
if(length < 0x80)
{
stream->data[0] = (uint8_t)length;
stream->data += 1;
}
else if(length < 0xffff)
{
stream->data[0] = 0x82;
stream->data[1] = (length>>8)&0x00ff;
stream->data[2] = length&0x00ff;
stream->data += 3;
}
else
{
stream->data[0] = 0x84;
stream->data[1] = (length>>24)&0x000000ff;
stream->data[2] = (length>>16)&0x000000ff;
stream->data[3] = (length>>8)&0x000000ff;
stream->data[4] = length&0x000000ff;
stream->data += 5;
}
return true;
}
bool axdrGetLength( AXDRStream* stream, uint32_t* length )
{
uint8_t value = stream->data[0];
if( (value&0x80) == 0)
{
*length = value;
stream->data += 1;
}
else
{
uint8_t numberOfBytes = value & 0x7f;
if(numberOfBytes == 2)
{
*length = (stream->data[1]<<8) | (stream->data[2]);
stream->data += 3;
}
else if(numberOfBytes == 4)
{
*length = (stream->data[1]<<24) | (stream->data[2]<<16) | (stream->data[3]<<8) | (stream->data[4]);
stream->data += 5;
}
else
{
stream->data += 1;
}
}
return true;
}
bool axdrSetOctetString( AXDRStream* stream, uint8_t* data, uint32_t numberOfBytes)
{
axdrSetByte(stream, DLMS_octet_string);
axdrSetLength(stream, numberOfBytes);
axdrSetBytes(stream, data,numberOfBytes);
return true;
}
bool axdrSetStruct( AXDRStream* stream, uint32_t numberOfFields)
{
axdrSetByte(stream, DLMS_structure);
axdrSetLength(stream, numberOfFields);
return true;
}
bool axdrSetArray( AXDRStream* stream, uint32_t numberOfElements)
{
axdrSetByte(stream, DLMS_array);
axdrSetLength(stream, numberOfElements);
return true;
}
bool axdrGetArray( AXDRStream* stream, uint32_t* numberOfElements)
{
axdrGetByteAndCheck( stream, NULL, DLMS_array );
axdrGetLength( stream, numberOfElements );
return true;
}
bool axdrGetStruct( AXDRStream* stream, uint32_t* numberOfFields)
{
axdrGetByteAndCheck( stream, NULL, DLMS_structure );
axdrGetLength( stream, numberOfFields );
return true;
}
bool axdrGetOctetString( AXDRStream* stream, uint8_t* data, uint32_t dataMaxSize, uint32_t* numberOfBytes)
{
axdrGetByteAndCheck( stream, NULL, DLMS_octet_string );
axdrGetLength( stream, numberOfBytes );
assert( *numberOfBytes <= dataMaxSize );
axdrGetBytes( stream, data,*numberOfBytes );
return true;
}
bool axdrSetDateTime( AXDRStream* stream, DLMSDateTime* datetime )
{
axdrSetByte(stream, DLMS_octet_string);
axdrSetByte(stream, 12);
axdrSetByte(stream, (datetime->date.year&0xff00)>>8);
axdrSetByte(stream, datetime->date.year&0xff);
axdrSetByte(stream, datetime->date.month);
axdrSetByte(stream, datetime->date.dayOfMonth);
axdrSetByte(stream, datetime->date.dayOfWeek);
axdrSetByte(stream, datetime->time.hour);
axdrSetByte(stream, datetime->time.minute);
axdrSetByte(stream, datetime->time.seconds);
axdrSetByte(stream, datetime->time.hundredths);
axdrSetByte(stream, (datetime->deviation&0xff00)>>8);
axdrSetByte(stream, datetime->deviation&0xff);
axdrSetByte(stream, datetime->status);
}
bool axdrSetDate( AXDRStream* stream, DLMSDate* date )
{
axdrSetByte(stream, DLMS_octet_string);
axdrSetByte(stream, 5);
axdrSetByte(stream, (date->year&0xff00)>>8);
axdrSetByte(stream, date->year&0xff);
axdrSetByte(stream, date->month);
axdrSetByte(stream, date->dayOfMonth);
axdrSetByte(stream, date->dayOfWeek);
}
bool axdrSetTime( AXDRStream* stream, DLMSTime* time )
{
axdrSetByte(stream, DLMS_octet_string);
axdrSetByte(stream, 4);
axdrSetByte(stream, time->hour);
axdrSetByte(stream, time->minute);
axdrSetByte(stream, time->seconds);
axdrSetByte(stream, time->hundredths);
}
bool axdrGetDateTime( AXDRStream* stream, DLMSDateTime* datetime )
{
axdrGetByteAndCheck( stream, NULL, DLMS_octet_string );
axdrGetByteAndCheck( stream, NULL, 12 );
uint8_t lo;
uint8_t hi;
axdrGetByte( stream, &hi );
axdrGetByte( stream, &lo );
datetime->date.year = (hi<<8) | lo;
axdrGetByte( stream, &datetime->date.month );
axdrGetByte( stream, &datetime->date.dayOfMonth );
axdrGetByte( stream, &datetime->date.dayOfWeek );
axdrGetByte( stream, &datetime->time.hour );
axdrGetByte( stream, &datetime->time.minute );
axdrGetByte( stream, &datetime->time.seconds );
axdrGetByte( stream, &datetime->time.hundredths );
axdrGetByte( stream, &hi );
axdrGetByte( stream, &lo );
datetime->deviation = (hi<<8) | lo;
uint8_t temp = 0;
axdrGetByte( stream, &temp );
datetime->status = temp;
}
bool axdrGetDate( AXDRStream* stream, DLMSDate* date )
{
axdrGetByteAndCheck( stream, NULL, DLMS_octet_string );
axdrGetByteAndCheck( stream, NULL, 5 );
uint8_t lo;
uint8_t hi;
axdrGetByte( stream, &hi );
axdrGetByte( stream, &lo );
date->year = (hi<<8) | lo;
axdrGetByte( stream, &date->month );
axdrGetByte( stream, &date->dayOfMonth );
axdrGetByte( stream, &date->dayOfWeek );
}
bool axdrGetTime( AXDRStream* stream, DLMSTime* time )
{
axdrGetByteAndCheck( stream, NULL, DLMS_octet_string );
axdrGetByteAndCheck( stream, NULL, 4 );
axdrGetByte( stream, &time->hour );
axdrGetByte( stream, &time->minute );
axdrGetByte( stream, &time->seconds );
axdrGetByte( stream, &time->hundredths );
}
//----------------------------------------------------------------------
// Test app.
int main()
{
AXDRStream stream;
uint8_t data[] = {0x7e, 0x00, 0x7e};
axdrStreamFromBytes( &stream, &data[0], sizeof(data) );
}
|
Python | UTF-8 | 899 | 2.96875 | 3 | [] | no_license | # Converts .json to .sql
import json
with open('./data/documents.json') as json_file:
data = json.load(json_file)
with open("./data/documents.sql", "a") as myfile:
i = 1
for row in data:
if (i % 100 == 0):
print(i)
url = row["url"].translate(str.maketrans({"'": r"''", "\n": " "}))
title = row["title"].translate(str.maketrans({"'": r"''", "\n": " ", "\\": ""}))
text = row["text"].translate(str.maketrans({"'": r"''", "\n": " ", "\\": ""}))
del row["url"]
del row["title"]
del row["text"]
plain_json = json.dumps(row).translate(str.maketrans({"'": r"''", "\n": " "}))
myfile.write(f"insert into blog (url, title, text, json) VALUES('{url}','{title}','{text}','{plain_json}');\n")
i += 1
|
C | UTF-8 | 10,741 | 3.546875 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Definimos los Struct
//Estructura de Alumno
typedef struct Alumno{
int boleta;
struct Alumno *sigAlumno;
}nodoAlumno;
//Estructura de Listas que contienen Alumno
typedef struct Lista {
struct Alumno *start;
}Lista;
//Funciones
//Comparar Listas
int compararListas( nodoAlumno *lista1 , nodoAlumno *lista2 ){
int val = 1;
nodoAlumno *iterador1 = lista1;
nodoAlumno *iterador2 = lista2;
while(iterador1 != NULL && iterador2 != NULL){
//Mientras los valores no sean nulos comparamos los valores de boleta
if(iterador1 -> boleta != iterador2 -> boleta){
val=0;
break;
}
iterador1 = iterador1 -> sigAlumno;
iterador2 = iterador2 -> sigAlumno;
}
if( (iterador1!=NULL && iterador2==NULL) || (iterador1==NULL && iterador2!=NULL) ){
val=0;
}
return val;
}
//Concatenar
nodoAlumno* concatenar( nodoAlumno *lista1 , nodoAlumno *lista2, int orden ){
/*Si el usuario introduce 1 la primer lista irá primero
Por el contrario si el usuario introduce 2, se pone la lista2 primero
y el último nodo recibe como siguienteALumno todos los valores de la
lista numero 1*/
if(orden==1){
if(lista1==NULL){
return lista2;
}else{
nodoAlumno*iterador=lista1;
while(iterador->sigAlumno!=NULL){
iterador = iterador -> sigAlumno;
}
iterador->sigAlumno=lista2;
return lista1;
}
}
if(orden==2){
if(lista2==NULL){
return lista1;
}else{
nodoAlumno*iterador=lista2;
while(iterador->sigAlumno!=NULL){
printf("%d\n", iterador -> boleta);
iterador = iterador -> sigAlumno;
}
iterador->sigAlumno=lista1;
return lista2;
}
}
}
//Inicialisa la lista de structs
void InicializarLista( Lista *aLista ){
aLista -> start = NULL;
}
//Insertar Valor al Inicio
void InsertarAlInicio( Lista *aLista , int boleta ){
nodoAlumno *posicionador;
posicionador = malloc( sizeof( nodoAlumno ));
posicionador -> boleta = boleta;
posicionador -> sigAlumno = aLista -> start;
aLista -> start = posicionador;
}
//Insertar un Elemento al final
nodoAlumno* InsertarAlFinal(){
int val=0;
nodoAlumno *posicionador;
posicionador = malloc( sizeof( nodoAlumno ));
puts("Escribe la boleta de este alumno");
scanf("%d",&(posicionador -> boleta));
setbuf(stdin,NULL);
posicionador -> sigAlumno = NULL;
nodoAlumno *iterador;
iterador=posicionador;
puts("Desea agragar otro alumno, 0 para no");
scanf("%d",&val);
setbuf(stdin,NULL);
while(val!=0){
iterador->sigAlumno= malloc( sizeof( nodoAlumno ));
iterador=iterador->sigAlumno;
puts("Escribe la boleta de este alumno");
scanf("%d",&(iterador -> boleta));
setbuf(stdin,NULL);
iterador->sigAlumno=NULL;
puts("Desea agragar otro alumno, 0 para no");
scanf("%d",&val);
setbuf(stdin,NULL);
}
return posicionador;
}
//Intercalar Nodos
nodoAlumno* intercalarNodos(nodoAlumno* lista1,nodoAlumno* lista2){
nodoAlumno* iterador1=lista1;
nodoAlumno* iterador2=lista2;
nodoAlumno* lista3=NULL;
lista3=malloc( sizeof( nodoAlumno ));
if(iterador1!=NULL){
lista3->boleta=iterador1->boleta;
iterador1=iterador1->sigAlumno;
}else{
if(iterador2!=NULL){
lista3->boleta=iterador2->boleta;
iterador2=iterador2->sigAlumno;
}
}
lista3->sigAlumno=NULL;
nodoAlumno* iterador3;
iterador3=lista3;
while(iterador1!=NULL || iterador2!=NULL){
if(iterador2!=NULL){
iterador3->sigAlumno=malloc( sizeof( nodoAlumno ));
iterador3=iterador3->sigAlumno;
iterador3->boleta=iterador2->boleta;
iterador2=iterador2->sigAlumno;
iterador3->sigAlumno=NULL;
}
if(iterador1!=NULL){
iterador3->sigAlumno=malloc( sizeof( nodoAlumno ));
iterador3=iterador3->sigAlumno;
iterador3->boleta=iterador1->boleta;
iterador1=iterador1->sigAlumno;
iterador3->sigAlumno=NULL;
}
}
return lista3;
}
//Invertir Lista
void invertirLista(nodoAlumno*lista, Lista *aLista){
nodoAlumno *iterador=lista;
while(iterador!=NULL){
/*La funcion se va a encargar que todo siguiente alumno
sea asignado al inicio de la lista hasta que no existan más alumnos*/
nodoAlumno *posicionador;
posicionador = malloc( sizeof( nodoAlumno ));
posicionador -> boleta = iterador->boleta;
posicionador -> sigAlumno = aLista -> start;
aLista -> start = posicionador;
iterador=iterador->sigAlumno;
}
}
//Imprimir Lista
void imprimirLista ( Lista *aLista ){
nodoAlumno *posicionador = aLista -> start;
while( posicionador != NULL ){
printf("%d\n", posicionador -> boleta);
posicionador = posicionador -> sigAlumno;
}
}
//ImprimirLista cuando tenemos un IterardorNodoALumno
void ImprimirLista2(nodoAlumno*posicionador){
nodoAlumno*iterador=posicionador;
while(iterador!=NULL){
printf("%d\n", iterador -> boleta);
iterador = iterador -> sigAlumno;
}
}
//Eliminar toda la lista
void EliminarListaCompleta( Lista *aLista ){
/*Debemos usar un for para eliminar nodo por nodo y liberar memoria*/
if( aLista -> start != NULL ){
nodoAlumno *posicionador = aLista -> start;
aLista -> start = aLista -> start -> sigAlumno;
free(posicionador);
}
}
//Eliminar toda la lista ALUMNO
void EliminarListaCompletaA( nodoAlumno **lista ){
if( (*lista) -> sigAlumno != NULL ){
nodoAlumno *posicionador = (*lista) -> sigAlumno;
(*lista) -> sigAlumno = (*lista) -> sigAlumno -> sigAlumno;
free(posicionador);
}
}
//Buscar Elemento
int buscarElemento(nodoAlumno*lista1,int num_boleta){
/*Esta funcion buscara que el elemento seleccionado exista
lo usaremos en la función sublista*/
nodoAlumno*iterador=lista1;
int val=-1;
while(iterador!=NULL){
if(iterador->boleta==num_boleta){
val=1;
break;
}
iterador=iterador->sigAlumno;
}
return val;
}
//InsertarElemento
void insertarElemento(nodoAlumno** lista1,int numBoleta){
/*Esta función nos sirve para insertar un elemento después de haberlo buscado
Como se mostrará en la función subLista*/
(*lista1)= malloc( sizeof( nodoAlumno ));
(*lista1)-> boleta = numBoleta;
(*lista1)-> sigAlumno = NULL;
}
//Crear una Sublista
nodoAlumno* subLista(nodoAlumno*lista1,nodoAlumno*lista2){
nodoAlumno*iterador=lista1;
int numBoleta,val;
puts("Estos son los elementos de la Lista:");
ImprimirLista2(iterador);
puts("Elije los elmentos de la sublista");
scanf("%d",&numBoleta);
setbuf(stdin,NULL);
if(buscarElemento(lista1,numBoleta)==1){
insertarElemento(&lista2,numBoleta);
}else{
puts("La boleta no se encuentra en la Lista");
}
nodoAlumno* iterador2=lista2;
puts("Deseas agregar otra boleta?, presione 1 para si");
scanf("%d",&val);
setbuf(stdin,NULL);
while(val==1){
puts("Escriba la boleta");
scanf("%d",&numBoleta);
if(buscarElemento(lista1,numBoleta)==1){
insertarElemento(&(iterador2->sigAlumno),numBoleta);
}else{
puts("La boleta no se encuentra en la Lista");
}
puts("Deseas agregar otra boleta?, presione 1 para si");
scanf("%d",&val);
setbuf(stdin,NULL);
}
return lista2;
}
int main(){
int opcion,val,x;
/*En este main lo principal es el menú de opciones para que el usuario
nos indique que operacion quiere realizar y así nosotros poder llamar
a las funciones anteriormente desarrolladas*/
do{
puts("Escriba la opcion que desea realizar:");
puts("1° Concatenar dos listas");
puts("2° Invertir lista");
puts("3° Intercalar nodos de 2 listas");
puts("4° Comparar listas");
puts("5° Generar subLista");
scanf("%d",&opcion);
setbuf(stdin,NULL);
/*El menu se realizó con un IF ANIDADO*/
if(opcion==1){
int orden;
puts("Escriba la primera lista");
nodoAlumno* lista1=InsertarAlFinal();
puts("Escriba la segunda lista");
nodoAlumno* lista2=InsertarAlFinal();
puts("Escriba el orden de la concatenacion 1 para la lista1 y 2 para la lista2");
scanf("%d",&orden);
setbuf(stdin,NULL);
nodoAlumno* lista_concatenada=concatenar(lista1,lista2,orden);
puts("La lista concatenada es:");
ImprimirLista2(lista_concatenada);
}else{
if(opcion==2){
Lista MiLista;
InicializarLista( &MiLista );
puts("Escriba la lista");
nodoAlumno* lista=InsertarAlFinal();
invertirLista(lista,&MiLista);
puts("La lista invertida es:");
imprimirLista(&MiLista);
}else{
if(opcion==3){
puts("Escriba la primera lista");
nodoAlumno* lista1=InsertarAlFinal();
puts("Escriba la segunda lista");
nodoAlumno* lista2=InsertarAlFinal();
nodoAlumno* lista3=intercalarNodos(lista1,lista2);
puts("La lista resultante es:");
EliminarListaCompletaA(&lista1);
EliminarListaCompletaA(&lista2);
ImprimirLista2(lista3);
}else{
if(opcion==4){
puts("Escriba la primera lista");
nodoAlumno* lista1=InsertarAlFinal();
puts("Escriba la segunda lista");
nodoAlumno* lista2=InsertarAlFinal();
int comparacion=compararListas(lista1,lista2);
if(comparacion==1){
puts("Las listas son iguales");
}else{
puts("Las listas no son iguales");
}
}else{
if(opcion==5){
puts("Escriba la primera lista");
nodoAlumno* lista1=InsertarAlFinal();
nodoAlumno* lista2=NULL;
lista2=subLista(lista1,lista2);
puts("La sublista generada es:");
ImprimirLista2(lista2);
}else{
printf("%s\n", "Opcion no valida");
}
}
}
}
}
puts("¿Desea realizar otra operacion? Presione 1 para si");
scanf("%d",&val);
setbuf(stdin,NULL);
}while(val==1);
} |
TypeScript | UTF-8 | 1,083 | 2.578125 | 3 | [] | no_license | import { Ingrediant } from "../shared/ingrediant.model";
import { Subject } from 'rxjs';
export class ShoppingListService{
ingrediantChanged = new Subject<Ingrediant[]>();
startedEditing = new Subject<number>();
ingrediants: Ingrediant[] = []
getIngrediants(){
return this.ingrediants.slice();
}
getIngrediant(index: number){
return this.ingrediants[index];
}
addIngrediant(ingred: Ingrediant){
this.ingrediants.push(ingred);
this.ingrediantChanged.next(this.ingrediants.slice());
}
updateIngrediant(index: number, newIngrediant: Ingrediant){
this.ingrediants[index] = newIngrediant;
this.ingrediantChanged.next(this.ingrediants.slice());
}
deleteIngrediant(index: number){
this.ingrediants.splice(index,1);
this.ingrediantChanged.next(this.ingrediants.slice());
}
addIngrediants(ingrediants: Ingrediant[]){
this.ingrediants.push(...ingrediants);
this.ingrediantChanged.next(this.ingrediants.slice());
}
} |
C++ | UTF-8 | 2,201 | 3.609375 | 4 | [] | no_license | #include "Maze.hpp"
#include <fstream>
#include <sstream>
#include <iostream>
using std::ifstream;
using std::istringstream;
using std::cout;
using std::endl;
Maze::Maze(string mazeFilename)
{
ifstream mazeFile(mazeFilename);
string line;
int i = 0;
while (getline(mazeFile, line))
{
int j = 0;
maze.push_back({});
tileNames.push_back({});
istringstream iss(line);
int tileNumber;
while (iss >> tileNumber) {
maze.at(i).push_back(tileNumber);
string tileName;
if (tileNumber % 11 == 0) {
start.first = i;
start.second = j;
} else if (tileNumber % 13 == 0) {
finish.first = i;
finish.second = j;
}
if (tileNumber % 7 == 0) {
tileName += "N";
}
if (tileNumber % 2 == 0) {
tileName += "E";
}
if (tileNumber % 3 == 0) {
tileName += "S";
}
if (tileNumber % 5 == 0) {
tileName += "W";
}
tileNames.at(i).push_back(tileName);
j++;
}
++i;
}
for (auto row : tileNames) {
for (auto tile : row) {
std::cout << tile << " ";
}
std::cout << std::endl;
}
}
bool Maze::canMoveNorth(int row, int col) const
{
return maze.at(row).at(col) % TILE_NORTH == 0;
}
bool Maze::canMoveEast(int row, int col) const
{
return maze.at(row).at(col) % TILE_EAST == 0;
}
bool Maze::canMoveSouth(int row, int col) const
{
return maze.at(row).at(col) % TILE_SOUTH == 0;
}
bool Maze::canMoveWest(int row, int col) const
{
return maze.at(row).at(col) % TILE_WEST == 0;
}
int Maze::getNumRows() const
{
return maze.size();
}
int Maze::getNumCols() const
{
return maze.at(0).size();
}
std::pair<int, int> Maze::getStart() const
{
return start;
}
std::pair<int, int> Maze::getFinish() const
{
return finish;
}
std::string Maze::getTilename(int row, int col) const
{
return tileNames.at(row).at(col);
} |
C# | UTF-8 | 673 | 2.890625 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/* Adds 1.0f to player when
* it picks up the health potion.
*/
public class HealthPotion : MonoBehaviour {
public int healthAmt = 5;
PlayerCharacter pc;
// Use this for initialization
void Awake()
{
pc = FindObjectOfType<PlayerCharacter>();
}
private void OnTriggerEnter(Collider other)
{
if (pc._health < 10)
{
Destroy(gameObject);
pc._health += healthAmt;
if (pc._health > 10)
{
pc._health = 10;
}
Debug.Log(pc._health);
}
}
}
|
C | UTF-8 | 3,589 | 2.8125 | 3 | [] | no_license | /**
* loop.c -- handling loop devices
*
* Author: Vincent Fourmond <fourmond@debian.org>
* Copyright 2011 by Vincent Fourmond
*
* This software is distributed under the terms and conditions of the
* GNU General Public License. See file GPL for the full text of the license.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* We unfortunately need regular expressions... */
#include <regex.h>
#include <libintl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "configuration.h"
#include "config.h"
#include "utils.h"
/* Hmmm, I'll need backquotes here... A fun thing to do safely... */
/**
Tries all whitelisted loop devices to find one which isn't used,
and returns it.
Returns NULL if no device could be found.
*/
static const char * loopdev_find_unused()
{
char ** devices = conffile_loop_devices();
if(! devices)
return NULL;
while(*devices) {
if(strlen(*devices) > 0) {
debug("Trying loop device: %s\n", *devices);
int result = spawnl(SPAWN_EROOT | SPAWN_NO_STDOUT | SPAWN_NO_STDERR,
LOSETUPPROG, LOSETUPPROG, *devices, NULL);
if(result == 1) /* Device is not configured, see losetup(8) */
return *devices;
}
devices++;
}
}
int loopdev_is_whitelisted(const char * device)
{
char ** devices = conffile_loop_devices();
if(! devices)
return 0;
while(*devices) {
if(! strcmp(*devices, device))
return 1;
devices++;
}
return 0;
}
int loopdev_dissociate(const char * device)
{
int result = 1 ;
int nb_tries = 0;
while(result && nb_tries < 10) {
result = spawnl(SPAWN_EROOT, LOSETUPPROG, LOSETUPPROG,
"-d", device, NULL);
if(result) {
debug("The loop device may be busy, trying again to dissociate\n");
sleep(1);
}
}
return result ? -1 : 0;
}
int loopdev_associate(const char * source, char * target, size_t size)
{
struct stat before;
const char * device;
char buffer[1024];
int result;
int fd;
fd = open(source, O_RDWR);
if( fd == -1 ) {
snprintf(buffer, sizeof(buffer),
_("Failed to open file '%s' for reading"),
source);
perror(buffer);
return -1;
}
/**
First, stat the file and check the permissions:
owner + read/write
@todo Maybe the simple fact that the above open will fail if
the user does not have read/write permissions is enough ?
*/
if(fstat(fd, &before)) {
snprintf(buffer, sizeof(buffer),
_("Failed to stat file '%s'"),
source);
perror(buffer);
close(fd);
return -1;
}
if(! (before.st_uid == getuid() &&
(before.st_mode & S_IRUSR) && /* readable */
(before.st_mode & S_IWUSR) /* writable */
)) {
fprintf(stderr, _("For loop mounting, you must be the owner of %s and "
"have read-write permissions on it\n"), source);
close(fd);
return -1;
}
device = loopdev_find_unused();
if(! device) {
fprintf(stderr, _("No whitelisted loop device available\n"));
close(fd);
return -1;
}
debug("Found an unused loop device: %s\n", device);
/* We use /dev/fd/... to ensure that the file used is the statted
one */
snprintf(buffer, sizeof(buffer), "/dev/fd/%d", fd);
result = spawnl(SPAWN_EROOT, LOSETUPPROG, LOSETUPPROG,
device, buffer, NULL);
close(fd); /* Now useless */
if(result) {
fprintf(stderr, _("Failed to setup loopback device\n"));
return -1;
}
/* Copy the device to the target */
snprintf(target, size, "%s", device);
return 0; /* Everything went fine ! */
}
|
TypeScript | UTF-8 | 637 | 3.140625 | 3 | [
"MIT"
] | permissive | type DataType = {
検査実施人数: number
陽性患者数: number
入院中: number
退院: number
死亡: number
}
type ConfirmedCasesType = {
検査実施人数: number
陽性患者数: number
入院中: number
退院: number
死亡: number
}
/**
* Format for *Chart component
*
* @param data - Raw data
*/
export default (data: DataType) => {
const formattedData: ConfirmedCasesType = {
検査実施人数: data['検査実施人数'],
陽性患者数: data['陽性患者数'],
入院中: data['入院中'],
退院: data['退院'],
死亡: data['死亡']
}
return formattedData
}
|
JavaScript | UTF-8 | 6,608 | 2.546875 | 3 | [
"MIT"
] | permissive | App = {
web3Provider: null,
contracts: {},
account: '0x0',
init: function () {
return App.initWeb3();
},
initWeb3: function () {
// TODO: refactor conditional
if (typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask.
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
web3 = new Web3(App.web3Provider);
}
return App.initContract();
},
initContract: function () {
//../build/contracts/Auction.json
$.getJSON('Auction.json', function (auction) {
// Instantiate a new truffle contract from the artifact
App.contracts.Auction = TruffleContract(auction);
// Connect provider to interact with contract
App.contracts.Auction.setProvider(App.web3Provider);
App.listenForEvents();
return App.render();
});
},
listenForEvents: function () {
App.contracts.Auction.deployed().then(function (instance) {
instance.highestBidSubmitted({}, {
fromBlock: 0,
toBlock: 'latest'
}).watch(function (error, event) {
//refresh
//App.render();
instance.highestBid().then(function (data) {
//getting data.c[0] as eth-value*1000
document.getElementById("highest-bid").innerText = 'ETH ' + data.c[0] / Math.pow(10, 4);
})
instance.highestBidder().then(function (data) {
console.log(data);
document.getElementById("highest-bidder").innerText = data;
})
});
});
},
render: function () {
var auctionInstance;
var loader = $("#loadingRow");
var content = $("#content");
var currentAccount;
loader.show();
content.hide();
// Load account data
web3.eth.getCoinbase(function (err, account) {
if (err === null) {
App.account = account;
currentAccount = account;
console.log('account', typeof (account))
console.log('account:', account);
document.getElementById('account-span').innerText = account;
const web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545"));
var balance = web3.eth.getBalance(account);
balance = web3.toDecimal(balance);
let accountBalance = balance / Math.pow(10, 18)
console.log(balance);
document.getElementById('balance-span').innerText = accountBalance;
}
});
// Load contract data
App.contracts.Auction.deployed().then(function (instance) {
auctionInstance = instance;
return {
auctioner: auctionInstance.auctioner(),
beneficiary: auctionInstance.beneficiary(),
item: auctionInstance.auctionItem(),
highestBid: auctionInstance.highestBid(),
highestBidder: auctionInstance.highestBidder(),
};
}).then(function (auctionDetails) {
auctionDetails.auctioner.then(function (data) {
//This did not work for some reason and henceforth,
//$('#auctioner-name').innerText=data[0];
document.getElementById('auctioner-name').innerText = data[0];
document.getElementById('auctioner-description').innerText = data[1];
document.getElementById('auctioner-image').setAttribute('src', data[2]);
});
// auctionDetails.beneficiary.then(function (data) {
// document.getElementById('beneficiary-name').innerText = data[0];
// document.getElementById('beneficiary-link').innerText = data[2];
// document.getElementById('beneficiary-link').setAttribute('href', data[2]);
// document.getElementById('beneficiary-image').setAttribute('src', data[1]);
// });
auctionDetails.item.then(function (data) {
document.getElementById('item-name').innerText = data[1];
document.getElementById('item-catalog').innerText = data[0];
document.getElementById('item-image').setAttribute('src', data[2]);
});
auctionDetails.highestBidder.then(function (data) {
document.getElementById('highest-bidder').innerText = data[0];
});
auctionDetails.highestBid.then(function (data) {
document.getElementById('highest-bid').innerText = data[0];
});
document.getElementById('bid-submit-button').addEventListener('click', () => {
console.log('clicked');
let bidValue = document.getElementById('bid-input').value;
if (bidValue) {
auctionInstance.bid({
from: currentAccount,
to: '0x56C10FC821263340f0DfAaD42BE565F34e85F537',
gas: 3000000,
value: bidValue,
}).then(function (result) {
//var balance = web3.eth.getBalance('0x56C10FC821263340f0DfAaD42BE565F34e85F537');
//balance = web3.toDecimal(balance);
//let accountBalance = balance / Math.pow(10, 18)
//console.log(accountBalance);
let highestBid = auctionInstance.highestBid();
let highestBidder = auctionInstance.highestBidder();
highestBid.then(function (data) {
document.getElementById('highest-bidder').innerText = data[0];
});
highestBidder.then(function (data) {
document.getElementById('highest-bid').innerText = data[0];
});
})
// web3.eth.sendTransaction({
// from: currentAccount,
// to: '0x31f9Aae8434Bb4A09d969871CDd59A5B12E90d5f',
// value: bidValue,
// }, function (result) {
// //var balance = web3.eth.getBalance('0x56C10FC821263340f0DfAaD42BE565F34e85F537');
// //balance = web3.toDecimal(balance);
// //let accountBalance = balance / Math.pow(10, 18)
// //console.log(accountBalance);
// let highestBid = auctionInstance.highestBid();
// let highestBidder = auctionInstance.highestBidder();
// highestBid.then(function (data) {
// document.getElementById('highest-bidder').innerText = data[0];
// });
// highestBidder.then(function (data) {
// document.getElementById('highest-bid').innerText = data[0];
// });
// });
}
});
loader.hide();
content.show();
}).catch(function (error) {
console.warn(error);
});
}
};
$(function () {
$(window).load(function () {
App.init();
});
});
|
Python | UTF-8 | 819 | 2.515625 | 3 | [] | no_license | import pandas as pd
df=pd.read_csv("helper_data/data.csv")
tohave=df["Unnamed: 0"].tolist()
colors= [
'#1f77b4',
'#ff7f0e',
'#2ca02c',
'#d62728',
'#9467bd',
'#8c564b',
'#e377c2',
'#7f7f7f',
'#bcbd22',
'#17becf'
]
df_2=pd.read_csv("helper_data/Diagnosis_important.csv")
lister=df_2["code"].tolist()
indices=[]
for i in lister:
#print(i)
try:
x=tohave.index(i)
indices.append(x)
except:
pass
trapcolors=['#1f77b4']*len(df)
cache=15
counter=0
marker=[1]*len(df)
kk=1
for i in indices:
counter+=1
if kk==0:
break
if counter>150:
counter=0
kk+=1
if kk==9:
kk=0
trapcolors[i]=colors[kk]
marker[i]=cache
cache=cache-.003
|
PHP | UTF-8 | 1,256 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
namespace BSForm\Types;
use BSForm\Interfaces\FieldInterface;
use BSForm\Interfaces\FieldContainerInterface;
use BSForm\Traits\FieldContainerTrait;
use BSForm\Traits\IndentableTrait;
use BSForm\Traits\SearchableTrait;
class ColumnType implements FieldInterface, FieldContainerInterface
{
use SearchableTrait;
use IndentableTrait;
use FieldContainerTrait;
protected $class;
public function setClass($class)
{
$this->class = $class;
return $this;
}
public function getClass()
{
return $this->class;
}
public function setName($name)
{
}
public function getName()
{
}
public function getField($indentations = 0)
{
$field = $this->indent($indentations);
$field .= "<div";
if (isset($this->class)) {
$field .= " class =\"{$this->class}\">\n";
}
foreach ($this->fields as $entry) {
$field .= $entry->getField($indentations + 1);
}
$field .= $this->indent($indentations);
$field .= "</div>\n";
return $field;
}
public function __toString()
{
return $this->getField();
}
} |
Python | UTF-8 | 5,329 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/env python
# Copyright (c) 2014, Paessler AG <support@paessler.com>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions
# and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
# and the following disclaimer in the documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
# or promote products derived from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import gc
import logging
import os.path
temp = True
if not os.path.exists("/sys/class/thermal/thermal_zone0/temp"):
temp = False
class CPUTemp(object):
def __init__(self):
gc.enable()
@staticmethod
def get_kind():
"""
return sensor kind
"""
return "mpcputemp"
@staticmethod
def get_sensordef(testing=False):
"""
Definition of the sensor and data to be shown in the PRTG WebGUI
"""
sensordefinition = {
"kind": CPUTemp.get_kind(),
"name": "CPU Temperature",
"description": "Returns the CPU temperature",
"default": "yes",
"help": "Returns the CPU temperature",
"tag": "mpcputempsensor",
"groups": [
{
"name": "Group",
"caption": "Temperature settings",
"fields": [
{
"type": "radio",
"name": "celfar",
"caption": "Choose between Celsius or Fahrenheit display",
"help": "Choose wether you want to return the value in Celsius or Fahrenheit",
"options": {
"C": "Celsius",
"F": "Fahrenheit"
},
"default": "C"
},
]
}
]
}
if not temp and not testing:
sensordefinition = ""
return sensordefinition
@staticmethod
def get_data(data, out_queue):
temperature = CPUTemp()
logging.debug("Running sensor: %s" % temperature.get_kind())
try:
tmp = temperature.read_temp(data)
except Exception as e:
logging.error("Ooops Something went wrong with '%s' sensor %s. Error: %s" % (temperature.get_kind(),
data['sensorid'], e))
data = {
"sensorid": int(data['sensorid']),
"error": "Exception",
"code": 1,
"message": "CPUTemp sensor failed. See log for details"
}
out_queue.put(data)
return 1
tempdata = []
for element in tmp:
tempdata.append(element)
data = {
"sensorid": int(data['sensorid']),
"message": "OK",
"channel": tempdata
}
del temperature
gc.collect()
out_queue.put(data)
return 1
@staticmethod
def read_temp(config):
data = []
chandata = []
tmp = open("/sys/class/thermal/thermal_zone0/temp", "r")
lines = tmp.readlines()
tmp.close()
temp_string = lines[0]
logging.debug("CPUTemp Debug message: Temperature from file: %s" % temp_string)
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
logging.debug("CPUTemp Debug message: Temperature after calculations:: %s" % temp_c)
if config['celfar'] == "C":
data.append(temp_c)
else:
data.append(temp_f)
for i in range(len(data)):
chandata.append({"name": "CPU Temperature",
"mode": "float",
"unit": "Custom",
"customunit": config['celfar'],
"LimitMode": 1,
"LimitMaxError": 40,
"LimitMaxWarning": 35,
"value": float(data[i])})
return chandata
|
C# | UTF-8 | 3,080 | 3.234375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KeyManagerData;
using System.Data.SQLite;
namespace KeyManagerClassLib
{
public class Location : IComparable<Location>
{
// list property
public List<Door> doors = new List<Door>(); // list of doors in this group/location
//Properties
public int Id { get; set; }
public string Name { get; set; }
public string Image { get; set; }
/// <summary>
/// Deletes this Location, and all references to it in db
/// Does not update the OOP.
/// </summary>
/// <returns></returns>
public bool Delete()
{
foreach (Door door in doors.ToArray()) // used ToArray to avoid modifying the list I'm iterating over.
{
RemoveDoor(door);
}
DataLayer dl = new DataLayer();
dl.DeleteRecord("location", Id);
return true;
}
/// <summary>
/// Create or update this location in the db. Does not update doors in the group.
/// For that use AddDoor and RemoveDoor methods.
/// </summary>
public void Save()
{
DataLayer dl = new DataLayer();
dl.AddValue("Name", Name);
dl.AddValue("image", Image);
if (Id == -1)
{
Id = dl.AddRecord("location");
}
else
{
dl.AlterRecord("location", Id);
}
}
//Default constructor
public Location()
{
Id = 0;
Name = "Name";
Image = "Image";
}
//Constructor
public Location(int pId, string pName, string pImage)
{
Id = pId;
Name = pName;
Image = pImage;
}
/// <summary>
/// Add a door to this group. Affects OOP and database.
/// </summary>
/// <param name="door"></param>
public void AddDoor(Door door)
{
doors.Add(door);
DataLayer dl = new DataLayer();
dl.AddValue("Door", "" + door.Id);
dl.AddValue("Location", "" + Id);
dl.AddRecord("door_to_location");
}
/// <summary>
/// Remove a door from this group. Affects OOP and Database.
/// </summary>
/// <param name="door"></param>
public void RemoveDoor(Door door)
{
doors.Remove(door);
// can't use DataLayer for this.
SQLiteConnection conn = DbSetupManager.GetConnection();
SQLiteCommand command = new SQLiteCommand(conn);
command.CommandText = "DELETE FROM door_to_location WHERE Door = " + door.Id + " AND Location = " + Id;
command.ExecuteNonQuery();
conn.Close();
}
public int CompareTo(Location other)
{
return this.Name.CompareTo(other.Name);
}
}
}
|
C | UTF-8 | 10,422 | 3.078125 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | /*
* Name: svstack.c
* Description: Stacks.
* Author: cosh.cage#hotmail.com
* File ID: 0318171803E0530191456L00306
*
* The following text is copied from the source code of SQLite and padded
* with a little bit addition to fit the goals for StoneValley project:
*
* The author disclaims copyright to this source code. In place of
* a legal notice, here is a blessing:
* May you do good and not evil.
* May you find forgiveness for yourself and forgive others.
* May you share freely, never taking more than you give.
* Hope you never need to push yourself or other people too hard.
*/
#include <stdlib.h> /* Using function malloc, free. */
#include <string.h> /* Using function memcpy. */
#include "svstack.h"
/* Function name: stkInitA
* Description: Allocate a stack.
* Parameters:
* pstka Pointer to the stack you want to allocate.
* num Number of elements.
* size Size of each elements.
* Return value: Pointer to the new allocated buffer.
* Caution: Address of pstka Must Be Allocated first.
*/
void * stkInitA(P_STACK_A pstka, size_t num, size_t size)
{
pstka->top = 0;
return strInitArrayZ(&pstka->arr, num, size);
}
/* Function name: stkFreeA
* Description: Deallocate a stack of which is allocated by function stkInitA.
* Parameter:
* pstka Pointer to the stack you want to deallocate.
* Return value: N/A.
* Caution: Address of pstka->arr.pdata Must Be Allocated first.
*/
void stkFreeA(P_STACK_A pstka)
{
strFreeArrayZ(&pstka->arr);
pstka->top = 0;
}
/* Function name: stkCreateA
* Description: Create a new array style stack dynamically.
* Parameters:
* num Number of elements.
* size Size of each elements.
* Return value: Pointer to the new stack.
*/
P_STACK_A stkCreateA(size_t num, size_t size)
{
P_STACK_A pstkn = (P_STACK_A) malloc(sizeof(STACK_A));
if (NULL == pstkn || NULL == stkInitA(pstkn, num, size))
{ /* Allocation failure. */
free(pstkn);
return NULL;
}
return pstkn;
}
/* Function name: stkDeleteA
* Description: Delete a stack of which is allocated by function stkCreateA.
* Parameter:
* pstka Pointer to the stack you want to delete.
* Return value: N/A.
* Caution: Parameter pstka Must Be Allocated first.
*/
void stkDeleteA(P_STACK_A pstka)
{
stkFreeA(pstka);
free(pstka);
}
/* Function name: stkIsEmptyA_O
* Description: Make a judgement whether a stack is empty or not.
* Parameter:
* pstka Pointer to the stack you want to check.
* Return value:
* TRUE Stack is empty.
* FALSE Stack is NOT empty.
* Tip: A macro version of this function named stkIsEmptyA_M is available.
*/
BOOL stkIsEmptyA_O(P_STACK_A pstka)
{
return !pstka->top;
}
/* Function name: stkIsFullA_O
* Description: Make a judgement whether a stack is full or not.
* Parameter:
* pstka Pointer to the stack you want to check.
* Return value:
* TRUE Stack is full.
* FALSE Stack is NOT full.
* Tip: A macro version of this function named stkIsFullA_M is available
*/
BOOL stkIsFullA_O(P_STACK_A pstka)
{
return (pstka->arr.num == pstka->top);
}
/* Function name: stkPushA_O
* Description: Push an element onto a stack.
* Parameters:
* pstka Pointer to the stack you want to operate with.
* pitem Pointer to the address of an element.
* Return value: Address of the new inserted element.
* Caution: You should check whether the target stack is full or not before invoking.
* Tip: A macro version of this function named stkPushA_M is available.
*/
void * stkPushA_O(P_STACK_A pstka, const void * pitem, size_t size)
{
return memcpy(pstka->arr.pdata + (pstka->top++) * size, pitem, size);
}
/* Function name: stkPopA_O
* Description: Pop an element out of a stack.
* Parameters:
* pitem Pointer to the address of an element.
* pstka Pointer to the stack you want to operate with.
* Return value: N/A.
* Caution: You should check whether the target stack is empty or not before invoking.
* Tip: A macro version of this function named stkPopA_M is available.
*/
void stkPopA_O(void * pitem, size_t size, P_STACK_A pstka)
{
memcpy(pitem, pstka->arr.pdata + (--pstka->top) * size, size);
}
/* Function name: stkPeepA_O
* Description: Have a peek at the top of the stack.
* Parameters:
* pitem Pointer to the address of an element.
* size Size of element in the stack.
* pstka Pointer to the stack you want to operate with.
* Return value: N/A.
* Caution: You should check whether the target stack is empty or not before invoking.
* Tip: A macro version of this function named stkPeepA_M is available.
*/
void stkPeepA_O(void * pitem, size_t size, P_STACK_A pstka)
{
memcpy(pitem, pstka->arr.pdata + (pstka->top - 1) * size, size);
}
/* Function name: stkLevelA_O
* Description: Get tier number of a stack.
* Parameter:
* pstka Pointer to the stack you want to check.
* Return value: Number of tiers of stack.
* Tip: You should better inline this function while linking.
* A macro version of this function named stkLevelA_M is available.
*/
size_t stkLevelA_O(P_STACK_A pstka)
{
return pstka->top;
}
/* Function name: stkInitL_O
* Description: Initialize a Linked-list stack.
* Parameters:
* pstka Pointer to the stack you want to create.
* size Size of each element in the stack.
* Return value: N/A.
* Caution: Address of pstkl Must Be Allocated first.
* Tip: This function can be inline for better performance.
* A macro version of this function named stkInitL_M is available.
*/
void stkInitL_O(P_STACK_L pstkl)
{
strInitLinkedListSC(pstkl);
}
/* Function name: stkFreeL_O
* Description: Deallocate a linked-list stack of which is allocated by function stkInitL.
* Parameter:
* pstkl Pointer to the stack you want to deallocate.
* Return value: N/A.
* Caution: Address of pstkl Must Be Allocated first.
* Tip: This function can be inline for better performance.
* A macro version of this function named stkFreeL_M is available.
*/
void stkFreeL_O(P_STACK_L pstkl)
{
strFreeLinkedListSC(pstkl);
}
/* Function name: stkCreateL_O
* Description: Create a new pointer with a new allocated Linked-list stack.
* Parameter: N/A.
* Return value: A pointer to a new allocated Linked-list stack.
* Tip: This function can be inline for better performance.
*/
P_STACK_L stkCreateL_O(void)
{
return strCreateLinkedListSC();
}
/* Function name: stkDeleteL_O
* Description: Destory a linked-list stack of which is allocated by function stkCreateL.
* Parameter:
* pstkl Pointer to the stack you want to delete from main-memory.
* Return value: N/A.
* Caution: Address of pstkl Must Be Allocated By Function stkCreateL at first.
* Tip: This function can be inline for better performance.
* A macro version of this function named stkDeleteL_M is available.
*/
void stkDeleteL_O(P_STACK_L pstkl)
{
strDeleteLinkedListSC(pstkl);
}
/* Function name: stkIsEmptyL
* Description: Make a judgement whether a stack is empty or not.
* Parameter:
* pstka Pointer to the stack you want to check.
* Return value:
* TRUE Stack is empty.
* FALSE Stack is not empty.
* Caution: Address of pstkl Must Be Allocated first.
* Tip: A macro version of this function named stkIsEmptyA_M is available.
*/
BOOL stkIsEmptyL_O(P_STACK_L pstkl)
{
return !(*pstkl);
}
/* Function name: stkPushL
* Description: Push an element onto stack.
* Parameters:
* ptop Pointer to the top element of a stack.
* pitem Pointer to the address of an element.
* size Size of that element.
* Return value: NULL if pushing failed or a valid pointer of the top element for the current stack.
* Caution: Address of pstkl Must Be Allocated first.
*/
P_NODE_S stkPushL(P_STACK_L pstkl, const void * pitem, size_t size)
{
REGISTER P_NODE_S ptmp;
if (NULL != (ptmp = strCreateNodeS(pitem, size)))
{
ptmp->pnode = *pstkl;
*pstkl = ptmp;
}
return ptmp;
}
/* Function name: stkPopL
* Description: Pop an element from a stack.
* Parameters:
* pitem Pointer to the address of an element.
* size Size of each elements.
* ptop Pointer to the top element of a stack.
* Return value: Address of current element.
* If function returned a NULL, it should mean there were no element settled in the stack anymore.
* Caution: You should check whether the target stack is empty or not before invoking.
* Address of pstkl Must Be Allocated first.
*/
P_NODE_S stkPopL(void * pitem, size_t size, P_STACK_L pstkl)
{
REGISTER P_NODE_S ptmp = NULL;
if (NULL != *pstkl)
{
ptmp = (*pstkl)->pnode;
memcpy(pitem, (*pstkl)->pdata, size);
strDeleteNodeS(*pstkl);
}
return *pstkl = ptmp;
}
/* Function name: stkPeepL_O
* Description: Have a peek at the top of the stack.
* Parameters:
* pitem Pointer to the address of an element.
* size Size of that element.
* ptop Pointer to the top element of a stack.
* Return value: N/A.
* Caution: You should check whether the target stack is empty or not before invoking.
* Address of pstkl Must Be Allocated first.
* Tip: A macro version of this function named stkPeepL_M is available.
*/
void stkPeepL_O(void * pitem, size_t size, P_STACK_L pstkl)
{
memcpy(pitem, (*pstkl)->pdata, size);
}
/* Function name: stkLevelL_O
* Description: Get tier number of a stack.
* Parameter:
* pstkl Pointer to the top element of a stack.
* Return value: Number of tiers.
* Caution: You should check whether the target stack is empty or not before invoking.
* Address of pstkl Must Be Allocated first.
* Tip: A macro version of this function named stkLevelL_M is available.
*/
size_t stkLevelL_O(P_STACK_L pstkl)
{
return strLevelLinkedListSC(*pstkl);
}
|
Python | UTF-8 | 2,720 | 2.5625 | 3 | [
"MIT"
] | permissive | import sys
sys.path.append("../")
import time
import cv2
import torch
import numpy as np
from duckietown_rl.gym_duckietown.simulator import Simulator
from duckietown_rl.ddpg import DDPG
from _loggers import Logger
env = Simulator(seed=123, map_name="zigzag_dists", max_steps=5000001, domain_rand=True, camera_width=640,
camera_height=480, accept_start_angle_deg=4, full_transparency=True, distortion=True,
randomize_maps_on_reset=True, draw_curve=False, draw_bbox=False, frame_skip=4, draw_DDPG_features=False)
state_dim = env.get_features().shape[0]
action_dim = env.action_space.shape[0]
max_action = float(env.action_space.high[0])
# Initialize policy
expert = DDPG(state_dim, action_dim, max_action, net_type="dense")
expert.load("model", directory="../duckietown_rl/models", for_inference=True)
# Initialize the environment
env.reset()
# Get features(state representation) for RL agent
obs = env.get_features()
EPISODES, STEPS = 400, 256
DEBUG = False
# please notice
logger = Logger(env, log_file=f'train-{int(EPISODES*STEPS/1000)}k.log')
start_time = time.time()
print(f"[INFO]Starting to get logs for {EPISODES} episodes each {STEPS} steps..")
with torch.no_grad():
# let's collect our samples
for episode in range(0, EPISODES):
for steps in range(0, STEPS):
# we use our 'expert' to predict the next action.
action = expert.predict(np.array(obs))
# Apply the action
observation, reward, done, info = env.step(action)
# Get features(state representation) for RL agent
obs = env.get_features()
if done:
print(f"#Episode: {episode}\t | #Step: {steps}")
break
closest_point, _ = env.closest_curve_point(env.cur_pos, env.cur_angle)
if closest_point is None:
done = True
break
# Cut the horizon: obs.shape = (480,640,3) --> (300,640,3)
observation = observation[150:450, :]
# we can resize the image here
observation = cv2.resize(observation, (120, 60))
# NOTICE: OpenCV changes the order of the channels !!!
observation = cv2.cvtColor(observation, cv2.COLOR_BGR2RGB)
# we may use this to debug our expert.
if DEBUG:
cv2.imshow('debug', observation)
cv2.waitKey(1)
logger.log(observation, action, reward, done, info)
logger.on_episode_done() # speed up logging by flushing the file
env.reset()
logger.close()
env.close()
end_time = time.time()
print(f"Process finished. It took {(end_time - start_time) / (60*60):.2f} hours!")
|
Swift | UTF-8 | 18,204 | 3.34375 | 3 | [] | no_license | //
// FactProvider.swift
// FunFacts
//
// Created by Melissa Oveson on 3/24/18.
// Copyright © 2018 Miss Geek Bunny. All rights reserved.
//
import GameKit
struct FactProvider {
let facts = ["Ants stretch when they wake up in the morning.",
"Ostriches can run faster than horses.",
"Olympic gold medals are actually made of silver",
"You are born with 300 bones; by the time you are an adult you will have 206",
"It takes about 8 minutes for light from the Sun to reach Earth",
"Some bamboo plants can grow almost a meter in just one day",
"The state of Florida is bigger than England",
"Some penguins can leap 2-3 meters out of the water",
"On average, it takes 66 days to form a new habit",
"Mammoths still walked the earth when the Great Pyramid was being built.",
"During a 2004 episode of Sesame Street, Cookie Monster said that before he started eating cookies, his name was Sid.",
"Mr. Rogers was an ordained minister.",
"Horses can’t vomit.",
"Before settling on the Seven Dwarfs we know today, Disney also considered Chesty, Tubby, Burpy, Deafy, Hickey, Wheezy, and Awful.",
"The unkempt Shaggy of Scooby-Doo fame has a rather proper real name, Norville Rogers.",
"A cat has 32 muscles in each ear.",
"An ostrich’s eye is bigger than its brain.",
"The characters Bert and Ernie, on Sesame Street, were named after Bert the cop and Ernie the taxi driver in Frank Capra’s \"It’s A Wonderful Life.\"",
"In England, the Speaker of the House is not allowed to speak.",
"\"Stewardesses\" is the longest word that is typed with only the left hand.",
"A jellyfish is 95% water",
"In Bangladesh, kids as young as 15 can be jailed for cheating on their finals.",
"The starfish is one of the only animals who can turn it’s stomach inside-out.",
"The elephant is the only mammal that can’t jump.",
"Q is the only letter in the alphabet that does not appear in the name of any of the United States.",
"The British once went to war over a sailor’s ear. It happened in 1739, when Britain launched hostilities against Spain because a Spanish officer had supposedly sliced off the ear of a ship’s captain named Robert Jenkins.",
"There are no words in the dictionary that rhyme with: orange, purple, and silver.",
"Fortune cookies were actually invented in America, in 1918, by Charles Jung.",
"Chewing gum while peeling onions will keep you from crying.",
"In England, in the 1880s, \"Pants\" was considered a dirty word.",
"The strongest muscle in the body is the tongue.",
"The Eiffel Tower is second only to the Golden Gate Bridge as a suicide location.",
"The Matterhorn at Disneyland in Anaheim had a full basketball court at the very top of the structure, because at the time it was built the only structures that could be that tall were sports arenas.",
"In the movie, ‘Star Wars’, during the scene in which Luke gets out of his X-wing fighter after blowing up the Death Star, he accidentally calls Princess Leia ‘Carrie’ (her real first name).",
"The first product to have a UPC bar code on its packaging was Wrigley’s gum.",
"Play-doh was first invented as a wallpaper cleaner.",
"Astronaut Neil Armstrong first stepped on the moon with his left foot.",
"The word ‘nerd’ was first coined by Dr. Seuss in ‘If I ran the Zoo’",
"Boys who have unusual first names are more likely to have mental problems than boys with common names. Girls don’t seem to have this problem.",
"Left-handedness is extremely common in twins. It is unusual, however, for both to be left-handed.",
"Every time you lick a stamp, you’re consuming 1/10th of a calorie.",
"Humans and dolphins are the only species that have sex for pleasure.",
"Polar bears are left handed.",
"A crocodile cannot stick its tongue out.",
"Butterflies taste with their feet.",
"The slipper-shelled snail starts life as a male and gradually turns female as it grows up.",
"Parthenophobia is the fear of virgins.",
"Almonds are a member of the peach family.",
"The word \"PEZ\" comes from the German word for peppermint, PfeffErminZ",
"In Peanuts in 1968, Snoopy trained to become a champion arm-wrestler. In the end, he was disqualified for not having thumbs.",
"Belmont University once offered a course called \"Oh, Look, a Chicken! Embracing Distraction as a Way of Knowing.\"",
"After an online vote in 2011, Toyota announced that the official plural of Prius was Prii.",
"The only number whose letters are in alphabetical order is 40 (f-o-r-t-y).",
"The string on boxes of animal crackers was originally placed there so the container could be hung from a Christmas tree.",
"Only female mosquitoes will bite you.",
"In the 1970s, Mattel sold a doll called \"Growing Up Skipper.\" Her breasts grew when her arm was turned.",
"M&M’s actually stands for \"Mars & Murrie’s,\" the last names of the candy’s founders.",
"The 3 Musketeers bar was originally split into three pieces with three different flavors: vanilla, chocolate and strawberry. When the other flavors became harder to come by during World War II, Mars decided to go all chocolate.",
"Camels chew in a figure 8 pattern.",
"A skunk’s smell can be detected by a human a mile away.",
"Koalas never drink water. They get fluids from the eucalyptus leaves they eat.",
"The cheetah is the only cat that can’t retract its claws.",
"A cat uses its whiskers to determine if a space is too small to squeeze through.",
"All letters addressed to Santa in the United States go to Santa Claus, Indiana",
"Beethoven dipped his head in cold water before he composed.",
"Barbie’s full name is \"Babara Millicent Roberts.\"",
"An average human scalp has 100,000 hairs.",
"Blondes have more hair than dark-haired people do.",
"Australian soldiers used the song \"We’re Off to See the Wizard\" as a marching song in WWII.",
"Antarctica is the only continent that does not have land areas below sea level.",
"Netherlands is the only country with a national dog.",
"When we think of Big Ben in London, we think of the clock. Actually, it’s the bell.",
"No matter where you stand in Michigan, you are never more than 85 miles from a Great Lake.",
"The official beverage of Ohio is tomato juice.",
"In Quebec, there is an old law that states margarine must be a different color than butter.",
"Denver, Colorado lays claim to the invention of the cheeseburger.",
"In Utah, it is illegal to swear in front of a dead person.",
"Salt Lake City, Utah has a law against carrying an unwrapped ukulele on the street.",
"It is illegal to hunt camels in the state of Arizona.",
"More people are allergic to cow’s milk than any other food.",
"A female ferret will die if it goes into heat and cannot find a mate.",
"John Adams, Thomas Jefferson, and James Monroe died on July 4th.",
"Stephen Hawking was born exactly 300 years after Galileo died.",
"\"Lassie\" was played by a group of male dogs; the main one was named Pal.",
"Abraham Lincoln’s ghost is said to haunt the White House.",
"Scotland has more redheads than any other part of the world.",
"A shrimp’s heart is in its head.",
"A healthy (non-colorblind) human eye can distinguish between 500 shades of gray.",
"A \"jiffy\" is the scientific name for 1/100th of a second.",
"The youngest pope ever was 11 years old.",
"Hedenophobic means fear of pleasure.",
"Every year 4 people in the UK die putting their trousers on.",
"Intelligent people have more zinc and copper in their hair.",
"The world’s youngest parents were 8 and 9 and lived in China in 1910.",
"Grapes explode when you put them in the microwave.",
"In The Empire Strikes Back there is a potato hidden in the asteroid field.",
"Walt Disney holds the world record for the most Academy Awards won by one person, he has won twenty statuettes, and twelve other plaques and certificates.",
"James Bond’s car had three different license plates in Goldfinger.",
"The very first song played on MTV was ‘Video Killed The Radio Star’ by the Buggles.",
"Bullet proof vests, fire escapes, windshield wipers, and laser printers were all invented by women.",
"In Disney’s Fantasia, the Sorcerer’s name is \"Yensid\" (Disney backwards.)",
"It was discovered on a space mission that a frog can throw up. The frog throws up its stomach first, so the stomach is dangling out of its mouth. Then the frog uses its forearms to dig out all of the stomach’s contents and then swallows the stomach back down.",
"Pearls melt in vinegar.",
"Humans are the only primates that don’t have pigment in the palms of their hands.",
"The fingerprints of koala bears are virtually indistinguishable from those of humans, so much so that they can be easily confused at a crime scene.",
"The first owner of the Marlboro company died of lung cancer.",
"Walt Disney was afraid of mice.",
"The king of hearts is the only king without a mustache.",
"Simplistic passwords contribute to over 80% of all computer password break-ins.",
"The top 3 health-related searches on the Internet are (in this order): Depression, Allergies, & Cancer.",
"NBA superstar Michael Jordan was originally cut from his high school basketball team.",
"You spend 7 years of your life in the bathroom.",
"Shakespeare is quoted 33,150 times in the Oxford English dictionary.",
"The word Pennsylvania is misspelled on the Liberty Bell.",
"A spider has transparent blood.",
"Van Gogh only sold one painting when he was alive.",
"A standard slinky measures 87 feet when stretched out.",
"Rubber bands last longer when refrigerated.",
"Virginia Woolf wrote all her books standing",
"The scene where Indiana Jones shoots the swordsman in Raider’s of the Lost Ark was Harrison Ford’s idea so that he could take a bathroom break.",
"Mozart wrote the nursery rhyme 'twinkle, twinkle, little star' at the age of 5.",
"In the Philippine jungle, the yo-yo was first used as a weapon.",
"The name of the girl on the statue of liberty is Mother of Exiles.",
"It is illegal to eat oranges while bathing in California.",
"Non-dairy creamer is flammable.",
"Each king in a deck of playing cards represents a great king from history. Spades – King David, Clubs – Alexander the Great, Hearts – Charlemagne, and Diamonds – Julius Caesar.",
"The only 15-letter word that can be spelled without repeating a letter is uncopyrightable.",
"Emus and kangaroos cannot walk backwards, and are on the Australian coat of arms for that reason.",
"Blueberry Jelly Bellies were created especially for Ronald Reagan.",
"Honking of car horns for a couple that just got married is an old superstition to insure great sex.",
"40,000 Americans are injured by toilets each year.",
"You can be fined up to $1,000 for whistling on Sunday in Salt Lake City, Utah.",
"Honey is the only food which does not spoil.",
"Hot water is heavier than cold.",
"The most common name in world is Mohammed.",
"The word \"lethologica\" describes the state of not being able to remember the word you want.",
"People photocopying their buttocks are the cause of 23% of all photocopier faults worldwide.",
"The storage capacity of human brain exceeds 4 Terabytes.",
"Any free-moving liquid in outer space will form itself into a sphere, because of its surface tension.",
"In 1999, Furbies were banned from the National Security Agency’s Maryland headquarters because it was feared the toys might repeat national security secrets.",
"When a Hawaiian woman wears a flower over her left ear, it means that she is not available.",
"Coca-Cola was originally green.",
"The average person spends about two years on the phone in a lifetime.",
"The Human eyes never grow, but nose and ears never stop growing.",
"The shortest war in history was between Zanzibar and England in 1896. Zanzibar surrendered after 38 minutes.",
"1 in 8 Americans has worked at a McDonalds restaurant.",
"A pregnant goldfish is called a twit.",
"Celery has negative calories! It takes more calories to eat a piece of celery than the celery has in it.",
"You burn more calories sleeping than you do watching TV.",
"If one places a tiny amount of liquor on a scorpion, it will instantly go mad and sting itself to death.",
"The plastic things on the end of shoelaces are called aglets.",
"There is approximately one chicken for every human being in the world.",
"Women manage the money and pay the bills in 75% of all Americans households.",
"Ninety percent of all species that have become extinct have been birds.",
"The electric chair was invented by a dentist.",
"A whale’s penis is called a dork.",
"Reindeer like to eat bananas.",
"Mel Blanc (the voice of Bugs Bunny) was allergic to carrots.",
"101 Dalmatians, Peter Pan, Lady and the Tramp, and Mulan are the only Disney cartoons where both parents are present and don’t die throughout the movie.",
"The state flower of Alaska is a forget-me-not.",
"Octavio Guillen and Adriana Martinez were married in Mexico City in 1969 after a world record engagement of 67 years.",
"Teddy Roosevelt had four sons. Three of them died in war.",
"An electric eel will short-circuit itself if put into salt water.",
"Kilts originated in France, not Scotland.",
"According to ancient Hindu law, the penalty for adultery was the removal of a person’s nose.",
"Most snakes can go without eating for an entire year.",
"Most monkeys are nearsighted.",
"It is against the law to sing out of tune in North Carolina.",
"A newborn baby cannot shed tears.",
"Only righthanded players can play polo according to the U.S. Polo Association.",
"Coffee is the world’s most recognizable smell.",
"Insects can shiver.",
"New Mexico is the only US state with two official languages – English and Spanish.",
"Lightning is the cause of most forest fires.",
"In China, the day a child is born it is considered one year old.",
"Abraham Lincoln was carrying Confederate money when he was assassinated.",
"The sound you hear in a seashell is actually the echo of the blood pulsing in your ear.",
"Rabbits talk to each other by tapping their feet.",
"Fish can become seasick if kept aboard a ship.",
"A fetus in the womb can get hiccups.",
"There are eleven time zones in Russia.",
"President Zachary Taylor never voted in a presidential election – not even his own.",
"France’s King Louis XIV was on the throne so long he was succeeded by his great grandson.",
"Jousting is the official state sport of Maryland.",
"Jellyfish evaporate every once in a while.",
"Sahara means desert in Arabic so the \"Sahara Desert\" is the \"Desert Desert\"",
"Months that start with Sunday, have Friday the 13th",
"There are Victoria's Secret models from every continent except Antarctica.",
"Wolfeschlegelsteinhausenbergerdorff is the longest recorded personal name",
"Cotton Candy was created by a dentist and originally called \"Fairy Floss\"",
"Many nursing homes in Germany have fake bus stops to round up dementia patients",
"In Texas, it's illegal to kill Bigfoot if you ever find him",
"The King of Norway is 73rd in line to the British throne.",
"Christmas was illegal in the U.S. until 1836 as it was considered an Ancient Pagan Holiday.",
"The white thin film over the tongue is actually bacteria build up. A pink tongue represents a healthy clean tongue.",
"Pagophagia is a disorder involving the compulsion to chew ice.",
"The creator of peanut M&Ms was allergic to peanuts.",
"The Louvre was never intended to be a museum. It was built as a fortress in 1190 to protect the City of Paris.",
"There are 4 states in the U.S. that ban oral sex but allow necrophilia.",
"The first online transaction ever was Stanford students buying marijuana from MIT students.",
"After 3 months in the womb, a fetus already has a preference for which hand it uses the most.",
"A natural predator of the Moose is the Killer Whale. They have been known to prey on moose swimming around America's Northwest Coast.",
"Around 42% of Americans play video games regularly.",
"Squirrels will adopt other squirrels babies if they are abandoned.",
"The design for Gene Roddenberry's USS Enterprise is based on a heating coil from an electric stove",
"Besides February 29, Christmas is the least common birthday.",
"Olympic gold medals are actually made mostly of silver",
"You are born with 300 bones; by the time you are an adult you will have 206",
"It takes about 8 minutes for the light from the Sun to reach Earth",
"Some bamboo plants can grow almost a meter in just one day",
"The state of Florida is bigger than England",
"Some penguins can leap 2-3 meters out of the water",
"On average, it takes 66 days to form a new habit",
"Mammoths still walked the Earth when the Great Pyramid was being built"]
func randomFact() -> String {
let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: facts.count)
return facts[randomNumber]
}
}
|
Java | UTF-8 | 3,743 | 1.9375 | 2 | [
"BSD-2-Clause"
] | permissive | /**
* Copyright (c) 2011-2013, ReXSL.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the ReXSL.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rexsl.maven.utils;
import com.jcabi.aspects.Loggable;
import com.jcabi.log.Logger;
import com.rexsl.maven.Environment;
import java.io.File;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.validation.constraints.NotNull;
/**
* To be executed before all other code.
*
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
*/
public final class RuntimeListener implements ServletContextListener {
@Override
@SuppressWarnings("PMD.UseProperClassLoader")
@Loggable(Loggable.DEBUG)
public void contextInitialized(@NotNull final ServletContextEvent event) {
final long start = System.currentTimeMillis();
final Environment env = new RuntimeEnvironment(
event.getServletContext()
);
final File dir = new File(env.basedir(), "src/test/rexsl/bootstrap");
if (dir.exists()) {
int counter = 0;
final GroovyExecutor exec = new GroovyExecutor(
event.getServletContext().getClassLoader(),
new BindingBuilder(env).build()
);
final FileFinder finder = new FileFinder(dir, "groovy");
for (final File script : finder.ordered()) {
Logger.info(this, "Running '%s'...", script);
try {
exec.execute(script);
} catch (GroovyException ex) {
throw new IllegalStateException(ex);
}
++counter;
}
Logger.debug(
this,
// @checkstyle LineLength (1 line)
"#contextInitialized(%s): initialized with %d script(s) in %[ms]s",
event.getClass().getName(),
counter,
System.currentTimeMillis() - start
);
} else {
Logger.info(
this,
"%s directory is absent, no bootstrap scripts to run",
dir
);
}
}
@Override
@Loggable(Loggable.DEBUG)
public void contextDestroyed(@NotNull final ServletContextEvent event) {
// nothing to do
}
}
|
Python | UTF-8 | 212 | 3.703125 | 4 | [] | no_license | thing = "animal"
animal = "cat"
if thing=="animal":
if animal == "dog":
print "this thing is a dog"
else:
print "this thing is an animal"
else:
print "I dont know what this thing is"
|
Python | UTF-8 | 3,872 | 3.1875 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
from sympy import mod_inverse
def printGr(a,b):
y, x = np.ogrid[-10:10:100j, -10:10:100j]
plt.contour(x.ravel(), y.ravel(), pow(y, 2) - pow(x, 3) - x * a - b, [0])
plt.grid()
plt.show()
def summ(x1, y1, x2, y2, fp):
t1=y2-y1
t2=x2-x1
x3 = ((t1*mod_inverse(t2,fp)%fp)**2-(x1+x2))%fp
y3 = (-y1+(t1*mod_inverse(t2,fp)%fp)*(x1-x3))%fp
return x3, y3
def summodinak(x1, y1, a, fp):
a=a%fp
t1=3*x1**2+a
t2=2*y1
x3 = (t1*mod_inverse(t2,fp)%fp)**2-2*x1
y3 = -y1+(t1*mod_inverse(t2,fp)%fp)*(x1-x3)
return x3 % fp, y3 % fp
def pov(x1, y1, fp, count, a):
zx, zy = x1, y1
while (count > 1):
if ((zx == x1)and(zy == y1)):
zx, zy = summodinak(x1, y1, a, fp)
else:
zx, zy = summ(zx, zy, x1, y1, fp)
count -= 1
return zx % fp, zy % fp
def tochki(a,b,fp):
"""Нахождение точек"""
slovar = {a: a ** 2 % fp for a in range(fp)}
print("z^=")
print(slovar)
korni = {y: (y ** 3 + a * y + b) % fp for y in range(fp)}
print("x0=,y0=")
for key, value in korni.items():
print("x", key, "=", key, " ", "y^2=", value)
print("Точки")
for key,value in korni.items():
for key1,value1 in slovar.items():
if value==value1:
print("P",key,"= (",key,key1,")")
def checkSimple(p):
if p%2==0:
print("Составное")
else:
rs=[i**(p-1)%p for i in range(2,5)]
if all(r==1 for r in rs):
print('Простое')
else:
print('Составное')
def checkDiskr(a,b,fp):
y=4*a**3+27*b**2%fp
print(y)
if __name__ == "__main__":
while True:
print('Режим работы:')
print(' 1 --- Проверить является ли число простым')
print(' 2 --- Проверить дискриминант')
print(' 3 --- Найти все точки')
print(' 4 --- Сложить две точки')
print(' 5 --- Умножить точку на число')
print(' 6 --- Вывести график')
case = input()
if case == '1':
print('Введите число: ', end='')
p = (input())
checkSimple(int(p))
elif case == '2':
a = int((input("Ведите а: ")))
b = int((input("Ведите b: ")))
fp= int((input("Ведите поле: ")))
checkDiskr(a,b,fp)
elif case == '3':
a = int((input("Ведите а: ")))
b = int((input("Ведите b: ")))
fp = int((input("Ведите поле: ")))
tochki(a,b,fp)
elif case == '4':
x1 = int((input("Ведите x1: ")))
y1 = int((input("Ведите y1: ")))
x2= int((input("Ведите x2: ")))
y2=int((input("Ведите y2: ")))
fp = int((input("Ведите поле: ")))
t1 = y2 - y1
t2 = x2 - x1
if t1 or t2==0:
print('besk')
else:
print(summ(x1, y1, x2, y2, fp))
elif case == '5':
x1 = int((input("Ведите x1: ")))
y1 = int((input("Ведите y1: ")))
count = int((input("Ведите множитель: ")))
a = int((input("Ведите a: ")))
fp = int((input("Ведите поле: ")))
print(pov(x1, y1, fp, count, a))
elif case == '6':
a = int((input("Ведите a ")))
b = int((input("Ведите b ")))
printGr(a,b)
print('Продолжить? да/нет')
fail_condition = input()
if fail_condition == 'нет':
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.