language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 1,154 | 2.515625 | 3 |
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
package edu.upenn.cis.ppod.model;
import static com.google.common.collect.Iterables.isEmpty;
import static com.google.common.collect.Lists.newArrayList;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;
import edu.upenn.cis.ppod.TestGroupDefs;
@Test(groups = TestGroupDefs.FAST)
public class RowTest {
@Test
public void clearCells() {
final OtuSet otuSet = new OtuSet();
final Otu otu = new Otu();
otuSet.addOtu(otu);
final StandardMatrix matrix = new StandardMatrix();
otuSet.addStandardMatrix(matrix);
// matrix.setColumnsSize(3);
matrix.clearAndAddCharacters(
newArrayList(
new StandardCharacter(),
new StandardCharacter(),
new StandardCharacter()));
final StandardRow row = new StandardRow();
matrix.putRow(otu, row);
row.clearAndAddCells(
newArrayList(
new StandardCell(),
new StandardCell(),
new StandardCell()));
row.clearCells();
assertTrue(isEmpty(row.getCells()));
for (final StandardCell cell : row.getCells()) {
assertNull(cell.getParent());
assertNull(cell.getPosition());
}
}
}
|
PHP
|
UTF-8
| 5,621 | 2.71875 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
<?php
namespace Simplon\Payment\Skrill\Vo;
class CheckoutQueryResponseVo
{
protected $_postData = [];
protected $_customCallbackData = [];
// ##########################################
/**
* @return mixed
*/
protected function _getPostData()
{
return $this->_postData;
}
// ##########################################
/**
* @param $key
* @return string|bool
*/
protected function _getPostDataByKey($key)
{
if(isset($this->_postData[$key]))
{
return $this->_postData[$key];
}
return FALSE;
}
// ##########################################
/**
* @param array $postData
* @return $this
*/
public function setData(array $postData)
{
// set post data
$this->_postData = $postData;
// identify custom callback fields
$this->_filterCustomCallbackFields();
return $this;
}
// ##########################################
/**
* @return $this
*/
protected function _filterCustomCallbackFields()
{
$postData = $this->_getPostData();
foreach($postData as $k => $v)
{
if(strpos($k, 'custom_') !== FALSE)
{
$this->_addCustomCallbackField(substr($k, 7), $v);
}
}
return $this;
}
// ##########################################
/**
* @param $key
* @param $value
* @return $this
*/
protected function _addCustomCallbackField($key, $value)
{
$this->_customCallbackData[$key] = $value;
return $this;
}
// ##########################################
/**
* @return bool|string
*/
public function getSkrillSha2Signature()
{
return $this->_getPostDataByKey('sha2sig');
}
// ##########################################
/**
* @return bool|string
*/
public function getSkrillMd5Signature()
{
return $this->_getPostDataByKey('md5sig');
}
// ##########################################
/**
* @return bool|string
*/
public function getSkrillStatus()
{
$response = $this->_getPostDataByKey('status');
if($response !== FALSE)
{
return (int)$response;
}
return FALSE;
}
// ##########################################
/**
* @return bool|string
*/
public function getSkrillTransactionId()
{
return $this->_getPostDataByKey('mb_transaction_id');
}
// ##########################################
/**
* @return bool|string
*/
public function getSkrillAmount()
{
return $this->_getPostDataByKey('mb_amount');
}
// ##########################################
/**
* @return bool|string
*/
public function getSkrillCurrency()
{
return $this->_getPostDataByKey('mb_currency');
}
// ##########################################
/**
* @return bool|string
*/
public function getSkrillMerchantId()
{
return $this->_getPostDataByKey('merchant_id');
}
// ##########################################
/**
* @return bool|string
*/
public function getPostedTransactionId()
{
return $this->_getPostDataByKey('transaction_id');
}
// ##########################################
/**
* @return bool|string
*/
public function getSkrillCustomerId()
{
return $this->_getPostDataByKey('customer_id');
}
// ##########################################
/**
* @return bool|string
*/
public function getPostedAmount()
{
return $this->_getPostDataByKey('amount');
}
// ##########################################
/**
* @return bool|string
*/
public function getPostedCurrency()
{
return $this->_getPostDataByKey('currency');
}
// ##########################################
/**
* @return bool|string
*/
public function getSkrillPaymentType()
{
return $this->_getPostDataByKey('payment_type');
}
// ##########################################
/**
* @return bool|string
*/
public function getPostedMerchantAccountEmail()
{
return $this->_getPostDataByKey('pay_to_email');
}
// ##########################################
/**
* @return bool|string
*/
public function getSkrillPayFromEmail()
{
return $this->_getPostDataByKey('pay_from_email');
}
// ##########################################
/**
* @return array
*/
public function getPostedCustomCallbackData()
{
return $this->_customCallbackData;
}
}
|
Markdown
|
UTF-8
| 2,591 | 2.984375 | 3 |
[
"Apache-2.0"
] |
permissive
|
In the current CodaLab competition model a competition is constructed with a set of Reference Data and a Scoring Program. The way competitions work currently the Reference Data is compared with a participants submission and the differences in the two are scored using the Scoring Program.
The program.zip bundle contains the Scoring Program that compares the participants submission with the reference data (in the reference.zip bundle) to score the submission. In this example the reference data contains the value of pi. The program.zip bundle computes the absolute difference of the submitted value from the reference value.
Here are the contents of the reference.zip file:
```
reference.zip
|- answer.txt (Contains: 3.14159265359)
|- metadata (Contains: This is the authoritative result.)
```
A submission.zip for this competition would look similar:
```
submission.zip
|- answer.txt (Contains: 3.1415359)
```
Here are the contents of the program.zip file:
```
program.zip
|- evaluate.exe (The program that's run)
|- metadata (Contents below...)
|- supporting modules and libraries for evaluate.exe to run in isolation.
```
The program.zip metadata file contains:
```
command: $program/evaluate.exe $input $output
description: Example competition evaluation program.
```
Here are the assumptions about the scoring process and the scoring program:
1. There is a fixed directory structure that the scoring program operates within. It looks like this:
```
Submission Directory
|- input
|- ref (This is the reference data unzipped)
|- res (This is the user submission unzipped)
|- program (This is the scoring program [and any included dependencies] unzipped)
|- output (This is where the scores.txt file needs to be written by the scoring program)
```
1. The scoring program will be invoked as ```<program> <input directory> <output directory>```
1. The scoring program is executed so that stderr and stdout are captured
1. The scoring program will generate a scores.txt file (it has to be named scores.txt) that contains key value pairs of metrics. This is a score file for the example competition:
```
Difference: 0.0057
```
1. Each key in the scores.txt file is identical to a leaderboard column key in the competition.yaml. (e.g. "DIFFERENCE" in the [example competition.yaml](https://github.com/codalab/codalab/wiki/12.-Building-a-Competition-Bundle). This is how scores are related to the competition for reporting so it is critical the leaderboard keys and the keys in the scores.txt are identical.
|
Python
|
UTF-8
| 443 | 2.59375 | 3 |
[] |
no_license
|
def solution(land):
for i in range(1,len(land)):
a,b,c,d = land[i-1][0],land[i-1][1],land[i-1][2],land[i-1][3]
for j in range(4):
if j == 0:
land[i][j] += max(b,c,d)
elif j == 1:
land[i][j] += max(a,c,d)
elif j == 2:
land[i][j] += max(a,b,d)
else:
land[i][j] += max(a,b,c)
return max(land[len(land)-1])
|
Java
|
UTF-8
| 593 | 1.734375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.eudemon.ratelimiter.rule.source;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.eudemon.ratelimiter.rule.source.FileRuleConfigSource;
import com.eudemon.ratelimiter.rule.source.RuleConfigSource;
import com.eudemon.ratelimiter.rule.source.UniformRuleConfigMapping;
/**
* TODO(zheng): add more tests.
*/
@Test
public class FileRuleConfigSourceTest {
public void testLoad() {
RuleConfigSource source = new FileRuleConfigSource();
UniformRuleConfigMapping ruleConfigMapping = source.load();
Assert.assertNotNull(ruleConfigMapping);
}
}
|
C++
|
UTF-8
| 6,669 | 3.359375 | 3 |
[] |
no_license
|
#include <iostream>
#include<string>
#include<fstream>
#include <sstream>
#include <cmath>
using namespace std;
class Node
{
public:
string name;
double rating;
int votes;
Node *next;
Node()
{
next =nullptr;
}
Node(string n, float r, int v)
{
name=n;
rating=r;
votes=v;
next=nullptr;
}
};
class Search
{
public:
Node *my_array[1000];
Search()
{
for(int x=0; x<1000; x++)
my_array[x]=nullptr;
}
//***********************************Reading File******************************************//
void reader()
{
ifstream in;
in.open("data.txt");
string movie_name;
string rating;
string votes;
string line;
while(getline(in, line))
{
movie_name="";
rating="";
votes="";
int choice=0;
for(int x=0; line[x]!='\0' ; x++)
{
if(line[x]==9)
choice++;
if(line[x] !=9 && line[x] != 32)
{
if(choice==0)
movie_name=movie_name+line[x];
else if(choice==1)
rating=rating+line[x];
else if(choice==2)
votes=votes+line[x];
}
}
stringstream r(rating);
stringstream v(votes);
int int_votes;
float int_rating;
r>>int_rating;
v>>int_votes;
add_data(movie_name,int_rating,int_votes);
}
cout<<"Done file reading\n";
}
//***************************************************End**********************************************************//
//********************//
//********************************************Add at start Seprate Chaining*************************************//
void add_data(string movie_name,float rating,int votes)
{
int place=abs((rating*100)-1);
if(my_array[place]==nullptr)
{
my_array[place] = new Node(movie_name,rating,votes);
}
else
{
Node *temp = my_array[place];
Node *temp1=new Node(movie_name,rating,votes);
temp1->next=temp->next;
temp->next=temp1;
}
}
//***************************************************End**********************************************************//
//********************//
//*********************************************Search Functions****************************************************//
void q1()
{
int place=abs((10.0*100)-1);
Node *temp = my_array[place];
while(temp != nullptr)
{
cout<<temp->name;
temp=temp->next;
}
}
void q2()
{
int place=abs((1.0*100)-1);
Node *temp = my_array[place];
while(temp != nullptr)
{
cout<<temp->name;
temp=temp->next;
}
}
void q3()
{
Node *temp1=new Node();
temp1->votes=0;
for(int x=0; x<1000; x++)
{
if(my_array[x] != nullptr)
{
Node *temp = my_array[x];
while(temp != nullptr)
{
if(temp->votes>temp1->votes)
{
temp1=temp;
}
temp=temp->next;
}
}
}
cout<<"Movie Name "<<temp1->name<<"With rating "<<temp1->rating;
}
void q4()
{
Node *temp1=new Node();
temp1->votes=99999;
for(int x=0; x<1000; x++)
{
if(my_array[x] != nullptr)
{
Node *temp = my_array[x];
while(temp != nullptr)
{
if(temp->votes<temp1->votes)
{
temp1=temp;
}
temp=temp->next;
}
}
}
cout<<"Movie Name "<<temp1->name<<" With votes"<<temp1->votes<<endl;
}
void q5()
{
int counter=0;
float r=0.0;
for(int x=0; x<1000; x++)
{
if(my_array[x] != nullptr)
{
Node *temp = my_array[x];
while(temp != nullptr)
{
r=r+temp->rating;
counter++;
temp=temp->next;
}
}
}
cout<<"Average Rating: "<<r/counter<<endl;
}
void q6(string n)
{
for(int x=0; x<1000; x++)
{
if(my_array[x] != nullptr)
{
Node *temp = my_array[x];
while(temp != nullptr)
{
if(n==temp->name)
cout<<n<<" has rating: "<<temp->rating<<" and votes: "<<temp->votes<<endl;
temp=temp->next;
}
}
}
}
void disp()
{
int counter=0;
for(int x=0; x<1000; x++)
{
if(my_array[x] != nullptr)
{
Node *temp = my_array[x];
while(temp != nullptr)
{
cout<<temp->name;
temp=temp->next;
counter++;
}
}
}
}
};
int main()
{
Search se;
se.reader();
while(true)
{
int choice;
cout<<"Enter\n1 to display movie with highest rating\n2 to display movie with lowest rating\n3 to display most popular movie\n4 to display least popular movie\n5 to get average rating\n6 to search by movie name\n";
cin>>choice;
switch(choice)
{
case 1:
se.q1();
break;
case 2:
se.q2();
break;
case 3:
se.q3();
break;
case 4:
se.q4();
break;
case 5:
se.q5();
break;
case 6:
{
string name; cout<<"Enter name of movie : "; cin>>name;
se.q6(name);
}
}
}
return 0;
}
|
PHP
|
ISO-8859-1
| 1,530 | 2.828125 | 3 |
[] |
no_license
|
<?php
include("../tool/header.php");
head("Tutorial Area - SQL");
?>
<h1> SQL </h1>
<h2> Requte SQL : Modifier une table </h2>
<h4> Ajouter une entrée </h4>
<p> Les requtes suivantes sont les requtes brutes, je ne mettrais plus "$requete = ..." pour des raisons de simplicité </p>
<p> La commande <q> INSERT </q> permet d'insérer des données. Par exemple, dans la table Adresse caractérisée par un ID, un champ nom, un champ prenom, un champ ge, je peux insérer DUPONT Jean, 42 ans:</p>
<pre class = "code">
INSERT INTO Adresse VALUES ( NULL, 'DUPONT', 'Jean', '42');
</pre>
<p> J'ai cité le champ ID. Un ID est un entier (<i> int </i>). Ce nombre permet d'identifier de manière unique un élément de la table. Il s'autoincrémente par défaut, c'est à dire que l'ID d'un nouvel élément inséré sera automatiquement l'ID le plus grand incrémenté de 1, d'o le NULL. Cette caractéristique se définit au moment de la création de la table (option à cocher lors de la création de la table).
<h4> Supprimer une entrée </h4>
<pre class = "code">
DELETE FROM matable WHERE `id` = '3';
</pre>
<h4> Modifier une entrée </h4>
<pre class = "code">
UPDATE carnet_adresse
SET `nom` = 'Lol', `prenom` = 'blague'
WHERE `id` = '3';
</pre>
<?php
include("../tool/footer.php");
?>
|
PHP
|
UTF-8
| 5,348 | 2.671875 | 3 |
[] |
no_license
|
<?php
/*
file path: http://localhost/projects/demo%20database/PHP/login.php
*/
?>
<?php
if(isset($_POST["submit"]))
{
$username=$_POST["user"];
$password=$_POST["pass"];
$u_fname=$u_mname=$u_lname=$u_gender=$u_dob=$u_mobile=$u_email=$u_address=$u_city=$u_state=$u_country="Not mentioned";
require "db_connection.php";
$pre_query1="SELECT * from user WHERE email='$username'";
$query_opt1=insert_query($conn,$pre_query1);
$val_array1=mysqli_fetch_assoc($query_opt1);
$rows1=mysqli_num_rows($query_opt1);
?>
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<link rel="stylesheet" type="text/css" href="../CSS/login.css">
</head>
<body>
<?php
if($rows1)
{
$pre_query2="SELECT * FROM user WHERE email='$username' AND mobile='$password'";
$query_opt2=insert_query($conn,$pre_query2);
$val_array2=mysqli_fetch_assoc($query_opt2);
$rows2=mysqli_num_rows($query_opt2);
if($rows2)
{
$u_fname=$val_array2["userfname"];
$u_mname=$val_array2["usermname"];
$u_lname=$val_array2["userlname"];
$u_gender=$val_array2["gender"];
$u_dob=$val_array2["dob"];
$u_mobile=$val_array2["mobile"];
$u_email=$val_array2["email"];
$u_address=$val_array2["address"];
$u_city=$val_array2["city"];
$u_state=$val_array2["state"];
$u_country=$val_array2["country"];
?>
<p class="text30px">YOUR DATABASE DETAILS ARE</p>
<table class="table" align="center">
<tr class="tabler">
<th class="tableh">
First Name:
</th>
<td class="tablec">
<?php echo $u_fname; ?>
</td>
</tr>
<tr class="tabler">
<th class="tableh">
Middle Name:
</th>
<td class="tablec">
<?php echo $u_mname; ?>
</td>
</tr>
<tr class="tabler">
<th class="tableh">
Last Name:
</th>
<td class="tablec">
<?php echo $u_lname; ?>
</td>
</tr>
<tr class="tabler">
<th class="tableh">
Gender:
</th>
<td class="tablec">
<?php echo $u_gender; ?>
</td>
</tr>
<tr class="tabler">
<th class="tableh">
DOB:
</th>
<td class="tablec">
<?php echo $u_dob; ?>
</td>
</tr>
<tr class="tabler">
<th class="tableh">
Mobile:
</th>
<td class="tablec">
<?php echo $u_mobile; ?>
</td>
</tr>
<tr class="tabler">
<th class="tableh">
Email:
</th>
<td class="tablec">
<?php echo $u_email; ?>
</td>
</tr>
<tr class="tabler">
<th class="tableh">
Address:
</th>
<td class="tablec">
<?php echo $u_address; ?>
</td>
</tr>
<tr class="tabler">
<th class="tableh">
City:
</th>
<td class="tablec">
<?php echo $u_city; ?>
</td>
</tr>
<tr class="tabler">
<th class="tableh">
State:
</th>
<td class="tablec">
<?php echo $u_state; ?>
</td>
</tr>
<tr class="tabler">
<th class="tableh">
Country:
</th>
<td class="tablec">
<?php echo $u_country; ?>
</td>
</tr>
<tr align="center" class="tabler"><td>
<form action="delete.php">
<style type="text/css">
.main_button
{
border-radius: 15px;
background-color: black;
color: white;
height: 40px;
width: 90px;
}
.main_button:hover
{
background-color:white;
color: black;
height: 45px;
width: 100px;
}
</style>
<input div="but" class="main_button" type="submit" value="Delete Data" name="submit">
</form>
</td>
<td><a class='link' href="index.php">Home Page</a></td>
</tr>
<?php
}
else
{
?>
<style type="text/css">
body{
background-color:black;
color: white;
text-align: center;
font-family: Arial;
}
.link
{
text-decoration: none;
font-size: 20px;
color: white;
}
</style>
<br><br><script type="text/javascript">
alert("Invalid Email or Password");
</script>
<a class="link" href="index.php">Login again</a>
<?php
}
}
else
{
?>
<style type="text/css">
body{
background-color:black;
color: white;
text-align: center;
font-family:Coronetscript;
}
.link
{
text-decoration: none;
font-size: 20px;
color: white;
}
</style>
<br><br><script type="text/javascript">
alert("No records found");
</script>
<a class="link" href="register.php">Register yourself</a>
<?php
}
}
else
{
?>
<style type="text/css">
body{
background-color:black;
color: white;
text-align: center;
font-family: Arial;
}
.link
{
text-decoration: none;
font-size: 20px;
color: white;
}
</style>
<br><br><script type="text/javascript">
alert("Go to main page");
</script>
<a class="link" href="index.php">Go to main page</a>
<?php
}
?>
</table>
</body>
</html>
|
C#
|
UTF-8
| 2,601 | 2.828125 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Tomlyn.Model
{
/// <summary>
/// Runtime representation of a TOML table array
/// </summary>
public sealed class TomlTableArray : TomlObject, IList<TomlTable>
{
private readonly List<TomlTable> _items;
public TomlTableArray() : base(ObjectKind.TableArray)
{
_items = new List<TomlTable>();
}
internal TomlTableArray(int capacity) : base(ObjectKind.TableArray)
{
_items = new List<TomlTable>(capacity);
}
public List<TomlTable>.Enumerator GetEnumerator()
{
return _items.GetEnumerator();
}
IEnumerator<TomlTable> IEnumerable<TomlTable>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(TomlTable item)
{
if (item == null) throw new ArgumentNullException(nameof(item));
_items.Add(item);
}
public void Clear()
{
_items.Clear();
}
public bool Contains(TomlTable item)
{
if (item == null) throw new ArgumentNullException(nameof(item));
return _items.Contains(item);
}
public void CopyTo(TomlTable[] array, int arrayIndex)
{
_items.CopyTo(array, arrayIndex);
}
public bool Remove(TomlTable item)
{
if (item == null) throw new ArgumentNullException(nameof(item));
return _items.Remove(item);
}
public int Count => _items.Count;
public bool IsReadOnly => false;
public int IndexOf(TomlTable item)
{
if (item == null) throw new ArgumentNullException(nameof(item));
return _items.IndexOf(item);
}
public void Insert(int index, TomlTable item)
{
if (item == null) throw new ArgumentNullException(nameof(item));
_items.Insert(index, item);
}
public void RemoveAt(int index)
{
_items.RemoveAt(index);
}
public TomlTable this[int index]
{
get => _items[index];
set => _items[index] = value ?? throw new ArgumentNullException(nameof(value));
}
}
}
|
Java
|
UTF-8
| 1,227 | 3.53125 | 4 |
[] |
no_license
|
package commands.client;
import server.models.cards.Card;
/**
* When a player passes without playing any card server draws a card to his hand and inform other players using this command.
*/
public class DrawCard extends ClientCommand {
/**
* PRIVATES
*/
private int seatNumber;
private String card;
/**
* CONSTRUCTOR
*/
public DrawCard() {
super(CommandNames.DRAW_CARD);
}
/**
* CONSTRUCTOR
*
* @param seatNumber the seat number of the player who draws a card.
* @param card the card drawn from the deck.
*/
public DrawCard(int seatNumber, String card) {
this();
this.seatNumber = seatNumber;
this.card = card;
addParameter(seatNumber);
addParameter(card);
}
/**
* @param commandStr
*/
@Override
public void doParse(String commandStr) {
seatNumber = scanner.nextInt();
card = scanner.next();
}
/**
*
*/
@Override
protected void doExecute() {
try {
manager.drawCard(seatNumber, Card.fromString(card));
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
|
Python
|
UTF-8
| 2,786 | 2.625 | 3 |
[] |
no_license
|
from main.crawlers.main import Main
from main.helpers.price import convert_price
from bs4 import BeautifulSoup
class StoreMercadoLivre(Main):
store = "MercadoLivre"
url_domain_https = "https://produto.mercadolivre.com"
url_domain_http = "http://produto.mercadolivre.com"
def __init__(self, url):
if not url.startswith(self.url_domain_https):
if not url.startswith(self.url_domain_http):
raise Exception("Url don't pertence this store")
self.url = url
@property
def page(self):
if not hasattr(self, "_page"):
self._page = self._extract_page()
return self._page
@property
def result(self):
if not hasattr(self, "_result"):
self._result = self._extract_result()
return self._result
@property
def name(self):
if not hasattr(self, "_name"):
try:
self._name = self.result.title.string
except Exception:
self._name = None
return self._name
@property
def price(self):
if not hasattr(self, "_price"):
try:
price = self.result.select(".ui-pdp-price__second-line")[0].meta.get("content")
price = convert_price(price)
except Exception:
price = None
self._price = price
return self._price
@property
def description(self):
if not hasattr(self, "_description"):
try:
self._description = self.result.select('.ui-pdp-description__content')[0].text
except Exception:
self._description = None
return self._description
@property
def image(self):
if not hasattr(self, "_image"):
try:
self._image = self.result.select('.ui-pdp-gallery__figure')[0].img.get("src")
except Exception:
self._image = None
return self._image
@property
def avaliable_sizes(self):
sizes = []
if not hasattr(self, "_avaliable_sizes"):
try:
# items = self.result.select(".product-size-selector")[0].select(".radio-options")[0].select(".product-item")
# for item in items:
# if item.text not in sizes:
# sizes.append(item.text)
self._avaliable_sizes = None
except Exception:
self._avaliable_sizes = None
return self._avaliable_sizes
def _extract_page(self):
return super()._request_page(self.url)
def _extract_result(self):
return BeautifulSoup(self.page, "html.parser")
def display_attributes(self):
return super().show_attributes(self)
|
Java
|
UTF-8
| 969 | 2.453125 | 2 |
[] |
no_license
|
package com.fiuba.gaff.comohoy.model.purchases;
public enum RequestStatus{
WaitingConfirmation("Esperando confirmación"),
OnPreparation("En preparación"),
OnTheWay("En camino"),
Delivered("Entregado"),
CanceledByUser("Cancelado"),
CanceledByCommerce("Rechazado"),
Unknown("Indeterminado");
private final String mText;
RequestStatus(String text) {
mText = text;
}
public String toString() {
return mText;
}
public static RequestStatus fromString(String value) {
switch (value) {
case "WAITING_CONFIRMATION": return WaitingConfirmation;
case "ON_PREPARATION": return OnPreparation;
case "ON_THE_WAY": return OnTheWay;
case "DELIVERED": return Delivered;
case "CANCELLED_BY_USER": return CanceledByUser;
case "CANCELLED_BY_COMMERCE": return CanceledByCommerce;
default: return Unknown;
}
}
}
|
Python
|
UTF-8
| 31,642 | 2.703125 | 3 |
[] |
no_license
|
import scraperwiki
import urllib2
import lxml.etree
'''
Code to pull data out of the timing related press releases issued by FIA for Formula One races.
This code is provided solely for your own use, without guarantee, so you can publish F1 timing data,
according to license conditions specified by FIA,
without having to rekey the timing data as published on the PDF press releases yourself.
If you want to run the code in your own Python environment, you can what the pdftoxml function calls here:
https://bitbucket.org/ScraperWiki/scraperwiki/src/7d6c7a5393ed/scraperlibs/scraperwiki/utils.py
Essentially, it seems to be a call to the binary /usr/bin/pdftohtml ? [h/t @frabcus]
??pdf2html - this one? http://sourceforge.net/projects/pdftohtml/
'''
'''
To run the script, you need to provide a couple of bits of info...
Check out the PDF URLs on the F1 Media Centre timings page:
http://www.fia.com/en-GB/mediacentre/f1_media/Pages/timing.aspx
You should see a common slug identifying the race (note that occasionally the slug may differ on the timing sheets)
'''
#Enter slug for race here
race='sin'
#chn, mal, aus, tur, esp, mco, can, eur, gbr, ger, hun, bel, ita
'''
...and then something relevant for the rest of the filename
'''
#enter slug for timing sheet here
typ='race-chart'
#enter page footer slug
slug="<b>2011 FORMULA 1"
#typ can be any of the following (if they use the same convention each race...)
src='f1mediacentre'
'''
session1-classification.+
session1-times.x
session2-classification.+
session2-times.x
session3-classification.+
session3-times.x
x qualifying-classification
qualifying-trap.+
qualifying-speeds.+
qualifying-sectors.+
qualifying-times.x
race-laps.+
race-speeds.+
race-sectors.+
race-trap.+
race-analysis.x
race-summary.+
race-history.+
race-chart.+
**Note that race-analysis and *-times may have minor glitches**
The report list is a bit casual and occasionally a lap mumber is omitted and appears at the end of the list
A tidying pass on the data that I'm reporting is probably required...
BROKEN (IMPOSSIBLE AFTER SIGNING?)
race-classification <- under development; getting null response? Hmmm -seems to have turned to an photocopied image?
qualifying-classification <- seems like this gets signed and photocopied too :-(
IMPOSSIBLE?
race-grid
'''
#only go below here if you need to do maintenance on the script...
#...which you will have to do in part to get the data out in a usable form
#...at the moment, I only go so far as to preview what's there
#Here's where we construct the URL for the timing sheet.
#I assume a similar naming convention is used for each race?
TYP=typ
if src =='f1mediacentre': url = "http://www.fia.com/en-GB/mediacentre/f1_media/Documents/"+race+"-"+typ+".pdf"
else: url="http://dl.dropbox.com/u/1156404/"+race+"-"+typ+".pdf"
#url='http://dl.dropbox.com/u/1156404/mal-race-analysis.pdf'
pdfdata = urllib2.urlopen(url).read()
print "The pdf file has %d bytes" % len(pdfdata)
xmldata = scraperwiki.pdftoxml(pdfdata)
'''
print "After converting to xml it has %d bytes" % len(xmldata)
print "The first 2000 characters are: ", xmldata[:2000]
'''
root = lxml.etree.fromstring(xmldata)
pages = list(root)
print "The pages are numbered:", [ page.attrib.get("number") for page in pages ]
#Pairs: from eg [a,b,c,d] return (a,b), (c,d)
def pairs(seq):
it = iter(seq)
try:
while True:
yield it.next(), it.next()
except StopIteration:
return
#Preferred time format
def formatTime(t):
return float("%.3f" % t)
# Accept times in the form of hh:mm:ss.ss or mm:ss.ss
# Return the equivalent number of seconds
def getTime(ts):
t=ts.strip()
t=ts.split(':')
if len(t)==3:
tm=60*int(t[0])+60*int(t[1])+float(t[2])
elif len(t)==2:
tm=60*int(t[0])+float(t[1])
else:
tm=float(t[0])
return formatTime(tm)
def tidyup(txt):
txt=txt.strip()
txt=txt.strip('\n')
txt=txt.strip('<b>')
txt=txt.strip('</b>')
txt=txt.strip()
return txt
def contains(theString, theQueryValue):
return theString.find(theQueryValue) > -1
def gettext_with_bi_tags(el):
res = [ ]
if el.text:
res.append(el.text)
for lel in el:
res.append("<%s>" % lel.tag)
res.append(gettext_with_bi_tags(lel))
res.append("</%s>" % lel.tag)
if el.tail:
res.append(el.tail)
return "".join(res)
#I use the stub() routine to preview the raw scrape for new documents...
def stub():
page = pages[0]
scraping=1
for el in list(page)[:200]:
if el.tag == "text":
if scraping:
print el.attrib,gettext_with_bi_tags(el)
#The scraper functions themselves
#I just hope the layout of the PDFs, and the foibles, are the same for all races!
def storeRaceHistory(rawdata):
for result in rawdata:
lap=result[0]
for cardata in result[1:]:
if len(cardata)==2: gap=''
else: gap= cardata[2]
scraperwiki.sqlite.save(unique_keys=['lapDriver'], table_name=TYP, data={ 'lapDriver':lap+'_'+cardata[0], 'lap':lap,'driverNum':cardata[0],'time':getTime(cardata[1]), 'gap':gap})
def race_history():
lapdata=[]
txt=''
for page in pages:
lapdata=race_history_page(page,lapdata)
txt=txt+'new page'+str(len(lapdata))+'\n'
#Here's the data
for lap in lapdata:
print lap
print lapdata
print txt
print 'nlaps timing',str(len(lapdata))
storeRaceHistory(lapdata)
def race_history_page(page,lapdata=[]):
scraping=0
cnt=0
cntz=[2,2]
laps={}
lap=''
results=[]
microresults=[]
headphase=0
phase=0
pos=1
for el in list(page):
if el.tag == "text":
if scraping:
#print el.attrib,gettext_with_bi_tags(el)
txt=tidyup(gettext_with_bi_tags(el))
if txt.startswith("LAP") or txt.startswith("Page"):
if lap!='' and microresults!=[]:
results.append(microresults)
laps[lap]=results
lapdata.append(results)
pos=2
else:
print ';;;;'
pos=1
lap=txt
headphase=1
results=[]
results.append(txt.split(' ')[1])
microresults=[]
cnt=0
if headphase==1 and txt.startswith("TIME"):
headphase=0
elif headphase==0:
if cnt<cntz[phase] or (pos==1 and txt=='PIT'):
microresults.append(txt)
cnt=cnt+1
else:
cnt=0
results.append(microresults)
#print microresults,phase,cnt,headphase,pos,'....'
microresults=[txt]
if phase==0:
phase=1
else:
txt=gettext_with_bi_tags(el)
txt=txt.strip()
if txt.startswith(slug):
scraping=1
#print laps
return lapdata
def storeSessionRaceChart(rawdata):
for result in rawdata:
#scraperwiki.sqlite.save(unique_keys=['lap'], table_name=TYP, data={'lap':result[0],'positions':'::'.join(result[1:])})
lap=result[0]
pos=1
for carpos in result[1:]:
scraperwiki.sqlite.save(unique_keys=['lapPos'], table_name=TYP, data={'lapPos':lap+'_'+str(pos), 'lap':lap,'position':pos,'driverNum':carpos})
pos=pos+1
def race_chart():
laps=[]
for page in pages:
laps=race_chart_page(page,laps)
#Here's the data
for lap in laps:
print lap
print laps
storeSessionRaceChart(laps)
def race_chart_page(page,laps):
cnt=0
cntz=[2,2]
scraping=0
lap=''
results=[]
headphase=0
phase=0
pos=1
for el in list(page):
if el.tag == "text":
if scraping:
#print el.attrib,gettext_with_bi_tags(el)
txt=tidyup(gettext_with_bi_tags(el))
if txt.startswith("GRID"):
lap=txt
results=[txt]
elif txt.startswith("LAP"):
if lap !='':
laps.append(results)
lap=txt
results=[txt]
elif txt.startswith("Page"):
laps.append(results)
else:
for t in txt.split():
results.append(t)
else:
txt=gettext_with_bi_tags(el)
txt=txt.strip()
if txt.startswith(slug):
scraping=1
#print laps
return laps
def storeSessionRaceSummary(rawdata):
for result in rawdata:
scraperwiki.sqlite.save(unique_keys=['car_stop'], table_name=TYP, data={'car_stop':result[0]+'_'+result[3],'pos':result[0],'team':result[2],'stop':result[3],'lap':result[4],'name':result[1],'stoptime':result[6],'totalstoptime':result[7],'driverNum':result[0], 'timeOfDay':result[5]})
def race_summary():
stops=[]
for page in pages:
stops=race_summary_page(page,stops)
#Here's the data
for stop in stops:
print stop
print stops
storeSessionRaceSummary(stops)
def race_summary_page(page,stops=[]):
scraping=0
cnt=0
cntz=6
results=[]
pos=1
for el in list(page):
if el.tag == "text":
if scraping:
#print el.attrib,gettext_with_bi_tags(el)
txt=gettext_with_bi_tags(el)
if cnt<cntz:
if cnt==0:
results.append([])
txt=txt.split("<b>")
for t in txt:
if t !='':
results[pos-1].append(tidyup(t))
cnt=cnt+1
else:
cnt=0
txt=txt.split("<b>")
for t in txt:
results[pos-1].append(tidyup(t))
#print pos,results[pos-1]
pos=pos+1
else:
txt=gettext_with_bi_tags(el)
txt=txt.strip()
if txt.startswith(slug):
scraping=1
for result in results:
if not result[0].startswith("Page"):
stops.append(result)
return stops
def storeSessionTimes(rawdata):
for result in rawdata:
print result
datapair=pairs(result)
driverNum,driverName=datapair.next()
for lap,laptime in datapair:
scraperwiki.sqlite.save(unique_keys=['driverLap'], table_name=TYP, data={'driverLap':driverNum+'_'+lap,'lap':lap, 'laptime':laptime, 'name':driverName, 'driverNum':driverNum, 'laptimeInS':getTime(laptime)})
def qualifying_times():
pos=1
dpos=[]
#pos,dpos=qualifying_times_page(pages[4],pos,dpos)
for page in pages:
pos,dpos=qualifying_times_page(page,pos,dpos)
#Here's the data
for pos in dpos:
print pos
dposcorr=[]
for pos in dpos:
dupe=[]
print pos
prev=0
fixed=0
for p in pos:
if p.count(':')>0:
if prev==1:
print "oops - need to do a shuffle here and insert element at [-1] here"
dupe.append(pos[-1])
prev=1
else:
prev=0
if len(dupe)<len(pos):
dupe.append(p)
print 'corr?',dupe
print dposcorr.append(dupe)
print dpos
print 'hackfix',dposcorr
storeSessionTimes(dposcorr)
def linebuffershuffle(oldbuffer, newitem):
oldbuffer[2]=oldbuffer[1]
oldbuffer[1]=oldbuffer[0]
oldbuffer[0]=newitem
return oldbuffer
def qualifying_times_page(page,pos,dpos):
#There are still a few issues with this one:
#Some of the lap numbers appear in the wrong position in results list
scraping=0
cnt=0
cntz=5
drivers=[]
results=[]
phase=0
linebuffer=["","",""]
for el in list(page):
if el.tag == "text":
txt=gettext_with_bi_tags(el)
txt=tidyup(txt)
items=txt.split(" <b>")
for item in items:
linebuffer=linebuffershuffle(linebuffer, item)
#print linebuffer
if scraping:
#print el.attrib,gettext_with_bi_tags(el)
if phase==0 and txt.startswith("NO"):
phase=1
cnt=0
results=[]
print '??',linebuffer
results.append(linebuffer[2])
results.append(linebuffer[1])
elif phase==1 and cnt<3:
cnt=cnt+1
elif phase==1:
phase=2
results.append(txt)
elif phase==2 and txt.startswith("NO"):
phase=1
print results,linebuffer[2],linebuffer[1]
if linebuffer[2] in results: results.remove(linebuffer[2])
if linebuffer[1] in results: results.remove(linebuffer[1])
for tmp in results:
if contains(tmp,'<b>'): results.remove(tmp)
print '>>>',pos,results
dpos.append(results)
pos=pos+1
drivers.append(results)
results=[]
cnt=0
results.append(linebuffer[2])
results.append(linebuffer[1])
elif phase==2 and txt.startswith("Page"):
#print '>>>',pos,results
dpos.append(results)
drivers.append(results)
pos=pos+1
elif phase==2:
items=txt.split(" <b>")
for item in items:
results.append(item)
else:
txt=gettext_with_bi_tags(el)
txt=txt.strip()
if txt.startswith(slug):
scraping=1
return pos,dpos
def storeRaceAnalysis(rawdata):
for result in rawdata:
print result
datapair=pairs(result)
driverNum,driverName=datapair.next()
for lap,laptime in datapair:
scraperwiki.sqlite.save(unique_keys=['driverLap'], table_name=TYP, data={'driverLap':driverNum+'_'+lap,'lap':lap, 'laptime':laptime, 'name':driverName, 'driverNum':driverNum, 'laptimeInS':getTime(laptime)})
def race_analysis():
pos=1
dpos=[]
dposcorr=[]
for page in pages:
pos,dpos=race_analysis_page(page,pos,dpos)
#Here's the data
for pos in dpos:
print pos
dupe=[]
prev=0
fixed=0
for p in pos:
if p.count(':')>0:
if prev==1:
print "oops - need to do a shuffle here and insert element at [-1] here"
dupe.append(pos[-1])
prev=1
else:
prev=0
if len(dupe)<len(pos):
dupe.append(p.strip())
print dupe
print dposcorr.append(dupe)
print dpos
print dposcorr
storeRaceAnalysis(dposcorr)
def race_analysis_page(page,pos,dpos):
#There are still a few issues with this one:
#Some of the lap numbers appear in the wrong position in results list
scraping=0
cnt=0
cntz=5
drivers=[]
results=[]
phase=0
linebuffer=["","",""]
for el in list(page):
if el.tag == "text":
txt=gettext_with_bi_tags(el)
txt=tidyup(txt)
items=txt.split(" <b>")
for item in items:
linebuffer=linebuffershuffle(linebuffer, item)
if scraping:
#print el.attrib,gettext_with_bi_tags(el)
if phase==0 and txt.startswith("LAP"):
phase=1
cnt=0
results=[]
results.append(linebuffer[2])
results.append(linebuffer[1])
elif phase==1 and cnt<3:
cnt=cnt+1
elif phase==1:
phase=2
results.append(txt)
elif phase==2 and txt.startswith("LAP"):
phase=1
if linebuffer[2] in results: results.remove(linebuffer[2])
if linebuffer[1] in results: results.remove(linebuffer[1])
for tmp in results:
if contains(tmp,'<b>'): results.remove(tmp)
print results,linebuffer[2],linebuffer[1]
#results.remove(linebuffer[2])
#results.remove(linebuffer[1])
#print '>>>',pos,results
dpos.append(results)
pos=pos+1
drivers.append(results)
results=[]
cnt=0
results.append(linebuffer[2])
results.append(linebuffer[1])
elif phase==2 and txt.startswith("Page"):
#print '>>>',pos,results
dpos.append(results)
drivers.append(results)
pos=pos+1
elif phase==2:
items=txt.split(" <b>")
for item in items:
results.append(item)
else:
txt=gettext_with_bi_tags(el)
txt=txt.strip()
if txt.startswith(slug):
scraping=1
return pos,dpos
def storeSessionClassification(rawdata):
for result in rawdata:
scraperwiki.sqlite.save(unique_keys=['name','driverNum'], table_name=TYP, data={'pos':result[0],'fastlap':getTime(result[5]), 'name':result[2], 'team':result[4],'nationality':result[3],'driverNum':result[1], 'laps':result[-1], 'kph':result[8]})
def session1_classification():
page = pages[0]
scraping=0
cnt=0
cntz=[7,8,9]
results=[]
pos=1
phase=0
print 'pages:',len(pages)
for el in list(page):
if el.tag == "text":
txt=gettext_with_bi_tags(el)
if scraping:
print el.attrib,gettext_with_bi_tags(el),txt
txt=tidyup(txt)
if txt!='Timekeeper:':
if cnt<cntz[phase]:
if cnt==0:
results.append([])
txt=txt.split("<b>")
for t in txt:
results[pos-1].append(t.strip())
cnt=cnt+1
else:
if phase<2:
phase=phase+1
cnt=0
results[pos-1].append(txt)
#print pos,results[pos-1]
pos=pos+1
else:
txt=gettext_with_bi_tags(el)
txt=txt.strip()
if txt.startswith("<b>TIME OF"):
scraping=1
#Here is the data
for pos in results:
print pos
print 'results:',results
storeSessionClassification(results)
def storeSessionQualiSectors(rawdata):
ss=1
for sector in rawdata:
for result in sector:
scraperwiki.sqlite.save(unique_keys=['sector_pos','sector_driver'], table_name=TYP, data={'sector_pos':str(ss)+'_'+result[0],'sector_driver':str(ss)+'_'+result[1],'pos':result[0],'name':result[2],'sectortime':result[3],'driverNum':result[1]})
ss=ss+1
def qualifying_sectors():
sectors=["<b>SECTOR 1</b>\n","<b>SECTOR 2</b>\n","<b>SECTOR 3</b>\n"]
sector=1
scraping=0
results=[]
sectorResults=[]
pos=1
cnt=0
cntz=2
for el in list(page):
if el.tag == "text":
if scraping:
#print el.attrib,gettext_with_bi_tags(el)
txt=gettext_with_bi_tags(el)
if txt in sectors:
sector=sector+1
sectorResults.append(results)
#print sectorResults
#print "Next sector"
scraping=0
continue
if cnt<cntz:
if cnt==0:
results.append([])
txt=txt.strip()
txt=txt.split("<b>")
for t in txt:
t=tidyup(t)
results[pos-1].append(t)
cnt=cnt+1
else:
cnt=0
txt=txt.strip()
txt=txt.split("<b>")
for t in txt:
t=tidyup(t)
results[pos-1].append(t)
#print pos,results[pos-1]
pos=pos+1
else:
txt=gettext_with_bi_tags(el)
txt=txt.strip()
if txt.startswith("<b>TIME"):
scraping=1
results=[]
pos=1
cnt=0
sectorResults.append(results)
#print sectorResults
#Here's the data
for result in sectorResults:
print result
print sectorResults
storeSessionQualiSectors(sectorResults)
def storeSessionQualiSpeeds(rawdata):
ss=1
for sector in rawdata:
for result in sector:
scraperwiki.sqlite.save(unique_keys=['sector_pos','sector_driver'], table_name=TYP, data={'sector_pos':str(ss)+'_'+result[0],'sector_driver':str(ss)+'_'+result[1],'pos':result[0],'name':result[2],'speed':result[3],'driverNum':result[1]})
ss=ss+1
def qualifying_speeds():
sessions=["<b>INTERMEDIATE 1</b>\n","<b>INTERMEDIATE 2</b>\n","<b>FINISH LINE</b>\n"]
session=1
scraping=0
results=[]
sessionResults=[]
pos=1
cnt=0
cntz=2
for el in list(page):
if el.tag == "text":
if scraping:
#print el.attrib,gettext_with_bi_tags(el)
txt=gettext_with_bi_tags(el)
if txt in sessions:
session=session+1
sessionResults.append(results)
#print sessionResults
#print "Next session"
scraping=0
continue
if cnt<cntz:
if cnt==0:
results.append([])
txt=txt.strip()
txt=txt.split("<b>")
for t in txt:
t=tidyup(t)
results[pos-1].append(t)
cnt=cnt+1
else:
cnt=0
txt=txt.strip()
txt=txt.split("<b>")
for t in txt:
txt=tidyup(t)
results[pos-1].append(t)
#print pos,results[pos-1]
pos=pos+1
else:
txt=gettext_with_bi_tags(el)
txt=txt.strip()
if txt.startswith("<b>KPH"):
scraping=1
results=[]
pos=1
cnt=0
sessionResults.append(results)
#Here's the data
for session in sessionResults:
for pos in session:
print pos
for session in sessionResults:
print session
print sessionResults
storeSessionQualiSpeeds(sessionResults)
def storeSessionQualiTrap(rawdata):
for result in rawdata:
scraperwiki.sqlite.save(unique_keys=['pos','driverNum'], table_name=TYP, data={'pos':result[0],'name':result[2],'speed':result[3],'driverNum':result[1],'timeOfDay':result[4]})
def qualifying_trap():
page = pages[0]
scraping=0
cnt=0
cntz=3
results=[]
pos=1
for el in list(page):
if el.tag == "text":
if scraping:
#print el.attrib,gettext_with_bi_tags(el)
txt=gettext_with_bi_tags(el)
if cnt<cntz:
if cnt==0:
results.append([])
txt=txt.split("<b>")
for t in txt:
results[pos-1].append(tidyup(t))
cnt=cnt+1
else:
cnt=0
txt=txt.split("<b>")
for t in txt:
results[pos-1].append(tidyup(t))
#print pos,results[pos-1]
pos=pos+1
else:
txt=gettext_with_bi_tags(el)
txt=txt.strip()
print txt
if txt.startswith("<b>TIME OF"):
scraping=1
#Here's the data
for pos in results:
print pos
print results
storeSessionQualiTrap(results)
def storeQualiClassification(rawdata):
for result in rawdata:
if len(result)>4: q1_laps=result[4]
else: q1_laps=''
if len(result)>5: q2_laps=result[5]
else: q2_laps=''
if len(result)>8: q3_laps=result[8]
else: q3_laps=''
if len(result)>9: q1_time=result[9]
else: q1_time=''
if len(result)>11: q2_time=result[11]
else: q2_time=''
if len(result)>12: q3_time=result[12]
else: q3_time=''
scraperwiki.sqlite.save(unique_keys=['name','driverNum','pos'], table_name=TYP, data={'pos':result[0],'fastlap':getTime(result[5]), 'name':result[2], 'team':result[3],'driverNum':result[1], 'q1_laps':q1_laps,'q2_laps':q2_laps,'q3_laps':q3_laps, 'q1_time':q1_time,'q2_time':q2_time,'q3_time':q3_time})
def qualifying_classification():
# print the first hundred text elements from the first page
page = pages[0]
scraping=0
session=1
cnt=0
pos=1
results=[]
cntz=[13,10,6]
posz=[10,17,24]
inDNS=0
for el in list(page):
if el.tag == "text":
if scraping:
#print el.attrib,gettext_with_bi_tags(el)
txt=gettext_with_bi_tags(el)
txt=tidyup(txt)
if session<4:
if cnt<cntz[session-1]:
if cnt==0:
results.append([])
txt=txt.strip()
txt=txt.split()
print txt
for j in txt:
results[pos-1].append(j)
cnt=cnt+1
else:
if len(results[pos-1])>4:
txt=txt.split()
print '->',txt
for j in txt:
results[pos-1].append(j)
cnt=cnt+1
if j=='DNS' or j=='DNF':
inDNS=1
if session==1 or session==2:
cnt=cnt+3
else:
cnt=cnt+1
if inDNS==1:
if cnt==cntz[session-1]-3:
cnt=cnt+3
else:
results[pos-1].append(txt)
cnt=cnt+1
else:
if pos==posz[session-1]:
session=session+1
print "session",session
inDNS=0
cnt=0
txt=txt.split()
for j in txt:
results[pos-1].append(j)
print txt,pos,results[pos-1]
pos=pos+1
else:
txt=gettext_with_bi_tags(el)
txt=txt.strip()
if txt.startswith(slug):
scraping=1
#Here's the data
for result in results:
print 'result',result
#del results[-1]
print results
storeQualiClassification(results)
def storeRaceClassification(rawdata):
pos=1
for result in rawdata:
if result[0]!='FASTEST LAP':
try: fastlap=getTime(result[5])
except: fastlap=''
scraperwiki.sqlite.save(unique_keys=['name','driverNum'], table_name=TYP, data={'pos':result[5],'fastlap':fastlap, 'name':result[1], 'team':result[3],'nationality':result[2],'driverNum':result[0], 'laps':result[4], 'result':pos, 'gap':result[6], 'fastlap':result[-2],'speed':result[-3]})
pos=pos+1
def race_classification():
#under development - need to handle 'NOT CLASSIFIED'
page = pages[0]
scraping=0
cnt=0
cntz=[8,9,10,8]
results=[]
pos=1
phase=0
for el in list(page):
#print "broken?",el
if el.tag == "text":
txt=gettext_with_bi_tags(el)
if scraping:
#print el.attrib,gettext_with_bi_tags(el)
txt=tidyup(txt)
if cnt<cntz[phase]:
if cnt==0:
results.append([])
txt=txt.split("<b>")
for t in txt:
results[pos-1].append(t.strip())
cnt=cnt+1
else:
if phase<2:
phase=phase+1
cnt=0
if txt.startswith("NOT CLASS"):
phase=3
else:
results[pos-1].append(txt)
print pos,results[pos-1]
pos=pos+1
else:
txt=gettext_with_bi_tags(el)
txt=txt.strip()
print "...",txt
if txt.startswith("<b>LAP<"):
scraping=1
print results
storeRaceClassification(results)
if typ=="qualifying-classification":
qualifying_classification()
elif typ=="qualifying-trap" or typ=="race-trap":
qualifying_trap()
elif typ=="qualifying-speeds" or typ=="race-speeds":
qualifying_speeds()
elif typ=="qualifying-sectors" or typ=="race-sectors":
qualifying_sectors()
elif typ=="session1-classification" or typ=="session2-classification" or typ=="session3-classification" or typ=="race-laps":
session1_classification()
if typ=="race-classification":
race_classification()
elif typ=="qualifying-times" or typ=="session3-times" or typ=="session2-times" or typ=="session1-times":
print "Trying qualifying times"
qualifying_times()
if typ=="race-analysis":
race_analysis()
elif typ=="race-summary":
race_summary()
elif typ=="race-history":
race_history()
elif typ=="race-chart":
race_chart()
# If you have many PDF documents to extract data from, the trick is to find what's similar
# in the way that the information is presented in them in terms of the top left bottom right
# pixel locations. It's real work, but you can use the position visualizer here:
# http://scraperwikiviews.com/run/pdf-to-html-preview-1/
|
JavaScript
|
UTF-8
| 1,116 | 2.6875 | 3 |
[] |
no_license
|
const connectionFactory = require('./ConnectionFactory')
class ProdutosDAO{
constructor(){
this.connection = connectionFactory();
}
pegaTodosOsLivros(callback){
this.connection.query('SELECT * FROM livros', (errs, results) => {
this.connection.end();
const produtos = results;
callback(produtos);
});
}
pegaUmLivroPorId(idDoLivro, callback){
this.connection.query(`SELECT * FROM livros WHERE id=${idDoLivro}`, (errs, results) =>{
this.connection.end();
const livro = results;
callback(livro)
})
}
gravaUmNovoLivro(livro){
return new Promise((resolve, reject)=>{
this.connection.query(`
INSERT INTO livros (titulo,preco,descricao) values
('${livro.titulo}', ${livro.preco}, '${livro.descricao}')
`, (errs, results)=>{
this.connection.end()
resolve(results.insertId)
})
})
}
}
module.exports = ProdutosDAO
|
TypeScript
|
UTF-8
| 292 | 2.515625 | 3 |
[] |
no_license
|
import { User } from "../Models/Users";
export const userTypes = {
USER_PROFILE_UPDATE: 'USER_PROFILE_UPDATE'
}
export function updateProfileUser(loginUser:User|null){
return {
type: userTypes.USER_PROFILE_UPDATE,
payload:{
loginUser
}
}
}
|
Swift
|
UTF-8
| 1,978 | 2.921875 | 3 |
[] |
no_license
|
//
// ViewController.swift
// NewApp
//
// Created by apple on 1/27/20.
// Copyright © 2020 apple. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var imagename:[String] = ["A1","A2","A3","A4","A5"]
var imagedetails:[String] = ["This photo is taken by: 1 Jan, 2020","This photo is taken by: 2 Jan, 2020", "This photo is taken by: 3 Jan, 2020","This photo is taken by: 4 Jan, 2020","This photo is taken by: 5 Jan, 2020"]
var authorname:[String] = ["Rasel","Shishir","Ria","Murad","Afreen"]
@IBOutlet weak var array2: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
array2.delegate = self
array2.dataSource = self
self.array2.rowHeight = 250.0
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return imagename.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "show") as! MyTableViewCell
cell.Nameshow.text = authorname[indexPath.row]
cell.detailsshow1.text = imagedetails[indexPath.row]
cell.imageshow.image = UIImage(named: imagename[indexPath.row])
cell.accessoryType = .disclosureIndicator
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = storyboard?.instantiateViewController(identifier: "story") as! ScrollViewController
vc.getname = authorname[indexPath.row]
vc.getdetails = imagedetails[indexPath.row]
vc.getimg = UIImage(named: imagename[indexPath.row])!
self.navigationController?.pushViewController(vc, animated: true)
}
}
|
Markdown
|
UTF-8
| 6,395 | 3.28125 | 3 |
[] |
no_license
|
# Parser
The MiniLatex parser is written in Elm using
Evan Czaplicki's [parser combinator package](https://package.elm-lang.org/packages/elm/parser/latest/).
We will take a look at some of the top level parsers, then examine in detail
the parser for environments, which is both the most important and the most complex one.
## The top level parser
Here is the top-level parsing function:
```elm
latexExpression : Parser LatexExpression
latexExpression =
oneOf
[ texComment
, displayMathDollar
, displayMathBrackets
, inlineMath ws
, macro ws
, smacro
, words
, lazy (\_ -> environment)
]
```
The `oneOf` parser tries each parser in its argument list in turn, succeeding by
applying the first parser to succeed, and failing otherwise.
```
oneOf : List (Parser a) -> Parser a
```
The expression `lazy (\_ -> environment)` is needed to ensure
that recursion works. If one reads down the argument list of `oneOf`, one can extract a production
for a grammar for MiniLatex:
```elm
LatexExpression -> Comment
| DisplayMath
| InlineMath
| Macro
| SMacro
| LXString
| Environment env
```
We will come back to this later when we discuss the MiniLatex grammar.
There is no one-to-one correspondence between parser functions and productions,
but there is a close relations.
## Macro parser
Let us look at one of the components of the `latexExpression` parser, say,
the parsers for macros -- expressions like
like `\italic{Wow!}`. For this we use the`elm/parser` pipeline construction,
which sequences parsers:
```elm
macro : Parser () -> Parser LatexExpression
macro wsParser =
succeed Macro
|= macroName
|= itemList optionalArg
|= itemList arg
|. wsParser
```
The rough idea of the pipeline is to apply the parsers
`macroName`, `itemList optionalArg`, `itemList arg`,
and `wsParser` in sequence, chomping away at the input,
keeping the parse result in the case of `|=` and ignoring
it in the case `|.`
```elm
(|=) : Parser (a -> b) -> Parser a -> Parser b
(|.) : Parser keep -> Parser ignore -> Parser keep
```
In the case at hand, the pipeline
will feed three arguments to the type constructor
`Macro`. Since `succeed` has type `succeed : a -> Parser a`,
the result will be a `Parser LatexExpression`.
Note that the `macro` function takes a parser as input
and produces a `Parser LatexExpression` as output.
The input, which has type `Parser ()` should parse
white space -- perhaps just `' '`, or perhaps
newlines as well. This definition of `macro`
gives added flexibility.
As with the top level parser, we can derive a production for the
MiniLatex grammar directlh from the defintion of the parser:
```elm
Macro -> MacroName | OptionalArg* | Arg*
```
Rather than pursuing the rabbit down its hole to explain
the parsers `macroName`, `itemList`, `optionalArg`, `arg`,
and the possible whitespace parsers, we refer to
the [source code](https://github.com/jxxcarlson/meenylatex/blob/master/src/MiniLatex/Parser.elm).
## The environment parser
The environnment parser is the most complex of the parsers.
We give a simplified version, then discuss the changes
needed to obtain the actual parser.
```elm
environment : Parser LatexExpression
environment =
envName |> andThen environmentOfType
```
The envName parser recognizes text of the form `\\begin{foo}`, extracting
the string `foo`:
```el
envName : Parser String
envName =
succeed identity
|. PH.spaces
|. symbol "\\begin{"
|= parseToSymbol "}"
```
There is a companion parser `endWord`, which recognizes text like
`\\end{foo}`. The parser `andThen` is used to sequence parsers:
```elm
andThen : (a -> Parser b) -> Parser a -> Parser b
```
Consider now the second parser which makes up `environment`
```elm
environmentOfType : String -> Parser LatexExpression
environmentOfType envType =
let
theEndWord = "\\end{" ++ envType ++ "}"
in
environmentParse theEndWord envType
```
One sees that the types match, since
```
envName |> andThen environmentOfType == andThen environmentOfType envName
```
The result is that the information gathered by `environment` is passed
to `environmentParser` with arguments of the form `\\end{foo}` and `foo`.
At this point the use of the two arguments is redundant. However,
for the "real" parser, `envType` needs to be transformed: in some cases,
it is passed through as is, while in others it is changed.
Below is the definition of `environmentParser`. It is simple
application of the parser pipeline construct.
```elm
environmentParser : String -> String -> Parser LatexExpression
environmentParser endWord_ envType =
succeed (Environment envType)
|. ws
|= (nonemptyItemList latexExpression) |> map LatexList)
|. ws
|. symbol endWord_
|. ws
```
## Digression: Monads in Elm
Although Elm does not explicitly mention the much (and mistakenly) feared
notion of monad, monads are implicit in Elm. Indeed, the `andThen` function
is a variant of the bind function for the `Parser` monad.
Compare the type signatures for `andThen` and the monadic bind operator
`>>=`:
```
andThen : (a -> Parser b) -> Parser a -> Parser b
(>>=) : M a -> (a -> M b) -> M b
```
Up to a permutation and renaming of arguments, they are the same.
### Note
My favorite way of thinking about **bind** is to use the function
```elm
beta : (a -> M b) -> M a -> M b
```
Consider first functions `f : a -> b` and `g : b -> c`.
They can be composed: we can form `g o f : a -> c`.
Now let `f : a -> M b` and `g : b -> M c` be "monadic" functions,
where `M` is a type constructor (Elm) or a functor (Haskell).
They cannot be composed as is. However, with the aid of
`beta`, they can be:
```elm
g o' f = \x -> beta g (f x)
```
**Conclusion:** beta gives a way of composing monadic functions `f`
and `g`, where `M` is the monad. Bind does the same thing:
```
g o' f = \x -> (f x) >>= g
```
All the rigamarole about functors, monads, etc., is important,
because the monad conditions on `M` guarantee that the new composition
operator `o'` does what we expect it to, e.g., obey the associative law:
```
h o' (g o' f) = (h o' g) o' f
```
This is the point of view of Kliesli categories, which I learned
from the writings and videos of Bartosz Milewski. (INSERT REFERENCE)
|
JavaScript
|
UTF-8
| 3,458 | 3.28125 | 3 |
[] |
no_license
|
var btn = document.getElementById('submit')
var new_btn = document.getElementById('final')
var total_expense = 0;
var total_income = 0;
//Declaration of total income and total expense
function expense_manager(){
//Program for calculation of save and expense
event.preventDefault()
var query = document.getElementById('query').value
var amount = document.getElementById("amount").value
var name = document.getElementById('fname').value
var desc = document.getElementById('desc').value
if (query == "Income"){
var div1 = document.getElementById('output_Income')
var name = document.getElementById('fname').value
var h2 = document.createElement('h2')
var h22 = document.createElement('h2')
h2.style.color = "green"
h2.style.fontSize = '20px'
h2.style.fontWeight="bold"
h2.style.backgroundColor ="lightgrey"
h22.style.color = "green"
h22.style.fontSize = '20px'
h22.style.fontWeight="bold"
h22.style.backgroundColor ="lightgrey"
total_income += Number(amount)
h2.innerHTML = "Hi"+" "+name+" "+"Your income via "+desc+" "+"is"+" "+ amount
h22.innerHTML = "Total Income ==>" + total_income
div1.append(h2,h22)
//appending final result on income div
}
else if(query == "Expense"){
//If user chooses expense
var div2 = document.getElementById('output_expense')
var h2 = document.createElement('h2')
var h22 = document.createElement('h2')
h2.style.color = "brown"
h2.style.fontSize = '20px'
h2.style.fontWeight="bold"
h2.style.backgroundColor ="lightgrey"
h22.style.color = "brown"
h22.style.fontSize = '20px'
h22.style.fontWeight="bold"
h22.style.backgroundColor ="lightgrey"
total_expense += Number(amount)
h2.innerHTML ="your expense for"+" "+desc+ "==>" +amount
h22.innerHTML ="Total Expense" +"==>"+total_expense
div2.append(h2,h22)
//appending final result on expense div
}
//To make the input values empty
document.getElementById("desc").value= ""
document.getElementById("amount").value= ""
}
function final_sum(){
//To give the final output
event.preventDefault()
function expense_manager(){
//retaining and fetching values from expense manager
event.preventDefault()
total_expense
total_income
}
if(Number(total_income-total_expense)>total_expense && total_income> total_income/2 ){
//alert("GOOD JOB")
var doc = document.getElementById("first_half")
var h1 = document.getElementById("result")
h1.style.color = "Green"
var net_amount = Number(total_income-total_expense)
h1.innerHTML = "GOOD JOB!! NET SAVINGS"+" "+ net_amount+ ","+"Superb!"+ " "+"You are saving Nicely!"
doc.setAttribute('id','final_image')
}
else if(Number(total_income-total_expense)<total_expense){
//When Expense is more or saving is too less
//alert("TRY TO SAVE MORE")
var net_amount = Number(total_income-total_expense)
var doc = document.getElementById("first_half")
doc.setAttribute('id','expense_image')
var h1 = document.getElementById("result")
h1.style.color = "RED"
h1.innerHTML = "Your net saving is"+" "+net_amount +" ,"+ "You need to SAVE!"
}
}
btn.addEventListener('click',expense_manager)
new_btn.addEventListener('click',final_sum)
|
Java
|
UTF-8
| 617 | 2.640625 | 3 |
[] |
no_license
|
package com.tp.LeagueApp.persistance.postgres.mappers;
import com.tp.LeagueApp.models.Rune;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
public class RuneMapper implements RowMapper<Rune> {
@Override
public Rune mapRow(ResultSet resultSet, int i) throws SQLException {
Rune mappedRune = new Rune();
mappedRune.setRuneId(resultSet.getInt("runeId"));
mappedRune.setRuneName(resultSet.getString("runeName"));
mappedRune.setRuneDescription(resultSet.getString("runeDescription"));
return mappedRune;
}
}
|
Python
|
UTF-8
| 2,290 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#coding:utf-8
import gevent.monkey
gevent.monkey.patch_all()
from gevent.queue import Empty, Queue
import gevent
import requests
from urlparse import urlparse, parse_qs
from extract import extract, extract_all
from route import route
ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1'
class Spider(object):
cookie = None
headers = {}
def __init__(self, route):
self.queue = Queue()
self.route = route
def _fetch(self):
queue = self.queue
timeout = self.timeout
route = self.route
while True:
try:
url = queue.get(timeout=timeout+10)
except Empty:
return
headers = self.headers
if self.cookie:
headers['Cookie'] = self.cookie
headers['User-Agent'] = ua
try:
req = requests.get(url, timeout=timeout, headers=headers)
p = urlparse(req.url)
cls, args = route.match(p.path)
if cls:
o = cls(req)
r = o.get(*args)
if r:
for i in r:
if i:
queue.put(i)
except requests.exceptions.Timeout as e:
print 'timeout:',url
self.queue.put(url)
def run(self, num=10, timeout=60):
self.timeout = timeout
for i in xrange(num):
g = gevent.spawn(self._fetch)
g.join()
# gevent.shutdown()
def put(self, url):
self.queue.put(url)
class Handler(object):
def __init__(self, request):
p = urlparse(request.url)
request.arguments = parse_qs(p.query, 1)
self.request = request
self.html = request.content
def get_argument(self, name, default=None):
result = self.request.arguments.get(name, None)
if result is None:
return default
return result[0].encode('utf-8', 'ignore')
def extract(self, begin, end):
return extract(begin, end, self.html)
def extract_all(self, begin, end):
return extract_all(begin, end, self.html)
spider = Spider(route)
|
Shell
|
UTF-8
| 2,681 | 3.84375 | 4 |
[] |
no_license
|
#!/usr/bin/env bash
echo "*******************REED************************"
echo "Starting run_get_files_tests.sh"
date
# This script is run inside the Docker image, for single experiment (one project)
# Should only be invoked by the run_experiment.sh script
if [[ $1 == "" ]] || [[ $2 == "" ]] || [[ $3 == "" ]] || [[ $4 == "" ]]; then
echo "arg1 - GitHub SLUG"
echo "arg2 - Number of rounds"
echo "arg3 - Timeout in seconds"
echo "arg4 - Test name"
exit
fi
slug=$1
rounds=$2
timeout=$3
fullTestName=$4
fullClassName=$( echo ${fullTestName} | rev | cut -d . -f 2- | rev )
className=$( echo ${fullClassName} | rev | cut -d . -f 1 | rev )
testName=$( echo ${fullTestName} | rev | cut -d . -f 1 | rev )
# Setup prolog stuff
cd /home/awshi2/dt-fixing-tools/scripts/
# Incorporate tooling into the project, using Java XML parsing
cd /home/awshi2/${slug}
idflakiesSha=$( git rev-parse HEAD )
echo $idflakiesSha
MVNOPTIONS="-Denforcer.skip=true -Drat.skip=true -Dmdep.analyze.skip=true -Dmaven.javadoc.skip=true"
# Gather the results, put them up top
RESULTSDIR=/home/awshi2/output/
mkdir -p ${RESULTSDIR}
# Incorporate tooling into the project, using Java XML parsing
/home/awshi2/dt-fixing-tools/scripts/docker/pom-modify/modify-project.sh .
# Step 1 : Run the entire test suite and save all tests' file
# Run the plugin, get test locations
echo "*******************REED************************"
echo "Running the get test files tools"
date
timeout ${timeout}s /home/awshi2/apache-maven/bin/mvn testrunner:testplugin ${MVNOPTIONS} -Dtestplugin.className=edu.illinois.cs.dt.tools.utility.GetTestFilePlugin -Ddt.detector.original_order.retry_count=1 -Ddt.detector.original_order.all_must_pass=false -fn -B -e |& tee get-test-file.log
echo "*******************REED************************"
echo "Finished getting test files tools"
date
cp get-test-file.log ${RESULTSDIR}
# Redirect to a different name in case the test-to-file.csv is already in .
# This is necessary because cat cannot read and redirect output to the same file
find . -name test-to-file.csv | xargs cat > ./test-to-file-temp.csv
mv -f test-to-file-temp.csv test-to-file.csv
cp /home/awshi2/$slug/test-to-file.csv ${RESULTSDIR}
testInfo=$(grep "$fullTestName," /home/awshi2/$slug/test-to-file.csv)
moduleName=$(echo $testInfo | cut -d"," -f3)
# Step 6 : Run iDFlakies on that commit
/home/awshi2/dt-fixing-tools/scripts/docker/run_random_class_method.sh $slug ${rounds} ${timeout} ${RESULTSDIR} ${moduleName} "false"
mv mvn-test-time.log ${RESULTSDIR}
mv mvn-test.log ${RESULTSDIR}
echo "*******************REED************************"
echo "Finished run_get_files_tests.sh"
date
|
Java
|
UTF-8
| 2,865 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
package com.nemanjapetrovic.streaming.radio.player.Commands;
import com.nemanjapetrovic.streaming.radio.player.Data.Station;
import com.nemanjapetrovic.streaming.radio.player.Data.DataController;
import com.sun.jna.NativeLibrary;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
import uk.co.caprica.vlcj.component.AudioMediaListPlayerComponent;
import uk.co.caprica.vlcj.player.MediaPlayer;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by nemanja on 10/1/16.
*/
public class Command implements ICommand {
private static final String NATIVE_LIBRARY_SEARCH_PATH = "/home/vlc";
public Command() {
DataController.getInstance().LoadStations();
}
public void Help() {
StringBuffer buffer = new StringBuffer();
buffer.append("\n\n\nStreaming radio player commands: \n");
buffer.append("\tadd [name] [url] ; add a station to a list of stations \n");
buffer.append("\tremove [name] ; remove a station from a list of stations \n");
buffer.append("\tlist ; show all saved radio stations \n");
buffer.append("\tplay [name] ; play a radio station \n");
buffer.append("\n*** Created by Nemanja Petrovic github: @nemanjapetrovic ***\n\n\n");
System.out.println(buffer.toString());
}
public void Add(String name, String url) {
DataController.getInstance().AddStation(new Station(name, url));
}
public void Remove(String name) {
boolean ret = DataController.getInstance().RemoveStation(new Station(name, ""));
if (ret) {
System.out.println("Station successfully removed!");
} else {
System.out.println("Station don't exist!");
}
}
public void List() {
DataController.getInstance().print();
}
public void Play(String name) {
try {
//Get the station
final Station station = DataController.getInstance().getStation(name);
if (station == null) {
System.out.println("This station does not exist!");
return;
}
//Get library
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), NATIVE_LIBRARY_SEARCH_PATH);
//Create media and audio
AudioMediaListPlayerComponent factoryMy = new AudioMediaListPlayerComponent();
MediaPlayer mediaPlayer = factoryMy.getMediaPlayer();
//Play
mediaPlayer.playMedia(station.getUrl());
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
|
Python
|
UTF-8
| 181 | 3.171875 | 3 |
[] |
no_license
|
"""
4 2 1 0
0 0 1 0 = number 1
0 1 0 0 = numer 2
&
0 1 0 0 = resulta o numero 1
Por isso que usar o & com o numero 1 vai dizer se o numero e par ou impar
"""
a = 2
print(a & 1)
|
Java
|
UTF-8
| 1,424 | 2.71875 | 3 |
[] |
no_license
|
package org.cocina.util;
/**
* Clase con métodos generales para las diversas clases en la lógica de negocio.
*/
public class Utilitario {
@Deprecated
public static String obtenerSqlQueryCamareroSinJoins() {
StringBuilder sqlString = new StringBuilder();
sqlString.append("select c.id id_camarero, c.nombre nombre, c.primer_apellido apellido, ");
sqlString.append("(select coalesce(sum(d.importe),0) ");
sqlString.append("from factura f, detalle_factura d ");
sqlString.append("where f.id = d.factura_id ");
sqlString.append("and f.camarero_id = c.id ");
sqlString.append("and f.fecha_factura between ?1 and ?2 ");
sqlString.append(") sumatoriaImporte ");
sqlString.append("from camarero c ");
sqlString.append("order by 4 desc ");
return sqlString.toString();
}
public static String obtenerSqlQueryCamareroConJoins() {
StringBuilder sqlString = new StringBuilder();
sqlString.append("select c.id id_camarero, c.nombre nombre, c.primer_apellido apellido, coalesce(sum(d.importe),0) sumatoriaImporte ");
sqlString.append("from camarero c ");
sqlString.append("left outer join factura f on f.camarero_id = c.id and f.fecha_factura between ?1 and ?2 ");
sqlString.append("left outer join detalle_factura d on f.id = d.factura_id ");
sqlString.append("group by c.id, c.nombre, c.primer_apellido ");
sqlString.append("order by 4 desc ");
return sqlString.toString();
}
}
|
Python
|
UTF-8
| 1,270 | 2.890625 | 3 |
[] |
no_license
|
Python 3.7.0b5 (v3.7.0b5:abb8802389, May 31 2018, 01:54:01) [MSC v.1913 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> list=[1,2,3,4]
>>> b=bytes(list)
>>> b
b'\x01\x02\x03\x04'
>>> for n in b:
print(n)
1
2
3
4
>>> b[0]=1
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
b[0]=1
TypeError: 'bytes' object does not support item assignment
>>> list=[1,1.2,1.2]
>>> b=bytes(list)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
b=bytes(list)
TypeError: 'float' object cannot be interpreted as an integer
>>> list=[1.2,1.2]
>>> b=bytes(list)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
b=bytes(list)
TypeError: 'float' object cannot be interpreted as an integer
>>> list=[450,1]
>>> b=bytes(list)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
b=bytes(list)
ValueError: bytes must be in range(0, 256)
>>> b=bytearray(list)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
b=bytearray(list)
ValueError: byte must be in range(0, 256)
>>> list=[1,2,3]
>>> b=bytearray(list)
>>> for n in b:
print(n)
1
2
3
>>> b[0]=12
>>> for n in b:
print(n)
12
2
3
>>>
|
Markdown
|
UTF-8
| 6,987 | 3.921875 | 4 |
[] |
no_license
|
---
title: 数组的基本方法
date: 2019-04-30 19:12:59
tags:
- javascript
- Array
categories:
- 笔记
---
### 数组基础知识
#### 数组基础结构和遍历
> 数组也是对象类型的 `typeOf [] -> 'object'`
> 数组也有属性名,只不过属性名是数字,我们把数字属性名称为它的索引:数组是以数字作为索引,索引从零开始。有一个length属性代表属性的长度
> 类数组:类似于数组但不是数组
> 1、通过getElementsByTagName获取的元素集合是类数组
> 2、函数中的实参集合arguments也是类数组
#### 数组中的常用方法
> `console.dir(Array.prototype)`:查看数组中的方法
> 记忆维度
> - 1、方法的意义和作用
> - 2、方法的形参
> - 3、方法的返回值
> - 4、通过此方法,原来的数组是否发生了变化
`数组的增加、修改、删除`
```
var ary = [12,23,34];
//=>增加
//=>1、push:向数组的末尾追加新内容
//=>2、unshift:向数组开头追加新元素
//=>3、把它当做一个普通对象来操作:使用对象键值对操作,给其设置新的属性(索引):ary[ary.length]=xxx,向数组末尾追加了新的内容
//=>删除
//=>1、pop:删除数组最后一项
//=>2、shift:删除数组第一项
//=>3、delete:把数组当做普通对象操作,delete ary[索引]:删除指定索引这一项(当前项被删除后,原有数组其他项的索引不会改变,当前数组的length也不会改变:不推荐使用)
//=>4、ary.length--:删除数组最后一项
//=>修改
//=>
```
`push`
> 向数组末尾追加新内容
> 参数:一到多个,任何数据类型都可以,要给数组末尾追加什么,直接传递到push方法中即可,传递多个用逗号隔开
> 返回值:新增后数组的长度
> 原有数组改变了
`unshift`
> 向数组开头追加新元素
> 参数:需要追加的内容(可以是多个任何数据类型的值)
> 返回值:新增后数组的长度
> 原来数组改变了
`pop`
> 删除数组最后一项
> 参数:无参数,即输入什么删除的都是最后一项
> 返回值:被删除的那一项内容
> 原有数组改变了
`shift`
> 删除数组第一项
> 参数:无参数,即输入什么都是删除第一项
> 返回值:被删除的那一项内容
> 原有数组改变了,使用shift删除第一项后,后面每一项的索引都要向前进一位(导致后面项的索引发生改变)
`splice`
> 数组中内置方法:可以实现数组增加,修改,删除,本意是删除
> 实现删除:
> - splice(n,m) :从索引n开始删除m个(若没有参数m则从n删除到数组的末尾;n也不写则是一项也不删除 ) 返回值:被删除的内容(以一个新数组保存) 原有数组该变了
> - splice(0):清空数组
> - splice():一项都不删除,返回一个新的空数组
>
> 实现修改
> - splice(n,m,x):在原有删除的基础上,把x代替删除的内容
>
>
> 实现增加
> - splice(n,0,x):在修改的基础上,我们一项都不删除,把x插入到索引n的前面
> - ary.splice(0,0,x) : 向数组开头追加新的内容
> - ary.splice(ary.length,0,x):向数组末尾追加新的内容
`数组的查询`
>
```
slice:数组查询
```
`slice`
> 数组的查询
> 参数:slice(n,m) 从索引N开始找到索引M处(不包括M)
> 返回值:把找到的部分以一个新数组返回
> 原来的数组不变
> - slice(n) 从索引N开始找到末尾
> - slice(0)/slice() 数组克隆,克隆一份和原来数组一模一样的新数组
> - slice支持负数索引,如果传递的索引为负数,浏览器解析的时候是按照 总长度+负数索引 来处理的
> - 思考题:若在slice中传的参数值是小数,非数据类型,值超越范围会是什么情况?
> 总结:若参数值是小数,其会向下取整;若是非数据类型,会转换为数据类型;超出范围得到的是空数组。
<!-- more -->
`将两个数组进行拼接:concat`
> concat:将多个数组拼接在一起
> - 参数:要拼接的内容,把内容放在原数组后面,可以是一个数组,也可以是一些数据值
> - 返回:拼接后的新数组
> - 原有数组不变
> - concat() 什么都没有拼接,相当于把原有数组进行克隆
`把数组转化为字符串`
> 1、toString()
> - 实现把数组转化为字符串,转化后的字符串是以 逗号分隔每一项
> - 参数:无
> - 返回值:转换的字符串
> - 原有数组不变
>2、 join:把数组按照指定的分隔符转换为字符串,和字符串中的split相对应
> - 参数:指定的连接符
> - 返回值:转化后的字符串
> - 原有数组不变
```
//=>已知数组中的每一项都是数字,想实现数组求和,我们如何实现?
//=>1、用循环求和
//=>2、利用join
var total=eval(ary.join('+'))
//=>eval:把字符串变为JS表达式执行
```
`实现数组中每一项的排序和排列`
```
/*
*1、reverse:把数组中的每一项倒过来排列
* 参数:无
* 返回值:排列后的数组
* 原有数组改变
*
*/
/*
* 2、sort:实现数组的排序
* 参数:无或者回调函数
* 返回值:排序后的数组
* 原有数组改变
* 在不传递参数的情况下:可以给10以内的数字进行升序排列,但是超过10的就无法处理了(多位数只识别第一位)
*
* ary.sort(function(a,b)){
* return a-b; //=>升序
* return b-a;//=>降序
*
* })
*/
```
`验证数组中是否包含某一项`
```
/* indexOf / lastIndexOf :获取当前项在数组中第一次或者最后一次出现位置的索引
* 数组中的这两个方法在IE6-8下不兼容
* 字符串中的这两个方法兼容所有的浏览器
* 如果当前数组中没有这一项,返回的索引是-1,我们根据这一点可以验证数组中是否包含这一项
*/
if(ary.indexOf(12)>-1){
//=>数组中包含12
}
//=>不兼容下的验证数组中是否包含某一项的处理方式
Arrary.prototype.myIndexOf=function myIndexOf(value){
var result=-1;
for(var i=0;i<this.length;i++){
if(value===this[i]){
result=i;
break;
}
}
return result;
}
ary.myIndexOf(12);
```
`遍历数组中每一项的方法`
> 以下的方法在IE6-8下都不兼容
```
/*
forEach :遍历数组中的每一项
*/
ary.forEach(function(value,index){
//=>数组中有多少项,当前回调函数执行多少次,每一次传递进来的value就是当前遍历数组这一项的值,index就是遍历这一项的索引
});
/*
map: 遍历数组中的每一项,在forEach的基础上,可以修改每一项的值
*/
ary.map(function(value,index){
//=>数组中有多少项,当前回调函数执行多少次,每一次传递进来的value就是当前遍历数组这一项的值,index就是遍历这一项的索引
return xxx;//=>return后面返回的结果就是把当前遍历的这一项修改为xxx
});
```
|
PHP
|
UTF-8
| 3,763 | 2.734375 | 3 |
[] |
no_license
|
<?php declare(strict_types=1);
namespace TomasVotruba\Website\TweetPublisher;
use Symplify\Statie\Renderable\File\PostFile;
use TomasVotruba\Website\TweetPublisher\Exception\TweetImageNotFoundException;
use TomasVotruba\Website\TweetPublisher\Exception\TweetTooLongException;
final class PostTweetsProvider
{
/**
* @var int
*/
private const TWEET_MAX_LENGTH = 140;
/**
* @var int
* @see https://dev.twitter.com/basics/tco#how-do-i-calculate-if-a-tweet-with-a-link-is-going-to-be-over-140-characters-or-not
*/
private const SHORTENED_URL_LENGTH = 23;
/**
* @var string
*/
private $siteUrl;
/**
* @var PostsProvider
*/
private $postsProvider;
public function __construct(string $siteUrl, PostsProvider $postsProvider)
{
$this->siteUrl = $siteUrl;
$this->postsProvider = $postsProvider;
}
/**
* @todo Make sure the order is from the newest to the oldest, like Twitter API.
* @return string[][]
*/
public function provide(): array
{
$postTweets = [];
foreach ($this->postsProvider->provide() as $post) {
$postConfiguration = $post->getConfiguration();
if (! isset($postConfiguration['tweet'])) {
continue;
}
$postTweet = $this->appendAbsoluteUrlToTweet($post, $postConfiguration);
$this->ensureTweetFitsAllowedLength($postConfiguration['tweet'], $post);
$tweetImage = $this->resolveTweetImage($post, $postConfiguration);
$postTweets[] = [
'text' => $postTweet,
'image' => $tweetImage
];
}
return $postTweets;
}
private function ensureTweetFitsAllowedLength(string $tweet, PostFile $postFile): void
{
$tweetLength = mb_strlen($tweet);
if ($tweetLength <= self::TWEET_MAX_LENGTH) {
return;
}
throw new TweetTooLongException(sprintf(
'Tweet message "%s" is too long, after adding its url. It has %d chars, shorten it under %d.' .
PHP_EOL .
PHP_EOL .
'Look to "%s" file.',
$tweet,
$tweetLength,
self::TWEET_MAX_LENGTH - self::SHORTENED_URL_LENGTH,
realpath($postFile->getFilePath())
));
}
/**
* @param mixed[] $postConfiguration
*/
private function appendAbsoluteUrlToTweet(PostFile $postFile, array $postConfiguration): string
{
$url = $this->getAbsoluteUrlForPost($postFile);
return $postConfiguration['tweet'] . ' ' . $url . '/';
}
private function getAbsoluteUrlForPost(PostFile $postFile): string
{
return $this->siteUrl . '/' . $postFile->getRelativeUrl();
}
/**
* @param mixed[] $postConfiguration
*/
private function resolveTweetImage(PostFile $postFile, array $postConfiguration): ?string
{
if (! isset($postConfiguration['tweet_image'])) {
return null;
}
$sourceDirectory = __DIR__ . '/../../source/';
$localFilePath = $sourceDirectory . $postConfiguration['tweet_image'];
$this->ensureTweetImageExists($postFile, $localFilePath);
return $this->siteUrl . '/' . $postConfiguration['tweet_image'];
}
private function ensureTweetImageExists(PostFile $postFile, string $localFilePath): void
{
if (! file_exists($localFilePath)) {
throw new TweetImageNotFoundException(sprintf(
'Tweet image "%s" for "%s" file not found. Check "tweet_image" option.',
$localFilePath,
realpath($postFile->getFilePath())
));
}
}
}
|
TypeScript
|
UTF-8
| 1,598 | 2.6875 | 3 |
[] |
no_license
|
import jwt from 'jsonwebtoken';
import httpStatus from 'http-status';
import APIError from './apiError';
import {
GENERATE_TOKEN_ERROR,
JSON_WEB_TOKEN_ERROR,
TOKEN_EXPIRED,
} from '../constants/token';
import { ERROR } from '../constants/general';
const JWT_SECRET = process.env['JWT_SECRET'];
type PayloadType = {
userId: string;
userType: string;
};
class Token {
private _token: string;
private _tokenDecoded: PayloadType;
get token(): string {
return this._token;
}
set token(newToken: string) {
this._token = newToken;
}
get tokenDecoded(): PayloadType {
return this._tokenDecoded;
}
constructor(newToken: string = null) {
this._token = newToken;
}
generateToken = async (
payload: PayloadType,
expiresIn: string = '7d'
): Promise<void> => {
try {
this._token = await jwt.sign(payload, JWT_SECRET, { expiresIn });
} catch (error) {
throw new APIError(
GENERATE_TOKEN_ERROR,
httpStatus.INTERNAL_SERVER_ERROR,
error
);
}
};
verifyToken = async (): Promise<void> => {
try {
this._tokenDecoded = await (<PayloadType>(
jwt.verify(this._token, JWT_SECRET)
));
} catch (error) {
if (error.name === 'TokenExpiredError') {
throw new APIError(TOKEN_EXPIRED, httpStatus.UNAUTHORIZED);
} else if (error.name === 'JsonWebTokenError') {
throw new APIError(JSON_WEB_TOKEN_ERROR, httpStatus.BAD_REQUEST, error);
}
throw new APIError(ERROR, httpStatus.INTERNAL_SERVER_ERROR, error);
}
};
}
export default Token;
|
Markdown
|
UTF-8
| 2,732 | 2.8125 | 3 |
[] |
no_license
|
## Jest-Puppeteer-Atm-Reporter:
This is a plugin for uploading test execution results in real time (during execution - per `describe` block) for JEST tests to Adaptavist Test Management tool (Kanoah).
One `describe` block is mapped to one ATM test (`Test case ID` for which can be set using reporter method). Each `test` or `it` block in `describe` will be considered as unique step of that test. Testcase will be marked as `Fail` on failure of atleast one step.
## Install:
```
npm install jest-puppeteer-atm-reporter
npm install dotenv
```
### Environment Variables:
Set following environment variables on your machine:
```
BASE_URL = baseurl (e.g. --> jira.abcdef.com)
JIRA_USERNAME = username
JIRA_PASSWORD = password
PROJECT_KEY = XYZ
TEST_CYCLE_ID = OPQ
```
### Note:
In case you want to create new `TEST_CYCLE_ID` for every run then remove entry for `TEST_CYCLE_ID` from environment variable and use the npm module `GENERATE-ATM-TEST-CYCLE`(https://www.npmjs.com/package/generate-atm-test-cycle) to generate test cycle at runtime programatically.
## Usage:
Set following in package.json for using the jest-atm-reporter:
```
"jest": {
"reporters": [
"jest-puppeteer-atm-reporter"
]
},
```
### How to set value `Test case ID` and `Test Environment` from test file. Snippet from a sample JEST test below -
```
beforeAll(async () => {
reporter.setTestCaseID('<TestCaseID>');
reporter.setEnvironment('<TestEnvironment>');
});
```
### How to get screenshot of failure or final verification step. This screenshot will be auto uploaded to ATM TC. Snippet from a sample jest-puppeteer test below -
```
afterAll(async () => {
let name = '<UniqueFileName.jpeg>';
await page.screenshot({ path: name, fullPage: true});
reporter.setScreenshotName(name);
});
```
Note: `reporter` is global.
### Features:
* Creates new test environment in Kanoah(ATM) in case the provided test environment is missing in ATM
* Supports appropriate result upload for both type of JEST test execution - `Sequential` and `Parallel`
* Allows addition of metadata information - `Test case ID` and `Test Environment` per `describe` block
* Uploads test execution results to Kanoah (ATM) with following information -
* __Pass / Fail__ test in real time (per JEST `describe` block execution)
* Uploads the __actual time taken__ for the test to execute
* Uploads __failure reason__ with *Fail* tests
* Uploads __failure__ or __final verification__ screenshot with test
* Each test result upload displays respective environment information as set using the `reporter` method - `setEnvironment` (eg. values - `<applicationName>_desktop_en` or `chrome`)
|
Java
|
UTF-8
| 9,209 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2001-present Stephen Colebourne
*
* 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.joda.primitives.list.impl;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections.list.AbstractTestList;
import org.joda.primitives.list.ShortList;
import org.joda.primitives.iterator.ShortIterator;
/**
* Abstract base class for testing AbstractShortList subclasses.
*
* @author Stephen Colebourne
* @author Jason Tiscione
* @author Grzegorz Rozniecki
* @version CODE GENERATED
* @since 1.0
*/
public abstract class AbstractTestShortList extends AbstractTestList {
// This file is CODE GENERATED. Do not change manually.
public AbstractTestShortList(String name) {
super(name);
}
//-----------------------------------------------------------------------
/**
* Override to indicate that clone is not supported for this object.
*/
public boolean isCloneSupported() {
return true;
}
//-----------------------------------------------------------------------
public boolean isNullSupported() {
return false;
}
public Short[] getFullNonNullElements() {
return new Short[] {
new Short((short)2),new Short((short)-2),new Short((short)38),new Short((short)0),new Short((short)1000),new Short((short)202),new Short(Short.MIN_VALUE),new Short(Short.MAX_VALUE)
};
}
public Short[] getOtherNonNullElements() {
return new Short[] {
new Short((short)-33),new Short((short)66),new Short((short)-99)
};
}
public void testIsModifiable() {
resetFull();
ShortList plist = (ShortList) collection;
assertEquals(isAddSupported() || isRemoveSupported() || isSetSupported(), plist.isModifiable());
}
public void testToValueArray() {
resetFull();
ShortList plist = (ShortList) collection;
short[] values = plist.toShortArray();
int i = 0;
for (ShortIterator it = plist.iterator(); it.hasNext(); i++) {
short next = it.nextShort();
assertEquals(values[i], next);
}
}
public void testToValueArrayInsert() {
resetFull();
ShortList plist = (ShortList) collection;
short[] array = new short[2];
try {
plist.toShortArray(array, -1);
fail();
} catch (IndexOutOfBoundsException ex) {}
short[] values = plist.toShortArray();
// array null
short[] result = plist.toShortArray(null, 1);
assertEquals((short) 0, result[0]);
for (int i = 1; i < result.length; i++) {
assertEquals(values[i - 1], result[i]);
}
// array too small
array = new short[2];
array[0] = (short) 2;
array[1] = (short) 6;
result = plist.toShortArray(array, 1);
assertEquals((short) 2, array[0]);
assertEquals((short) 6, array[1]);
assertEquals(plist.size() + 1, result.length);
assertEquals((short) 2, result[0]);
for (int i = 0; i < values.length; i++) {
assertEquals(values[i], result[i + 1]);
}
// array big enough
array = new short[values.length + 2];
Arrays.fill(array, (short) 2);
result = plist.toShortArray(array, 1);
assertSame(array, result);
assertEquals((short) 2, array[0]);
assertEquals((short) 2, array[array.length - 1]);
for (int i = 0; i < values.length; i++) {
assertEquals(values[i], result[i + 1]);
}
}
//-----------------------------------------------------------------------
public void testRemoveRange() {
if (isRemoveSupported() == false) {
return;
}
resetFull();
int size = collection.size();
ShortList plist = (ShortList) collection;
plist.removeRange(size - 4, size - 2);
((List<?>) confirmed).remove(size - 4);
((List<?>) confirmed).remove(size - 4);
verify();
}
//-----------------------------------------------------------------------
public void testContainsAllArray() {
resetFull();
ShortList plist = (ShortList) collection;
assertEquals(true, plist.containsAll((short[]) null));
}
public void testAddAllArray() {
if (isAddSupported() == false) {
return;
}
resetFull();
ShortList plist = (ShortList) collection;
plist.addAll((short[]) null);
verify();
}
public void testAddAllArrayIndexed() {
if (isAddSupported() == false) {
return;
}
resetFull();
ShortList plist = (ShortList) collection;
plist.addAll(0, (short[]) null);
verify();
}
public void testRemoveAllArray() {
if (isRemoveSupported() == false) {
return;
}
resetFull();
ShortList plist = (ShortList) collection;
plist.removeAll((short[]) null);
verify();
}
public void testRetainAllArray() {
if (isRemoveSupported() == false) {
return;
}
resetFull();
ShortList plist = (ShortList) collection;
plist.retainAll((short[]) null);
confirmed.clear();
verify();
}
//-----------------------------------------------------------------------
public void testFirstShort_empty() {
resetEmpty();
ShortList plist = (ShortList) collection;
try {
plist.firstShort();
fail();
} catch (IndexOutOfBoundsException ex) {
// expected
}
}
public void testFirstShort_notEmpty() {
if (isAddSupported() == false) {
return;
}
resetEmpty();
ShortList plist = (ShortList) collection;
plist.add((short) 0);
plist.add((short) 6);
assertEquals((short) 0, plist.firstShort());
}
public void testLastShort_empty() {
resetEmpty();
ShortList plist = (ShortList) collection;
try {
plist.lastShort();
fail();
} catch (IndexOutOfBoundsException ex) {
// expected
}
}
public void testLastShort_notEmpty() {
if (isAddSupported() == false) {
return;
}
resetEmpty();
ShortList plist = (ShortList) collection;
plist.add((short) 0);
plist.add((short) 6);
assertEquals((short) 6, plist.lastShort());
}
//-----------------------------------------------------------------------
public void testFirst_empty() {
resetEmpty();
ShortList plist = (ShortList) collection;
assertNull(plist.first());
}
public void testFirst_notEmpty() {
if (isAddSupported() == false) {
return;
}
resetEmpty();
ShortList plist = (ShortList) collection;
plist.add((short) 0);
plist.add((short) 6);
assertEquals(new Short((short) 0), plist.first());
}
public void testLast_empty() {
resetEmpty();
ShortList plist = (ShortList) collection;
assertNull(plist.last());
}
public void testLast_notEmpty() {
if (isAddSupported() == false) {
return;
}
resetEmpty();
ShortList plist = (ShortList) collection;
plist.add((short) 0);
plist.add((short) 6);
assertEquals(new Short((short) 6), plist.last());
}
//-----------------------------------------------------------------------
public void testClone() {
resetFull();
ShortList coll = (ShortList) collection;
if (isCloneSupported()) {
ShortList coll2 = (ShortList) coll.clone();
assertTrue(coll != coll2);
assertEquals(coll, coll2);
} else {
try {
coll.clone();
fail();
} catch (UnsupportedOperationException ex) {}
}
}
//-----------------------------------------------------------------------
public void testSubListNotImplemented() {
resetFull();
ShortList coll = (ShortList) collection;
try {
coll.subList(0, coll.size());
fail();
} catch (UnsupportedOperationException expected) {}
}
}
|
C#
|
UTF-8
| 583 | 2.90625 | 3 |
[] |
no_license
|
using System;
namespace Fight_for_The_Life.Domain.GameObjects
{
public class BirthControl : GameObject
{
private const double VelocityCoefficient = 1.5;
public BirthControl(int y, double spermVelocity)
{
HeightCoefficient = 0.16;
WidthCoefficient = 0.05958;
if (y > Game.FieldHeight - 1 - Game.FieldHeight * HeightCoefficient || y < 0)
throw new ArgumentException("Y was outside the game field!");
Y = y;
Velocity = spermVelocity * VelocityCoefficient;
}
}
}
|
Java
|
UTF-8
| 861 | 2.65625 | 3 |
[] |
no_license
|
package com.msg91.shubham.msg91;
import android.content.Context;
/**
* This class is use to verify the OTP from MSG91
*/
public class VerifyOTP {
/**
* This method is use to verify the OTP.
*
* @param context Current Context
* @param AuthKey Authentication key which is provided by MSG91.com
* @param Mobile Mobile number in which OTP was sent
* @param EnteredOTP The OTP which is entered by the user
* @param listener Callback interface to return the response or error
*/
public static void verify(Context context, String AuthKey, String Mobile, String EnteredOTP, OtpResponseListener listener) {
String url = ServerHelper.VerifyOTPURL() + "?authkey=" + AuthKey + "&mobile=" + Mobile + "&otp=" + EnteredOTP;
SMSOTPVerificationRequest.sendRequest(context, url, listener);
}
}
|
Shell
|
UTF-8
| 829 | 2.65625 | 3 |
[] |
no_license
|
#!/bin/sh
source /etc/profile
cd /data/wwwroot/echo.adsense.cig.com.cn
PID=$(ps auxf|grep "echo-1.1.0-fat.jar" |grep -v grep|awk '{print $2}')
echo "kill $PID"
kill $PID
sleep 3
nohup java -Djava.net.preferIPv4Stack=true -server -Xms16g -Xmx16g -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -XX:InitiatingHeapOccupancyPercent=70 -XX:ParallelGCThreads=15 -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintTenuringDistribution -XX:+PrintHeapAtGC -Xloggc:/data/wwwlogs/echo.adsense.cig.com.cn/g1gc-`date +'%Y-%m-%d_%H-%M-%S'`.log -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/data/wwwlogs/echo.adsense.cig.com.cn -XX:ErrorFile=/data/wwwlogs/echo.adsense.cig.com.cn/jvm-error-`date +'%Y-%m-%d_%H-%M-%S'`.log -jar echo-1.1.0-fat.jar > echoServer-`date +'%Y-%m-%d_%H-%M-%S'`.log 2>&1&
echo $! > pid.txt
|
PHP
|
UTF-8
| 89 | 3.046875 | 3 |
[] |
no_license
|
<?php
$valor = "ola";
$valor2 = sprintf("$valor %a", "aaaaaaaaaaaa");
printf ($valor2);
|
Java
|
UTF-8
| 451 | 1.773438 | 2 |
[] |
no_license
|
package com.lhf.sportMeeting.facade.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/index")
public class IndexController {
@GetMapping
public String toIndex(){
return "index";
}
@GetMapping("/home")
public String home(){
return "login/signin";
}
}
|
Python
|
UTF-8
| 548 | 3.140625 | 3 |
[] |
no_license
|
class Solution:
def detectCapitalUse(self, word):
case_all_upper = True
case_all_lower = True
case_title = True
for i in range(0, len(word)):
c = word[i]
case_all_upper = case_all_upper and c.isupper()
case_all_lower = case_all_lower and not c.isupper()
if i == 0:
case_title = case_title and c.isupper()
else:
case_title = case_title and not c.isupper()
return case_title or case_all_lower or case_all_upper
|
Java
|
UTF-8
| 765 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
package ru.alex9127.app.classes;
import androidx.annotation.NonNull;
import java.util.ArrayList;
public class Inventory {
private final ArrayList<InventoryItem> list;
private final int maxSize;
public Inventory(int maxSize) {
this.list = new ArrayList<>();
this.maxSize = maxSize;
}
public void add(InventoryItem item) {
if (this.list.size() < maxSize) {
list.add(item);
}
}
public void remove(InventoryItem item) {
list.remove(item);
}
@NonNull
@Override
public String toString() {
StringBuilder s = new StringBuilder();
for (InventoryItem item:this.list) {
s.append(item).append(" ");
}
return s.toString();
}
}
|
JavaScript
|
UTF-8
| 1,896 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
'use strict';
const {PngImg} = require('../dist');
const RGBToString = require('../dist/utils').RGBToString;
const testData = require('./data');
describe('set', () => {
const rgbaTestRawImg = testData.readFileSync('rgba4x1.png');
let img;
beforeEach(() => {
img = new PngImg(rgbaTestRawImg);
});
it('should throw if x out of the bounds', () => {
assert.throws(() => img.set(5, 0, '#ffffff'));
});
it('should throw if y out of the bounds', () => {
assert.throws(() => img.set(0, 1, '#ffffff'));
});
it('should throw if bad color passed', () => {
assert.throws(() => img.set(0, 0, 'asdf'));
});
it('should set black if empty color object passed', () => {
img.set(0, 0, {});
assert.equal(RGBToString(img.get(0, 0)), '#000000');
});
it('should set color passed as rgb object', () => {
const white = {r: 255, g: 255, b: 255, a: 255};
img.set(0, 0, white);
assert.deepEqual(img.get(0, 0), white);
});
it('should set color passed as string', () => {
const white = '#ffffff';
img.set(0, 0, white);
assert.equal(RGBToString(img.get(0, 0)), white);
});
it('should set alpha too', () => {
const transparentWhite = {r: 255, g: 255, b: 255, a: 50};
img.set(0, 0, transparentWhite);
assert.deepEqual(img.get(0, 0), transparentWhite);
});
it('should ignore alpha in image without alpha', () => {
const noAlphaRaw = testData.readFileSync('rgb3x1_noalpha.png');
const noAlphaImg = new PngImg(noAlphaRaw);
const transparentWhite = {r: 255, g: 255, b: 255, a: 50};
noAlphaImg.set(0, 0, transparentWhite);
assert.equal(noAlphaImg.get(0, 0).a, 255);
});
it('should return this object', () => {
assert.equal(img.set(0, 0, '#ffffff'), img);
});
});
|
Markdown
|
UTF-8
| 11,014 | 4.21875 | 4 |
[
"MIT"
] |
permissive
|
数组去重的十四种方法
===
<!-- TOC -->
- [数组去重的十四种方法](#数组去重的十四种方法)
- [Methods 1: 定义一个新数组,并存放原数组的第一个元素,然后将元素组一一和新数组的元素对比,若不同则存放在新数组中。](#methods-1-定义一个新数组并存放原数组的第一个元素然后将元素组一一和新数组的元素对比若不同则存放在新数组中)
- [Methods 2: 利用sort()](#methods-2-利用sort)
- [Methods 3: 利用对象属性存在的特性,如果没有该属性则存入新数组。](#methods-3-利用对象属性存在的特性如果没有该属性则存入新数组)
- [Methods 4: 利用数组的indexOf下标属性来查询。](#methods-4-利用数组的indexof下标属性来查询)
- [Methods 5: 利用数组原型对象上的includes方法。](#methods-5-利用数组原型对象上的includes方法)
- [Methods 6: 利用数组原型对象上的 filter 和 includes方法。](#methods-6-利用数组原型对象上的-filter-和-includes方法)
- [Methods 7: 利用数组原型对象上的 forEach 和 includes方法。](#methods-7-利用数组原型对象上的-foreach-和-includes方法)
- [Methods 8: 利用for嵌套for,然后splice去重。](#methods-8-利用for嵌套for然后splice去重)
- [Methods 9: 利用数组原型对象上的 lastIndexOf 方法。](#methods-9-利用数组原型对象上的-lastindexof-方法)
- [Methods 10: 利用 ES6的 set 方法。](#methods-10-利用-es6的-set-方法)
- [Methods 11: 利用数组原型对象上的 filter 和 obj.hasOwnProperty方法](#methods-11-利用数组原型对象上的-filter-和-objhasownproperty方法)
- [Methods 12: 利用递归去重](#methods-12-利用递归去重)
- [Methods 13: 利用Map数据结构去重](#methods-13-利用map数据结构去重)
- [Methods 14: 利用reduce+includes](#methods-14-利用reduceincludes)
- [测试](#测试)
<!-- /TOC -->
## Methods 1: 定义一个新数组,并存放原数组的第一个元素,然后将元素组一一和新数组的元素对比,若不同则存放在新数组中。
```js
function unique(arr) {
var res = [arr[0]];
for (var i = 1; i < arr.length; i++) {
var repeat = false;
for (var j = 0; j < res.length; j++) {
if (arr[i] === res[j]) {
repeat = true;
break;
}
}
if (!repeat) {
res.push(arr[i]);
}
}
return res;
}
console.log("------------方法一---------------");
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]));
//{}没有去重
```
## Methods 2: 利用sort()
思路:先将原数组排序,在与相邻的进行比较,如果不同则存入新数组。
```js
function unique2(arr) {
var arr2 = arr.sort();
var res = [arr2[0]];
for (var i = 1; i < arr2.length; i++) {
if (arr2[i] !== res[res.length - 1]) {
res.push(arr2[i]);
}
}
return res;
}
console.log("------------方法二---------------");
console.log(unique2([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]));
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique2(arr))
// [0, 1, 15, "NaN", NaN, NaN, {…}, {…}, "a", false, null, true, "true", undefined]
// NaN、{}没有去重
```
## Methods 3: 利用对象属性存在的特性,如果没有该属性则存入新数组。
```js
function unique3(arr) {
var res = [];
var obj = {};
for (var i = 0; i < arr.length; i++) {
if (!obj[arr[i]]) {
obj[arr[i]] = 1;
res.push(arr[i]);
}
// else {
// obj[arr[i]]++
// }
}
console.log(obj, 'obj')
return res;
}
console.log("------------方法三---------------");
console.log(unique3([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]));
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique3(arr))
// [1, "true", 15, false, undefined, null, NaN, 0, "a", {…}]
// 两个true直接去掉了,NaN和{}去重
```
## Methods 4: 利用数组的indexOf下标属性来查询。
```js
function unique4(arr) {
if (!Array.isArray(arr)) {
console.log('type error!')
return
}
var res = [];
for (var i = 0; i < arr.length; i++) {
if (res.indexOf(arr[i]) == -1) {
res.push(arr[i]);
}
}
return res;
}
console.log("------------方法四---------------");
console.log(unique4([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]));
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique4(arr))
// [1, "true", true, 15, false, undefined, null, NaN, NaN, "NaN", 0, "a", {…}, {…}]
// NaN、{}没有去重
```
## Methods 5: 利用数组原型对象上的includes方法。
```js
function unique5(arr) {
var res = [];
for (var i = 0; i < arr.length; i++) {
if (!res.includes(arr[i])) { // includes 检测数组是否有某个值
// 如果res新数组包含当前循环item
res.push(arr[i]);
}
}
return res;
}
console.log("------------方法五---------------");
console.log(unique5([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]));
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique5(arr))
//[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {…}, {…}]
//{}没有去重
```
## Methods 6: 利用数组原型对象上的 filter 和 includes方法。
```js
function unique6(arr) {
var res = [];
res = arr.filter(function(item) {
return res.includes(item) ? "" : res.push(item);
});
return res;
}
console.log("------------方法六---------------");
console.log(unique6([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]));
// 同上 {}没有去重
```
## Methods 7: 利用数组原型对象上的 forEach 和 includes方法。
```js
function unique7(arr) {
var res = [];
arr.forEach(function(item) {
res.includes(item) ? "" : res.push(item);
});
return res;
}
console.log("------------方法七---------------");
console.log(unique7([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]));
```
## Methods 8: 利用for嵌套for,然后splice去重。
```js
function unique8(arr) {
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) { // 第一个等同于第二个,splice方法删除第二个
arr.splice(j, 1);
j--;
}
}
}
return arr;
}
console.log("------------方法八---------------");
console.log(unique8([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]));
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique8(arr))
//[1, "true", 15, false, undefined, NaN, NaN, "NaN", "a", {…}, {…}]
// NaN和{}没有去重,两个null直接消失了
```
## Methods 9: 利用数组原型对象上的 lastIndexOf 方法。
```js
function unique9(arr) {
var res = [];
for (var i = 0; i < arr.length; i++) {
res.lastIndexOf(arr[i]) !== -1 ? "" : res.push(arr[i]);
}
return res;
}
console.log("------------方法九---------------");
console.log(unique9([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]));
```
## Methods 10: 利用 ES6的 set 方法。
```js
function unique10(arr) {
//Set数据结构,它类似于数组,其成员的值都是唯一的
return Array.from(new Set(arr)); // 利用Array.from将Set结构转换成数组
// return [...new Set(arr)]
}
console.log("------------方法十---------------");
console.log(unique10([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]));
```
## Methods 11: 利用数组原型对象上的 filter 和 obj.hasOwnProperty方法
```js
// 重点需要掌握
function unique11(arr) {
var obj = {};
return arr.filter(function(item, index, array) {
return obj.hasOwnProperty(typeof item + item)
? false
: (obj[typeof item + item] = true);
});
}
const unique = arr => {
let obj = {};
return arr.filter(item => {
return obj.hasOwnProperty(typeof item + item)
? false
: (obj[typeof item + item] = true);
})
}
console.log("------------方法十一---------------");
console.log(unique11([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]));
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique11(arr))
// [1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {…}]
// 所有的都去重
```
## Methods 12: 利用递归去重
```js
function unique12(arr) {
var array = arr;
var len = array.length;
array.sort(function(a, b) {
//排序后更加方便去重
return a - b;
});
function loop(index) {
if (index >= 1) {
if (array[index] === array[index - 1]) {
array.splice(index, 1);
}
loop(index - 1); //递归loop,然后数组去重
}
}
loop(len - 1);
return array;
}
console.log("------------方法十二---------------");
console.log(unique12([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]));
```
## Methods 13: 利用Map数据结构去重
```js
function unique13(arr) {
let map = new Map();
let array = new Array(); // 数组用于返回结果
for (let i = 0; i < arr.length; i++) {
if (map.has(arr[i])) {
// 如果有该key值
map.set(arr[i], true);
} else {
map.set(arr[i], false); // 如果没有该key值
array.push(arr[i]);
}
}
return array;
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log("------------方法十三---------------");
console.log(unique(arr))
//[1, "a", "true", true, 15, false, 1, {…}, null, NaN, NaN, "NaN", 0, "a", {…}, undefined]
```
## Methods 14: 利用reduce+includes
```js
function unique(arr) {
return arr.reduce(
(prev, cur) => (prev.includes(cur) ? prev : [...prev, cur]),
[]
);
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log("------------方法十四---------------");
console.log(unique(arr));
// [1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {…}, {…}]
```
## 测试
当我把数组的长度变得很大的时候(如下所示),测试了一下不同方法的执行时间长短,会发现方法三、四、五、六、七相对来说会更有优势,而方法八的执行速度似乎一直垫底。
```js
//这里只是举例方法三(如果你把所有方法放在一起测试,会更直观的看到执行时间的差异)
var time3 = new Date().getTime();
function unique3(arr){
var res = [];
var obj = {};
for(var i=0; i<arr.length; i++){
if( !obj[arr[i]] ){
obj[arr[i]] = 1;
res.push(arr[i]);
}
}
return res;
}
console.log('------------方法三---------------');
console.log( unique3(arr) );
console.log('3所花时间: ' + (new Date().getTime() - time3));
```
|
Java
|
UTF-8
| 5,925 | 2.34375 | 2 |
[
"Apache-2.0"
] |
permissive
|
/**
* IFT2905 : Interface personne machine
* Projet de session: FlibityBoop.
* Team: Vincent CABELI, Henry LIM, Pamela MEHANNA, Emmanuel NOUTAHI, Olivier TASTET
* @author: Emmanuel Noutahi, Vincent Cabeli
*/
package com.maclandrol.flibityboop;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
/**
* API, superclasse de toutes les classes de requêtes vers une API spécifique
*/
public class API {
public String baseURL;
public String key;
String erreur;
/*
* Enum
* MediaType specifie le type de media (Film ou TVShow) pour les requêtes
*/
public enum MediaType {
Movies("movie"), TVShow("tv"), Any("");
private String name = "";
MediaType(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
public API(String baseURL, String key) {
this.baseURL = baseURL;
this.key = key;
erreur = null;
}
public API() {
baseURL = "";
key = "";
erreur = null;
}
/*
* getBitmapPoster, retourne l'image Bitmap à partit d'un url
*/
public static Bitmap getBitmapPoster(String poster_url) {
Bitmap webposter = null;
Log.d("url", poster_url);
try {
InputStream in = new java.net.URL(poster_url).openStream();
BufferedInputStream buf = new BufferedInputStream(in);
webposter = BitmapFactory.decodeStream(buf);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (MalformedURLException e) {
Log.e("url", "malformedURL");
} catch (IOException e) {
Log.e("Error", "IO exception");
}
return webposter;
}
/*
* getADDdata, retourne les données additionnelles d'un mediainfo par une requête sur OMDBAPI
*/
public HashMap<String, String> getADDdata(String imdb_id, String title,
boolean tomatoes) {
JSONObject js = this.getJSON("http://www.omdbapi.com/?i=" + imdb_id
+ "&tomatoes=" + tomatoes);
HashMap<String, String> imdb_res = new HashMap<String, String>();
if (js == null || !js.optBoolean("Response")) {
title = Uri.encode(title);
js = this.getJSON("http://www.omdbapi.com/?t=" + title
+ "&tomatoes=" + tomatoes);
}
if (js != null && js.optBoolean("Response")) {
imdb_res.put("iTitle", js.optString("Title"));
imdb_res.put("iYears", js.optString("Year"));
imdb_res.put("iRated", js.optString("Rated"));
imdb_res.put("iRuntime", js.optString("Runtime"));
imdb_res.put("iGenre", js.optString("Genre"));
imdb_res.put("iDirector", js.optString("Director"));
imdb_res.put("iWriter", js.optString("Writer"));
imdb_res.put("iActors", js.optString("Actors"));
imdb_res.put("iPlot", js.optString("Plot"));
imdb_res.put("iPoster", js.optString("Poster"));
imdb_res.put("iAwards", js.optString("Awards"));
imdb_res.put("iRating", js.optString("imdbRating"));
imdb_res.put("iVotes", js.optString("imdbVotes"));
imdb_res.put("iMetascore", js.optString("Metascore"));
String type = js.optString("Type");
if (type.equals("movie") && js.opt("tomatoMeter") != null) {
imdb_res.put("rtUserMeter", js.optString("tomatoUserMeter"));
imdb_res.put("rtUserRating", js.optString("tomatoUserRating"));
imdb_res.put("rtMeter", js.optString("tomatoMeter"));
imdb_res.put("rtRating", js.optString("tomatoRating"));
imdb_res.put("rtUserVotes", js.optString("tomatoUserReviews"));
imdb_res.put("rtVotes", js.optString("tomatoReviews"));
imdb_res.put("rtCertification", js.optString("tomatoImage"));
imdb_res.put("rtConsensus", js.optString("tomatoConsensus"));
imdb_res.put("rtProduction", js.optString("Production"));
imdb_res.put("rtWebsite", js.optString("Website"));
imdb_res.put("rtBoxOffice", js.optString("BoxOffice"));
}
}
return imdb_res;
}
/*
* getJSON, retourne l'objet json à partir d'une url
*/
public JSONObject getJSON(String url) {
JSONObject js = null;
try {
HttpEntity page = GetReq(url);
js = new JSONObject(EntityUtils.toString(page, HTTP.UTF_8));
} catch (ClientProtocolException e) {
erreur = "Erreur HTTP (protocole) :" + e.getMessage();
} catch (IOException e) {
erreur = "Erreur HTTP (IO) :" + e.getMessage();
} catch (ParseException e) {
erreur = "Erreur JSON (parse) :" + e.getMessage();
} catch (JSONException e) {
erreur = "Erreur JSON :" + e.getMessage();
}
return js;
}
/*
* getJSONArray, retourne l'objet JsonArray à partir d'un url
*/
public JSONArray getJSONArray(String url) {
JSONArray jarray = null;
try {
HttpEntity page = GetReq(url);
jarray = new JSONArray(EntityUtils.toString(page, HTTP.UTF_8));
} catch (ClientProtocolException e) {
erreur = "Erreur HTTP (protocole) :" + e.getMessage();
} catch (IOException e) {
erreur = "Erreur HTTP (IO) :" + e.getMessage();
} catch (ParseException e) {
erreur = "Erreur JSON (parse) :" + e.getMessage();
} catch (JSONException e) {
erreur = "Erreur JSON :" + e.getMessage();
}
return jarray;
}
/*
* getReq, retourne le résultat de la requête effectué à partir de l'url
*/
public HttpEntity GetReq(String url) throws ClientProtocolException,
IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpGet http = new HttpGet(url);
HttpResponse response = httpClient.execute(http);
return response.getEntity();
}
}
|
Python
|
UTF-8
| 12,946 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 24 17:44:54 2019
@author: meliude
"""
import pygrib
import pandas as pd
years = ['1998.grib', '1999.grib', '2000.grib', '2001.grib', '2002.grib', '2003.grib', '2004.grib', '2005.grib', '2006.grib', '2007.grib', '2008.grib']
data = []
dp = [] #dewpoint
tp = [] #totalprecipitation
for i in range(0,11):
data.append(pygrib.open(years[i]))
dp.append(data[i].select(name = '2 metre dewpoint temperature'))
tp.append(data[i].select(name = 'Total precipitation'))
#leapyears: 2000, 2004 and 2008
##jan(0,31),feb(31,60),mar(60,91),apr(91,121),may(121,152),jun(152,182),jul(182,213),aug(213,244)
##sep(244,274),oct(274,305),nov(305,335),dec(335,366)
#for dewpoint temperature
jan_dp,feb_dp,mar_dp,apr_dp,may_dp,jun_dp,jul_dp,aug_dp,sep_dp,oct_dp,nov_dp,dec_dp=[], [], [], [], [], [], [], [], [], [], [], []
#convert Kelvin to Celsius
def convert(x):
return x-273.15
for i in range(0,11):
if i==2:
for j in range(0,31):
jan_dp.append(convert(dp[i][j].values))
for j in range(31,60):
feb_dp.append(convert(dp[i][j].values))
for j in range(60,91):
mar_dp.append(convert(dp[i][j].values))
for j in range(91,121):
apr_dp.append(convert(dp[i][j].values))
for j in range(121,152):
may_dp.append(convert(dp[i][j].values))
for j in range(152,182):
jun_dp.append(convert(dp[i][j].values))
for j in range(182,213):
jul_dp.append(convert(dp[i][j].values))
for j in range(213,244):
aug_dp.append(convert(dp[i][j].values))
for j in range(244,274):
sep_dp.append(convert(dp[i][j].values))
for j in range(274,305):
oct_dp.append(convert(dp[i][j].values))
for j in range(305,335):
nov_dp.append(convert(dp[i][j].values))
for j in range(335,366):
dec_dp.append(convert(dp[i][j].values))
elif i==6:
for j in range(0,31):
jan_dp.append(convert(dp[i][j].values))
for j in range(31,60):
feb_dp.append(convert(dp[i][j].values))
for j in range(60,91):
mar_dp.append(convert(dp[i][j].values))
for j in range(91,121):
apr_dp.append(convert(dp[i][j].values))
for j in range(121,152):
may_dp.append(convert(dp[i][j].values))
for j in range(152,182):
jun_dp.append(convert(dp[i][j].values))
for j in range(182,213):
jul_dp.append(convert(dp[i][j].values))
for j in range(213,244):
aug_dp.append(convert(dp[i][j].values))
for j in range(244,274):
sep_dp.append(convert(dp[i][j].values))
for j in range(274,305):
oct_dp.append(convert(dp[i][j].values))
for j in range(305,335):
nov_dp.append(convert(dp[i][j].values))
for j in range(335,366):
dec_dp.append(convert(dp[i][j].values))
elif i==10:
for j in range(0,31):
jan_dp.append(convert(dp[i][j].values))
for j in range(31,60):
feb_dp.append(convert(dp[i][j].values))
for j in range(60,91):
mar_dp.append(convert(dp[i][j].values))
for j in range(91,121):
apr_dp.append(convert(dp[i][j].values))
for j in range(121,152):
may_dp.append(convert(dp[i][j].values))
for j in range(152,182):
jun_dp.append(convert(dp[i][j].values))
for j in range(182,213):
jul_dp.append(convert(dp[i][j].values))
for j in range(213,244):
aug_dp.append(convert(dp[i][j].values))
for j in range(244,274):
sep_dp.append(convert(dp[i][j].values))
for j in range(274,305):
oct_dp.append(convert(dp[i][j].values))
for j in range(305,335):
nov_dp.append(convert(dp[i][j].values))
for j in range(335,366):
dec_dp.append(convert(dp[i][j].values))
else:
for j in range(0,31):
jan_dp.append(convert(dp[i][j].values))
for j in range(31,59):
feb_dp.append(convert(dp[i][j].values))
for j in range(59,90):
mar_dp.append(convert(dp[i][j].values))
for j in range(90,120):
apr_dp.append(convert(dp[i][j].values))
for j in range(120,151):
may_dp.append(convert(dp[i][j].values))
for j in range(151,181):
jun_dp.append(convert(dp[i][j].values))
for j in range(181,212):
jul_dp.append(convert(dp[i][j].values))
for j in range(212,243):
aug_dp.append(convert(dp[i][j].values))
for j in range(243,273):
sep_dp.append(convert(dp[i][j].values))
for j in range(273,304):
oct_dp.append(convert(dp[i][j].values))
for j in range(304,334):
nov_dp.append(convert(dp[i][j].values))
for j in range(334,365):
dec_dp.append(convert(dp[i][j].values))
#jan,mar,may,jul,aug,oct,dec
def totalsum(x,a=1,b=2):
return sum(x[a],x[b])
##0,30,31,61,62,92,93,123,124,154,155,185,186,216,217,247,248,278,279,309,310,340
lb=[0,31,62,93,124,155,186,217,248,279,310]
up=[30,61,92,123,154,185,216,247,278,309,340]
jan_tdp, mar_tdp, may_tdp, jul_tdp, aug_tdp,oct_tdp,dec_tdp=[], [], [], [], [], [], []
for i,j in zip(lb,up):
jan_tdp.append(totalsum(jan_dp,a=i,b=j))
mar_tdp.append(totalsum(mar_dp,a=i,b=j))
may_tdp.append(totalsum(may_dp,a=i,b=j))
jul_tdp.append(totalsum(jul_dp,a=i,b=j))
aug_tdp.append(totalsum(aug_dp,a=i,b=j))
oct_tdp.append(totalsum(oct_dp,a=i,b=j))
dec_tdp.append(totalsum(dec_dp,a=i,b=j))
jan_tdp, mar_tdp, may_tdp, jul_tdp, aug_tdp,oct_tdp,dec_tdp=sum(jan_tdp)/11, sum(mar_tdp)/11, sum(may_tdp)/11, sum(jul_tdp)/11, sum(aug_tdp)/11, sum(oct_tdp)/11, sum(dec_tdp)/11
pd.DataFrame(jan_tdp).to_csv('grid_jan.csv')
pd.DataFrame(mar_tdp).to_csv('grid_mar.csv')
pd.DataFrame(may_tdp).to_csv('grid_may.csv')
pd.DataFrame(jul_tdp).to_csv('grid_jul.csv')
pd.DataFrame(aug_tdp).to_csv('grid_aug.csv')
pd.DataFrame(oct_tdp).to_csv('grid_oct.csv')
pd.DataFrame(dec_tdp).to_csv('grid_dec.csv')
#apr,jun,sep,nov
##0,29,30,59,60,89,90,119,120,149,150,179,180,209,210,239,240,269,270,299,300,329
lb=[0,30,60,90,120,150,180,210,240,270,300]
ub=[29,59,89,119,149,179,209,239,269,299,329]
apr_tdp, jun_tdp, sep_tdp, nov_tdp=[], [], [], []
for i,j in zip(lb,ub):
apr_tdp.append(totalsum(apr_dp,a=i,b=j))
jun_tdp.append(totalsum(jun_dp,a=i,b=j))
sep_tdp.append(totalsum(sep_dp,a=i,b=j))
nov_tdp.append(totalsum(nov_dp,a=i,b=j))
apr_tdp, jun_tdp, sep_tdp, nov_tdp=sum(apr_tdp)/11, sum(jun_tdp)/11, sum(sep_tdp)/11, sum(nov_tdp)/11
pd.DataFrame(apr_tdp).to_csv('grid_apr.csv')
pd.DataFrame(jun_tdp).to_csv('grid_jun.csv')
pd.DataFrame(sep_tdp).to_csv('grid_sep.csv')
pd.DataFrame(nov_tdp).to_csv('grid_nov.csv')
#feb
##0,27,28,55,56,84,85,112,113,140,141,168,169,197,198,225,226,253,254,281,282,310
lb=[0,28,56,85,113,141,169,198,226,254,282]
ub=[27,55,84,112,140,168,197,225,253,281,310]
feb_tdp=[]
for i,j in zip(lb,ub):
feb_tdp.append(totalsum(feb_dp,a=i,b=j))
feb_tdp=sum(feb_tdp)/11
pd.DataFrame(feb_tdp).to_csv('grid_feb.csv')
############################################################################################
#for total prepicipation
jan_tp,feb_tp,mar_tp,apr_tp,may_tp,jun_tp,jul_tp,aug_tp,sep_tp,oct_tp,nov_tp,dec_tp=[], [], [], [], [], [], [], [], [], [], [], []
for i in range(0,11):
if i==2:
for j in range(0,31):
jan_tp.append(tp[i][j].values)
for j in range(31,60):
feb_tp.append(tp[i][j].values)
for j in range(60,91):
mar_tp.append(tp[i][j].values)
for j in range(91,121):
apr_tp.append(tp[i][j].values)
for j in range(121,152):
may_tp.append(tp[i][j].values)
for j in range(152,182):
jun_tp.append(tp[i][j].values)
for j in range(182,213):
jul_tp.append(tp[i][j].values)
for j in range(213,244):
aug_tp.append(tp[i][j].values)
for j in range(244,274):
sep_tp.append(tp[i][j].values)
for j in range(274,305):
oct_tp.append(tp[i][j].values)
for j in range(305,335):
nov_tp.append(tp[i][j].values)
for j in range(335,366):
dec_tp.append(tp[i][j].values)
elif i==6:
for j in range(0,31):
jan_tp.append(tp[i][j].values)
for j in range(31,60):
feb_tp.append(tp[i][j].values)
for j in range(60,91):
mar_tp.append(tp[i][j].values)
for j in range(91,121):
apr_tp.append(tp[i][j].values)
for j in range(121,152):
may_tp.append(tp[i][j].values)
for j in range(152,182):
jun_tp.append(tp[i][j].values)
for j in range(182,213):
jul_tp.append(tp[i][j].values)
for j in range(213,244):
aug_tp.append(tp[i][j].values)
for j in range(244,274):
sep_tp.append(tp[i][j].values)
for j in range(274,305):
oct_tp.append(tp[i][j].values)
for j in range(305,335):
nov_tp.append(tp[i][j].values)
for j in range(335,366):
dec_tp.append(tp[i][j].values)
elif i==10:
for j in range(0,31):
jan_tp.append(tp[i][j].values)
for j in range(31,60):
feb_tp.append(tp[i][j].values)
for j in range(60,91):
mar_tp.append(tp[i][j].values)
for j in range(91,121):
apr_tp.append(tp[i][j].values)
for j in range(121,152):
may_tp.append(tp[i][j].values)
for j in range(152,182):
jun_tp.append(tp[i][j].values)
for j in range(182,213):
jul_tp.append(tp[i][j].values)
for j in range(213,244):
aug_tp.append(tp[i][j].values)
for j in range(244,274):
sep_tp.append(tp[i][j].values)
for j in range(274,305):
oct_tp.append(tp[i][j].values)
for j in range(305,335):
nov_tp.append(tp[i][j].values)
for j in range(335,366):
dec_tp.append(tp[i][j].values)
else:
for j in range(0,31):
jan_tp.append(tp[i][j].values)
for j in range(31,59):
feb_tp.append(tp[i][j].values)
for j in range(59,90):
mar_tp.append(tp[i][j].values)
for j in range(90,120):
apr_tp.append(tp[i][j].values)
for j in range(120,151):
may_tp.append(tp[i][j].values)
for j in range(151,181):
jun_tp.append(tp[i][j].values)
for j in range(181,212):
jul_tp.append(tp[i][j].values)
for j in range(212,243):
aug_tp.append(tp[i][j].values)
for j in range(243,273):
sep_tp.append(tp[i][j].values)
for j in range(273,304):
oct_tp.append(tp[i][j].values)
for j in range(304,334):
nov_tp.append(tp[i][j].values)
for j in range(334,365):
dec_tp.append(tp[i][j].values)
#jan,mar,may,jul,aug,oct,dec
jan_ttp, mar_ttp, may_ttp, jul_ttp, aug_ttp,oct_ttp,dec_ttp=[], [], [], [], [], [], []
for i,j in zip(lb,up):
jan_ttp.append(totalsum(jan_tp,a=i,b=j))
mar_ttp.append(totalsum(mar_tp,a=i,b=j))
may_ttp.append(totalsum(may_tp,a=i,b=j))
jul_ttp.append(totalsum(jul_tp,a=i,b=j))
aug_ttp.append(totalsum(aug_tp,a=i,b=j))
oct_ttp.append(totalsum(oct_tp,a=i,b=j))
dec_ttp.append(totalsum(dec_tp,a=i,b=j))
jan_ttp, mar_ttp, may_ttp, jul_ttp, aug_ttp,oct_ttp,dec_ttp=sum(jan_ttp)/11, sum(mar_ttp)/11, sum(may_ttp)/11, sum(jul_ttp)/11, sum(aug_ttp)/11, sum(oct_ttp)/11, sum(dec_ttp)/11
pd.DataFrame(jan_ttp).to_csv('grid_jan_p.csv')
pd.DataFrame(mar_ttp).to_csv('grid_mar_p.csv')
pd.DataFrame(may_ttp).to_csv('grid_may_p.csv')
pd.DataFrame(jul_ttp).to_csv('grid_jul_p.csv')
pd.DataFrame(aug_ttp).to_csv('grid_aug_p.csv')
pd.DataFrame(oct_ttp).to_csv('grid_oct_p.csv')
pd.DataFrame(dec_ttp).to_csv('grid_dec_p.csv')
#apr,jun,sep,nov
apr_ttp, jun_ttp, sep_ttp, nov_ttp=[], [], [], []
for i,j in zip(lb,ub):
apr_ttp.append(totalsum(apr_tp,a=i,b=j))
jun_ttp.append(totalsum(jun_tp,a=i,b=j))
sep_ttp.append(totalsum(sep_tp,a=i,b=j))
nov_ttp.append(totalsum(nov_tp,a=i,b=j))
apr_ttp, jun_ttp, sep_ttp, nov_ttp=sum(apr_ttp)/11, sum(jun_ttp)/11, sum(sep_ttp)/11, sum(nov_ttp)/11
pd.DataFrame(apr_ttp).to_csv('grid_apr_p.csv')
pd.DataFrame(jun_ttp).to_csv('grid_jun_p.csv')
pd.DataFrame(sep_ttp).to_csv('grid_sep_p.csv')
pd.DataFrame(nov_ttp).to_csv('grid_nov_p.csv')
#feb
feb_ttp=[]
for i,j in zip(lb,ub):
feb_ttp.append(totalsum(feb_tp,a=i,b=j))
feb_ttp=sum(feb_ttp)/11
pd.DataFrame(feb_ttp).to_csv('grid_feb_p.csv')
|
Python
|
UTF-8
| 9,647 | 3.15625 | 3 |
[] |
no_license
|
from pygame import draw, Vector2
from random import randint, random
from abc import abstractmethod, ABC
class BaseCreature(ABC):
def __init__(self, world, color, coord=None, radius=None):
self.world = world
self.color = color
self.energy = 3000
self._maxenergy = 3000
self.alive = True
self.qtd_breed = 0
self.qtd_alive = 0
if coord:
self.coord = coord
# Avoid rendering outside the screen
width, height = self.world.width, self.world.height
if self.coord.x > width: self.coord.x = width
elif self.coord.x < 0: self.coord.x = 0
if self.coord.y > height: self.coord.y = height
elif self.coord.y < 0: self.coord.y = 0
else: self.coord = Vector2((randint(0, world.width), randint(0, world.height)))
if radius: self.radius = radius
else: self.radius = (random()*10)%8 + 2
def die(self):
self.world.creatures_to_remove.append(self)
self.alive = False
@abstractmethod
def breed(self):
self.qtd_breed += 1
@abstractmethod
def check_necessities(self):
pass
@abstractmethod
def process(self, time_elapsed):
if self.alive:
self.qtd_alive += time_elapsed
def render(self, screen):
draw.circle(screen, self.color, (round(self.coord.x), round(self.coord.y)), round(self.radius))
@property
def get_type(self):
return '{}'.format(type(self).__name__)
@property
def get_consumed_energy(self):
return self._maxenergy/2 * self.radius
class Plant(BaseCreature):
def __init__(self, world, color=(0, randint(0, 155)+100, 0), coord=None, radius=None):
super().__init__(world, color, coord=coord, radius=radius)
def breed(self):
super().breed()
if (random()*100000+1) <= self.radius:
self.world.creatures_to_add.append(Plant(self.world, self.color, self.coord + Vector2((randint(-50,50), randint(-50,50))), self.radius))
self.energy -= 1 + self.radius * (1.1 - self.color[1]/255)
def check_necessities(self):
if self.energy <= 0:
self.die()
def process(self, time_elapsed):
super().process(time_elapsed)
if self.alive:
self.check_necessities()
self.breed()
self.energy -= time_elapsed * self.radius * (1.05 - self.color[1]/255)
class Animal(BaseCreature, ABC):
def __init__(self, world, color, gender=bool(randint(0,1)), coord=None, radius=None, vision=None, velocity=None):
super().__init__(world, color, coord=coord, radius=radius)
self.danger = False
self.hungry = False
self.horny = False
self.gender = gender
self.destiny = Vector2((randint(0, self.world.width), randint(0, self.world.height)))
if vision: self.vision = vision
else: self.vision = (random()*100)%200 + 20
if velocity: self.velocity = velocity
else: self.velocity = (random()*10) + 15
def check_necessities(self):
if self.energy <= 0:
self.die()
else:
if randint(1, 1000) == 1:
if self.energy > 10 + self.energy-self.radius:
self.horny = True
else:
self.horny = False
if self.energy < self._maxenergy/2:
self.hungry = True
else:
self.hungry = False
def process(self, time_elapsed):
super().process(time_elapsed)
if self.alive:
self.check_necessities()
d = 0
if self.danger:
d = self.run(time_elapsed)
elif self.hungry:
d = self.hunt(time_elapsed)
elif self.horny:
d = self.search_mate(time_elapsed)
else:
d = self.move(time_elapsed)
self.energy -= d * (1 + self.radius) + time_elapsed * self.radius
def move(self, time_elapsed, factor=1):
if self.coord.distance_to(self.destiny) > 5:
heading = self.destiny - self.coord
heading = heading.normalize()
dist = self.velocity * factor * time_elapsed
dist = heading * dist
d = self.coord.distance_to(self.coord + dist)
self.coord += dist
if self.coord[0] > self.world.width or self.coord[1] > self.world.height or self.coord[0] < 0 or self.coord[1] < 0:
self.coord -= dist
self.destiny = Vector2((randint(0,self.world.width), randint(0,self.world.height)))
return self.move(time_elapsed, factor)
return d
else:
self.destiny = Vector2((randint(0, self.world.width), randint(0, self.world.height)))
return self.move(time_elapsed, factor)
def run(self, time_elapsed):
return self.move(time_elapsed, factor=2)
@abstractmethod
def search_mate(self):
pass
@abstractmethod
def hunt(self):
pass
class Herbivore(Animal):
def __init__(self, world, color=(0, 0, randint(0, 155)+100), gender=bool(randint(0,1)), coord=None, radius=None, vision = None, velocity = None,):
super().__init__(world, color, gender, coord=coord, radius=radius, vision=vision, velocity=velocity)
def check_necessities(self):
super().check_necessities()
if self.alive:
predators = [p for p in self.world.creatures['Carnivore'] if self.coord.distance_to(p.coord) <= self.vision]
if len(predators) > 0:
self.danger = True
predators.sort(key=lambda x: self.coord.distance_to(x.coord))
self.destiny = -predators[0].coord
else:
self.danger = False
def breed(self, creature):
if self.gender:
self.world.creatures_to_add.append(Herbivore(self.world,
color = ((self.color[0]+creature.color[0])/2, (self.color[1]+creature.color[1])/2, (self.color[2]+creature.color[2])/2),
coord = self.coord + Vector2((randint(-10, 10), randint(-10, 10))),
velocity = (self.velocity+creature.velocity)/2,
vision = (self.vision+creature.vision)/2,
radius =(self.radius+creature.radius)/2))
self.energy -= self.radius
self.horny = False
def search_mate(self, time_elapsed):
mates = [m for m in self.world.creatures['Herbivore'] if m.gender != self.gender and self.coord.distance_to(m.coord) <= self.vision and m.horny]
if len(mates) > 0:
mates.sort(key= lambda x: self.coord.distance_to(x.coord))
self.destiny = mates[0].coord
if self.coord.distance_to(self.destiny) <= 10:
self.breed(mates[0])
return self.run(time_elapsed)
else:
return self.move(time_elapsed)
def hunt(self, time_elapsed):
preys = [p for p in self.world.creatures['Plant'] if self.coord.distance_to(p.coord) <= self.vision]
if len(preys) > 0:
preys.sort(key= lambda plant: self.coord.distance_to(plant.coord) - plant.color[1] * (1+plant.radius) )
self.destiny = preys[0].coord
if self.coord.distance_to(self.destiny) <= 10:
preys[0].die()
self.energy += preys[0].get_consumed_energy
return self.run(time_elapsed)
else:
return self.move(time_elapsed)
class Carnivore(Animal):
def __init__(self, world, color=(randint(0, 155)+100, 0, 0), gender=bool(randint(0,1)), coord=None, radius=None, vision = None, velocity = None,):
super().__init__(world, color, gender, coord=coord, radius=radius, vision=vision, velocity=velocity)
def breed(self, creature):
if self.gender:
self.world.creatures_to_add.append(Carnivore(self.world,
color = ((self.color[0]+creature.color[0])/2, (self.color[1]+creature.color[1])/2, (self.color[2]+creature.color[2])/2),
coord = self.coord + Vector2((randint(-10, 10), randint(-10, 10))),
velocity = (self.velocity+creature.velocity)/2,
vision = (self.vision+creature.vision)/2,
radius =(self.radius+creature.radius)/2))
self.energy -= self.radius
self.horny = False
def search_mate(self, time_elapsed):
mates = [m for m in self.world.creatures['Carnivore'] if m.gender != self.gender and self.coord.distance_to(m.coord) <= self.vision and m.horny]
if len(mates) > 0:
mates.sort(key= lambda x: self.coord.distance_to(x.coord))
self.destiny = mates[0].coord
if self.coord.distance_to(self.destiny) <= 10:
self.breed(mates[0])
return self.run(time_elapsed)
else:
return self.move(time_elapsed)
def hunt(self, time_elapsed):
preys = [p for p in self.world.creatures['Herbivore'] if self.coord.distance_to(p.coord) <= self.vision and self.radius >= p.radius]
if len(preys) > 0:
preys.sort(key= lambda herb: self.coord.distance_to(herb.coord))
self.destiny = preys[0].coord
if self.coord.distance_to(self.destiny) <= 10:
preys[0].die()
self.energy += preys[0].get_consumed_energy
return self.run(time_elapsed)
else:
return self.move(time_elapsed)
|
PHP
|
UTF-8
| 2,200 | 2.59375 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
<?php
namespace anstiss\guias\cto_guiaOdontologia;
use anstiss\complexTypes\ct_procedimentoDados;
use anstiss\complexTypes\denteRegiao;
class procedimentosExecutados {
/**
*
* @var ct_procedimentoDados $procSolic
* @access public
*/
public $procSolic = null;
/**
*
* @var denteRegiao $denteRegiao
* @access public
*/
public $denteRegiao = null;
/**
*
* @var string $denteFace
* @see st_texto5
* @access public
*/
public $denteFace = null;
/**
*
* @var int $qtdProc
* @see st_numerico2
* @access public
*/
public $qtdProc = null;
/**
*
* @var float $qtdUS
* @see st_decimal8-2
* @access public
*/
public $qtdUS = null;
/**
*
* @var float $valorProc
* @see st_decimal8-2
* @access public
*/
public $valorProc = null;
/**
*
* @var float $valorFranquia
* @see st_decimal8-2
* @access public
*/
public $valorFranquia = null;
/**
*
* @var string $autorizado
* @see st_logico
* @access public
*/
public $autorizado = null;
/**
*
* @var string $dataRealizacao
* @see st_data
* @access public
*/
public $dataRealizacao = null;
/**
*
* @param ct_procedimentoDados $procSolic
* @param denteRegiao $denteRegiao
* @param string $denteFace
* @param int $qtdProc
* @param float $qtdUS
* @param float $valorProc
* @param float $valorFranquia
* @param string $autorizado
* @param string $dataRealizacao
* @access public
*/
public function __construct($procSolic, $denteRegiao, $denteFace, $qtdProc, $qtdUS, $valorProc, $valorFranquia, $autorizado, $dataRealizacao) {
$this->procSolic = $procSolic;
$this->denteRegiao = $denteRegiao;
$this->denteFace = $denteFace;
$this->qtdProc = $qtdProc;
$this->qtdUS = $qtdUS;
$this->valorProc = $valorProc;
$this->valorFranquia = $valorFranquia;
$this->autorizado = $autorizado;
$this->dataRealizacao = $dataRealizacao;
}
}
|
PHP
|
UTF-8
| 1,704 | 3.125 | 3 |
[] |
no_license
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PHP Lesson 17</title>
</head>
<body>
<?php
/* echo date_default_timezone_get();
echo "<br>";
date_default_timezone_set('Europe/Rome');
echo date_default_timezone_get();
echo "<br>"; */
/* date_default_timezone_set('Europe/Moscow');
echo date('Y-M-d a H:i:s', time()); */
// echo '2010 - '. date(Y);
// phpinfo();
/* $date = getdate();
print_r($date);
echo '<br>' . $date; */
// echo date('Y-M-d H:i:s', strtotime("+1 day 1 hour"));
/* echo time();
echo '<br>';
echo mktime( date("H"), date("i"), date("s"), date("m"), date("d"), date("Y"));
echo '<br>';
echo date('Y-M-d H:i:s', mktime(1, 2, 3, 2, 3, 4));
echo '<br>';
$t = mktime( date("H"), date("i"), date("s"), date("m"), date("d"), date("Y")+1);
echo date('Y-M-d H:i:s', $t);
$date = date_create(date('Y-m-d H:i:s'));
// print_r($date);
echo date_format($date, 'Y-m-d H:i:s');
date_add($date, date_interval_create_from_date_string('2 days + 2 hours + 10 minutes'));
echo '<br>';
echo date_format($date, 'Y-m-d H:i:s'); */
// echo microtime();
// var_dump(microtime());
$start = microtime(true);
// usleep(1000000);
for ($i = 1; $i <= 100000000; $i++){
if ($i == 100000000) {
echo 'Countdown complite<br>';
}
}
$end = microtime(true);
echo $end - $start;
?>
</body>
</html>
|
Java
|
UTF-8
| 1,570 | 2.765625 | 3 |
[] |
no_license
|
package com.hibernateTutorial.oneToOneRelationBidirectional;
import java.io.File;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class MainApp {
private static final String HIBERNATE_CONFIG_PATH = "/home/mehmetozanguven/eclipse-workspace/HibernateTutorial/src/main/resources/hibernate-cfg.xml";
public static void main( String[] args ){
Configuration hibernateConf = new Configuration()
.configure(new File(HIBERNATE_CONFIG_PATH))
.addAnnotatedClass(SimpleInstructor.class)
.addAnnotatedClass(SimpleInstructorDetail.class);
SessionFactory factory = hibernateConf.buildSessionFactory();
Session session = factory.getCurrentSession();
try {
findInstructorFromInstructorDetail(session, (long)2);
}finally {
session.close();
}
}
private static void findInstructorFromInstructorDetail(Session session, Long instructorDetailId) {
session.beginTransaction();
//get the instructor_detail by id
SimpleInstructorDetail tempInstructorDetail = session.get(SimpleInstructorDetail.class, instructorDetailId);
if (tempInstructorDetail == null)
System.out.println("There is no data with these instructor_detail_id: " + instructorDetailId);
else {
System.out.println("Here is the instuctor detail object: " + tempInstructorDetail);
System.out.println("Here is the instructor from instructor detail: " + tempInstructorDetail.getSimpleInstructor());
}
}
}
|
JavaScript
|
UTF-8
| 2,511 | 2.765625 | 3 |
[] |
no_license
|
const fetch = require('node-fetch');
const model = require('../utilities/parser')
const globalVariable = require('../constants/global')
module.exports = {
fetchTitlesFromUrl: async (req, res) => {
if (Object.keys(req.query).length > 0) {
let { address } = req.query
let myObj = { title: [], address: [] }
if (!Array.isArray(address)) {
if (String(address).includes(globalVariable.dotCom)) {
const condition = [globalVariable.http, globalVariable.https]
const test = condition.some(el => address.includes(el))
address = test == true ? address : globalVariable.http + address
try {
let response = await fetch(address)
let result = await response.text()
let title = model.parseTitle(result)
myObj.title.push(title)
} catch (error) {
myObj.title.push(globalVariable.noResponseError)
}
} else {
myObj.title.push(globalVariable.noResponseError)
}
myObj.address.push(address)
} else {
for (let index = 0; index < address.length; index++) {
let url = address[index]
if (String(url).includes(globalVariable.dotCom)) {
let condition = [globalVariable.http, globalVariable.https]
let test = condition.some(el => url.includes(el))
url = test == true ? url : globalVariable.http + url
try {
let response = await fetch(url)
let result = await response.text()
let title = model.parseTitle(result)
myObj.title.push(title)
} catch (error) {
myObj.title.push(globalVariable.noResponseError)
}
}
else {
myObj.title.push(globalVariable.noResponseError)
}
myObj.address.push(url)
}
}
return res.status(200).render(globalVariable.title, { url: myObj })
} else {
return res.status(404).send(globalVariable.noAddressError)
}
}
}
|
Java
|
UTF-8
| 548 | 1.882813 | 2 |
[] |
no_license
|
package com.proccorp.eventory.app;
import com.proccorp.eventory.app.configuration.ConfigurationModule;
import com.proccorp.eventory.controllers.RestController;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class Application {
Injector injector;
public Application() {
this.injector = Guice.createInjector(new ConfigurationModule());
}
public void start() {
RestController restController = injector.getInstance(RestController.class);
restController.setupEndpoints();
}
}
|
PHP
|
UTF-8
| 5,892 | 2.71875 | 3 |
[] |
no_license
|
<?php
namespace Kriss\Nacos\DTO\Request;
use Kriss\Nacos\Model\InstanceModel;
use Kriss\Nacos\Support\Json;
class InstanceParams
{
/**
* 服务实例IP
* @var string
*/
private $ip;
/**
* 服务实例port
* @var int
*/
private $port;
/**
* 服务名
* @var string
*/
private $serviceName;
/**
* 命名空间ID
* @var string|null
*/
private $namespaceId;
/**
* 权重
* @var double|null
*/
private $weight;
/**
* 是否上线
* @var boolean|null
*/
private $enabled;
/**
* 是否健康
* @var boolean|null
*/
private $healthy;
/**
* 扩展信息
* @var array|null
*/
private $metadata;
/**
* 集群名
* @var string|null
*/
private $clusterName;
/**
* 分组名
* @var string|null
*/
private $groupName;
/**
* 是否临时实例
* @var boolean|null
*/
private $ephemeral;
public function __construct(string $ip, int $port, string $serviceName)
{
$this->ip = $ip;
$this->port = $port;
$this->serviceName = $serviceName;
}
/**
* @param InstanceModel $instance
* @return static
*/
public static function loadFromInstanceModel(InstanceModel $instance): self
{
return (new static($instance->ip, $instance->port, $instance->serviceName))
->setServiceName($instance->serviceName)
->setNamespaceId($instance->namespaceId)
->setWeight($instance->weight)
->setEnabled($instance->enabled)
->setHealthy($instance->healthy)
->setMetadata($instance->metadata)
->setClusterName($instance->clusterName)
->setGroupName($instance->groupName)
->setEphemeral($instance->ephemeral);
}
/**
* @return string
*/
public function getIp(): string
{
return $this->ip;
}
/**
* @param string $ip
* @return InstanceParams
*/
public function setIp(string $ip): InstanceParams
{
$this->ip = $ip;
return $this;
}
/**
* @return int
*/
public function getPort(): int
{
return $this->port;
}
/**
* @param int $port
* @return InstanceParams
*/
public function setPort(int $port): InstanceParams
{
$this->port = $port;
return $this;
}
/**
* @return string
*/
public function getServiceName(): string
{
return $this->serviceName;
}
/**
* @param string $serviceName
* @return InstanceParams
*/
public function setServiceName(string $serviceName): InstanceParams
{
$this->serviceName = $serviceName;
return $this;
}
/**
* @return string|null
*/
public function getNamespaceId(): ?string
{
return $this->namespaceId;
}
/**
* @param string|null $namespaceId
* @return InstanceParams
*/
public function setNamespaceId(?string $namespaceId): InstanceParams
{
$this->namespaceId = $namespaceId;
return $this;
}
/**
* @return float|null
*/
public function getWeight(): ?float
{
return $this->weight;
}
/**
* @param float|null $weight
* @return InstanceParams
*/
public function setWeight(?float $weight): InstanceParams
{
$this->weight = $weight;
return $this;
}
/**
* @return bool|null
*/
public function getEnabled(): ?bool
{
return $this->enabled;
}
/**
* @param bool|null $enabled
* @return InstanceParams
*/
public function setEnabled(?bool $enabled): InstanceParams
{
$this->enabled = $enabled;
return $this;
}
/**
* @return bool|null
*/
public function getHealthy(): ?bool
{
return $this->healthy;
}
/**
* @param bool|null $healthy
* @return InstanceParams
*/
public function setHealthy(?bool $healthy): InstanceParams
{
$this->healthy = $healthy;
return $this;
}
/**
* @return array|null
*/
public function getMetadata(): ?array
{
return $this->metadata;
}
/**
* @return string|null
*/
public function getMetadataJson(): ?string
{
if ($this->metadata) {
return Json::encode($this->metadata);
}
return null;
}
/**
* @param array|null $metadata
* @return InstanceParams
*/
public function setMetadata(?array $metadata): InstanceParams
{
$this->metadata = $metadata;
return $this;
}
/**
* @return string|null
*/
public function getClusterName(): ?string
{
return $this->clusterName;
}
/**
* @param string|null $clusterName
* @return InstanceParams
*/
public function setClusterName(?string $clusterName): InstanceParams
{
$this->clusterName = $clusterName;
return $this;
}
/**
* @return string|null
*/
public function getGroupName(): ?string
{
return $this->groupName;
}
/**
* @param string|null $groupName
* @return InstanceParams
*/
public function setGroupName(?string $groupName): InstanceParams
{
$this->groupName = $groupName;
return $this;
}
/**
* @return bool|null
*/
public function getEphemeral(): ?bool
{
return $this->ephemeral;
}
/**
* @param bool|null $ephemeral
* @return InstanceParams
*/
public function setEphemeral(?bool $ephemeral): InstanceParams
{
$this->ephemeral = $ephemeral;
return $this;
}
}
|
Python
|
UTF-8
| 390 | 2.953125 | 3 |
[] |
no_license
|
import dateparser as dp
import sys
DUE = 'due'
ANY = 'any'
ONLY = 'only'
LIST = 'list'
arguments = sys.argv[1:]
print(arguments)
# testing dateparser
if DUE in arguments:
due_index = arguments.index(DUE)
due_date = ' '.join(arguments[due_index + 1:])
arguments = arguments[:due_index]
print(due_date)
print(dp.parse(due_date))
print(f'arguments after removal {arguments}')
|
JavaScript
|
UTF-8
| 767 | 3.046875 | 3 |
[] |
no_license
|
const apiWeather = "https://api.openweathermap.org/data/2.5/weather?id=5604473&units=imperial&APPID=376518d3f8cbf59c812b2a2aebacf5d7";
fetch(apiWeather)
.then((response) => response.json())
.then((jsObject) => {
console.log(jsObject);
const wDescription = document.getElementById('description');
const currentTemp = document.getElementById('curTemp');
const humidityVal = document.getElementById('humidity');
const windSpeedVal = document.getElementById('windSpeed');
wDescription.innerHTML = jsObject.weather[0].description;
currentTemp.innerHTML = jsObject.main.temp;
humidityVal.innerHTML = jsObject.main.humidity;
windSpeedVal.innerHTML = jsObject.wind.speed;
});
|
C#
|
UTF-8
| 445 | 2.9375 | 3 |
[] |
no_license
|
using System;
namespace Isogram
{
public class Sentence
{
public static bool IsogramSentence(string word){
word = word.ToLower();
char[] arr = word.ToCharArray();
Array.Sort(arr);
for (int i = 0; i < word.Length -1 ; i++) {
if (arr[i] == arr[i + 1] && arr[i] != '-')
return false;
}
return true;
}
}
}
|
Java
|
UTF-8
| 1,254 | 1.78125 | 2 |
[] |
no_license
|
/* (C) Copyright 2009 Hewlett-Packard Development Company, LP
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
For more information: www.smartfrog.org
*/
package org.smartfrog.services.hadoop.benchmark.test.unit;
import junit.framework.TestCase;
import org.smartfrog.services.hadoop.benchmark.citerank.Utils;
/**
*
*/
public class UtilsTest extends TestCase {
public void testEmptyURL() {
assertEquals("", Utils.createCitationURL("","something"));
}
public void testSimple() {
assertEquals("/something.html", Utils.createCitationURL("/","something"));
}
}
|
Java
|
UTF-8
| 492 | 2.1875 | 2 |
[] |
no_license
|
package com.xiao.blog.constants;
/**
* Shiro 相关常量
* @author wangmx
* @date 2020-12-01
*/
public class ShiroConstants {
/**
* 分隔符
*/
public static final String NAMES_DELIMETER = ",";
/**
* 加密方式
*/
public final static String HASH_ALGORITHM_NAME = "MD5";
/**
* 循环次数
*/
public final static int HASH_ITERATIONS = 1024;
/**
* 加盐长度
*/
public final static int SALT_LENGTH = 18;
}
|
JavaScript
|
UTF-8
| 1,813 | 2.703125 | 3 |
[] |
no_license
|
let totalPage = 0;
$(function () {
Load();
});
function Load() {
currentPage(1);
}
//查询当前页码的核心ajax逻辑
function currentPage(num) {
$.ajax({
url: "user",
type: "get",
data: {m: "page", currentPage: num},
dataType: "json",
//text类型 ajax直接接收字符串类型
success: function (info) {
totalPage = info.pages;
let trs = "";
for (let user of info.list) {
trs += "<tr><td>" + user.id + "</td>" +
"<td>" + user.username + "</td>" +
"<td><img src='" + user.imagePath + "' width='50px'></td>" +
"<td>" + user.phone + "</td>" +
"<td>" + user.email + "</td>" +
"<td>" + user.userLevel + "</td></tr>";
}
$('#content').html(trs);
let lis="<li><a href='javascript:;' onclick='prePage("+info.pageNum+")'>上一页</a></li>";
for (let i = 1; i <=info.pages; i++) {
if (i==info.pageNum){
lis+="<li class='active'><a href='javascript:;'>"+i+"</a></li>"
}else {
lis+="<li><a href='javascript:;' onclick='currentPage("+i+")'>"+i+"</a></li>"
}
}
lis+="<li><a href='javascript:;' onclick='nextPage("+info.pageNum+")'>下一页</a></li>";
$('#pageNav').html(lis);
$('#showUser').fadeIn(2000);
}
});
}
//ajax查询上一页
function prePage(num) {
if (num == 1) {
currentPage(totalPage)
}else {
currentPage(num-1)
}
}
//ajax查询下一页
function nextPage(num) {
if (num == totalPage) {
currentPage(1)
}else {
currentPage(num+1)
}
}
|
Python
|
UTF-8
| 1,087 | 3.09375 | 3 |
[] |
no_license
|
__author__ = 'Mike'
print("Gopnik Help Bot v.2.0 - GitHub version")
print("""
What do you need help with?
b. Show features and bug fixes
1. WiFi password
2. Why did you put this on GitHub?
3. What do i do when I see a Vadim?
4. Is DOOM as good as CS 1.6?
5. Is DOOM good on it's own?
6. Where's the name interpreter?
""")
question = input()
if question == ("1"):
print("It's 'kolev12345678'")
else:
if question == ("2"):
print("I just felt like it")
if question == ('3'):
print("""Just run vadimalert.py
(it's in the same folder as this bot)
and it'll do the work for you.""")
if question == ('4'):
print("Kind of")
if question == ('5'):
print("Yeah")
if question == ("6"):
print("Sorry man. not making one")
if question == ("b"):
print("""new features and bug fixes for v.2.0
1. Added 4 new questions/answers
2. Added bug fix/feature option
3. fixed spelling mistakes""")
input("Press ENTER key to exit")
|
C++
|
UTF-8
| 3,839 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
/***************************************************
Adafruit MQTT Library Arduino Yun Example
Make sure your Arduino Yun is connected to a WiFi access point which
has internet access. Also note this sketch uses the Console class
for debug output so make sure to connect to the Yun over WiFi and
open the serial monitor to see the console output.
Works great with the Arduino Yun:
----> https://www.adafruit.com/products/1498
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Tony DiCola for Adafruit Industries.
MIT license, all text above must be included in any redistribution
****************************************************/
#include <Bridge.h>
#include <Console.h>
#include <BridgeClient.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
/************************* Adafruit.io Setup *********************************/
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883
#define AIO_USERNAME "...your AIO username (see https://accounts.adafruit.com)..."
#define AIO_KEY "...your AIO key..."
/************ Global State (you don't need to change this!) ******************/
// Create a BridgeClient instance to communicate using the Yun's bridge & Linux OS.
BridgeClient client;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
/****************************** Feeds ***************************************/
// Setup a feed called 'photocell' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/photocell");
// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/onoff");
/*************************** Sketch Code ************************************/
void setup() {
Bridge.begin();
Console.begin();
Console.println(F("Adafruit MQTT demo"));
// Setup MQTT subscription for onoff feed.
mqtt.subscribe(&onoffbutton);
}
uint32_t x=0;
void loop() {
// Ensure the connection to the MQTT server is alive (this will make the first
// connection and automatically reconnect when disconnected). See the MQTT_connect
// function definition further below.
MQTT_connect();
// this is our 'wait for incoming subscription packets' busy subloop
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(1000))) {
if (subscription == &onoffbutton) {
Console.print(F("Got: "));
Console.println((char *)onoffbutton.lastread);
}
}
// Now we can publish stuff!
Console.print(F("\nSending photocell val "));
Console.print(x);
Console.print("...");
if (! photocell.publish(x++)) {
Console.println(F("Failed"));
} else {
Console.println(F("OK!"));
}
// ping the server to keep the mqtt connection alive
if(! mqtt.ping()) {
Console.println(F("MQTT Ping failed."));
}
delay(1000);
}
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Console.print("Connecting to MQTT... ");
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Console.println(mqtt.connectErrorString(ret));
Console.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
}
Console.println("MQTT Connected!");
}
|
Ruby
|
UTF-8
| 410 | 3.390625 | 3 |
[] |
no_license
|
require 'pry'
def power_sumDigTerm(nth)
sequence = []
start_number = 81
until sequence.size == nth
digits_sum = start_number.to_s.chars.map {|x| x.to_i}.reduce(:+)
list = (0..nth).to_a.map {|x| digits_sum ** x}
if list.include?(start_number)
sequence << start_number
start_number += 1
else
start_number += 1
end
end
sequence[nth-1]
end
p power_sumDigTerm(4)
|
Java
|
UTF-8
| 18,001 | 1.890625 | 2 |
[
"MIT"
] |
permissive
|
package stream.com.streamapp.home;
import android.content.ContentValues;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.jzxiang.pickerview.TimePickerDialog;
import com.yalantis.phoenix.PullToRefreshView;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import org.litepal.crud.DataSupport;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import stream.com.streamapp.R;
import stream.com.streamapp.db.Bills;
import stream.com.streamapp.login;
import static java.lang.String.valueOf;
/**
* Created by KathyF on 2017/11/26.
*/
public class BillFragment extends Fragment {
private static RecyclerView recyclerView;
private LinearLayoutManager mLayoutManager;
private final static int REQUEST_CODE = 1;
private List<Integer> iconList;
private List<Integer> categoryList;
private List<String> dataList;
private List<Bills> bills;
private myAdapter mAdapter;
private TextView incomeSum, expenseSum;
private LinearLayout pickTime;
double income,expense;
private PullToRefreshView mPullToRefreshView;
private TextView yearTV, monthTV;
String mYear = "0";
String mMonth = "0";
TimePickerDialog timePickerDialog;
View view;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragemnt_bill, null);
if (mYear.equals("0"))
{
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String text = sf.format(new Date());
mYear = text.substring(0,4);
mMonth = text.substring(5,7);
}
initData();
initView();
incomeSum.setText(String.valueOf(income)+" 元");
expenseSum.setText(String.valueOf(expense)+" 元");
//setListener();
return view;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// 当otherActivity中返回数据的时候,会响应此方法
// requestCode和resultCode必须与请求startActivityForResult()和返回setResult()的时候传入的值一致。
if (requestCode == REQUEST_CODE && resultCode == BillDetail.RESULT_CODE) {
Bundle bundle=data.getExtras();
boolean changed = bundle.getBoolean("result");
Log.e("changed",Boolean.toString(changed));
if(changed)
new MyTask().execute();
}
}
private void initView(){
incomeSum = (TextView)view.findViewById(R.id.incomeSum);
expenseSum = (TextView)view.findViewById(R.id.expenseSum);
yearTV = view.findViewById(R.id.yearTV);
monthTV = view.findViewById(R.id.monthTV);
yearTV.setText(mYear+"年");
monthTV.setText(mMonth+"月");
recyclerView=view.findViewById(R.id.bill_recycler);
mLayoutManager = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new MyItemDivider());
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter = new myAdapter());
timePickerDialog = new TimePickerDialog.Builder()
.setType(Type.YEAR_MONTH)
.setThemeColor(R.color.colorPrimary)
.setCallBack(new OnDateSetListener(){
@Override
public void onDateSet(TimePickerDialog timePickerDialog, long millseconds) {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String text = sf.format(new Date(millseconds));
mYear = text.substring(0,4);
mMonth = text.substring(5,7);
//Log.d("year", mYear);
yearTV.setText(mYear+"年");
monthTV.setText(mMonth+"月");
initData();
new MyTask().execute();
}
})
.build();
pickTime = view.findViewById(R.id.pickTime);
pickTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
timePickerDialog.show(getChildFragmentManager(),"选择日期");
}
});
mAdapter.setOnItemClickListener(new MyItemClickListener() {
@Override
public void onItemClick(View view, int postion) {
Intent intent = new Intent(getContext(), BillDetail.class);
int BillId = bills.get(postion).getId();
intent.putExtra("BillId",BillId);
startActivityForResult(intent, REQUEST_CODE);
}
});
mAdapter.setOnItemLongClickListener(new MyItemLongClickListener(){
@Override
public void onLongItemClick(View v, int position){
final int pos = position;
PopupMenu popupMenu = new PopupMenu(getContext(),v);
popupMenu.getMenuInflater().inflate(R.menu.deletemenu,popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int BillId = bills.get(pos).getId();
ContentValues values = new ContentValues();
values.put("state", 3);
DataSupport.update(Bills.class, values, BillId);
try {
UpdateData.UploadBill();
} catch (InterruptedException e) {
e.printStackTrace();
}
new MyTask().execute();
Toast.makeText(getActivity(),"已删除",Toast.LENGTH_SHORT).show();
return true;
}
});
popupMenu.show();
}
});
//TODO:add divider
// recyclerView.addItemDecoration(new);
// swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
// swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.colorPrimaryDark), getResources().getColor(R.color.colorAccent));
// swipeRefreshLayout.setProgressViewOffset(false,0, 50);
mPullToRefreshView=(PullToRefreshView)view.findViewById(R.id.pull_to_refresh);
mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
@Override
public void onRefresh() {
mPullToRefreshView.postDelayed(new Runnable() {
@Override
public void run() {
new MyTask().execute();
mPullToRefreshView.setRefreshing(false);
}
}, 2000);
}
});
}
private void initData(){
String nextYear = mMonth.equals("12")? String.valueOf(Integer.valueOf(mYear)+1):mYear;
//Log.d("nextyear", nextYear);
String nextMonth = "";
switch (mMonth){
case "01": nextMonth="02";break;
case "02": nextMonth="03";break;
case "03": nextMonth="04";break;
case "04": nextMonth="05";break;
case "05": nextMonth="06";break;
case "06": nextMonth="07";break;
case "07": nextMonth="08";break;
case "08": nextMonth="09";break;
case "09": nextMonth="10";break;
case "10": nextMonth="11";break;
case "11": nextMonth="12";break;
case "12": nextMonth="01";break;
default:break;
}
//Log.d("nextmonth", nextMonth);
income = DataSupport.where("user_id = ? and date >= ? and date < ? and inOrOut = ? and state <> 3 ", String.valueOf(login.getUser_id()), mYear+"-"+mMonth+"-01", nextYear+"-"+nextMonth+"-01" ,"in" ).sum(Bills.class, "amount", double.class);
expense= DataSupport.where("user_id = ? and date >= ? and date < ? and inOrOut = ? and state <> 3 ", String.valueOf(login.getUser_id()), mYear+"-"+mMonth+"-01", nextYear+"-"+nextMonth+"-01" ,"out" ).sum(Bills.class, "amount", double.class);
dataList =new ArrayList<String>();
iconList = new ArrayList<Integer>();
categoryList = new ArrayList<Integer>();
//Log.d("date", mYear+"-"+mMonth+"-01");
bills = DataSupport.where("user_id = ? and date >= ? and date < ? and state <> 3 ", String.valueOf(login.getUser_id()), mYear+"-"+mMonth+"-01", nextYear+"-"+nextMonth+"-01").order("date desc").limit(5).find(Bills.class);
for (int i = 0; i < /*((bills.size()>5)?5:*/bills.size(); i++) {
dataList.add( (bills.get(i).getInOrOut().equals("in") ? "+":"-") + String.valueOf(bills.get(i).getAmount()));
switch(bills.get(i).getType())
{
case "meal":
categoryList.add(R.string.meal);
iconList.add(R.drawable.meal);
break;
case "transportation":
categoryList.add(R.string.transportation);
iconList.add(R.drawable.transportation);
break;
case "shopping":
categoryList.add(R.string.shopping);
iconList.add(R.drawable.shopping);
break;
case "daily":
categoryList.add(R.string.daily);
iconList.add(R.drawable.daily);
break;
case "clothes":
categoryList.add(R.string.clothes);
iconList.add(R.drawable.clothes);
break;
case "vegetables":
categoryList.add(R.string.vegetable);
iconList.add(R.drawable.vegetable);
break;
case "fruit":
categoryList.add(R.string.fruit);
iconList.add(R.drawable.fruit);
break;
case "snack":
categoryList.add(R.string.snack);
iconList.add(R.drawable.snack);
break;
case "book":
categoryList.add(R.string.book);
iconList.add(R.drawable.book);
break;
case "study":
categoryList.add(R.string.study);
iconList.add(R.drawable.study);
break;
case "house":
categoryList.add(R.string.house);
iconList.add(R.drawable.house);
break;
case "investment":
categoryList.add(R.string.investment);
iconList.add(R.drawable.investment);
break;
case "social":
categoryList.add(R.string.social);
iconList.add(R.drawable.social);
break;
case "amusement":
categoryList.add(R.string.amusement);
iconList.add(R.drawable.amusement);
break;
case "makeup":
categoryList.add(R.string.makeup);
iconList.add(R.drawable.makeup);
break;
case "call":
categoryList.add(R.string.call);
iconList.add(R.drawable.call);
break;
case "sport":
categoryList.add(R.string.sport);
iconList.add(R.drawable.sport);
break;
case "travel":
categoryList.add(R.string.travel);
iconList.add(R.drawable.travel);
break;
case "medicine":
categoryList.add(R.string.medicine);
iconList.add(R.drawable.medicine);
break;
case "office":
categoryList.add(R.string.office);
iconList.add(R.drawable.office);
break;
case "digit":
categoryList.add(R.string.digit);
iconList.add(R.drawable.digit);
break;
case "gift":
categoryList.add(R.string.gift);
iconList.add(R.drawable.gift);
break;
case "repair":
categoryList.add(R.string.repair);
iconList.add(R.drawable.repair);
break;
case "wine":
categoryList.add(R.string.wine);
iconList.add(R.drawable.wine);
break;
case "redpacket":
categoryList.add(R.string.redpacket);
iconList.add(R.drawable.redpacket);
break;
case "other":
categoryList.add(R.string.other);
iconList.add(R.drawable.other);
break;
case "parttime":
categoryList.add(R.string.parttime);
iconList.add(R.drawable.parttime);
break;
case "salary":
categoryList.add(R.string.salary);
iconList.add(R.drawable.salary);
break;
}
}
}
class myAdapter extends RecyclerView.Adapter<myAdapter.myViewHolder> {
private MyItemClickListener mItemClickListener;
private MyItemLongClickListener myItemLongClickListener;
public void setOnItemClickListener(MyItemClickListener listener){
this.mItemClickListener=listener;
}
public void setOnItemLongClickListener(MyItemLongClickListener listener){
this.myItemLongClickListener = listener;
}
@Override
public myAdapter.myViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
myAdapter.myViewHolder holder = new myAdapter.myViewHolder(LayoutInflater.from(
getActivity()).inflate(R.layout.bill_item_layout, parent,
false),mItemClickListener,myItemLongClickListener);
return holder;
}
@Override
public void onBindViewHolder(myAdapter.myViewHolder holder, int position)
{
holder.data.setText(dataList.get(position));
holder.category.setText(categoryList.get(position));
holder.icon.setImageResource(iconList.get(position));
}
@Override
public int getItemCount()
{
return dataList.size();
}
class myViewHolder extends RecyclerView.ViewHolder {
TextView category;
TextView data;
ImageView icon;
private MyItemClickListener mListener;
private MyItemLongClickListener myItemLongClickListener;
public myViewHolder(View view,MyItemClickListener listener,MyItemLongClickListener longClickListener){
super (view);
category = (TextView)view.findViewById(R.id.category);
data = (TextView)view.findViewById(R.id.data);
icon = (ImageView)view.findViewById(R.id.icon);
this.mListener = listener;
this.myItemLongClickListener=longClickListener;
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mListener != null){
mListener.onItemClick(v,getAdapterPosition());
}
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if(myItemLongClickListener!=null){
myItemLongClickListener.onLongItemClick(v,getAdapterPosition());
}
return false;
}
});
}
}
}
public class MyTask extends AsyncTask{
@Override
protected Object doInBackground(Object[] objects){
initData();
try {
UpdateData.UploadBill();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Object o){
expenseSum.setText(String.valueOf(expense)+" 元");
incomeSum.setText(String.valueOf(income)+" 元");
super.onPostExecute(o);
mAdapter.notifyDataSetChanged();
}
}
}
|
C++
|
UTF-8
| 7,839 | 2.75 | 3 |
[] |
no_license
|
/*
* Copyright (C) 2017 Edupals project
*
* Author:
* Enrique Medina Gremaldos <quiqueiii@gmail.com>
*
* Source:
* https://github.com/edupals/edupals-base-toolkit
*
* This file is a part of edupals-base-toolkit.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
*/
#include <cmd.hpp>
#include <iostream>
#include <stdexcept>
using namespace std;
using namespace edupals::cmd;
static int find_long_option(vector<Option> & options,string long_name)
{
for (size_t n=0;n<options.size();n++) {
if (options[n].long_name==long_name) {
return n;
}
}
return -1;
}
static int find_short_option(vector<Option>& options,char short_name)
{
for (size_t n=0;n<options.size();n++) {
if (options[n].short_name==short_name) {
return n;
}
}
return -1;
}
Option::Option(char short_name,string long_name,ArgumentType argument_type)
{
this->short_name=short_name;
this->long_name=long_name;
this->argument_type=argument_type;
}
Option::Option(char short_name,ArgumentType argument_type): Option(short_name,"",argument_type)
{
}
Option::Option(string long_name,ArgumentType argument_type) : Option('\0',long_name,argument_type)
{
}
bool ParseResult::success()
{
return (unknowns.size()==0 and missings.size()==0);
}
void ArgumentParser::add_option(Option option)
{
options.push_back(option);
}
ParseResult ArgumentParser::parse(int argc,char* argv[])
{
ParseResult result;
bool eatr=false;
bool eato=false;
string left,right;
string tmp;
for (int n=0;n<argc;n++) {
tmp = argv[n];
// single letter
if (tmp.size()==1) {
result.args.push_back(tmp);
}
else {
// short option(s)
if (tmp[0]=='-') {
//optional argument is not comming
eato=false;
//Error: missing long option required argument
if (eatr) {
result.missings.push_back(left);
eatr=false;
}
//long option
if (tmp[1]=='-') {
//stop parsing options
if (tmp.size()==2) {
//TODO
}
else {
//check for equal character
size_t equal=tmp.find('=');
if (equal!=string::npos) {
left=tmp.substr(2,equal-2);
right=tmp.substr(equal+1);
}
else {
left=tmp.substr(2);
}
int oindex=find_long_option(options,left);
//Error: unknown long option
if (oindex==-1) {
result.unknowns.push_back(left);
}
else {
Option option=options[oindex];
//required argument
if (option.argument_type==ArgumentType::Required) {
//there is equal
if (right.size()>0) {
option.value=right;
result.options.push_back(option);
}
else {
//eat next
eatr=true;
result.options.push_back(option);
}
}
//no argument
if (option.argument_type==ArgumentType::None) {
result.options.push_back(option);
}
//optional argument
if (option.argument_type==ArgumentType::Optional) {
//there is equal
if (right.size()>0) {
option.value=right;
result.options.push_back(option);
}
else {
//eat next
eato=true;
result.options.push_back(option);
}
}
}
}
}
else {
// short option processing
for (size_t sn=1;sn<tmp.size();sn++) {
int oindex = find_short_option(options,tmp[sn]);
if (oindex>=0) {
Option option=options[oindex];
if (option.argument_type==ArgumentType::None) {
result.options.push_back(option);
}
if (option.argument_type==ArgumentType::Required) {
string arg = tmp.substr(sn+1);
//Error: missing short option required argument
if (arg.size()==0) {
result.missings.push_back(string(1,tmp[sn]));
}
option.value=arg;
result.options.push_back(option);
break;
}
if (option.argument_type==ArgumentType::Optional) {
option.value = tmp.substr(sn+1);
result.options.push_back(option);
break;
}
}
else {
//Error: unknown short option
result.unknowns.push_back(string(1,tmp[sn]));
}
}
}
}
else {
//eat argument
if (eatr or eato) {
result.options.back().value=tmp;
eato=false;
eatr=false;
}
else {
result.args.push_back(tmp);
}
}
}
}
//Error: missing required long option argument
if (eatr) {
result.missings.push_back(left);
}
return result;
}
|
Markdown
|
UTF-8
| 218 | 3.1875 | 3 |
[] |
no_license
|
# LogMessage
Python 3.6 class for logging to a text file.
To initialize LogMessage:
message = LogMessage('log.txt')
To read the log:
message.read()
To write to the log:
message.write('whatever you want to log.')
|
Markdown
|
UTF-8
| 4,369 | 2.890625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
---
license: >
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
title: notification.prompt
---
# notification.prompt
Affiche une boîte de dialogue d'invite personnalisable.
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **message**: message de la boîte de dialogue. *(String)*
* **promptCallback**: rappel à appeler lorsque vous appuyez sur un bouton. *(Fonction)*
* **titre**: titre *(String)* (facultatif, la valeur par défaut de dialogue`Prompt`)
* **buttonLabels**: tableau de chaînes spécifiant les bouton *(Array)* (facultatif, par défaut, les étiquettes`["OK","Cancel"]`)
* **defaultText**: zone de texte par défaut entrée valeur ( `String` ) (en option, par défaut : chaîne vide)
## Description
La `notification.prompt` méthode affiche une boîte de dialogue natif qui est plus personnalisable que le navigateur `prompt` fonction.
## promptCallback
Le `promptCallback` s'exécute lorsque l'utilisateur appuie sur un bouton dans la boîte de dialogue d'invite. Le `results` objet passé au rappel contient les propriétés suivantes :
* **buttonIndex**: l'index du bouton activé. *(Nombre)* Notez que l'index utilise base d'indexation, la valeur est `1` , `2` , `3` , etc..
* **entrée 1**: le texte entré dans la boîte de dialogue d'invite. *(String)*
## Plates-formes prises en charge
* Android
* iOS
## Petit exemple
// process the promp dialog results
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
// Show a custom prompt dialog
//
function showPrompt() {
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
}
## Exemple complet
<!DOCTYPE html>
<html>
<head>
<title>Notification Prompt Dialog Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
// Empty
}
// process the promptation dialog result
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
// Show a custom prompt dialog
//
function showPrompt() {
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
}
</script>
</head>
<body>
<p><a href="#" onclick="showPrompt(); return false;">Show Prompt</a></p>
</body>
</html>
## Bizarreries Android
* Android prend en charge un maximum de trois boutons et ignore plus que cela.
* Sur Android 3.0 et versions ultérieures, les boutons sont affichés dans l'ordre inverse pour les appareils qui utilisent le thème Holo.
|
JavaScript
|
UTF-8
| 2,192 | 2.828125 | 3 |
[] |
no_license
|
import React, { Component } from 'react';
import Entry from '../Entry/Entry.js';
import LetterHeader from '../LetterHeader/LetterHeader.js';
import './EntryList.css';
class EntryList extends Component {
compareEntryNames(entry1,entry2) {
var lastNameComparison = entry1.entryData.lname.localeCompare(entry2.entryData.lname);
if (lastNameComparison===0) {
return entry1.entryData.fname.localeCompare(entry2.entryData.fname);
} else {
return lastNameComparison;
}
}
sortEntriesAlphabetically(entryDataArray) {
return entryDataArray.sort((entry1,entry2)=> this.compareEntryNames(entry1,entry2))
}
getFirstLetterOfLastName(entry) {
return entry.entryData.lname.charAt(0).toUpperCase();
}
renderEntriesAndLetterHeaders() {
var sortedEntryDataArray = this.sortEntriesAlphabetically(this.props.entryDataArray);
var mostRecentLetter = "";
return sortedEntryDataArray.map((entry) => {
if (this.getFirstLetterOfLastName(entry)!==mostRecentLetter) {
mostRecentLetter=this.getFirstLetterOfLastName(entry);
return (
<div key={entry.idx}>
<LetterHeader letter={this.getFirstLetterOfLastName(entry)} />
<Entry
idx={entry.idx}
expanded={false}
handleClosedEntryClick={this.props.handleClosedEntryClick}
entryData={entry.entryData} />
</div>
);
} else {
return (
<Entry
idx={entry.idx}
key={entry.idx}
expanded={false}
handleClosedEntryClick={this.props.handleClosedEntryClick}
entryData={entry.entryData} />
);
}
});
}
renderOnlySelectedEntry() {
var dataOfExpandedEntry = this.props.getEntryById(this.props.expandedEntryId).entryData;
return (
<Entry
expanded={true}
entryData={dataOfExpandedEntry}
handleBack={this.props.handleBack}
handleEdit={this.props.handleEdit}
handleDelete={this.props.handleDelete} />
);
}
render() {
if (this.props.expandedEntryId!=="") {
return (
<div className="entrylist">
{this.renderOnlySelectedEntry()}
</div>
);
} else {
return (
<div className="entrylist">
{this.renderEntriesAndLetterHeaders()}
</div>
);
}
}
}
export default EntryList;
|
Java
|
UTF-8
| 1,710 | 2.140625 | 2 |
[] |
no_license
|
package bk.chat.web;
import bk.chat.model.ChatMessage;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.security.Principal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Controller
public class ChatController {
@Autowired
private HttpSession session;
private static final Logger logger = LoggerFactory.getLogger(ChatController.class);
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@MessageMapping("/chats/{chatRoomId}")
public void handleChat(@Payload ChatMessage message, @DestinationVariable("chatRoomId") String chatRoomId, MessageHeaders messageHeaders, Principal user) {
logger.info(messageHeaders.toString());
this.simpMessagingTemplate.convertAndSend("/topic/chats." + chatRoomId, "[" + getTimestamp() + "]:" + user.getName() + ":" + message.getMessage());
}
private String getTimestamp() {
LocalDateTime date = LocalDateTime.now();
return date.format(DateTimeFormatter.ISO_DATE_TIME);
}
@ResponseBody
@RequestMapping("/sessionId")
public String sessionId() {
return this.session.getId();
}
}
|
C++
|
UHC
| 239 | 3.265625 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int main() {
int x;
cout << "ԷϽÿ>>";
cin >> x;
if (x > 10)
cout << x << " 10 ũ\n";
else
cout << x << " 10 ۰ų .\n";
return 0;
}
|
C++
|
UTF-8
| 514 | 2.953125 | 3 |
[] |
no_license
|
#ifndef Topic_hxx
#define Topic_hxx
#include "Subject.hxx"
class Topic : public Subject{
protected: std::string _theme;
public:
Topic()
: _theme ("")
{
}
Topic(const std::string &theme)
: _theme(theme)
{
}
const std::string theme() {
return _theme;
}
void theme( const std::string &theme) {
_theme = theme;
}
void subscribeClient(Client *subscriptor){
addObserver(subscriptor);
}
void subscribeChannel(Channel *subscriptor){
addObserver(subscriptor);
}
};
#endif
|
Java
|
UTF-8
| 940 | 2.96875 | 3 |
[] |
no_license
|
package enums;
public class Padding {
public float left, top, right, bottom;
public float getHorizontal() {
return left + right;
}
public float getVartical() {
return top + bottom;
}
public boolean isAllValueSame() {
if(left == top && right == bottom && left == right)
return true;
else
return false;
}
@Override
public String toString() {
if(left == top && right == bottom && left == right) {
return Float.toString(left);
}
else if(left == right && bottom == top) {
return Float.toString(top).concat(",").concat(Float.toString(left));
}
else if(left == right) {
return Float.toString(top).concat(",").concat(Float.toString(left)).concat(",").concat(Float.toString(bottom));
}
else {
return Float.toString(top).concat(",").concat(Float.toString(right)).concat(",").concat(Float.toString(bottom)).concat(",").concat(Float.toString(left));
}
}
}
|
JavaScript
|
UTF-8
| 4,508 | 3.078125 | 3 |
[] |
no_license
|
var STATE;
(function (STATE) {
STATE[STATE["INDENT"] = 0] = "INDENT";
STATE[STATE["FUNC_NAME"] = 1] = "FUNC_NAME";
STATE[STATE["FUNC_NAME_END"] = 2] = "FUNC_NAME_END";
STATE[STATE["ARG_START"] = 3] = "ARG_START";
STATE[STATE["ARG_MIDDLE"] = 4] = "ARG_MIDDLE";
STATE[STATE["ARG_END"] = 5] = "ARG_END";
STATE[STATE["COMMENT_START"] = 6] = "COMMENT_START";
STATE[STATE["COMMENT"] = 7] = "COMMENT";
STATE[STATE["DONE"] = 8] = "DONE";
STATE[STATE["FAIL"] = 9] = "FAIL";
})(STATE || (STATE = {}));
function ParseFunc(line) {
var indent = '';
var funcName = '';
var args = [];
var comment = '';
var argIndex = -1;
var curr;
var state = STATE.INDENT;
for (var i = 0; i < line.length; i++) {
curr = line.charAt(i);
switch (state) {
case STATE.INDENT:
if (curr.match(/\s/)) { // whitespace
indent += curr;
}
else if (curr.match(/[a-zA-Z_]/)) { // first character of identifier (alphabet, underscore)
funcName = curr;
state = STATE.FUNC_NAME;
}
else {
state = STATE.FAIL;
}
break;
case STATE.FUNC_NAME:
if (curr.match(/[\w_]/)) { // alphanumeric, underscore
funcName += curr;
}
else if (curr.match(/\s/)) { // whitespace
state = STATE.FUNC_NAME_END;
}
else if (curr === '(') {
state = STATE.ARG_START;
}
else {
state = STATE.FAIL;
}
break;
case STATE.FUNC_NAME_END:
if (curr === '(') {
state = STATE.ARG_START;
}
else if (curr.match(/\S/)) { // non-whitespace
state = STATE.FAIL;
}
break; // ignore whitespace
case STATE.ARG_START:
if (curr.match(/[\w\&\*]/)) { // alphanumeric, ampersand, asterisk
args[++argIndex] = curr;
state = STATE.ARG_MIDDLE;
}
else if (curr === ')') {
state = STATE.COMMENT_START;
}
else if (curr.match(/\S/)) { // non-whitespace\
state = STATE.FAIL;
}
break; // ignore whitespace
case STATE.ARG_MIDDLE:
if (curr.match(/[\w_]/)) { // alphanumeric, underscore
args[argIndex] += curr;
}
else if (curr === ',') {
state = STATE.ARG_START;
}
else if (curr.match(/\s/)) { // whitespace
args[argIndex] += curr;
state = STATE.ARG_END;
}
else if (curr === ')') {
state = STATE.COMMENT_START;
}
else {
state = STATE.FAIL;
}
break;
case STATE.ARG_END:
if (curr === ',') {
state = STATE.ARG_START;
}
else if (curr === ')') {
state = STATE.COMMENT_START;
}
else if (curr.match(/\s/)) { // whitespace
args[argIndex] += curr;
}
else {
state = STATE.FAIL;
}
break;
case STATE.COMMENT_START:
comment = line.substr(i, line.length);
state = STATE.DONE;
break;
default:
state = STATE.FAIL;
break;
}
if (state === STATE.DONE || state === STATE.FAIL) {
break;
}
}
if (state === STATE.DONE || state === STATE.ARG_START || state === STATE.ARG_MIDDLE || state === STATE.ARG_END || state === STATE.COMMENT_START || state === STATE.COMMENT)
return new FuncCall(indent, funcName, args, comment);
else {
return new FuncCall('', '', [], '');
}
/*
if (state === STATE.DONE && argIndex !== -1) {
return new FuncCall(indent, funcName, args, comment);
}
else {
return new FuncCall('', '', [], '');
}
*/
}
|
TypeScript
|
UTF-8
| 1,870 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
import { Component } from '@angular/core';
import { User } from '../_models';
import { ficheService, AlertService, UserService } from '../_services/index';
// Composant qui permet de rajouter des frais forfait au mois en cours
@Component({
moduleId: module.id,
templateUrl: 'fraisForfait.component.html'
})
export class fraisForfaitComponent {
currentUser: User;
ficheDeFrais: any;
//Type de frais possible, rajouter ici si on veux des nouveaux frais forfait
types: any = [];
montantTotal: number = 0;
model: any = {};
constructor(
private ficheService: ficheService,
private alertService: AlertService,
private userService: UserService
) {
this.currentUser = this.userService.user;
this.types = [
{
libelle: "restaurant",
montant_unitaire: 40
}, {
libelle: "hotel",
montant_unitaire: 60
}, {
libelle: 'mixte',
montant_unitaire: 100
}, {
libelle: 'kilométrique',
montant_unitaire: 0.5
}
]
}
//Lors de la modification de la quantité ou du montant unitaire, le montant total ce met à jour
changeTotal() {
if (this.model.quantite) {
this.montantTotal = this.model.quantite * this.model.type.montant_unitaire;
}
}
//ajoute le frais a la fiche du mois en cours
ajoutFrais() {
//définie l'état du frais à nouveau
this.model.etat = "Creer";
// on envoie l'id de l'utilisateur actuel ainsi qu'un objet contenant toute les donner du frais
this.ficheService.ajoutFrais(this.currentUser._id, this.model)
.subscribe( data => {
//si aucune erreur n'est arriver on affiche une notification de succès
this.alertService.success('frais rajouter à ce mois', true);
}, error => {
// on affiche l'erreur.
this.alertService.error(error);
})
}
}
|
Python
|
UTF-8
| 2,090 | 3.328125 | 3 |
[] |
no_license
|
#when player presses 'c' to construct this menu will appear
import pyglet
from pyglet.gl import *
from pyglet.window import key
from Inventory import Inventory
from Property import Property
# import bankruptcy screen, auction screen, mortgage screen, board screen
class GameWindow(pyglet.window.Window):
"""Represents the game window"""
def __init__(self, *args, **kwargs):
"""Initialises the game window"""
super().__init__(*args, **kwargs)
self.background = pyglet.graphics.Batch()
self.set_location(100, 100)
self.frame_rate = 1/60.0
self.option = ""
def on_draw(self):
"""Draws the game window. Receives labels in a list and draws each one"""
self.render()
def render(self):
"""Renders the screen"""
self.clear()
image_sprite.draw()
for l in labels:
l.draw()
def update(self, dt):
"""Updates the window"""
pass
def exit_callback(self, t):
self.close()
def on_key_press(self, symbol, modifiers):
"""Get users input from keyboard"""
if symbol == key._1:
self.option = "house"
elif symbol == key._2:
self.option = "hotel"
elif symbol == key.ENTER or symbol == key.RETURN:
if self.option == "hotel":
# check that player owns all properties of a colour grouping and has 4 houses
# on each property
elif self.option == "house":
#check player owns all properties of a colour group
if __name__ == "__main__":
window = GameWindow(1000, 800, "Monopoly", resizable=False)
image = pyglet.image.load("resources/house_hotel.png")
image_sprite = pyglet.sprite.Sprite(image, x=200,y=300)
label = pyglet.text.Label("Buy a house or hotel", font_name="Times New Roman",
font_size = 48, x=window.width//2, y=window.height -100,
anchor_x='center', anchor_y='center', color=(255,255,255,255))
label2 = pyglet.text.Label("Press '1' to buy a house or '2' to buy a hotel", font_name="Times New Roman",
font_size = 32, x=window.width//2, y=window.height-600,
anchor_x='center', anchor_y='center', color=(255,255,255,255))
labels = [label, label2]
pyglet.gl.glClearColor(0.5, 0, 0, 1)
pyglet.app.run()
|
Java
|
UTF-8
| 1,065 | 2.5 | 2 |
[] |
no_license
|
package ohtu;
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.junit.*;
import static org.testfx.api.FxAssert.verifyThat;
import org.testfx.framework.junit.ApplicationTest;
import static org.testfx.matcher.base.NodeMatchers.hasText;
public class ExampleTest extends ApplicationTest {
private Stage stage;
@Override
public void start(Stage stage) throws Exception {
Main sovellus = new Main();
Application app = Application.class.cast(sovellus);
app.start(stage);
this.stage = stage;
}
@Test
public void tekstiKopioituu() {
TextField teksti = find("#vasen_teksti");
teksti.setText("koe");
clickOn("#nappi");
verifyThat("#oikea_teksti", hasText("koe"));
}
public <T extends Node> T find(final String query) {
/** TestFX provides many operations to retrieve elements from the loaded GUI. */
return lookup(query).query();
}
}
|
C++
|
UTF-8
| 4,970 | 2.90625 | 3 |
[] |
no_license
|
#include <iostream>
#include <ros/package.h>
/* OpenCV 2 */
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cv.hpp>
#include <math.h>
using namespace cv;
class voxelGrid {
public:
// Constructor setting all private parameters and projecting the voxels into the camera image
voxelGrid();
// Main function taking a 480X640 depth image and returning the filled in voxels in second input
void fillVoxels(Mat, Mat);
// input the voxels according to:
// int sz[3] = {gridsize,gridsize,gridsize};
// Mat FilledVoxels(3,sz, CV_32FC1, Scalar::all(0));
void setParameters(int,float,Mat,Mat,Mat);
std::vector<float> units; // [meters]
private:
/* Parameters */
int gridsize;
float spacing_in_m;
float d_margin;
float d_truncate;
Mat intrinsicMat; // (3, 3, CV_32F)
Mat R; // (3, 3, CV_32F)
Mat tVec; // (3, 1, CV_32F)
Mat Voxels; // Voxels as 3 channel mat, [xpix, ypix, z-value]
/* Functions */
float TSDF(float);
void calcVoxel_Depth_Pixels();
};
/* ========================================== *\
* Constructor function
\* ========================================== */
voxelGrid::voxelGrid() {
intrinsicMat = Mat(3, 3, CV_32F); // intrinsic matrix
R = Mat(3, 3, CV_32F);
tVec = Mat(3, 1, CV_32F); // Translation vector in camera frame
}
/* ========================================== *\
* Parameters
\* ========================================== */
void voxelGrid::setParameters(int a_gridsize, float a_spacing_in_m, Mat a_intrinsicMat, Mat a_R, Mat a_tVec) {
// Set private parameters
gridsize = a_gridsize;
spacing_in_m = a_spacing_in_m;
intrinsicMat = a_intrinsicMat;
R = a_R;
tVec = a_tVec;
// TSDF parameters
d_margin = spacing_in_m*4.0;
d_truncate = spacing_in_m*5.0;
// Calculate a vector for the voxel positions in space in [meters]
units = std::vector<float> (gridsize);
for (int n = 0; n<gridsize; n++)
{
units[n] = spacing_in_m*((n+1)-(gridsize+1)/2.0);
}
int sz[3] = {gridsize,gridsize,gridsize};
Voxels = Mat(3,sz, CV_32FC3, Scalar::all(0));
// Project voxels into image plane and create Mat Voxels
calcVoxel_Depth_Pixels();
}
/* ========================================== *\
* Configure voxel grid
\* ========================================== */
void voxelGrid::calcVoxel_Depth_Pixels(){
// Some temporary variables
cv::Mat pointin3d(3, 1, CV_32F);
cv::Mat camframe(3, 1, CV_32F);
cv::Mat pix(3, 1, CV_32F);
// Loop over the whole voxel grid
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < gridsize; j++)
for (int k = 0; k < gridsize; k++)
{
// Convert Voxel index to 3d point
pointin3d.at<float>(0) = units[i];
pointin3d.at<float>(1) = units[j];
pointin3d.at<float>(2) = units[k];
camframe = R*pointin3d + tVec;
// Assign z-value in camera frame
Voxels.at<cv::Vec3f>(i,j,k)[2] = camframe.at<float>(2);
// Convert to pixels
pix = intrinsicMat*camframe;
// Assign pixel values
Voxels.at<cv::Vec3f>(i,j,k)[0] = pix.at<float>(0)/pix.at<float>(2);
Voxels.at<cv::Vec3f>(i,j,k)[1] = pix.at<float>(1)/pix.at<float>(2);
// Check if pixels are within image
if (Voxels.at<cv::Vec3f>(i,j,k)[0]>=640 || Voxels.at<cv::Vec3f>(i,j,k)[0]<0)
Voxels.at<cv::Vec3f>(i,j,k)[0] = NAN;
if (Voxels.at<cv::Vec3f>(i,j,k)[1]>=480 || Voxels.at<cv::Vec3f>(i,j,k)[1]<0)
Voxels.at<cv::Vec3f>(i,j,k)[1] = NAN;
}
}
/* ========================================== *\
* Fill voxel grid
\* ========================================== */
void voxelGrid::fillVoxels(Mat image, Mat FilledVoxels)
{
// Temporary variable
float d_meas;
// Loop over the whole voxel grid
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < gridsize; j++)
for (int k = 0; k < gridsize; k++)
{
// If pixel is not in image return NAN
if (isnan(Voxels.at<cv::Vec3f>(i,j,k)[0]) || isnan(Voxels.at<cv::Vec3f>(i,j,k)[1])){
FilledVoxels.at<float>(i,j,k) = NAN;
}
else{
// Get measured depth at pixel value: image(y,x)
d_meas = image.at<float>( (int)Voxels.at<cv::Vec3f>(i,j,k)[1] , (int)Voxels.at<cv::Vec3f>(i,j,k)[0] );
// Evaluate the TSDF with the depth difference and store the result
FilledVoxels.at<float>(i,j,k) = TSDF(Voxels.at<cv::Vec3f>(i,j,k)[2] - d_meas );
}
}
}
/* ========================================== *\
* Distance function
\* ========================================== */
float voxelGrid::TSDF(float d_in)
{
// |-| d_margin
// 1 -----
// \
// \
// \
// \
// -1 ----------
// |0 ->+ |d_truncate
// All distances in m
if (d_in> d_truncate){
return NAN;
}
else if (d_in<-d_margin){
return 1.0;
}
else if (d_in>d_margin){
return -1.0;
}
else {
return -d_in/d_margin;
}
}
|
JavaScript
|
UTF-8
| 498 | 2.734375 | 3 |
[] |
no_license
|
const btnEntrar = document.querySelector("#entrar")
const txtUsuario = document.querySelector("#usuario")
const txtSenha = document.querySelector("#senha")
btnEntrar.addEventListener("click",function(){
let usuario = txtUsuario.value
let senha = txtSenha.value
console.log(usuario,senha);
if(usuario=="" || senha==""){
alert("Completar usúario e senha")
}else if(usuario=="fatec" && senha=="fatec2407"){
window.location = "./conteudo/covid.html"
}
})
|
JavaScript
|
UTF-8
| 745 | 3.390625 | 3 |
[] |
no_license
|
let thesePpl=[], a;
function setup() {
// createCanvas(400, 400);
// person = new Student();
// p1 = new Student();
// p2 = new Student();
for(let i=0; i<200; i++)
{
thesePpl[i]=new Student(i);
}
// person.display();
// p1.display();
// p2.display();
}
function draw() {
background(220);
for(let i=0; i<thesePpl.length - 1; i++)
{
thesePpl[i].display();
}
// let r= int(random( 0,thesePpl.length - 1));
// thesePpl[r].display();
}
class Student {
constructor(a,i) {
this.name = "Alphabet";
this.address = a;
this.number = int(random((-100,100)));
}
display() {
print("name:", this.name);
print("adress:", this.address);
print("Roll No.:", this.number);
}
}
|
Java
|
UTF-8
| 361 | 1.984375 | 2 |
[] |
no_license
|
package com.rafaelmorales.colegio.repository;
import com.rafaelmorales.colegio.entities.Estudiante;
import com.rafaelmorales.colegio.enums.Estado;
import org.springframework.data.jpa.repository.JpaRepository;
public interface EstudianteRepository extends JpaRepository<Estudiante, Long> {
Estudiante findByEdadAndEstado (int edad, Estado estado);
}
|
Java
|
UTF-8
| 5,699 | 3.53125 | 4 |
[] |
no_license
|
package application;
//That's probably necessary for JavaFX
import java.util.ArrayList;
import java.util.Random;
//I recall that arraylists are a kind of resizeable array.
public class Cell{
int destX;
int destY;
Cell[][] globalCell;
private final int GRID_WIDTH = 10;
private final int GRID_HEIGHT = 10;
//A sample grid length. The default.
//What Id is for, idk.
String id; //This is what id was. A string!
int xPosition;
int yPosition;
//Who is using these values? The player? Maybe its intended for all.
//Empty empty;
Monster monster;
Empty empty;
//Monster must be defined here.
ArrayList<Empty> emptyArray = new ArrayList<Empty>();
//emptyArray must be for later use.
public Cell[][] fillGrid(Cell[][] cell)
//public Cell[][] fillGrid(Cell[][] globalCell)
//fillGrid function.
{
for ( int j = 0; j < GRID_HEIGHT; j++)
{
for (int i = 0 ; i < 10 ; i++)
//Iterate through the two.
{
cell[i][j] = new Empty( i , j);
//System.out.println("Empty cell created at i =" + i + "j: " +j);
for(int a =0; a<10; a++)
{
cell[a][0] = new Block();
}
for(int a =1; a<9; a++)
{
cell[a][9] = new Block();
}
for(int a =1; a<10; a++)
{
cell[0][a] = new Block();
}
for(int a =1; a<10; a++)
{
cell[9][a] = new Block();
}
for(int a =2; a<5; a++)
{
cell[2][a] = new Block();
}
for(int a =2; a<5; a++)
{
cell[7][a] = new Block();
}
for(int a =2; a<4; a++)
{
for(int b =4;b<6;b++)
{
cell[b][a]=new Block();
}
}
for(int a =4; a<6; a++)
{
cell[a][5] = new Block();
}
for(int a =2; a<4; a++)
{
cell[a][7] = new Block();
}
for(int a =6; a<8; a++)
{
cell[a][7] = new Block();
}
}
}
cell[Monster.getxPos()][Monster.getyPos()] = new Monster(Monster.getxPos() ,Monster.getyPos());
cell[Hero.getxPos()][Hero.getyPos()] = new Hero(Hero.getxPos() ,Hero.getyPos()); //It was 6,6 orginally
return cell;
}
public Cell[][] initGrid(){
//Instantiate a new 2d array for the world to share.
/*
Cell[][] cellGrid = new Cell[][] {
{empty, empty , empty, empty , empty, empty , empty, empty , empty, empty},
{empty, empty , empty, empty , empty, empty , empty, empty , empty, empty},
{empty, empty , empty, empty , empty, empty , empty, empty , empty, empty},
{empty, empty , empty, empty , empty, empty , empty, empty , empty, empty},
{empty, empty , empty, empty , empty, empty , empty, empty , empty, empty},
{empty, empty , empty, empty , empty, empty , empty, empty , empty, empty},
{empty, empty , empty, empty , empty, empty , empty, empty , empty, empty},
{empty, empty , empty, empty , empty, empty , empty, empty , empty, empty},
{empty, empty , empty, empty , empty, empty , empty, empty , empty, empty},
{empty, empty , empty, empty , empty, empty , empty, empty , empty, empty},
};
*/
Cell[][] cellGrid2 = new Cell[10][10];
//Cell[][] cell = new Cell[10][10];
return cellGrid2;
//return globalCell;
}
public void printGrid(Cell[][] cell)
{
for ( int j = 0; j < GRID_HEIGHT; j++)
{
System.out.print("|");
System.out.print(j);
for (int i = 0 ; i < 10 ; i++)
{
//Iterate and print out the row.
if ( cell[i][j].id.equals("EMPTY"))
{
System.out.print("|"); // "| " represents empty.
System.out.print(" ");
}
else if (cell[i][j].id.equals("MONSTER")) // Just like my code.
{
System.out.print("|");
System.out.print("*");
}
else if (cell[i][j].id.equals("HERO"))
{
System.out.print("|");
System.out.print("H");
}
else if (cell[i][j].id.equals("BLOCK"))
{
System.out.print("|");
System.out.print("0");
}
}
System.out.print("|");
System.out.println(""); //Endcaps.
}
}
//Cell[][] cellRef;
public void heroMoveUp(Cell[][] cell) //Try passing the cell array as an argument! //Try not using an argument!
{
destY = (Hero.getyPos() - 1);
//checkYdir(cellRef);
//Insert checking functionality here rather than making separate functions? Because that doesn't work?
//The reactions to the cell contents go here in each movement function. It is clunky and requires us to copy and paste, but it works.
//The next step is to make the responses to the cell contents, i.e. if it's a block, no movement happens. If it's a monster, the kill player function happens, etc.
if (cell[Hero.getxPos()][destY].id.equals("EMPTY"))
{
System.out.println("Empty cell registered! Movement possible!");
}
Hero.setypos(destY);
//printGrid
}
void heroMoveDown(Cell[][] cell)
{
destY = (Hero.getyPos() + 1);
if (cell[Hero.getxPos()][destY].id.equals("EMPTY"))
{
System.out.println("Empty cell registered! Movement possible!");
}
Hero.setypos(destY);
//printGrid
}
void heroMoveLeft(Cell[][] cell)
{
destX = (Hero.getxPos() - 1);
if (cell[destX][Hero.getyPos()].id.equals("EMPTY"))
{
System.out.println("Empty cell registered! Movement possible!");
}
Hero.setxpos(destX);
}
void heroMoveRight(Cell[][] cell)
{
destX = (Hero.getxPos() + 1);
if (cell[destX][Hero.getyPos()].id.equals("EMPTY"))
{
System.out.println("Empty cell registered! Movement possible!");
}
Hero.setxpos(destX);
}
/*
void checkYdir(Cell[][] cellRef)
{
if (cellRef[Hero.getxPos()][destY].id.equals("EMPTY"))
{
System.out.println("Empty cell registered! Movement possible!");
}
}
*/
void checkXdir()
{
}
}
//test
|
Rust
|
UTF-8
| 2,110 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
use chrono::DateTime;
use har;
use regex::RegexSet;
use std::fs;
use std::path::Path;
pub fn filter_har_and_calculate_time(data: &har::v1_2::Log, whitelist_file: &Path) -> (har::v1_2::Log, i64) {
let whitelist = read_whitelist(whitelist_file);
let filtered_entries = filter_entries(&data, &whitelist);
let elapsedtime = calculate_elapsedtime(&filtered_entries);
(filtered_entries, elapsedtime)
}
fn filter_entries(data: &har::v1_2::Log, whitelist: &Vec<String>) -> har::v1_2::Log {
let regexset = match RegexSet::new(whitelist) {
Ok(x) => { x }
Err(_) => {
eprintln!("error: compiling whitelist regex");
std::process::exit(1)
}
};
let filtered_entries: Vec<_> = data.entries.clone()
.into_iter()
.filter(|x| {
regexset.is_match(&x.request.url)
})
.collect();
let new_data = har::v1_2::Log {
browser: data.browser.clone(),
creator: data.creator.clone(),
pages: data.pages.clone(),
entries: filtered_entries,
comment: data.comment.clone()
};
new_data
}
fn read_whitelist(path: &Path) -> Vec<String> {
let wholefile = match fs::read_to_string(path){
Ok(x) => { x }
Err(_) => {
eprintln!("error: reading whitelist file");
std::process::exit(1)
}
};
wholefile.lines()
.filter(|x| {!x.is_empty()})
.map(|x| {x.to_string()})
.collect()
}
// TODO: remove unwraps
fn calculate_elapsedtime(log: &har::v1_2::Log) -> i64 {
let (mut start_datetimes, mut end_datetimes): (Vec<_>, Vec<_>) = log.entries.iter().map(|x|{
let starttime = DateTime::parse_from_rfc3339(&x.started_date_time).unwrap();
// TODO better time resolution so i dont have to round
(starttime, starttime.checked_add_signed(chrono::Duration::milliseconds(x.time.round() as i64)).unwrap())
}).unzip();
start_datetimes.sort();
end_datetimes.sort();
end_datetimes.last().unwrap().timestamp_millis() - start_datetimes.first().unwrap().timestamp_millis()
}
|
PHP
|
UTF-8
| 1,095 | 3 | 3 |
[] |
no_license
|
<?php
require("inc/db.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
//Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Select all the rows in the markers table
$sql = "SELECT * FROM markers WHERE 1";
$query = $db->query($sql);
$result = $query->fetchAll();
// Iterate through the rows, adding XML nodes for each
for($i = 0; $i <count($result);$i++){
// Add to XML document node
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$result[$i]['name']);
$newnode->setAttribute("address", $result[$i]['address']);
$newnode->setAttribute("lat", $result[$i]['lat']);
$newnode->setAttribute("lng", $result[$i]['lng']);
$newnode->setAttribute("type", $result[$i]['type']);
}
echo $dom->saveXML();
?>
|
C++
|
GB18030
| 2,957 | 3.109375 | 3 |
[] |
no_license
|
#include "utility.h"
#include <limits>
#include <algorithm>
#include "vec3.h"
// ҳƵ½
int divUp(int a, int b) { return (a + b - 1) / b; }
aabb point_cloud_bounds(const std::vector<float3>& pc)
{
float3 lower, upper;
lower.x = std::numeric_limits<float>::max();
upper.x = std::numeric_limits<float>::min();
lower.y = std::numeric_limits<float>::max();
upper.y = std::numeric_limits<float>::min();
lower.z = std::numeric_limits<float>::max();
upper.z = std::numeric_limits<float>::min();
for (float3 pt : pc)
{
lower.x = std::min(lower.x, pt.x);
upper.x = std::max(upper.x, pt.x);
lower.y = std::min(lower.y, pt.y);
upper.y = std::max(upper.y, pt.y);
lower.z = std::min(lower.z, pt.z);
upper.z = std::max(upper.z, pt.z);
}
return aabb(lower, upper);
}
const float3 color0 = make_float3(0, 0, 0);
const float3 color2 = make_float3(0, 0, 1);
const float3 color4 = make_float3(0, 1, 1);
const float3 color6 = make_float3(0, 1, 0);
const float3 color8 = make_float3(1, 1, 0);
const float3 color10 = make_float3(1, 0, 0);
float3 heat_color(float value, float max_value)
{
if (max_value < 1.0)
return color0;
float pct = value / max_value;
float t;
if (pct < 0.20)
{
t = (pct - 0.0) / (0.20 - 0.0);
return lerp(color0, color2, t);
}
if (pct < 0.40)
{
t = (pct - 0.20) / (0.40 - 0.20);
return lerp(color2, color4, t);
}
if (pct < 0.50)
{
t = (pct - 0.40) / (0.50 - 0.40);
return lerp(color4, color6, t);
}
if (pct < 0.70)
{
t = (pct - 0.50) / (0.70 - 0.50);
return lerp(color6, color8, t);
}
if (pct < 1.00)
{
t = (pct - 0.70) / (1.00 - 0.70);
return lerp(color8, color10, t);
}
else
return color10;
}
const float4 colorf0 = make_float4(0, 0, 0, 0.2);
const float4 colorf2 = make_float4(0, 0, 1, 0.4);
const float4 colorf4 = make_float4(0, 1, 1, 0.6);
const float4 colorf6 = make_float4(0, 1, 0, 0.7);
const float4 colorf8 = make_float4(1, 1, 0, 0.8);
const float4 colorf10 = make_float4(1, 0, 0, 0.9);
float4 heat_color4(float value, float max_value)
{
if (max_value < 1.0)
return colorf0;
float pct = value / max_value;
float t;
if (pct < 0.20)
{
t = (pct - 0.0) / (0.20 - 0.0);
return lerp(colorf0, colorf2, t);
}
if (pct < 0.40)
{
t = (pct - 0.20) / (0.40 - 0.20);
return lerp(colorf2, colorf4, t);
}
if (pct < 0.50)
{
t = (pct - 0.40) / (0.50 - 0.40);
return lerp(colorf4, colorf6, t);
}
if (pct < 0.70)
{
t = (pct - 0.50) / (0.70 - 0.50);
return lerp(colorf6, colorf8, t);
}
if (pct < 1.00)
{
t = (pct - 0.70) / (1.00 - 0.70);
return lerp(colorf8, colorf10, t);
}
else
return colorf10;
}
|
Markdown
|
UTF-8
| 369 | 2.59375 | 3 |
[] |
no_license
|
**Update Airport**
----
Update an airport
* **URL**
/rs/airport/:id
* **Method:**
`PUT`
* **URL Params**
**Required:** `id=[integer]`
* **Data Params**
**Required:** `airportcode=[string]`
**Required:** `city=[string]`
**Required:** `country=[string]`
**Required:** `name=[string]`
* **Success Response:**
* **Code:** 200
|
Python
|
UTF-8
| 630 | 3.140625 | 3 |
[] |
no_license
|
class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
def gen(left, right, size, current, result): # size is the number of left or right parentheses
if left == size and right == size:
result.append(current)
return
if left > right and left <= size:
gen(left, right + 1, size, current + ")", result)
if left <= size:
gen(left + 1, right, size, current + "(", result)
result = []
gen(0, 0, n, "", result)
return result
|
Markdown
|
UTF-8
| 2,517 | 3.34375 | 3 |
[] |
no_license
|
# Minisql V2.0
*Скачать: https://t.me/joinchat/rZ1DR8YL7tsxNmJi*
В общем есть 6 функций: add, read, get, edit, sread. request.
Add - добавить значения в БД
Read - прочитать всю таблицу
Get - узнать какое-то значение из таблицы
Edit - изменить значения в таблице
Sread - прочитать всю таблицу и отсортировать её по какому-то столбцу
### Начало работы
В начале нам надо импортировать библиотеку и задать базу с таблицей, или без таблицы, чтобы её потом добавить:
```
from minisql import Database
db = Database(db="sqltest.db", table="test")
```
Вариант отдельно задать базу и таблицу:
```
from minisql import Database
db = Database(db="sqltest.db")
db.tableset("test")
```
### Add
```
db.add(keys=("id", "text"), values=(1, "user"))
```
Работает это так:
(ряд, информация)
### Read
```
z = db.read()
```
Возвращает всю инфу с базы. Можно пройтись циклом. Пример того, что возвращает:
`[(1, 'user'), (456, 'margaryt'), (1245, 'test')]`
### Get
```
z = db.get("text", "id", 1)
```
Работает это так:
(ячейка данные из которой хотим достать, ключ, чему равен ключ)
Возвращает, в моем случае, user.
Мой вариант использования:
```
db.get(value="text", where="id", equal=1)
```
### Edit
```
db.edit("text", "roshen", "id", 1)
```
Работает это так:
(что хотим поменять, на что хотим поменять, ключ, чему равен ключ)
Мой вариант (я считаю так удобнее):
```
db.edit(value="text", new_index="roshen", where="id", equal=1)
```
### Sread
```
z = db.sread("id")
```
Возвращает всю инфу с базы как read, при этом отсортировав её. Есть 2 варианта сортирования: ASC, DESC. По умолчанию ASC. Указать свой тип:
```
z = db.sread("id", sort_type='DESC')
```
### Request
```
db.request("SELECT ...")
```
Сделать свой запрос к базе.
**Различные примеры вы можете найти в папке examples.**
|
C++
|
UTF-8
| 9,648 | 2.9375 | 3 |
[] |
no_license
|
//
// Created by ravip on 8/6/2018.
//
#include <fstream>
#include<stdio.h>
#include <string.h>
#include <iostream>
#include<cmath>
#ifndef PROJECT2_IMAGESTUFF_H
#define PROJECT2_IMAGESTUFF_H
class Pixel{
public:
unsigned char R;
unsigned char G;
unsigned char B;
Pixel & operator =(const Pixel &p){
R=p.R;
G=p.G;
B=p.B;
return *this;
}
Pixel & operator *(const Pixel &p){
float tempR1, tempR2, tempG1, tempG2, tempB1, tempB2;
tempR1=R/255.0f;
tempR2=p.R/255.0f;
tempG1=G/255.0f;
tempG2=p.G/255.0f;
tempB1=B/255.0f;
tempB2=p.B/255.0f;
R= (unsigned char)(tempR1*tempR2*255 +0.5);
G=(unsigned char)(tempG1*tempG2*255+0.5);
B= (unsigned char)(tempB1*tempB2*255+0.5);
return *this;
}
Pixel & operator +(const Pixel &p){
R+=p.R;
G+=p.G;
B+=p.B;
if(R>255){
R=255;
}
if(G>255){
G=255;
}
if(B>255){
B=255;
}
return *this;
}
Pixel & operator -(const Pixel &p){
R-=p.R;
G-=p.G;
B-=p.B;
if(R<0){
R=0;
}
if(G<0){
G=0;
}
if(B<0){
B=0;
}
return *this;
}
Pixel pixRead(std::ifstream &myFile){
myFile.read((char*)&B,1);
myFile.read((char*)&G,1);
myFile.read((char*)&R,1);
return *this;
}
};
struct imageHeader{
char idLength;
char colourMapType;
char dataTypeCode;
short colourMapOrigin;
short colourMapLength;
char colourMapDepth;
short xOrigin;
short yOrigin;
short width;
short height;
char bitsPerPixel;
char imageDescriptor;
Pixel * image;
void readIn( std::ifstream &myFile){
myFile.read(&idLength,1);
myFile.read(&colourMapType,1);
myFile.read(&dataTypeCode,1);
myFile.read((char*)&colourMapOrigin,2);
myFile.read((char*)&colourMapLength,2);
myFile.read(&colourMapDepth,1);
myFile.read((char*)&xOrigin,2);
myFile.read((char*)&yOrigin,2);
myFile.read((char*)&width, 2);
myFile.read((char*)&height,2);
myFile.read(&bitsPerPixel,1);
myFile.read(&imageDescriptor,1);
image = new Pixel[width*height];
for(int i =0; i < width*height;i++){
image[i].pixRead(myFile);
}
}
void Write(std::ofstream &outFile){
outFile.write(&idLength, 1);
outFile.write(&colourMapType, 1);
outFile.write(&dataTypeCode, 1);
outFile.write((char*)&colourMapOrigin, 2);
outFile.write((char*)&colourMapLength, 2);
outFile.write(&colourMapDepth, 1);
outFile.write((char*)&xOrigin, 2);
outFile.write((char*)&yOrigin, 2);
outFile.write((char*)&width, 2);
outFile.write((char*)&height, 2);
outFile.write(&bitsPerPixel, 1);
outFile.write(&imageDescriptor, 1);
for(int i = 0; i < width*height; i++){
outFile.write(( char*)&image[i].B,1);
outFile.write(( char*)&image[i].G,1);
outFile.write((char*)&image[i].R,1);
}
}
void insertHeader(imageHeader Head){
this->idLength=Head.idLength;
this->colourMapType=Head.colourMapType;
this->dataTypeCode=Head.dataTypeCode;
this->colourMapOrigin=Head.colourMapOrigin;
this->colourMapLength=Head.colourMapLength;
this->colourMapDepth=Head.colourMapDepth;
this->xOrigin=Head.xOrigin;
this->yOrigin=Head.yOrigin;
this->width=Head.width;
this->height=Head.height;
this->bitsPerPixel=Head.bitsPerPixel;
this->imageDescriptor=Head.imageDescriptor;
}
void MultBlend( imageHeader Head1, imageHeader Head2){
int size=Head1.width*Head1.height;
image=new Pixel[size];
for(int i =0; i < size; i++){
image[i]=(Head1.image[i]*Head2.image[i]);
}
}
void SubBlend(imageHeader Head1, imageHeader Head2){
int size=Head1.height*Head1.width;
image=new Pixel[size];
for(int i =0; i < size; i++){
if(Head1.image[i].R > Head2.image[i].R){
image[i].R=Head1.image[i].R-Head2.image[i].R;
}
else{
image[i].R=0;
}
if(Head1.image[i].G > Head2.image[i].G){
image[i].G=Head1.image[i].G-Head2.image[i].G;
}
else{
image[i].G=0;
}
if(Head1.image[i].B > Head2.image[i].B){
image[i].B=Head1.image[i].B-Head2.image[i].B;
}
else{
image[i].B=0;
}
}
}
void AddGreen(imageHeader Head){
image=new Pixel[Head.width*Head.height];
for(int i = 0 ; i < Head.width*Head.height;i++) {
image[i]=Head.image[i];
}
for(int i = 0; i < Head.width*Head.height;i++){
if(image[i].G>55){
image[i].G=255;
}else {
image[i].G += 200;
}
}
}
void Screen(imageHeader Head1, imageHeader Head2){
int size=Head1.width*Head1.height;
image=new Pixel[size];
for(int i=0; i < size; i++){
float R = Head1.image[i].R/255.0f;
float G = Head1.image[i].G/255.0f;
float B = Head1.image[i].B/255.0f;
float R2 = Head2.image[i].R/255.0f;
float G2 = Head2.image[i].G/255.0f;
float B2 = Head2.image[i].B/255.0f;
image[i].R=(1-(1-R)*(1-R2))*255 +0.5;
image[i].G=(1-(1-G)*(1-G2))*255+0.5;
image[i].B=(1-(1-B)*(1-B2))*255+0.5;
}
}
void Overlay(imageHeader Head1, imageHeader Head2){
int size= Head1.width*Head1.height;
image=new Pixel[size];
for(int i=0; i<size;i++){
float R = Head1.image[i].R/255.0f;
float G = Head1.image[i].G/255.0f;
float B = Head1.image[i].B/255.0f;
float R2 = Head2.image[i].R/255.0f;
float G2 = Head2.image[i].G/255.0f;
float B2 = Head2.image[i].B/255.0f;
if(R2<=0.5f){
image[i].R=std::round((2*R*R2)*255);
}
else{
image[i].R=std::round((1-(2*(1-R)*(1-R2)))*255);
}
if(G2<=0.5f){
image[i].G=std::round((2*G*G2)*255);
}
else{
image[i].G=std::round((1-(2*(1-G)*(1-G2)))*255);
}
if(B2<=0.5f){
image[i].B=std::round((2*B*B2)*255);
}
else{
image[i].B=std::round((1-(2*(1-B)*(1-B2)))*255);
}
}
}
void ScaleRedBlue(imageHeader Head){
int size=Head.width*Head.height;
image=new Pixel[size];
for(int i=0; i < Head.width*Head.height;i++){
image[i]=Head.image[i];
}
for(int i =0; i<Head.width*Head.height;i++){
image[i].B=0;
if(image[i].R*4>255){
image[i].R=255;
}
else {
image[i].R *= 4;
}
}
}
void SplitRed(imageHeader Head){
image= new Pixel[Head.width*Head.height];
for(int i = 0; i < Head.width*Head.height;i++){
image[i]=Head.image[i];
}
for(int i =0; i < Head.width*Head.height;i++){
image[i].G=image[i].R;
image[i].B=image[i].R;
}
}
void SplitGreen(imageHeader Head){
image=new Pixel[Head.width*Head.height];
for(int i = 0; i < Head.width*Head.height;i++){
image[i]=Head.image[i];
}
for(int i =0; i < Head.width*Head.height;i++){
image[i].R=image[i].G;
image[i].B=image[i].G;
}
}
void SplitBlue(imageHeader Head){
image=new Pixel[Head.height*Head.width];
for(int i = 0; i < Head.width*Head.height;i++){
image[i]=Head.image[i];
}
for(int i =0; i < Head.width*Head.height;i++){
image[i].G=image[i].B;
image[i].R=image[i].B;
}
}
void combine(imageHeader Head1, imageHeader Head2, imageHeader Head3){
image=new Pixel[Head1.width*Head1.height];
for(int i =0; i < Head1.width*Head1.height;i++){
image[i].R=Head1.image[i].R;
}
for(int i =0; i < Head1.width*Head1.height;i++){
image[i].G=Head2.image[i].G;
}
for(int i =0; i < Head1.width*Head1.height;i++){
image[i].B=Head3.image[i].B;
}
}
void imageFlip(imageHeader Head){
int size = Head.width*Head.height;
image=new Pixel[size];
for(int i = 0; i < size;i++){
image[i]=Head.image[size-i-1];
}
}
};
void QuickCompare(int testnum, imageHeader head1, imageHeader head2){
int n;
n= memcmp(head1.image, head2.image, head1.width*head1.height*3);
if(n==0){
std::cout<<"Test" <<testnum<<" successful!"<<std::endl;
}
else{
std::cout<<"Test "<<testnum<<" failed"<<std::endl;
}
}
#endif //PROJECT2_IMAGESTUFF_H
|
Python
|
UTF-8
| 626 | 3.453125 | 3 |
[] |
no_license
|
import math
def find_primes_to_n(n):
primes_so_far = [2, 3]
num_to_check = 5
while num_to_check < n:
is_prime = True
for prime in primes_so_far:
if prime > math.sqrt(num_to_check):
is_prime = True
break
if num_to_check % prime == 0:
is_prime = False
break
if is_prime == True:
primes_so_far.append(num_to_check)
if (num_to_check + 1) % 6 == 0:
num_to_check += 2
else:
num_to_check += 4
return primes_so_far
print(sum(find_primes_to_n(2000000)))
|
C++
|
UTF-8
| 1,111 | 2.65625 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
int L, B, T;
int dp[202][101][101];
bool can(int P, int TF, int TH){
int tB = B;
int tmp;
tmp = min(tB , P);
P -= tmp;
tB -= tmp;
tmp = min(tB, TF);
TF -= tmp;
tB -= tmp;
return (tB == 0) && (P + TH + (2 * TF) >= L);
}
int wow(int pinggir, int tengah_full, int tengah_half){
if (dp[pinggir][tengah_full][tengah_half] != -1)
return dp[pinggir][tengah_full][tengah_half];
if (can(pinggir, tengah_full, tengah_half)){
dp[pinggir][tengah_full][tengah_half] = 0;
return 0;
}
int res = 9999999;
res = min( res , 1 + wow(pinggir + 1 , tengah_full + 1 , tengah_half) ); //colok di pinggir
if (tengah_half)
res = min( res , 1 + wow(pinggir + 2 , tengah_full + 1 , tengah_half - 1) ); //colok di tengah yg masih kosong
if (tengah_full)
res = min( res , 1 + wow(pinggir + 2 , tengah_full , tengah_half + 1) ); //colok di tengah yg udah dicolok sampingnya
dp[pinggir][tengah_full][tengah_half] = res;
return res;
}
int main(){
cin >> T;
while (T--) {
cin >> L >> B;
memset(dp,-1,sizeof dp);
cout << 1 + wow(2,1,0) << endl;
}
}
|
Java
|
UTF-8
| 650 | 3.546875 | 4 |
[] |
no_license
|
public class Edge implements Comparable<Edge>{
private int cost;
private int[] towns;
public Edge(int cost, int town1index, int town2index) {
this.cost = cost;
towns = new int[2];
towns[0] = town1index;
towns[1] = town2index;
}
public int compareTo(Edge o) {
return (this.cost - o.cost);
}
public int getCost() {
return cost;
}
public int hasTown(int town) {
if (towns[0] == town)
return 0;
if (towns[1] == town)
return 1;
return -1;
}
public int[] getTowns() {
return towns;
}
public String toString(){
return cost + ": " + towns[0] + "--" + towns[1];
}
}
|
Swift
|
UTF-8
| 539 | 3.4375 | 3 |
[] |
no_license
|
class Solution {
func maxArea(_ height: [Int]) -> Int {
var maxS: Int = 0
var left: Int = 0
var right: Int = height.count - 1
while left < right{
maxS = max(maxS, min(height[left], height[right]) * (right - left))
if height[left] < height[right]{
left += 1
}else{
right -= 1
}
}
return maxS
}
}
let solution = Solution()
let input: [Int] = [1,8,6,2,5,4,8,3,7]
print(solution.maxArea(input))
|
Java
|
UTF-8
| 2,868 | 1.953125 | 2 |
[] |
no_license
|
package test.order;
import static org.junit.Assert.assertEquals;
import org.apache.commons.httpclient.methods.PostMethod;
import org.junit.BeforeClass;
import org.junit.Test;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import test.BaseTest;
public class AddorderTest extends BaseTest {
@BeforeClass
public static void login(){
PostMethod method= getPostMethod("/api/mobile/member!login.do");
method.addParameter("username", "13664288387");
method.addParameter("password", "123456");
JSONObject o = getJson(method);
}
// @Test
// public void testToCount(){
// PostMethod method = getPostMethod("/api/mobile/favorite!list.do");
//
// JSONObject o =getJson(method);
// assertEquals(1, o.getIntValue("result"));
// JSONObject data = o.getJSONObject("data");
// }
// @Test
// public void testToCount(){
// PostMethod method = getPostMethod("/api/mobile/order!list.do");
// method.addParameter("status","0");
// JSONObject o =getJson(method);
// assertEquals(1, o.getIntValue("result"));
// JSONObject data = o.getJSONObject("data");
// }
@Test
public void testToCount(){
PostMethod method = getPostMethod("/api/mobile/order!storeCartGoods.do");
method.addParameter("countCart","[{cart_id=3857,cart_num=1}]");
JSONObject o =getJson(method);
assertEquals(1, o.getIntValue("result"));
JSONObject data = o.getJSONObject("data");
}
// @Test
// public void testgetTotalPrice(){
// PostMethod method = getPostMethod("/api/mobile/order!getTotalPrice.do");
// method.addParameter("type_id","1");
// method.addParameter("address_id","44");
// method.addParameter("bonus_id","41");
// method.addParameter("storeId","1");
// method.addParameter("storeBonusId","1");
// method.addParameter("advancePay","150");
// method.addParameter("cart_id","241,242");
// JSONObject o =getJson(method);
// assertEquals(1, o.getIntValue("result"));
// JSONObject data = o.getJSONObject("data");
// }
// @Test
// public void testCreateOrder() throws Exception{
// PostMethod method = getPostMethod("/api/mobile/order!create.do");
// method.addParameter("TypeId","1");
// method.addParameter("paymentId","1");
// method.addParameter("addressId","44");
// method.addParameter("shipDay","234");
// method.addParameter("shipTime","0");
// method.addParameter("cart_id","289");
// method.addParameter("receipt","1");
// method.addParameter("receiptType","2");
// method.addParameter("receiptContent","hello");
// method.addParameter("receiptTitle","hello");
// method.addParameter("bonusid","41");
// JSONObject o =getJson(method);
// assertEquals(1, o.getIntValue("result"));
// assertEquals("添加订单成功", o.getString("message"));
// JSONObject data = o.getJSONObject("data");
//
// }
}
|
Java
|
UTF-8
| 1,280 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
package qword.repositories;
import qword.domain.Player;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Comparator.comparingDouble;
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.toList;
public class InMemoryPlayerRepository implements PlayerRepository {
private final Map<Integer, Player> players = new HashMap<>();
@Override
public List<Player> getPlayersByRanking() {
return players.values().stream()
.sorted(comparingDouble(Player::getRating).reversed())
.collect(toList());
}
@Override
public List<Player> getPlayersByScore() {
// TODO: check if the sort by score/position has a different meaning than the sort by ranking
return getPlayersByRanking();
}
@Override
public List<Player> getPlayersByWinsAndLosses() {
return players.values().stream()
.sorted(comparingInt(Player::getWinLossesDifference).reversed())
.collect(toList());
}
@Override
public Player getPlayerById(int id) {
return players.get(id);
}
@Override
public void addPlayer(Player player) {
players.put(player.getId(), player);
}
}
|
Python
|
UTF-8
| 7,998 | 3.734375 | 4 |
[] |
no_license
|
#
# @lc app=leetcode id=1286 lang=python3
#
# [1286] Iterator for Combination
#
# https://leetcode.com/problems/iterator-for-combination/description/
#
# algorithms
# Medium (64.96%)
# Likes: 88
# Dislikes: 10
# Total Accepted: 4.5K
# Total Submissions: 7K
# Testcase Example: '["CombinationIterator","next","hasNext","next","hasNext","next","hasNext"]\r' + '\n[["abc",2],[],[],[],[],[],[]]\r'
#
# Design an Iterator class, which has:
#
#
# A constructor that takes a string characters of sorted distinct lowercase
# English letters and a number combinationLength as arguments.
# A function next() that returns the next combination of length
# combinationLength in lexicographical order.
# A function hasNext() that returns True if and only if there exists a next
# combination.
#
#
#
#
# Example:
#
#
# CombinationIterator iterator = new CombinationIterator("abc", 2); // creates
# the iterator.
#
# iterator.next(); // returns "ab"
# iterator.hasNext(); // returns true
# iterator.next(); // returns "ac"
# iterator.hasNext(); // returns true
# iterator.next(); // returns "bc"
# iterator.hasNext(); // returns false
#
#
#
# Constraints:
#
#
# 1 <= combinationLength <= characters.length <= 15
# There will be at most 10^4 function calls per test.
# It's guaranteed that all calls of the function next are valid.
#
#
#
# @lc code=start
class CombinationIterator:
def __init__(self, characters: str, combinationLength: int):
# Backtracking
# Time complexity: O(k x C(k, N))
# Space compleixty: O(C(k, N))
# self.c = characters
# self.n = combinationLength
# self.i = 0
# self.ans = []
# self.permute("", 0)
# Bitmasking: Precomputation
# Time complexity: O(2^N x N) to generate 2^N bitmasks and then count a number of bits set in each bitmask in O(N) time. O(1) runtime.
# Space complexity: O(k x C(k, N)) to keep C(k, N) combinations of length k.
# self.combinations = []
# n, k = len(characters), combinationLength
# # generate bitmasks from 0..00 to 1..11
# for bitmask in range(1 << n):
# # use bitmasks with k 1-bits
# if bin(bitmask).count('1') == k:
# # convert bitmask into combination
# # 111 --> "abc", 000 --> ""
# # 110 --> "ab", 101 --> "ac", 011 --> "bc"
# curr = [characters[j] for j in range(n) if bitmask & (1 << n - j - 1)]
# self.combinations.append(''.join(curr))
# Bitmasking: Next Combination
# Time complexity: O(2^N x N / C(k, N)) in average.
# Space complexity: O(k)
self.n = n = len(characters)
self.k = k = combinationLength
self.chars = characters
# generate first bitmask 1(k)0(n - k)
self.b = (1 << n) - (1 << n - k)
# Algorithm L by D. E. Knuth: Lexicographic Combinations: Precomputation
# Time complexity: O(k x C(k, N))
# Space complexity: O(k x C(k, N))
# self.combinations = []
# n, k = len(characters), combinationLength
# # init the first combination
# nums = list(range(k)) + [n]
# j = 0
# while j < k:
# # add current combination
# curr = [characters[n - 1 - nums[i]] for i in range(k - 1, -1, -1)]
# self.combinations.append(''.join(curr))
# # Generate next combination.
# # Find the first j such that nums[j] + 1 != nums[j + 1].
# # Increase nums[j] by one.
# j = 0
# while j < k and nums[j + 1] == nums[j] + 1:
# nums[j] = j
# j += 1
# nums[j] += 1
# Algorithm L by D. E. Knuth: Lexicographic Combinations: Next Combination
# Time complexity: O(k) both for init() and next() functions. The algorithm generates a new combination from the previous one in O(k) time.
# Space complexity: O(k)
# self.n = len(characters)
# self.k = k = combinationLength
# self.chars = characters
# # init the first combination
# self.nums = list(range(k))
# self.has_next = True
def permute(self, s: str, start: int) -> None:
# Backtracking
# Time complexity: O(k x C(k, N))
# Space compleixty: O(C(k, N))
if len(s) == self.n:
self.ans.append(s)
return
else:
for i in range(start, len(self.c)):
self.permute(s + self.c[i], i + 1)
def next(self) -> str:
# Backtracking
# Time complexity: O(k x C(k, N))
# Space compleixty: O(C(k, N))
# ans = self.ans[self.i]
# self.i += 1
# return ans
# generate bitmasks from 0..00 to 1..11
# Time complexity: O(2^N x N) to generate 2^N bitmasks and then count a number of bits set in each bitmask in O(N) time. O(1) runtime.
# Space complexity: O(k x C(k, N)) to keep C(k, N) combinations of length k.
# return self.combinations.pop()
# Bitmasking: Next Combination
# Time complexity: O(2^N x N / C(k, N)) in average.
# Space complexity: O(k)
# convert bitmasks into combinations
# 111 --> "abc", 000 --> ""
# 110 --> "ab", 101 --> "ac", 011 --> "bc"
curr = [self.chars[j] for j in range(self.n) if self.b & (1 << self.n - j - 1)]
# generate next bitmask
self.b -= 1
while self.b > 0 and bin(self.b).count('1') != self.k:
self.b -= 1
return ''.join(curr)
# Algorithm L by D. E. Knuth: Lexicographic Combinations: Precomputation
# Time complexity: O(k x C(k, N))
# Space complexity: O(k x C(k, N))
# return self.combinations.pop()
# Algorithm L by D. E. Knuth: Lexicographic Combinations: Next Combination
# Time complexity: O(k) both for init() and next() functions. The algorithm generates a new combination from the previous one in O(k) time.
# Space complexity: O(k)
nums = self.nums
n, k = self.n, self.k
curr = [self.chars[j] for j in nums]
# Generate next combination.
# Find the first j such that nums[j] != n - k + j.
# Increase nums[j] by one.
# j = k - 1
# while j >= 0 and nums[j] == n - k + j:
# j -= 1
# nums[j] += 1
# if j >= 0:
# for i in range(j + 1, k):
# nums[i] = nums[j] + i - j
# else:
# self.has_next = False
# return ''.join(curr)
def hasNext(self) -> bool:
# Backtracking
# Time complexity: O(k x C(k, N))
# Space compleixty: O(C(k, N))
# return self.i < len(self.ans)
# generate bitmasks from 0..00 to 1..11
# Time complexity: O(2^N x N) to generate 2^N bitmasks and then count a number of bits set in each bitmask in O(N) time. O(1) runtime.
# Space complexity: O(k x C(k, N)) to keep C(k, N) combinations of length k.
# return self.combinations
# Bitmasking: Next Combination
# Time complexity: O(2^N x N / C(k, N)) in average.
# Space complexity: O(k)
return self.b > 0
# Algorithm L by D. E. Knuth: Lexicographic Combinations: Precomputation
# Time complexity: O(k x C(k, N))
# Space complexity: O(k x C(k, N))
# return self.combinations
# Algorithm L by D. E. Knuth: Lexicographic Combinations: Next Combination
# Time complexity: O(k) both for init() and next() functions. The algorithm generates a new combination from the previous one in O(k) time.
# Space complexity: O(k)
# return self.has_next
# Your CombinationIterator object will be instantiated and called as such:
# obj = CombinationIterator(characters, combinationLength)
# param_1 = obj.next()
# param_2 = obj.hasNext()
# @lc code=end
|
Python
|
UTF-8
| 808 | 2.5625 | 3 |
[] |
no_license
|
from marshmallow import Schema, fields, validate
class EventBody:
def __init__(self, eventName, metadata, timestampUTC):
self.eventName = eventName
self.metadata = metadata
self.timestampUTC = timestampUTC
class EventSchema(Schema):
eventName = fields.String(
required=True,
error_messages={"required": {"message": "eventName required", "code": 400}},
)
metadata = fields.List(
fields.String(),
required=True,
validates=validate.Length(min=1),
error_messages={
"required": {"message": "At least one metadata is required", "code": 400}
},
)
timestampUTC = fields.Integer(
required=True,
error_messages={"required": {"message": "timestampUTC required", "code": 400}},
)
|
Java
|
UTF-8
| 6,309 | 2.21875 | 2 |
[] |
no_license
|
package arbell.research.peripheral.usb;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.hardware.usb.*;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import arbell.research.R;
import java.util.HashMap;
/**
* Author: YinLanShan
* Date: 14-1-23
* Time: 17:18
*/
public class UsbReceiver extends Activity implements View.OnClickListener
{
private UsbManager mManager;
private UsbDevice mDevice;
private UsbEndpoint mInEP;
private UsbEndpoint mOutEP;
private UsbInterface mInterface;
private UsbDeviceConnection mConnection;
private TextView mText;
private static final String TAG = "USB_COM";
private static final String ACTION_USB_PERMISSION =
"research.ivory.usb.USB_PERMISSION";
private Receiver mReceiverThread = new Receiver();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.usb_receiver);
mText = (TextView)findViewById(R.id.text);
mText.setTypeface(Typeface.create("monospace", Typeface.BOLD));
mText.setTextSize(26);
Button button = (Button)findViewById(R.id.send);
button.setOnClickListener(this);
mManager = (UsbManager) getSystemService(USB_SERVICE);
HashMap<String, UsbDevice> map = mManager.getDeviceList();
UsbDevice dev = null;
for (String key : map.keySet())
{
UsbDevice d = map.get(key);
if (d.getVendorId() == 0x1915 && d.getProductId() == 0x0100)
{
dev = d;
break;
}
}
if (dev == null)
{
mText.setText("No target device");
return;
}
mDevice = dev;
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
mManager.requestPermission(dev, pendingIntent);
mText.setText("Requesting Permission");
}
@Override
protected void onDestroy()
{
super.onDestroy();
mReceiverThread.isStopped = true;
if (mConnection != null)
{
mConnection.releaseInterface(mInterface);
mConnection.close();
}
if (mDevice != null)
unregisterReceiver(mUsbReceiver);
}
private StringBuilder mMessage = new StringBuilder(200);
private int lineCount = 0;
private static final int MAX_LINE_COUNT = 20;
private final Runnable mTextWriter = new Runnable()
{
@Override
public void run()
{
mText.setText(mMessage);
}
};
private class Receiver extends Thread
{
public boolean isStopped = false;
@Override
public void run()
{
if (mConnection != null && mInEP != null)
{
byte[] data = new byte[40];
while (!isStopped)
{
int len = mConnection.bulkTransfer(mInEP, data, 32, 1000); // 1000ms timeout
//android.util.Log.d("usb", "Rx len:"+len);
if (len > 0)
{
mMessage.delete(0, mMessage.length());
for(int i = 0; i < len; i++)
{
mMessage.append(String.format("%02X ", data[i]));
}
mText.post(mTextWriter);
}
}
}
isStopped = true;
}
}
private void setupConn(UsbDevice device)
{
if (device != null)
{
mDevice = device;
mConnection = mManager.openDevice(device);
mInterface = device.getInterface(0);
mConnection.claimInterface(mInterface, true);
UsbEndpoint ep = mInterface.getEndpoint(0);
if (ep.getDirection() == UsbConstants.USB_DIR_IN)
mInEP = ep;
else
mOutEP = ep;
ep = mInterface.getEndpoint(1);
if (ep.getDirection() == UsbConstants.USB_DIR_IN)
mInEP = ep;
else
mOutEP = ep;
mText.setText("get Connected");
mReceiverThread.start();
}
}
@Override
public void onClick(View v)
{
if (mConnection != null && mOutEP != null)
{
byte[] data = new byte[1];
EditText et = (EditText)findViewById(R.id.input_text);
CharSequence cs = et.getText();
try{
data[0] = Byte.parseByte(cs.toString(), 10);
} catch (NumberFormatException e)
{
Toast.makeText(this, "Bad num format", Toast.LENGTH_SHORT).show();
return;
}
Log.d("usb", String.format("sent %d", data[0]));
mConnection.bulkTransfer(mOutEP, data, data.length, 1000);
}
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
setupConn(device);
} else
{
mText.setText("Permission Denied");
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
}
|
Python
|
UTF-8
| 5,395 | 2.765625 | 3 |
[] |
no_license
|
import numpy
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
from tkinter import *
from pygraphviz import *
from parse import Parse
class MainForm:
def __init__(self):
self.root = Tk()
self.root.title("Plot")
self.root.attributes("-zoomed", True)
self.title = "Calculus"
# Get root information
self.root.update()
self.width = self.root.winfo_width()
self.height = self.root.winfo_height()
self.__DPI = 110.0 # Average DPI for most monitor
#Loading GUI
self.GUI()
# Event Handler
self.state = False
self.root.bind("<F11>", self.toggle_fullscreen)
self.root.bind("<Escape>", self.end_fullscreen)
def graph(self):
self.parse = Parse(self.input.get())
fn = self.title + '.dot'
try:
print(self.parse.function)
except:
messagebox.showerror("Error", "Somethings gone wrong, please check your input again")
return
f = open(fn, 'w+')
f.write("graph calculus {\n")
f.write('\tnode [ fontname = "Arial"]\n')
self.parse.root.toGraph(-1, f)
f.write('}')
f.close()
G = AGraph(fn)
G.draw('test.png', prog='dot')
messagebox.showinfo("Info", "Success")
def plot (self):
self.parse = Parse(self.input.get())
try:
print(self.parse.function)
except:
messagebox.showerror("Error", "Somethings gone wrong, please check your input again")
return
t = numpy.linspace(self.left, self.right, (self.right-self.left)*self.seq+1)
y = numpy.zeros(len(t)) # allocate y with float elements
thresshole = 100
for i in range(len(t)):
x = t[i]
try:
y[i] = eval(self.parse.function)
if((y[i-1] + y[i])/2 > thresshole):
y[i-1] = numpy.nan
y[i] = numpy.nan
except:
y[i] = numpy.nan
pass
self.a.clear()
self.a.set_title(self.title, fontsize=16)
self.a.plot(t, y, color='red')
self.canvas.draw()
def on_key_hover(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
def toggle_fullscreen(self, event=None):
self.state = not self.state # Just toggling the boolean
self.root.attributes("-fullscreen", self.state)
return "break"
def end_fullscreen(self, event=None):
self.state = False
self.root.attributes("-fullscreen", False)
return "break"
def GUI(self):
#==========================================================================
# Top Frame
#==========================================================================
self.topFrame = Frame(self.root, width=self.width, bd = 2, relief = "raise")
self.topFrame.pack(side=TOP, fill=BOTH, expand = True)
"""
Top Left
"""
self.topFrameLeft = Frame(self.topFrame, width=self.width/2)
self.topFrameLeft.pack(side=LEFT, expand = True)
# Label
Label(self.topFrameLeft, text = "Input").grid(row=0, column=0, sticky=W, padx=2)
# Input field
self.input = Entry(self.topFrameLeft, width=30)
self.input.grid(row=0, column=1, sticky=W, padx=2)
# Button
Button(self.topFrameLeft, text="Parse", command=self.plot).grid(row=0, column=2, sticky=W, padx=2)
"""
Top Right
"""
self.topFrameRight = Frame(self.topFrame, width=self.width/2)
self.topFrameRight.pack(side=LEFT, expand = True)
# Button
self.btnGraph = Button(self.topFrameRight, text="Export Graph", command=self.graph)
self.btnGraph.pack()
#==========================================================================
# Bottom Frame
#==========================================================================
self.bottomFrame = Frame(self.root, width=self.width, bd = 2, relief = "raise")
self.bottomFrame.pack(side=TOP, fill=BOTH, expand = True)
"""
Ploting
"""
# Justify the plot
self.left = -10
self.right = 10
self.seq = 1000
# Figure
fig = Figure(figsize=(self.width/self.__DPI, self.height/self.__DPI))
self.a = fig.add_subplot(111)
self.a.set_title ("Calculus", fontsize=16)
self.a.set_ylabel("Y", fontsize=14)
self.a.set_xlabel("X", fontsize=14)
self.a.plot([], [], color='red')
self.a.grid(True)
self.canvas = FigureCanvasTkAgg(fig, master=self.bottomFrame)
self.canvas.draw()
self.canvas.get_tk_widget().pack(pady=5)
# Toolbar
self.toolbar = NavigationToolbar2Tk(self.canvas, self.bottomFrame)
self.toolbar.update()
self.canvas.get_tk_widget().pack()
if __name__ == '__main__':
form = MainForm()
form.canvas.mpl_connect("key_press_event", form.on_key_hover)
form.root.mainloop()
|
C#
|
UTF-8
| 1,696 | 2.65625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Data.SqlServerCe;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Dapper.Contrib.Extensions;
using SpeechToSpeech.Models;
using SpeechToSpeech.Services;
namespace SpeechToSpeech.Repositories
{
public class WebServiceRepository : IWebServiceRepository
{
private ISettingsService settingsService;
private Settings settings;
private string ConnectionString
{
get
{
return string.Format("DataSource=\"{0}\";Max Database Size={1};", settings.generalSettings.Database, settings.databaseSettings.MaxDatabaseSize);
}
}
public WebServiceRepository(ISettingsService settingsService)
{
this.settingsService = settingsService;
settings = settingsService.settings;
}
public async Task<List<WebService>> GetAll()
{
using (var cnn = new SqlCeConnection(ConnectionString))
{
var result = await cnn.GetAllAsync<WebService>();
return result.ToList();
}
}
public async Task<int> Insert(WebService webService)
{
using (var cnn = new SqlCeConnection(ConnectionString))
{
return await cnn.InsertAsync(webService);
}
}
public int InsertMultiple(List<WebService> webServices)
{
var ids = new List<int>();
using (var cnn = new SqlCeConnection(ConnectionString))
{
return (int)cnn.Insert(webServices);
}
}
public async Task<bool> Delete(int id)
{
using (var cnn = new SqlCeConnection(ConnectionString))
{
return await cnn.DeleteAsync(new WebService { Id = id });
}
}
}
}
|
Java
|
UTF-8
| 11,055 | 2.234375 | 2 |
[] |
no_license
|
package alienrabble.logging;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.jme.util.Timer;
/**
* This class stores the data recorded during the Sort phase of the game.
* It stores the initial locations of the objects and the order and timing
* of how they are collected.
*
* @author Caspar Addyman
*
*/
public class ARXMLSortData{
private static final long serialVersionUID = 1L;
private static final Logger logger
= Logger.getLogger(ARXMLSortData.class.getName());
//the names of the various node types in our xml doc
public static final String TOPLEVEL_NODE = "alienrabbledata";
public static final String ARVERSION_NODE = "AlienRabbleVersion";
public static final String SORT_SESSION_DETAILS_NODE = "SortSessionDetails";
public static final String ID_NODE = "id";
public static final String NAME_NODE = "name";
public static final String MODELSET_NODE = "modelset";
public static final String EXPERIMENTER_NODE = "experimenter";
public static final String PARTICIPANT_NODE = "participant";
public static final String TESTDATE_NODE = "testdate";
public static final String STARTING_POSITIONS = "startingpositions";
public static final String SORT_EVENTS = "sortevents";
public static final String SORT_ORDER = "sortorder";
public static final String SORT_GROUPS = "sortgroups";
public static final String SORT_GROUP = "sortgroup";
public static final String SORT_EVENT = "sortevent";
public static final String MOUSE_CLICKS = "mouseclicks";
public static final String MOUSE_CLICK = "mouseclick";;
public static final String ALIEN_ID_NODE = "alienid";
public static final String ALIEN_NAME_NODE = "alienname";
public static final String TESTSTART_NODE = "starttime";
public static final String EVENTTIME_NODE = "time";
public static final String TICKS_VALUE = "ticks";
public static final String SECS_VALUE = "secs";
public static final String LOCATION_NODE = "location";
public static final String CLICKED_OBJECT = "clickedobject";
public static final String EVENT_TYPE = "eventtype";
public static final String TYPE_SELECTALIEN = "selectalien";
public static final String TYPE_DESELECTALIEN = "deselectalien";
public static final String TYPE_SORTALIEN = "sortalien";
public static final String TYPE_ADDBOX = "addbox";
public static final String TYPE_REMOVEBOX = "removebox";
public static final String TYPE_SORTRESULT = "sortresult";
public static final String TYPE_CLICKNOTHING = "clicknothing";
public static final String DATE_FORMAT = "yyyy-MM-dd";
public static final String TIME_FORMAT = "hh:mm:ss";
private String ID; // participant's ID number
private String modelset; //the models used in this session
private String experimenter;
private Date testdate; // testing date
private Date starttime; // when testing began
private Date endtime; // when testing ended
private ArrayList<MouseEvent> startingpositions = new ArrayList<MouseEvent>();
private ArrayList<MouseEvent> mouseclicks = new ArrayList<MouseEvent>();
private ArrayList<SortEvent> sortevents = new ArrayList<SortEvent>();
private ArrayList<SortEvent> sortgroups = new ArrayList<SortEvent>();
private ArrayList<SortEvent> sortorder = new ArrayList<SortEvent>();
private Timer timer; //hold a reference to the main timer
/**
*
* @param filename
*/
public ARXMLSortData() {
timer = Timer.getTimer(); //there is only one timer in application, this fn retrieves it.
testdate = new Date();
starttime = new Date(); //should probably think of better time & place to set this
}
/**
* adds the Sort data to existing DOM document.
* checks if there is an existing element with this name and
* overwrites it
* @param doc - the current DOM settings document
*/
public Document writeSortData(Document doc){
NodeList origDoc = doc.getElementsByTagName(TOPLEVEL_NODE);
Element topElement = (Element) origDoc.item(0);
if (topElement == null){
topElement = doc.createElement(TOPLEVEL_NODE);
doc.appendChild(topElement);
}
NodeList oldSortList = topElement.getElementsByTagName(SORT_SESSION_DETAILS_NODE);
Node oldSortData = oldSortList.item(0);
Element e1 = doc.createElement(SORT_SESSION_DETAILS_NODE);
if (oldSortData != null)
{
topElement.replaceChild(e1, oldSortData);
}else{
topElement.appendChild(e1);
}
//add the id for this participant
Element e11 = doc.createElement(ID_NODE);
e11.setTextContent(ID);
e1.appendChild(e11);
//add the model set
Element e12 = doc.createElement(MODELSET_NODE);
e12.setTextContent(modelset);
e1.appendChild(e12);
//add the model set
Element e12b = doc.createElement(EXPERIMENTER_NODE);
e12b.setTextContent(experimenter);
e1.appendChild(e12b);
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
DateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
//add current date
Element e13 = doc.createElement(TESTDATE_NODE);
e13.setTextContent(dateFormat.format(testdate));
e1.appendChild(e13);
//start time (approximate - accurate logging in sort and grob data itself)
Element e14 = doc.createElement(TESTSTART_NODE);
e14.setTextContent(timeFormat.format(starttime));
e1.appendChild(e14);
//end time (approximate - accurate logging in sort and grob data itself)
endtime = new Date();
Element e14b = doc.createElement(TESTSTART_NODE);
e14b.setTextContent(timeFormat.format(endtime));
e1.appendChild(e14b);
//where were the individual aliens
Element e15 = doc.createElement(STARTING_POSITIONS);
e1.appendChild(e15);
for(int i=0; i<startingpositions.size();i++)
{
Element e15i = writeMouseEvent(doc,startingpositions.get(i));
e15.appendChild(e15i);
}
//where did the participants click (even if they didn't click on anything)
Element e16 = doc.createElement(MOUSE_CLICKS);
e1.appendChild(e16);
for(int i=0; i<mouseclicks.size();i++)
{
Element e16i = writeMouseEvent(doc,mouseclicks.get(i));
e16.appendChild(e16i);
}
Element e17 = doc.createElement(SORT_EVENTS);
e1.appendChild(e17);
for(int i=0; i<sortevents.size();i++)
{
Element e17i = writeSortEvent(doc,sortevents.get(i));
e17.appendChild(e17i);
}
Element e18 = doc.createElement(SORT_GROUPS);
e1.appendChild(e18);
for(int i=0; i<sortgroups.size();i++)
{
Element e18i = writeSortEvent(doc,sortgroups.get(i));
e18.appendChild(e18i);
}
Element e19 = doc.createElement(SORT_ORDER);
e1.appendChild(e19);
for(int i=0; i<sortorder.size();i++)
{
Element e19i = writeSortEvent(doc,sortorder.get(i));
e19.appendChild(e19i);
}
return doc;
}
/**
* writes the xml for a single mouse click event
*
* @param doc - xml document we are working with
* @param me - a single mouse click
* @return the element to add to the document
*/
public Element writeMouseEvent(Document doc, MouseEvent me){
Element mouseclick = doc.createElement(MOUSE_CLICK);
if (me.objectclicked){
Element g1 = doc.createElement(NAME_NODE);
g1.setTextContent(me.objectname);
mouseclick.appendChild(g1);
Element g2 = doc.createElement(ID_NODE);
g2.setTextContent(me.objectid);
mouseclick.appendChild(g2);
}
Element g3 = doc.createElement(EVENTTIME_NODE);
g3.setAttribute(TICKS_VALUE,Long.toString(me.clockTicks));
g3.setAttribute(SECS_VALUE,Float.toString(me.timeInSecs));
mouseclick.appendChild(g3);
Element g4 = doc.createElement(LOCATION_NODE);
g4.setAttribute("x",Float.toString(me.x_location));
g4.setAttribute("y",Float.toString(me.y_location));
mouseclick.appendChild(g4);
return mouseclick;
}
/**
* writes the xml for a single Sort event
*
* @param doc - xml document we are working with
* @param ge - a single Sort event
* @return the element to add to the document
*/
public Element writeSortEvent(Document doc, SortEvent se){
Element sortevent = doc.createElement(SORT_EVENT);
sortevent.setAttribute(EVENT_TYPE, se.type);
Element g1 = doc.createElement(NAME_NODE);
g1.setTextContent(se.objectname);
sortevent.appendChild(g1);
Element g1b = doc.createElement(ID_NODE);
g1b.setTextContent(se.objectid);
sortevent.appendChild(g1b);
Element g1c = doc.createElement(SORT_GROUP);
g1c.setTextContent(String.valueOf(se.sortgroup));
sortevent.appendChild(g1c);
Element g2 = doc.createElement(EVENTTIME_NODE);
g2.setAttribute(TICKS_VALUE,Long.toString(se.clockTicks));
g2.setAttribute(SECS_VALUE,Float.toString(se.timeInSecs));
sortevent.appendChild(g2);
Element g3 = doc.createElement(LOCATION_NODE);
g3.setAttribute("x",Float.toString(se.x_location));
g3.setAttribute("y",Float.toString(se.y_location));
sortevent.appendChild(g3);
return sortevent;
}
public void addStartingPosition(MouseEvent me){
startingpositions.add(me);
}
public void addSortEvent(SortEvent se){
//add a time stamp if one has been forgotten
if (se.clockTicks <= 0){
se.clockTicks = timer.getTime();
se.timeInSecs = se.clockTicks * 1f /timer.getResolution();
}
sortevents.add(se);
}
public void addSortOrderItem(SortEvent se){
//add a time stamp if one has been forgotten
if (se.clockTicks <= 0){
se.clockTicks = timer.getTime();
se.timeInSecs = se.clockTicks * 1f /timer.getResolution();
}
sortorder.add(se);
}
public void addSortGroupItem(SortEvent se){
//add a time stamp if one has been forgotten
if (se.clockTicks <= 0){
se.clockTicks = timer.getTime();
se.timeInSecs = se.clockTicks * 1f /timer.getResolution();
}
sortgroups.add(se);
}
public void addMouseEvent(MouseEvent me){
//add a time stamp if one has been forgotten
if (me.clockTicks <= 0){
me.clockTicks = timer.getTime();
me.timeInSecs = me.clockTicks * 1f /timer.getResolution();
}
mouseclicks.add(me);
}
/**
* A small helper class to hold a single mouse click event
* @author monkey
*
*/
public class MouseEvent{
public boolean objectclicked;
public String objectname;
public String objectid;
public long clockTicks;
public float timeInSecs;
public float x_location;
public float y_location;
//public float z_location; //only move in the vertical(screen) plane
public MouseEvent(){}
}
/**
* A helper class that will track the actual effects of the mouse clicks.
* Selecting/deselecting aliens, sending them into sorting boxes, etc.
* Also used for to record the sort results
* @author monkey
*
*/
public class SortEvent{
public String type;
public int sortgroup; //which group was this object placed in (if applicable)
public String objectname;
public String objectid;
public long clockTicks;
public float timeInSecs;
public float x_location;
public float y_location;
//public float z_location; //only move in the vertical(screen) plane
public SortEvent(){}
}
}
|
JavaScript
|
UTF-8
| 2,774 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
var cart = {
items : [],
itemsTotal: 0,
shipping: [],
formatCurrency: function (total) {
var neg = false;
if(total < 0) {
neg = true;
total = Math.abs(total);
}
return (neg ? "-" : '') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
},
getCartTotalItems: function() {
return this.items.length;
},
getCartTotalPrice: function() {
return this.itemsTotal;
},
getCart: function(){
//gets the current cart object from server's session.
var self = this;
$.getJSON( "php/ajax.php?getCart", function(json){
self.items=json.productids;
self.itemsTotal=parseFloat(json.totalPrice, 10);
self.shipping=json.shipping;
self.updateCartPopup();
});
},
sendCart: function() {
//send the current cart object to the server to be stored in session.
var payload = { "productids" : this.items, "totalPrice": this.itemsTotal};
$.ajax({
async: false,
cache: false,
type: "POST",
dataType: 'json',
data: payload,
url: "php/ajax.php?cartUpdate"
});
},
emptyCart : function(){
//add a cart item to the cart object and update the cart total items
this.items=[];
this.itemsTotal=0;
this.updateCartPopup();
$("div#cart-items-all").find(".cart-header").remove();
$("div#cart-cost").empty();
$("div#cart-items-all").append("<p class='text-uppercase'>your shopping bag is empty</p>");
},
openCloseCart: function() {
window.setTimeout(function() {
$("a.dropdown-toggle.cart").dropdown("toggle");
}, 500);
window.setTimeout(function() {
$("a.dropdown-toggle.cart").dropdown("toggle");
$("a.dropdown-toggle.cart").blur();
},2000);
},
updateCartPopup: function(){
$("div.cart-box span.simpleCart_total"). html(" <i class='fa fa-inr'></i>"+this.formatCurrency(this.getCartTotalPrice()));
$("div.cart-box span.simpleCart_quantity"). html(this.getCartTotalItems());
$("#badge"). html(this.getCartTotalItems());
},
updateCart : function(pid, pprice){
//add a cart item to the cart object and update the cart total items
pprice = parseFloat(pprice, 10);
pid = pid+"";
this.items.push(pid);
this.itemsTotal = this.itemsTotal + pprice;
this.sendCart();
this.updateCartPopup();
},
removeItem: function(pid, pprice){
pprice = parseFloat(pprice, 10);
var ix = this.items.indexOf(pid);
this.items.splice(ix, 1);
this.itemsTotal = this.itemsTotal - pprice;
this.sendCart();
this.updateCartPopup();
}
};
$(window).on('beforeunload', function(){
window.cart.sendCart();
return void(0);
});
$(document).ready(function(){
window.cart.getCart();
});
|
Java
|
UTF-8
| 29,576 | 2.390625 | 2 |
[] |
no_license
|
package src;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.Graphics; //for graphics
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import javax.swing.JFrame; //to render the frame
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Font;
import java.util.LinkedList;
import java.util.Timer; //to keep fps stable
import java.util.TimerTask;
@SuppressWarnings("serial")
public class attempt extends JPanel {
enum keyCode {
UP (0),
DOWN (1),
LEFT (2),
RIGHT (3),
RESET (4),
BALL (5),
VBALL (6),
WALL (7),
RWALL (8),
GRAV (9),
SGRAV (10),
ERASE (11),
SHIFT (12),
PAUSE (13),
CRAZY (14),
ART (15),
FREEZE (16),
REWIND (17),
FORWARD (18),
DEBUG (19),
SLOMO (20)
;
public int code;
keyCode(int code)
{
this.code = code;
}
}
static boolean[] key = new boolean[keyCode.values().length];
static boolean[] keyReleased = new boolean[keyCode.values().length];
static Timer timer = new Timer(true);
static JTextField ipText = new JTextField(0);
static String ip;
enum mode {BALL, WALL, RWALL,VBALL, ERASE, PAUSE, CRAZY};
static mode lastMode;
static attempt attempt = new attempt();
static final int PLAYER_SIZE = 60;
static final int FPS = 1;
static LinkedList<Proj> pro = new LinkedList<Proj>();
static LinkedList<Item> walls = new LinkedList<Item>();
static LinkedList<Proj> proPred= new LinkedList<Proj>();
static LinkedList<gamestate> states = new LinkedList<gamestate>();
static int curState = 0;
static long lastSave = 0;
static int totalBounce = 0;
static double totalDist = 0;
static int proSize;
static int wallSize;
static mode CurMode = mode.BALL;
static boolean FirstFreezeCheck = false;
static boolean isFrozen = false;
static boolean debug = true;
static boolean art = false;
static boolean isSlo = false;
static Coord mouseLocation = new Coord (0,0);
static Coord curMouseLoc = new Coord(0,0);
static boolean mouseInScreen;
static boolean mousePressed;
static Coord startLocation;
static Coord endLocation;
static Point windowLocation;
static long oldT;
static long newT;
static int oldHeight;
static int oldWidth;
public static void initilizeWall()
{
/*walls = new Item[] { new Wall(-100,100,attempt.getWidth()+100,-100), // floor
new Wall(-100,attempt.getHeight()+100,100,-100 ), // leftwall
new Wall(attempt.getWidth()-100,attempt.getHeight()+100,attempt.getWidth()+100,-100), // rightwall
new Wall(-100,attempt.getHeight()+100,attempt.getWidth()+100,attempt.getHeight()-100), // ceiling
new Wall(600,600,850,450),
new RoundWall(400,400,60),
new RoundWall(800,400,2)
}; // Wall array
wallSize = walls.length;*/
walls.clear();
walls.add(new Wall(-100,100,attempt.getWidth()+100,-100)); // floor
walls.add(new Wall(-100,attempt.getHeight()+100,100,-100 )); //leftwall
walls.add(new Wall(attempt.getWidth()-100,attempt.getHeight()+100,attempt.getWidth()+100,-100)); // rightwall
walls.add(new Wall(-100,attempt.getHeight()+100,attempt.getWidth()+100,attempt.getHeight()-100)); //ceiling
wallSize = walls.size();
}
public static void inintilizeProj() //initilize projectile array.
{
if (!pro.isEmpty())
pro.clear();
//pro.add(new Proj(300,300,PLAYER_SIZE));
//pro.add(new Proj(500,300,PLAYER_SIZE));
//pro.add(new Proj(300,300,PLAYER_SIZE));
//pro.add(new Proj(250,250,PLAYER_SIZE/2));
//pro.add(new Proj(250,250,PLAYER_SIZE/2));
//pro.add(new Proj(250,250,PLAYER_SIZE/2));
//pro.add(new Proj(250,250,PLAYER_SIZE/3));
//pro.add(new Proj(250,250,PLAYER_SIZE/4));
//pro.add(new Proj(250,250,PLAYER_SIZE/1.5));
//pro.add(new Proj(250,250,PLAYER_SIZE*2));
proSize = pro.size();
/*pro = new Proj[] { new Proj(300,300,PLAYER_SIZE),
new Proj(250,250,PLAYER_SIZE/2),
new Proj(250,250,PLAYER_SIZE/2),
new Proj(250,250,PLAYER_SIZE/2),
new Proj(250,250,PLAYER_SIZE/3),
new Proj(250,250,PLAYER_SIZE/4),
new Proj(250,250,PLAYER_SIZE/1.5)
};
pro[0]._mass = pro[1]._mass;
proSize = pro.length;*/
}
@Override // Overriding paint of Jpanel
public void paintComponent(Graphics g) {
//super.paint(g);
if (CurMode != mode.CRAZY)
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
putItems(g2d);
if(CurMode == mode.PAUSE) //pause menu
{
ipText.grabFocus();
Color tempCol = new Color(25,30,30,200);
g2d.setColor(tempCol);
g2d.fillRect(0, 0, attempt.getWidth(), attempt.getHeight());
g2d.setColor(Color.WHITE);
Font font = new Font ("Arial", 10, 50);
g2d.setFont(font);
String str = "Paused";
g2d.drawString(str, attempt.getWidth()/2- str.length()*12, attempt.getHeight()/2);
/*
font = new Font ("Arial", 10, 15);
g2d.setFont(font);
g2d.drawString("if you want to connect to another computer, put the ip here: " , attempt.getWidth()/2- str.length()*12, attempt.getHeight()/2 + 50);
ipText.setBounds(attempt.getWidth()/2 - str.length()*12 + 380, attempt.getHeight()/2 + 38, 200, 15);
g2d.setColor(new Color(255,255,255,100));
g2d.fillRect(attempt.getWidth()/2 - str.length()*12 + 380, attempt.getHeight()/2 + 38, 200, 15);
*/
}
else
{
ipText.setBounds(0,0,0,0);
}
}
public void putItems(Graphics2D g2d)
{
g2d.setColor(Color.black);
if (!pro.isEmpty())
{
for (int i = 0; i < proSize; i++) //paints projectiles
{
if (i == 0)
g2d.setColor(Color.blue);
if (i == 1)
g2d.setColor(Color.red);
Putstuff.putProj(pro.get(i),g2d); // Paint projectiles
g2d.setColor(Color.black);
}
}
g2d.setColor(Color.red);
//g2d.fillOval((int)(pro[1].cord1._x - pro[1]._rad), (int)(pro[1].cord1._y - pro[1]._rad), (int)pro[1]._rad*2, (int)pro[1]._rad*2); // Paint negetive proj
g2d.setColor(Color.black);
for (int i = 0; i < wallSize; i++) // Paints walls
{
if (!walls.isEmpty())
{
if (!walls.isEmpty() && walls.get(i) instanceof Wall)
Putstuff.putWall((Wall)walls.get(i),g2d);
if (!walls.isEmpty() && walls.get(i) instanceof RoundWall)
Putstuff.putRoundwall((RoundWall)walls.get(i),g2d);
}
}
if (startLocation != null) //if the cursor is clicked (a new item is added) draw a display
{
switch(CurMode)
{
case BALL:
{
double rad = Physics.CoordDist(startLocation, curMouseLoc)/2;
Coord cent = Physics.findMiddle(startLocation, curMouseLoc);
Proj temp = new Proj(cent, rad);
Putstuff.putProj(temp,g2d);
}
case RWALL:
{
double rad = Physics.CoordDist(startLocation, curMouseLoc)/2;
Coord cent = Physics.findMiddle(startLocation, curMouseLoc);
RoundWall temp = new RoundWall(cent, rad);
Putstuff.putRoundwall(temp,g2d);
break;
}
case VBALL:
{
double rad;
if (pro.isEmpty())
rad = PLAYER_SIZE/2;
else
rad = pro.get(pro.size()-1)._rad;
Coord cent = startLocation;
Proj temp = new Proj(cent, rad);
Putstuff.putProj(temp,g2d);
Coord strtLoc = startLocation.intoJcoord();
Coord curMseLoc = curMouseLoc.intoJcoord();
if (key[keyCode.SHIFT.code])
{
if (Math.abs(curMseLoc._x - strtLoc._x) >= Math.abs(curMseLoc._y - strtLoc._y))
curMseLoc._y = strtLoc._y;
else if (Math.abs(curMseLoc._x - strtLoc._x) < Math.abs(curMseLoc._y - strtLoc._y))
curMseLoc._x = strtLoc._x;
}
g2d.drawLine((int)strtLoc._x, (int)strtLoc._y, (int)curMseLoc._x, (int)curMseLoc._y);
break;
}
case WALL:
{
double minX = Math.min(startLocation._x, curMouseLoc._x);
double maxX = Math.max(startLocation._x, curMouseLoc._x);
double minY = Math.min(startLocation._y, curMouseLoc._y);
double maxY = Math.max(startLocation._y, curMouseLoc._y);
Coord c1 = new Coord(minX, maxY);
Coord c2 = new Coord(maxX, minY);
Wall temp = new Wall(c1,c2);
Putstuff.putWall(temp,g2d);
break;
}
case ERASE:
double minX = Math.min(startLocation._x, curMouseLoc._x);
double maxX = Math.max(startLocation._x, curMouseLoc._x);
double minY = Math.min(startLocation._y, curMouseLoc._y);
double maxY = Math.max(startLocation._y, curMouseLoc._y);
Coord c1 = new Coord(minX, maxY);
Coord c2 = new Coord(maxX, minY);
Wall temp = new Wall(c1,c2);
Putstuff.putErase(temp,g2d);
break;
default:
{
break;
}
}
}
Coord loc = curMouseLoc;
if (debug)
{
g2d.drawString(" mouse location: x = " + loc._x + " y = " + loc._y , 900, 150);
if (!pro.isEmpty())
{
g2d.setColor(Color.blue);
g2d.drawString("First proj: ", 200, 150); // Debug info
g2d.setColor(Color.black);
g2d.drawString("dir = " + pro.get(0)._vel.getDir(), 200, 175);
g2d.drawLine(350, 175, 350 + (int)(10 * Math.cos(pro.get(0)._vel.getDir())), 175 - (int)(10 * Math.sin(pro.get(0)._vel.getDir())));
g2d.fillOval(347 + (int)(10 * Math.cos(pro.get(0)._vel.getDir())), 172 - (int)(10 * Math.sin(pro.get(0)._vel.getDir())), 5, 5);
g2d.drawString("speed = " + pro.get(0)._vel.getSize(), 200, 200);
g2d.drawString("rad = " + pro.get(0)._rad, 200, 225);
g2d.drawString("x = " + pro.get(0).cord1._x + "\t y = " + pro.get(0).cord1._y, 200, 250);
if (pro.size() > 1)
{
g2d.setColor(Color.red);
g2d.drawString("Second proj: ", 500, 150); // Debug info
g2d.setColor(Color.black);
g2d.drawString("dir = " + pro.get(1)._vel.getDir(), 500, 175);
g2d.drawLine(650, 175, 650 + (int)(10 * Math.cos(pro.get(1)._vel.getDir())), 175 - (int)(10 * Math.sin(pro.get(1)._vel.getDir())));
g2d.fillOval(647 + (int)(10 * Math.cos(pro.get(1)._vel.getDir())), 172 - (int)(10 * Math.sin(pro.get(1)._vel.getDir())), 5, 5);
g2d.drawString("speed = " + pro.get(1)._vel.getSize(), 500, 200);
g2d.drawString("rad = " + pro.get(1)._rad, 500, 225);
g2d.drawString("x = " + pro.get(1).cord1._x + "\t y = " + pro.get(1).cord1._y, 500, 250);
}
double energy = 0;
for (int i = 0; i < proSize; i++)
energy += Physics.Energy(pro.get(i));
g2d.drawString("Energy = " + energy , 200, 300);
}
g2d.drawString("num of Proj: " + proSize , 200, 400);
g2d.drawString("total bounce's: " + totalBounce , 200, 450);
g2d.drawString("total distance: " + totalDist , 200, 500);
g2d.setColor(Color.white);
g2d.drawString("FPS = " + 100/FPS , 1000, 50);
g2d.drawString("curState = " + curState , 1100, 50);
if (ip != null)
g2d.drawString("ip = " + ip, 700,50);
}
g2d.drawString("Relevant keys:" , 5, 100);
g2d.drawString("B- ball" , 5, 120);
g2d.drawString("V- vball" , 5, 140);
g2d.drawString("W- wall" , 5, 160);
g2d.drawString("M- rwall" , 5, 180);
g2d.drawString("E- erase" , 5, 200);
g2d.drawString("G- grav" , 5, 220);
g2d.drawString("H- dirgrav" , 5, 240);
g2d.drawString("F- freeze" , 5, 260);
g2d.drawString("C- crazy" , 5, 280);
g2d.drawString("D- debug" , 5, 300);
g2d.drawString("S- slowmo" , 5, 320);
g2d.drawString("R- reset" , 5, 340);
if (isFrozen)
{
g2d.drawString("Press < while frozen to rewind to 0.1 earlier, or > to go forward" , 200, attempt.getHeight() - 30);
}
if (isSlo)
{
g2d.drawString("Slow Mo" , 200, attempt.getHeight() - 10);
}
switch (CurMode)
{
case BALL:
g2d.drawString("Current Mode: Ball" , 100, 50);
g2d.drawString("Press and hold the mouse to create a bouncing ball" , 200, attempt.getHeight() - 50);
break;
case RWALL:
g2d.drawString("Current Mode: Round Wall" , 100, 50);
g2d.drawString("Press and hold the mouse to create a ball shaped wall" , 200, attempt.getHeight() - 50);
break;
case VBALL:
g2d.drawString("Current Mode: Launch Ball" , 100, 50);
g2d.drawString("Press and hold the mouse to launch a bouncing ball at a controlled velocity" , 200, attempt.getHeight() - 50);
break;
case WALL:
g2d.drawString("Current Mode: Wall" , 100, 50);
g2d.drawString("Press and hold the mouse to create a rectangular wall" , 200, attempt.getHeight() - 50);
break;
case ERASE:
g2d.drawString("Current Mode: Erase" , 100, 50);
g2d.drawString("Press and hold the mouse erase objects" , 200, attempt.getHeight() - 50);
break;
case PAUSE:
g2d.drawString("paused" , 100, 50);
break;
case CRAZY:
g2d.drawString("CRAZY" , 100, 50);
g2d.drawString("CRAZY MODE" , 200, attempt.getHeight() - 50);
break;
default:
break;
}
}
public attempt() { // Implementing keylistener
InputManager manage = new InputManager();
KeyListener Klistener = manage.new MyActionListener();
MouseListener Mlistener = manage.new MyActionListener();
MouseMotionListener MMlistener = manage.new MyActionListener();
addKeyListener(Klistener);
addMouseListener(Mlistener);
addMouseMotionListener(MMlistener);
ipText.addKeyListener(Klistener);
setFocusable(true);
}
public static class SaveState extends TimerTask
{
@Override
public void run() {
if (!isFrozen)
{
states.add(new gamestate(pro,walls));
if (states.size() > 100)
states.removeFirst();
curState = states.size()-1;
}
}
}
public static class gameloop extends TimerTask
{
public attempt at;
static int action; //the action that the player is taking this frame
public gameloop(attempt att)
{
at = att;
}
public static void processInput()
{
if (key[keyCode.RESET.code])
{
System.out.println("reset");
inintilizeProj();
}
if (key[keyCode.BALL.code])
{
System.out.println("Ball");
CurMode = mode.BALL;
}
if (key[keyCode.VBALL.code])
{
System.out.println("Velocity Ball");
CurMode = mode.VBALL;
}
if (key[keyCode.WALL.code])
{
System.out.println("Wall");
CurMode = mode.WALL;
}
if (key[keyCode.RWALL.code])
{
System.out.println("Round Wall");
CurMode = mode.RWALL;
}
if (keyReleased[keyCode.PAUSE.code])
{
if (CurMode != mode.PAUSE)
{
lastMode = CurMode;
System.out.println("pause");
CurMode = mode.PAUSE;
}
else
CurMode = lastMode;
}
if (keyReleased[keyCode.GRAV.code])
{
System.out.println("Gravity");
if (Physics.grav.getSize() != 0)
Physics.grav.setSize(0);
else if (Physics.grav.getSize() == 0)
Physics.grav = new Vect(900, (float)(3*Math.PI/2));
}
if (keyReleased[keyCode.DEBUG.code])
{
debug = !debug;
}
if (keyReleased[keyCode.SLOMO.code])
isSlo = !isSlo;
if (isFrozen && keyReleased[keyCode.REWIND.code])
{
if (curState > 1)
curState--;
if (curState >= 0 && !states.isEmpty())
{
pro.clear();
walls.clear();
for (Proj p : states.get(curState).pro)
{
pro.add(p);
}
for (Item w : states.get(curState).walls)
{
walls.add(w);
}
}
proSize = pro.size();
wallSize = walls.size();
}
if (isFrozen && keyReleased[keyCode.FORWARD.code])
{
if (curState < states.size()-1)
curState++;
if (curState >= 0 && curState < states.size() && !states.isEmpty())
{
pro.clear();
walls.clear();
for (Proj p : states.get(curState).pro)
pro.add(p);
for (Item w : states.get(curState).walls)
walls.add(w);
}
proSize = pro.size();
wallSize = walls.size();
}
if (key[keyCode.ERASE.code])
{
System.out.println("Erase");
CurMode = mode.ERASE;
}
if (keyReleased[keyCode.SGRAV.code] && (key[keyCode.UP.code] || key[keyCode.DOWN.code] || key[keyCode.RIGHT.code] || key[keyCode.LEFT.code]))
{
System.out.println("Gravity sideways");
float dir;
Vect tempDir = new Vect(0,0.0);
Vect up = new Vect(1, (float)(Math.PI/2));
Vect down = new Vect(1, (float)(3*Math.PI/2));
Vect left = new Vect(1, (float)(Math.PI));
Vect right = new Vect(1, (float)(0));
if (key[keyCode.UP.code])
tempDir = Vec_Math.vectAdd(tempDir, up);
if (key[keyCode.DOWN.code])
tempDir = Vec_Math.vectAdd(tempDir, down);
if (key[keyCode.LEFT.code])
tempDir = Vec_Math.vectAdd(tempDir, left);
if (key[keyCode.RIGHT.code])
tempDir = Vec_Math.vectAdd(tempDir, right);
dir = tempDir.getDir();
Physics.grav.setDir(dir);
}
if (keyReleased[keyCode.CRAZY.code])
{
if (CurMode != mode.CRAZY)
{
lastMode = CurMode;
CurMode = mode.CRAZY;
}
else if (CurMode == lastMode)
CurMode = mode.BALL;
else
{
CurMode = lastMode;
}
}
if (keyReleased[keyCode.ART.code])
{
art = !art;
}
if (key[keyCode.FREEZE.code] && !isFrozen)
{
isFrozen = true;
}
if (keyReleased[keyCode.FREEZE.code] && !FirstFreezeCheck)
{
FirstFreezeCheck = true;
}
else if (keyReleased[keyCode.FREEZE.code] && FirstFreezeCheck)
{
isFrozen = false;;
FirstFreezeCheck = false;
while (states.size() >= curState+1)
states.remove(curState);
curState = states.size();
}
if (mousePressed && startLocation == null)
startLocation = new Coord(mouseLocation);
if (!mousePressed && startLocation != null)
{
endLocation = new Coord(mouseLocation);
switch(CurMode)
{
case BALL:
{
double rad = Physics.CoordDist(startLocation, endLocation)/2;
Coord cent = Physics.findMiddle(startLocation, endLocation);
if (rad != 0)
{
pro.add(new Proj(cent, rad));
proSize++;
}
break;
}
case WALL:
{
double minX = Math.min(startLocation._x, endLocation._x);
double maxX = Math.max(startLocation._x, endLocation._x);
double minY = Math.min(startLocation._y, endLocation._y);
double maxY = Math.max(startLocation._y, endLocation._y);
Coord c1 = new Coord(minX, maxY);
Coord c2 = new Coord(maxX, minY);
walls.add(new Wall(c1,c2));
wallSize++;
break;
}
case RWALL:
{
double rad = Physics.CoordDist(startLocation, endLocation)/2;
Coord cent = Physics.findMiddle(startLocation, endLocation);
walls.add(new RoundWall(cent, rad));
wallSize++;
break;
}
case VBALL:
{
double rad;
if (pro.isEmpty())
rad = PLAYER_SIZE/2;
else
rad = pro.get(pro.size()-1)._rad;
Coord cent = startLocation;
double dir = Math.atan2(startLocation._y - endLocation._y, startLocation._x - endLocation._x);
double size = Physics.CoordDist(startLocation, endLocation)*10;
if (size > 3000) //to prevent passing through walls.
size = 3000;
Vect vel = new Vect ((float)size, (float)dir);
if (key[keyCode.SHIFT.code])
{
if (Math.abs(vel.getX()) >= Math.abs(vel.getY()))
vel.setY(0);
else if (Math.abs(vel.getX()) < Math.abs(vel.getY()))
vel.setX(0);
}
pro.add(new Proj(cent, vel, rad));
proSize++;
break;
}
case ERASE:
{
int sumProErased = 0;
int sumWallErased = 0;
double minX = Math.min(startLocation._x, endLocation._x);
double maxX = Math.max(startLocation._x, endLocation._x);
double minY = Math.min(startLocation._y, endLocation._y);
double maxY = Math.max(startLocation._y, endLocation._y);
Coord c1 = new Coord(minX, maxY);
Coord c2 = new Coord(maxX, minY);
Wall temp = new Wall(c1,c2);
for (int i = 0; i < proSize; i++)
{
if (pro.get(i).isCol2(temp))
{
pro.remove(i);
proSize--;
sumProErased++;
i=-1; //the for loop will automatilcally do i++;
}
}
for (int i = 4; i < wallSize; i++)
{
if (walls.get(i).isCol(temp))
{
walls.remove(i);
wallSize--;
sumWallErased++;
i=3; //the for loop will automatilcally do i++;
}
}
System.out.println("Erased " + sumProErased + " projectiles and " + sumWallErased + " walls");
break;
}
default:
{
System.out.println("Got default in mode switch case");
break;
}
}
startLocation = null;
endLocation = null;
}
for (int i = 0; i < keyReleased.length ; i++)
keyReleased[i] = false;
}
public void run()
{
windowLocation = attempt.getLocation();
if (oldHeight != attempt.getHeight() || oldWidth != attempt.getWidth())
initilizeWall();
oldHeight = attempt.getHeight();
oldWidth = attempt.getWidth();
newT = System.currentTimeMillis(); //gets new time from the system.
if (CurMode == mode.PAUSE || isFrozen)
oldT = System.currentTimeMillis(); //if paused, make it so time doesnt pass
if (isSlo)
newT = oldT + FPS*(newT - oldT)/2;
long deltaT = newT - oldT; //gets the difference of the times between last frame and now.
if (CurMode != mode.PAUSE)
ipText.setText("");
// Upply gravity and friction to all projectiles.
if (!pro.isEmpty())
{
Physics.applyG(pro, proSize);
Physics.applyFric(pro, proSize);
}
for (int i = 0; i < proSize; i++) // Check all combination of items that can collide with each other
{
for (int j = 0; j < wallSize; j++)
{
if (Physics.areColliding((Item)pro.get(i),(Item)walls.get(j)))
{
totalBounce++;
System.out.println("bounce wall");
Physics.collision(pro.get(i),(Item)walls.get(j));
}
}
}
for (int i = 0; i < proSize; i++) // Check all combination of items that can collide with each other
{
for (int j = i+1; j < proSize; j++)
{
if (Physics.areColliding((Item)pro.get(i),(Item)pro.get(j)))
{
totalBounce++;
System.out.println("bounce");
Physics.collision(pro.get(i),pro.get(j));
}
}
}
for (int i = 0; i < proSize; i++) // apply speed to projectiles.
{
pro.get(i).cord1._x += deltaT*pro.get(i)._vel.getX()/1000; //divide by 1000 because messured by milliseconds.
pro.get(i).cord1._y += deltaT*pro.get(i)._vel.getY()/1000;
totalDist += deltaT*pro.get(i)._vel.getSize()/1000;
if (wallSize > 4)
{
if (pro.get(i).cord1._x < ((Wall)walls.get(1)).cord2._x)
pro.get(i).cord1._x = ((Wall)walls.get(1)).cord2._x + pro.get(i)._rad - 0.5;
if (pro.get(i).cord1._x > walls.get(2).cord1._x)
pro.get(i).cord1._x = walls.get(2).cord1._x - pro.get(i)._rad + 0.5;
if (pro.get(i).cord1._y < walls.get(0).cord1._y)
pro.get(i).cord1._y = walls.get(0).cord1._y + pro.get(i)._rad - 0.5;
if (pro.get(i).cord1._y > ((Wall)walls.get(3)).cord2._y)
pro.get(i).cord1._y = ((Wall)walls.get(3)).cord2._y - pro.get(i)._rad + 0.5;
}
}
at.repaint(); //repaint the screen
processInput();
oldT = System.currentTimeMillis();; //update oldT to newT to remember this frames time for the next frame.
}
}
public static void main(String[] args)
{
for (int i = 0 ; i < key.length ; i++) {
key[i] = false;}
inintilizeProj();
oldT = System.currentTimeMillis();
JFrame frame = new JFrame("game");
frame.add(attempt);
frame.setSize(1800, 1000); //setting window size
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
oldHeight = 1000;
oldWidth = 1800;
//int flipXcnt = 1;
//int flipYcnt = 1;
TimerTask gameloop = new gameloop(attempt);
TimerTask SaveState = new SaveState();
Timer timer = new Timer(true);
attempt.add(ipText);
timer.scheduleAtFixedRate(gameloop, 0, FPS); //setting fps
timer.scheduleAtFixedRate(SaveState,0,100);
}
}
|
Go
|
UTF-8
| 5,292 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
package beanstalk
import (
"crypto/sha1"
"encoding/hex"
"strconv"
"github.com/hashicorp/terraform/helper/schema"
)
type integrationType struct {
Name string
Attributes map[string]*schema.Schema
WriteOnlyAttributes []string
}
// The Beanstalk API has "integration" as a concept, but it is an abstract
// type that has a separate subtype for each integration type. Thus the
// implementation here is abstract and is instantiated for each of the
// physical resources.
func (it *integrationType) resource() *schema.Resource {
resourceSchema := map[string]*schema.Schema{
"id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"repository_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
}
for k, v := range it.Attributes {
resourceSchema[k] = v
}
return &schema.Resource{
Read: func(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Client)
return it.Read(d, client)
},
Create: func(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Client)
return it.Create(d, client)
},
Update: func(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Client)
return it.Update(d, client)
},
Delete: func(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Client)
return it.Delete(d, client)
},
Schema: resourceSchema,
}
}
func (it *integrationType) Read(d *schema.ResourceData, client *Client) error {
repositoryName := d.Get("repository_name").(string)
integrationId := d.Id()
data := map[string]interface{}{}
err := client.Get([]string{"repositories", repositoryName, "integrations", integrationId}, nil, &data)
if err != nil {
return err
}
it.refreshFromJSON(d, data["integration"].(map[string]interface{}))
return nil
}
func (it *integrationType) Create(d *schema.ResourceData, client *Client) error {
req := it.prepareForJSON(d)
type responseIntegration struct {
Id int `json:"id"`
}
type response struct {
Integration responseIntegration `json:"integration"`
}
res := &response{}
repositoryName := d.Get("repository_name").(string)
err := client.Post([]string{"repositories", repositoryName, "integrations"}, req, res)
if err != nil {
return err
}
d.SetId(strconv.Itoa(res.Integration.Id))
return nil
}
func (it *integrationType) Update(d *schema.ResourceData, client *Client) error {
req := it.prepareForJSON(d)
repositoryName := d.Get("repository_name").(string)
integrationId := d.Id()
return client.Put([]string{"repositories", repositoryName, "integrations", integrationId}, req, nil)
}
func (it *integrationType) Delete(d *schema.ResourceData, client *Client) error {
repositoryName := d.Get("repository_name").(string)
integrationId := d.Id()
return client.Delete([]string{"repositories", repositoryName, "integrations", integrationId})
}
func (it *integrationType) prepareForJSON(d *schema.ResourceData) map[string]interface{} {
ret := map[string]interface{}{}
ret["type"] = it.Name
isNew := d.IsNewResource()
for k, s := range it.Attributes {
if isNew || d.HasChange(k) {
ret[k] = prepareForJSON(s, d.Get(k))
}
}
return map[string]interface{}{
"integration": ret,
}
}
func (it *integrationType) refreshFromJSON(d *schema.ResourceData, data map[string]interface{}) {
for k, s := range it.Attributes {
wo := false
for _, a := range it.WriteOnlyAttributes {
if k == a {
wo = true
break
}
}
if !wo {
d.Set(k, decodeFromJSON(s, data[k]))
}
}
}
func prepareForJSON(s *schema.Schema, value interface{}) interface{} {
// This supports only what's required for the structures used by
// Beanstalk's integrations. Almost all fields are primitive types,
// but the modular webhook integration uses a nested object.
switch s.Type {
case schema.TypeList:
if s.MaxItems == 1 {
elem := s.Elem
if resource, ok := elem.(*schema.Resource); ok {
ret := map[string]interface{}{}
values := value.([]interface{})
valueMap := values[0].(map[string]interface{})
for k, s := range resource.Schema {
ret[k] = prepareForJSON(s, valueMap[k])
}
return ret
} else {
return prepareForJSON(elem.(*schema.Schema), value)
}
}
break
default:
// No transformation for other types
return value
}
// Unreachable
return nil
}
func decodeFromJSON(s *schema.Schema, value interface{}) interface{} {
// This supports only what's required for the structures used by
// Beanstalk's integrations. Almost all fields are primitive types,
// but the modular webhook integration uses a nested object.
switch s.Type {
case schema.TypeList:
if s.MaxItems == 1 {
elem := s.Elem
if resource, ok := elem.(*schema.Resource); ok {
ret := map[string]interface{}{}
valueMap := value.(map[string]interface{})
for k, s := range resource.Schema {
ret[k] = decodeFromJSON(s, valueMap[k])
}
return []interface{}{ret}
} else {
return value
}
}
break
default:
// No transformation for other types
return value
}
// Unreachable
return nil
}
func hashForState(v interface{}) string {
switch v.(type) {
case string:
hash := sha1.Sum([]byte(v.(string)))
return hex.EncodeToString(hash[:])
default:
return ""
}
}
|
Python
|
UTF-8
| 1,835 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
def broken_dist(dist):
"""count=0
for i in xrange(dist):
if '3' not in str(i):
count+=1
return count"""
#return len([i for i in xrange(dist) if '3' not in str(i)])
count=0
for i in xrange(dist):
while i!=0:
rem=i%10
if rem==3: break
i/=10
else:
count+=1
return count
def next_num_gen():
count=0
num=0
mydict = {}
while True:
num+=1
curnum=num
while curnum!=0:
rem=curnum%10
if rem==3: break
curnum/=10
else:
count+=1
mydict[num]=count
yield num, mydict
def dict_search():
mydict={}
curmax = 0
numgen = next_num_gen()
for tc in xrange(int(raw_input())):
#print broken_dist(int(raw_input()))
num = int(raw_input())
while curmax<num:
curmax, mydict = numgen.next()
print mydict
print mydict[num]
def next_num_gen_list():
count=0
num=0
mylist = []
while True:
num+=1
curnum=num
while curnum!=0:
rem=curnum%10
if rem==3: break
curnum/=10
else:
count+=1
mylist.append(count)
yield num, mylist
def list_search():
mylist=[]
curmax = 0
numgen = next_num_gen_list()
for tc in xrange(int(raw_input())):
#print broken_dist(int(raw_input()))
num = int(raw_input())
while curmax<num:
curmax, mylist = numgen.next()
#print mylist
print mylist[num-1]
if __name__ == "__main__":
#for tc in xrange(int(raw_input())):
#print broken_dist(int(raw_input()))
#dict_search() #too much memory used, slowing it down
list_search()
|
Markdown
|
UTF-8
| 2,550 | 2.71875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
<a id="group__intmapentry__words"></a>
# Integer Map Entries
Generic integer map entries are key-value pairs. Type-specific entries extend this generic type with implementation-dependent data.
**Requirements**:
* Map entry words use one single cell.
* Map entries must store at least a key and a value.
**Parameters**:
* **Key**: A word in the general case but can be a native integer for integer maps.
* **Value**: A word.
**Cell Layout**:
On all architectures the single-cell layout is as follows:
digraph {
node [fontname="Lucida Console,Courier" fontsize=14];
mapentry_word [shape=none, label=<
<table border="0" cellborder="1" cellspacing="0">
<tr><td border="0"></td>
<td sides="B" width="40" align="left">0</td><td sides="B" width="40" align="right">7</td>
<td sides="B" width="120" align="left">8</td><td sides="B" width="120" align="right">n</td>
</tr>
<tr><td sides="R">0</td>
<td href="@ref WORD_TYPEID" title="WORD_TYPEID" colspan="2">Type</td>
<td sides="R" colspan="2"></td>
</tr>
<tr><td sides="R">1</td>
<td colspan="4" sides="BR" width="320">Type-specific data</td>
</tr>
<tr><td sides="R">2</td>
<td href="@ref WORD_INTMAPENTRY_KEY" title="WORD_INTMAPENTRY_KEY" colspan="4">Key</td>
</tr>
<tr><td sides="R">3</td>
<td href="@ref WORD_MAPENTRY_VALUE" title="WORD_MAPENTRY_VALUE" colspan="4">Value</td>
</tr>
</table>
>]
}
## Submodules
* [Integer Trie Leaves](group__minttrieleaf__words.md#group__minttrieleaf__words)
* [Immutable Integer Trie Leaves](group__inttrieleaf__words.md#group__inttrieleaf__words)
## Integer Map Entry Accessors
<a id="group__intmapentry__words_1ga89e26360d76aaad985afd89da56d1539"></a>
### Macro WORD\_INTMAPENTRY\_KEY
![][public]
```cpp
#define WORD_INTMAPENTRY_KEY (((intptr_t *)(word))[2])( word )
```
Get/set key of integer map entry.
**Parameters**:
* **word**: Word to access.
?> Macro is L-Value and suitable for both read/write operations.
[public]: https://img.shields.io/badge/-public-brightgreen (public)
[C++]: https://img.shields.io/badge/language-C%2B%2B-blue (C++)
[private]: https://img.shields.io/badge/-private-red (private)
[Markdown]: https://img.shields.io/badge/language-Markdown-blue (Markdown)
[static]: https://img.shields.io/badge/-static-lightgrey (static)
|
Markdown
|
UTF-8
| 31,733 | 2.9375 | 3 |
[] |
no_license
|
Byron Trial Notes, Day 21 (Week 5)
==================================
(Late start because judge had sentencing)
* Anderson takes stand.
* C: Dr. Anderson wants to clarify something from yesterday.
* When asked about the subway bombings, what the approximate amount of explosives used in the bomb and said it was 2-3kg but it was 2-5kg. I further wanted to clarify that there were four attacks and that is the amount estimated per attack.
* D: Dr. Anderson, I believe we finished discussing how one could make TATP. And it would take you 2 to 4 hours to make 200 grams of TATP, given your experience. And it would take longer without that experience?
* Absolutely.
* By the end of that stage, there is crude TATP. It has precipitated from the liquid, and there's still liquid that is very acidic. So what is the next step?
* You would filter.
* Would the Buncher funnel work?
* Yes.
* Would you agree that is a standard tool in a lab?
* Not that kit.
* But a Buchner funnel and a vacuum?
* Yes.
* And an alternative would be to use gravitational filter, like pouring it into something like a coffee filter?
* Yes.
* Using the filtration apparatus, one could filter more quickly.
* Yes.
* (New picture) Am I correct that the Buchner funnel would go on top of the rectangular container?
* Yes.
* And you would put a filter in, or the TATP would just go through?
* Yes.
* And you would seal it, so you could make a vacuum.
* You don't remove all the air, but you would make a difference in pressure.
* Certainly, you couldn't make a perfect vacuum with a hand pump?
* Yes.
* Now at some point, once most of the liquid is gone, some liquid would be left but air would start getting pulled through.
* Sometimes you wash it with Sodium Bicarbonate ?
* Yes. I just use cold water.
* To neutralize the acid?
* Yes.
* And in fact, any time you're working with an acid, it is a good safety precaution of have a sodium bicarbonate solution on hand?
* Some people just use water...
* Then you would purify it with methyl hydrate
* And you wouldn't put it in type with a heating element?
* that would be unwise.
* So you would use what is essentially be a double boiler?
* Yes.
* So you would dissolve the TATP in boiling methanol?
* Yes. Supersaturate it.
* And then when you cooled it would recrystalize.
* Yes.
* And you wouldn't want to use lots of methyl hydrate with a little TATP? Because otherwise it wouldn't recrystalize out.
* We've worked out the optimal amounts.
* Explain saturation?
* The point you can't dissolve any more.
* Does the saturation vary with temperature.
* You do it when it is boiling because it takes up the maximum amount.
* And that's why you cool it. Because then it would be supersaturated.
* It's hard to keep it supersaturated...
* Then it would cyrstalize out, if there was a small impurity or crystal?
* Yes.
* How long would that take, for 200 grams.
* 15 min half an hour our to cool, then an hour in the fridge
* And the boiling and dissolving?
* An hour? Two to three hours for the whole thing.
* And how long to filter the crystals out?
* 15 minutes or so.
* And filtering it initially, I don't think I asked about it?
* Oh a few minutes with a vacuum pump.
* So that takes 4 to 7 hours.
* Yes, but you can have some overlap between batches.
* But you can't really do the acid adding in parallel, because it needs careful monitoring?
* Yes. It's very sensitive.
* How much volume is 200 grams of TATP?
* About 400 milileters.
* And if one did that 15 times, you'd get several liters of TATP?
* Yes.
* And you mentioned you use anti-static bags to store explosives?
* Yes.
* Would that hold any where close to six liters?
* I think we both know the answer is no.
* And you agree that there are other uses? That they are standard for storing electronics or anything sensitive to static electricity?
* Yes.
* Now your report is only in as a guide, but I wanted to draw attention... You say that acetone is a key component of TATP and HTMD...
* That is an error. It is not needed for HTMD.
* Back to TATP, once one is done the filtering of crystals, would one need to do anything?
* You need to let it dry. Put it on some TATP on paper towel and air dry?
* Now it would be covered in methanol?
* It would evaporate...
* Would a drying box be appropriate? Would the chemicals at the bottom that pull water out work for methanol?
* I don't really know. We air dry our TATP.
* How long would it take to air dry?
* Yes.
* To dry it you spread it out?
* Yes, to optimize the drying process.
* If you didn't, some at the middle or the bottom... it would take longer.
* It would certainly...
* If you had 6 liters of TATP, you would want to spread it thinly...
* It's a brave person that works with 3 kg of TATP.
* Now lets go to HTMD.
* One uses Hexamine... And there are acids, but the most common is citric acid?
* Yes.
* It's common as something one adds in canning?
* That sounds right. I don't have personal experience.
* If one was of the things it would be used is to prevent cans you make exploding?
* I'm not sure.
* I have down that you use it as a food aditive.
* Lets get into the production of HMTD...
* I don't want to get into specific quantities.
* I will stipulate that one wants to make HMTD in small amounts, 20 grams or 50 grams. It would take 2 to 4 hours...
* That is with your experience?
* Yes. I've done more remotely with special reactors, but I think it is clear that nothing like that was going on here.
* 50 grams is with my experience. You need to not just make it cold, but within a specific range.
* The first step is to dissolve hexamine it in hydrogen peroxide.
* Yes.
* Given the quantities of hexamine present, can you indicate if the hexamine or the hydrogen peroxide is the limiting reactant?
* Hexamine.
* There are 10 moles of hexamine. We require 15 moles of hydrogen peroxide. The volume depends on concentration...
* If you made the maximum of TATP, you wouldn't have enough to make the maximum amount of HTMD...
* You would have to use half the hydrogen peroxide...
* Now you add acid?
* Yes, but since citric acid is weak, you can add it at once.
* You need to keep it in a certain temperature range?
* For that amount, I'd be comfortable with between 20 to 30 Celcius.
* You need to actively monitor it?
* Yes.
* And you're left with crystals and a solution.
* Yes, but the solution isn't as acidic. And you don't need to recrystalize.
* A few hours.
* 4 to 7 hours?
* An expert in four, someone else would do it in 6 to 7 hours.
* And you'd have to do about 20 batches to make the full amount?
* Yes. If you did it in small batches.
* Someone working outside the government...
* Now Urea nitrate?
* Urea, add acid.
* It crystalizes out.
* It's a fairly forgiving process.
* I don't beleive you gave an estimate of how much urea nitrate could be produced. Could you do so?
* No, I didn't say that.
* ... 0.8 kilos of urea there....
* J: Lets take the morning break while Dr. Anderson calcuates.
(Break)
* Dr. Anderson, are you able to advise of the result of your calculuation as to how much urea nitrate could be produced from the ingredients found?
* The theoretical yeild is about 1.7 kilos... When you use chemicals you can add to make nitric acid in solution, and based on a 60% yield, you get about 750 grams.
* The 1.7 kilos is if there had been a sufficient amount of nitric acid...
* Assuming 100% yeild.
* You understand that nitric acid was not found...
* Yes.
* And my understanding of your evidence is that you could either make nitric acid from other things either separately or in situ.
* Yes.
* Do you have any concerns about making all 700 grams at once?
* No, we made 10 kilos at once.
* Because it is less sensitive?
* Yes.
* It is a secondary explosive. Where as TATP and HTMD are primary explosives. They are much easier set off.
* They are the most primary of primary.
* Secondary explosives won't be set off if you just put a match to it?
* They'll burn. Depending on circumstances, it could turn into an explosion.
* How long would it take to make 700 grams?
* 2 hours.
* Wash it?
* That's in there.
* Then dry it?
* That would be a few hours.
* HDN?
* Is similar to urea nitrate, and you make it the same way.
* The classic approach would involve using nitric acid, which wasn't found. There's a secondary process...
* I should say we've never tested the secondary process. In theory it should work.
* Theoretically if one can do the in stitu process in urea nitrate, one could do it with HDN.
* How much?
* The limiting factor is nitrate... Since you need twice as much nitrate, so you might get 500 grams.
* Over the lunch, you could do more thorough calculations?
* Yes.
* Potassium chlorate, combined with a fuel, would create a propellant. If you confined it, it could detonate.
* There is a serious risk associated with chlorates.
* You said potassium chlorate is used in firework?
* Canada does not allow their import.
* A firework contains a propellant to bring it up?
* Yes.
* There may be an explosive?
* A tiny bit, to spread apart the colors.
* Potassium chlorate is used, in the states, is used as a fuel in rocketry?
* I don't know the details.
* ANFO is a combination of amonium nitate and fuels?
* Yes.
* There are different fuels you can add to amonium nitrate to make it more of an explosive?
* Yes.
* You mentioned aluminum powder?
* Yes.
* Depending on what you combined, it could also be used as a propellant?
* I don't really have expertise in that.
* You blow things up, not launch them...
* Based on the chemistry?
* I don't know that it would burn faster.
* But you could add something that would make it burn faster?
* Possibly.
* Did you look into the possibility?
* No.
* Do you have any resources? Perhaps online? Could you look over the lunch break or this evening?
* Yes.
* The oxidizers we have are .. from those you can make two other oxidizers, urea nitrate or hexamine dinitrate.
* Would you just mix the oxidizer and fuel together?
* For an explosive...
* As a fuel, you'd need to shape it and compress it.
* As an explosive, you could take amonium nitrate prills and disel, and you would have ANFO. You could do things to improve it, grinding up ...
* Yes.
* And you would need more amonium nitrate than fuel.
* Ideally you need 94% amonium nitrate by mass.
* So it would be a damp powder.
* Grinding up the amonium nitrate, that is even more important for a fuel.
* Yes.
* Because that would make it burn more evenly.
* Yes.
* And then you would need to add something to hold them together?
* Yes.
* Do you understand that Dextrin?
* Perhaps. You could also use wax and compress it together. They'd also need to be packages.
* And you talked about pressing it together?
* Yes...
* And you talked about special shapes. The purpose would be to maximize the surface area exposed to the air.
* Yes.
* You would have more of the surface of the propellant that would be propelled out the other reaction?
* Yes.
* And also because you don't want it to explode
* And you want to have it burning not just up but also outwards int the cylinder...
* Now, there were ingredients found for these explosives?
* Yes.
* And the chemicals were all stored in jars, except the drying box.
* Yes.
* And none of the materials were in any state of preparation, besides the potassium...
* I'd hesitate to say that... They were in a state they could be use.
* They were all under a workbench in jars?
* Yes.
* Hexamine was in jars on the floors, I think.
* Items in the pictures had been moved?
* Yes
* Some of the chemicals were in different places through the house?
* Yes
* Nothing was out?
* Yes
* It wasn't as though someone was right about to start a production...
* And would the drying cell have a use with the electrochemical cell?
* Yes.
* But you'd want to use the vacuum filter, first? To increase the effiiencies?
* If you're talking about just putting the liquid in, that would take much longer.
* So the lab equipment that was out had a clear use in the production of potassium chlorate.
* Yes.
* You mentioned a number of items that were of concern, though not explosive.
* Potassium permanganate could be turned into something for use in a chemical triggering mechanism.
* Other uses?
* Disinfectant, pool shock...
* As a die?
* You could. It's an oxidizer...
* You mentioned that one could make thermite yesterday.
* Yes
* Regarding the electrochemical cell. You never saw it in person?
* No, I didn't.
* Photo 28b, exhibit 57. This is an electrochemical cell?
* Yes.
* It's a standard lab set up?
* It's common, I don' know about standard
* One has the electrical on
* Cathode is the negative and electrons flow to the anode...
* The type of materials of the cathode and anode is important?
* Yes.
* And if you have the wrong type, the reaction just won't happen?
* Yes.
* And there are several materials that would work with different efficiencies?
* Yes.
* And the nature of the cell, the voltage across it... would effect the reaction occurring?
* Yes.
* You said in your examination that there's a bit of magic in how electrochemical cells work?
* It's complicated. It obviously stills work. There's competing theories.
* There's a certain amount of trial and error that can be involved?
* Yes. There's a lot of information about that available...
* If you use the wrong cathode or anode, you could polute the material.
* The process is such that over time your anode will break down, will shed.
* Now, you mentioned a graphite rod earlier? If you used that, it would shed?
* Yes.
* (New picture) (Small box in window above cell)
* There's a drying material, and then sticks across the top.
* A petri dish could go inside?
* Yes.
* If one had a petri dish with a material one wanted to dry, it might be better because it would circulate...
* Not really
* If you had it on the prills, that would reduce the surface area by a lot?
* Relative to the volume, not really.
* (New picture, exhibit 48. "power supplies and solenoid")
* To clarify, the objects on the left you said are power supplies?
* Yes
* To the right would be the solenoids?
* Yes.
* You answered some questions in the preliminary inquiry?
* Yes.
* And you never examined it in person?
* Yes.
* A solenoid in an electromechanical device that moves a cylinder in and out.
* Yes.
* And you suggested that it could be used in a detonator?
* yes.
* How big are these?
* 10 to 15 cm.
* And are you familiar with ones that are much smaller?
* Yes.
* So this would be pretty bulky?
* Yes.
* Now, if we zoom in... It says $8.99 and then assorted DC motors. And another says assorted and has the same price... And the next one says it is a servos. And the other says it is a DC motor...
* Let's just say they're all motors.
* They're also electro-mechanical device. They have coils and make something plug in.
* There are DC motors and AC motors. These are DC motors from the label.
* Direct current...
* Yes. You'd need a transformer in order to use these.
* The have uses in make, say, model cars?
* They would.
* And they're used in printers, to move the print head around?
* Yes.
* (next picture) Now this is a camp stove. You've said you've never seen one quite this small...
* So there's an element, and a hose, and that would connect to gas and fuel would flow in...
* Yes.
* And there's a device to defuse the flames?
* Yes.
* And would you agree that there is a concave section that you could put a hexamine tablet?
* Yes. You could probably fit one.
* It would be much more efficient to use gas.
* You could just take a few instead of taking around a whole fuel canister.
* (pause) I don't see why you couldn't.
* ... In addition to using Hexamine as a starter, but you could use it as a fuel.
* ... Yes.
* A single pellet might not be enough to boil a pot of water, but you could warm a beverage.
* I've never tried and wouldn't want to comment.
(Break)
* I left you with two pieces of homework. Did you figure out how much HDM could be made?
* 600 to 650 grams
* And the propellants.
* I called a colleague to ask about amonium nitrate propellant. They have tested them.
* SO they are in use?
* They've been evaluated. I can't say if they're in use.
* The hexamine tablets are cylindrical?
* Yes.
* Sizes?
* I'd need to look at a picture.
* OK. Kevin isn't here right now and we were using his laptop. We'll come back to that.
* Do you agree that they can also come in other shapes
* You can also get rectangular pieces in boxes.
* Have you seen boxes with these round tablets?
* No.
* Would you agree that a cardboard box wouldn't provide good protection from water.
* Yes.
* And those jars probably would?
* Yes.
* And they would dissolve in water?
* Yes.
* And then they wouldn't be as useful as a fuel?
* It's a long way to get there, but yes.
* Perhaps Ms. Nadaeu could help with the photos...
* (She tries to hook up her computer to the projector...)
* Perhaps Mr. Registrar could provide the physical photo?
* Estimate the diameter of those cylinders?
* 2.5cm by 2.
* (Next picture) You mentioned that the tube in this picture could be used for venting chlorine gas?
* Yes, the white flexible one.
* If we zoom in on the picture, do you see how the cable is split down the middle. Wouldn't that be problematic?
* Not really, as long as you didn't stretch it apart.
* Could it be for guiding cables?
* ...
* (Anderson physically shown pictures) Do you agree those sort of crystals could be made from copper sulphate?
* Yes.
* (another photo) Wood across the beaker, with a string in a vial. Does that look like a set up for making a bomb?
* No, I haven't seen this before, but it looks like the set up for the classic sugar crystal experiment.
* Or copper sulphate crystals?
* Yes.
* To make a crystal, you would have to heat up the water...
* Yes, to saturate it.
* And the hot plate could have been used for that?
* Yes.
* (next picture) (looking at blue vials on desk) These look like crystals in the process of production.
* Yes.
* Now, lets talk about some of the chemicals the Crown asked you about.
* Acetone is a common solvent?
* Yes.
* Used for cleaning or as a paint thinner?
* Yes.
* Methyl hydrate has any uses other than a solvent?
* It's wind shield washer.
* Do you agree that not all solvents are suited for all purposes. So depending on what you want to remove, some solvents might be better than others?
* Yes.
* A face shield, dust mask... These has uses besides making bombs?
* These are standard pieces of safety equipment.
* If you were cutting wood, you might want to wear a dust mask?
* yes.
* Steel wool is a common house hold item?
* Yes.
* For cleaning?
* Yes.
* For finishing wood?
* Yes.
* Getting stuff of pan?
* You might scratch it.
* You were asked about PVC pipe. You said they could be to make a pipe bomb. But usually one uses a steel pipe so that it sends shrapnel...
* Yes.
* Any sort of plastic container would serve exactly the same role that would not provide shrapnel...
* Yes.
* One could use other metal containers and get shrapnel.
* Yes.
* They're limited by their imagination?
* Yes.
* Muriatic acid. Used for cleaning driveways you said?
* Yes.
* Good at getting oil off stone or ashphult surfaces?
* Yes.
* Good at getting rust or scales off ceramic surfaces?
* Let me check my notes...
* (Reads list of other uses, not on it)
* Cleaning side walk?
* Sure.
* Cleaning fire place?
* It wouldn't surprise me. It's a cleaning agent. A industrial cleaning agent.
* Now there are plastic tubes. You said that the the plastic tube was the wrong size for for a detonator... And that it could be used...
* Is nichrom wire is a standard wire used in heating element?
* I don't know?
* Hair dryers?
* I don't know.
* Wall sockets?
* Thin nichrom wire? No.
* Toasters?
* I don't know.
* I know it's used in detonators and to measure the speed of explosions...
* It would be fair to say that you know about it's uses in explosives, but not others?
* Yes
* Bag sealers?
* I don't know.
* Another wire, different composition. Do you remember what?
* It was contained iron...
* Please refer to the report...
* You said you thought it might be stainless steel. But it doesn't contain nickel...
* I couldn't say if all stainless steel contains nickel.
* You can't really comment on it's uses.
* Hydrometer found in the lab, it is a standard lab tool
* Not really a standard lab tool. Standard in detecting humidity. We have other ways to detect them in the lab.
* Hexamine is a standard camping supply?
* Yes.
* No restrictions on their sale?
* Yes.
* You find that concerning?
* Yes.
* Because it has a variety of benign and malicious uses?
* Yes.
* Amonium nitrate has a general use as fertilizer?
* Yes.
* It a restricted substance?
* A controlled substance.
* If you buy over a kiligram, there's an obligation on the part of the supplier to detail who it is?
* Yes.
* When it is mixed with water, it starts an endothermic reaction? Absorbs heat?
* Yes. It's a component of cold packs.
* So you can go to the drug store and buy cold packs that contain amonium nitrate.
* Urea also starts an endothermic reaction when masked water?
* Yes.
* Also used in cold packs?
* It wouldn't surprise me.
* Hydrogen peroxide is used to bleach hair?
* Yes.
* You could use it as a propellant in rocketry?
* It would be a pretty elaborate set up. It would be your oxidizer and then you'd be mix it...
* Could you do it in another way?
* I don't know. It's outside my expertise.
* Could you use platinum to catalyze it into water and...
* C: The defense is asking outside Dr. Anderson's expertise...
* D: The Crown finished by asking him whether there were any other uses... The crown first asked questions about rockets.
* That's fair, but don't get him to speculate...
* As your general knowledge of organic chemistry, you would have experience with catalyzers like this...
* Yes, but it would beyond my expertise in chemistry.
* Sulfamic acid has other uses... Could you use it to make smoke trails?
* I don't know.
* Potassium permangenate. You think it should be regulated?
* Yes.
* Because it can burn violently?
* Yes
* Are you aware as to whether it has improper uses in making drugs?
* I don't know.
* ...
* Also a component of black powder?
* Yes.
* The historical gun powder?
* Yes.
* Which is used in rocketry?
* Yes.
* And in food preservatives?
* Yes.
* And it can be used as a stump remover?
* Yes, as a slow explosive.
* I'm going to suggest that while it may be turned into an explosive to remove stumps, by itself it can be used to encourage fungus to get rid of one?
* Maybe.
* ... Hexachloro ethane in producing smoke?
* Yes.
* Charcoal is an element of black powder?
* Yes.
* And it could be used as propellant in a rocket?
* Yes.
* Dextrin yous said could be an explosive as a glue or thickener?
* Yes. And a fuel.
* And it could be used in a propellant as a binding agent and fuel?
* Yes.
* Potassium chloride might be a fertilizer?
* I'd think the chlorine would poison plants.
* It could be turned into potassium chlorate?
* Yes.
* Wax could be used as a binding agent in a propellant?
* Yes and a fuel.
* How much wax was found?
* Let me check ... I don't have it.
* ABS and PVC shavings could be used?
* Maybe, they were a bit thick.
* They could make dark smoke?
* Most materials can be used to make smoke.
* Potassium Carbonate Hydrate found in mislabeled jar.
* Is Potassium Hydroixde, which is what it was label, is hydroscopic.
* If it was just a bit of residue, it could react with water and carbon dioxide in the air and become Potassium carbonate Hydrate.
* Yes. That would be a legitimate reason for it to be labeled different.
* It was the only thing that was labeled differently that what it was?
* Yes
* Potassium chlorate, we've discussed, certainly has an application in amateur rocketry?
* Yes.
* There was a larger box in the laundry room, the silica gel...
* ... You would agree that not all drying agents are created equal?
* (laughs) Yes.
* Granular... can be turned into a chlorate you said. What type?
* I don't know, because I don't know how much hypochlorate.
* Potassium chlorate you said is a lot for rocketry. Would you agree that would depends on the size and number of rockets.
* Yes. And what you mixed.
* Restricted components act... none of these is over the limits.
* Over vendor limits.
* And one needs a license to make propellants and fireworks.
* Because of concerns about accidental explosions.
* Getting the license automatically triggers evaluation of your ability to safely produce and store them.
* Storage being the other concern, because if you have to much together it can be dangerous...
(Break)
* In your examination in chief, you were discussing some equipment that could be used in manufacturing a rocket engine?
* A drill press and jack.
* So that I understand, rocket engines are usually packed into cylinders.
* That's really outside my expertise.
* I'm just trying to understand what you said in your examination.
* You could use a drill press to press it.
* (picture) Drill press?
* It's too bad that we didn't see another side.
* And one could use a car jack?
* Yes.
* ...
* That's a rather Rube Goldberg way of doing things, but would work.
* (Flicker pictures) Car jack to the right, previously hand drawn diagrams. Diamond shape of the jack, frame, and then arrows going up and down.
* If you put the car jack in a frame like that...
* I would agree that it is a diagram for an improvised press.
* In your evidence, you described that one time you went into a cosmetics store to buy hydrogen peroxide?
* I wanted to see what the highest concentration I could get was.
* And you took gratification from them showing you out when you made inquiries of that nature.
* Yes.
* On a similar incident, I tried to buy calcium nitrate, and it triggered several alarms.
* I'm proud of the sort of uptake there's been of these measures in Canada.
* Regarding the cold packs, you are aware of colleagues checking for them and not finding them?
* Yes.
* Are you aware of any other colleagues testing the system?
* ... No.
* You said that there was no other reason I for all those materials?
* I don't know if I said exactly that, but yes.
* Many of the chemicals, you have said, had no relevance.
* Yes.
* And would you agree that what you see is informed by your expertise?
* Yes.
* You agree that your lack of knowledge of propellants might prevent you from seeing alternative reasons?
* I have a general knowledge...
* And these could be for multiple reasons for the chemicals, rather than several of them.
* Yes..
* And many are common house hold items?
* Yes.
* Some are fertilizers?
* Yes.
* Do you think any of this can be related to a desire to test the security of the system and raise alarms?
* C: Objection, this is an inappropriate question.
* J: Given the Crown's last question, I'm going to allow it.
* (pauses) Yes. I think it is a terrible idea, but yes.
* (Byron laughs) (Witness laughs)
* J: I'd be interested in know about the sort of risks one would be putting themselves, their spouse and home by doing something like this without your experience at their home. I leave it to Counsel to decide whether they want to ask this question, otherwise this will be a dead issue.
* There is lots of information on this on the Internet?
* Yes.
* And they have lots of cautionary information?
* Yes. Lots of cautionary words are used.
(Prosecution reexamines)
* Yesterday, you said that one can calculate energy based on the size?
* Yes, if one knows the density, and one can calculate if you know the fuel...
* How many motors would you be able to make from the chemicals present?
* Quite a number.
* You said you'd have to test them in designing efficient fuels...
* Yes.
* How would you do that?
* I'd make it and take it to a remote region to rest.
* Would 500 grams be enough TATP to make a bomb?
* Yes.
* How much TATP do you need to be a bomb?
* You'd need about 10 grams for a detonator.
* ... If you were making a booster as well, 50 grams.
* Can TATP go off if you drop it?
* If it is in a container?
* You said they could make three quarters kilograms of Amonium Nitrate... Is that a big explosion?
* It could hurt people in a small space.
* An explosive doesn't have to be for hurting people. It could be for blowing up a safe?
* Sure, it's a great way to apply a lot of energy.
* What about blowing up a fence or building?
* A fence sure, maybe not a building.
* A propellant can explode under certain circumstances?
* Yes.
* That's all.
* J: We haven't come back to the issue of the harddrive... Will that come up after our break?
* (yes)
* There are concerns about Officer Oullett's ability to answer technical questions.
* J: I'm familiar with underground sprinkler systems and black stakes for surface irrigation... I don't think counsel wants me to use my own knowledge.
* J: Similarly with the issue of greater than symbols for indentation and quoting.
* J: I don't think it is appropriate for me to handle the harddrive by myself. I don't want to make a fuss over things things that are irrelevant.
* C: It was the Crown's understanding that all evidence from the pretrial would be used, though there are more.
* C: We are anticipating recalling Mr. Letch to deal with technical issues.
* C: I don't think that I can eliminate Detective Oullett
* J: The harddrive evidence ... is water under the bridge.
* J: Taking out emails that are relevant and putting them on a CD.
* J: Copying parts of the harddrive onto the CD?
* C: ... There are things that the officers assumed were relevant, that the Crown doesn't wish to rely upon.
* J: What the Crown is relying upon needs to be teased out somehow...
* J: ... A memory stick of emails that are tendered with consent... I'd be prepared to read those... Then there would be issues of relevance and me not understanding what things are.
* J: Memorysticks aren't that expensive any more...
* C: We're completely on board about the sprinkler system.
* J: I've already disclosed that I watch Holmes on Homes.
* C: There is one contentious witness, an expert on the magnetron. I know there will be issues of relevance and admissibility.
* D: It's something that we raised in the pretrial. It relates to the relevance of the information about the device.
* J: So it's not an issue of timing...
* D: And there's also an issue of the witness' expertise.
* J: If you believe that a pretrial before another judge would be useful, the please arrange that.
* D: Since this is the last day of trial for this session, there is an issue we wish to deal with...
* D: With consent of my friend, these are other bail conditions for Mr. Sonne, that change from a form of house arrest to a form of curfew.
* J: How long has he been out of jail for?
* D: Six or seven months.
* J: That sounds reasonable. Ms. Nadeau have you looked over it?
* C: Yes, I've already signed it.
* D: There is one last thing. Kevin Tilly was called to the bar just days before Mr. Sonne's arrest... He may not be returning when we reconvene. We wanted to mark the occasion. Our firm's loss is at British Columbia's gain.
* J: I was going to ask. I'm glad to here Mr. Tilly will be continuing as a barrister somewhere. Good luck, Mr Tilly. Before you leave, could you do me one favor?
* Kevin: Of course, your Honor.
* J: Could you please give instructions to Mr. Di Luca on how to use the computer.
* (Laughs)
* Kevin: Certainly, your Honor.
* We reconvene on March 19th.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.