language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 1,521 | 2.5625 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
using Spice.ViewModels.Fields;
namespace Spice.WebAPI.Tests.Fields.Factories
{
internal static class ViewModelFactory
{
public static CreateFieldViewModel CreateValidCreationModel()
{
return new CreateFieldViewModel
{
Name = "Field A",
Description = "Lots of sun in the morning and in the early afternoon. Formerly there was a barn.",
Latitude = 50.9657062,
Longtitude = 22.3966112
};
}
public static CreateFieldViewModel CreateInvalidCreationModel()
{
return new CreateFieldViewModel
{
Name = "A",
Description = "B",
Latitude = 150.9657062,
Longtitude = 222.3966112
};
}
public static UpdateFieldViewModel CreateValidUpdateModel()
{
return new UpdateFieldViewModel
{
Name = "Field B",
Description = "Opposite site of the river. High risk of flooding on early spring.",
Latitude = 50.9659117,
Longtitude = 22.395711
};
}
public static UpdateFieldViewModel CreateInvalidUpdateModel()
{
return new UpdateFieldViewModel
{
Name = "B",
Description = "C",
Latitude = 250.9659117,
Longtitude = 122.395711
};
}
}
}
|
C#
|
UTF-8
| 764 | 2.75 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
// Parameters
[SerializeField] Attacker[] enemies;
[SerializeField] float spawnIntMin;
[SerializeField] float spawnIntMax;
bool keepSpawning = true;
int enemyToSpawn;
IEnumerator Start()
{
while (keepSpawning)
{
yield return new WaitForSeconds(Random.Range(spawnIntMin, spawnIntMax));
SpawnEnemies();
}
}
private void SpawnEnemies()
{
enemyToSpawn = Random.Range(0, enemies.Length);
Attacker newAttacker =
Instantiate(enemies[enemyToSpawn],
transform.position, Quaternion.identity);
newAttacker.transform.parent = transform;
}
public void DisableSpawning()
{
keepSpawning = false;
}
}
|
Python
|
UTF-8
| 2,074 | 2.875 | 3 |
[] |
no_license
|
from http.client import HTTPConnection
conn = None
regKey = 'daaae38eedaa6adf9766e73211c81cb1'
server = "apis.daum.net"
host = "smtp.gmail.com" # Gmail SMTP 서버 주소.
port = "587"
def userURIBuilder(server, **user):
str = "https://" + server + "/contents/movie" + "?"
for key in user.keys():
str += key + "=" + user[key] + "&"
return str
def connectOpenAPIServer():
global conn, server
conn = HTTPConnection(server)
def getMovieDataFromTitle(title):
import urllib
global server, regKey, conn
if conn == None:
connectOpenAPIServer()
uri = userURIBuilder(server, apikey=regKey, q=urllib.parse.quote(title), output="xml") # 다음 검색 URL
conn.request("GET", uri)
req = conn.getresponse()
print(req.status)
if int(req.status) == 200:
return extractMovieData(req.read())
else:
return None
def extractMovieData(strXml):
thumbnailList = []
titleList = []
trailerList = []
from xml.etree import ElementTree
tree = ElementTree.fromstring(strXml)
print(strXml)
# Movie 엘리먼트를 가져옵니다.
itemElements = tree.getiterator("item") # return list type
print(itemElements)
for item in itemElements:
thumbnailElements = item.getiterator("thumbnail")
titleElements = item.getiterator("title")
trailerElements = item.getiterator("trailer")
for thumbnail in thumbnailElements:
thumbnailContent = thumbnail.find("content")
thumbnailList += [thumbnailContent.text]
for title in titleElements:
titleContent = title.find("content")
titleList += [titleContent.text]
for trailer in trailerElements:
trailerContent = trailer.find("link")
if (trailerContent.text != None):
trailerList += [trailerContent.text]
else:
trailerList += ["None"]
print(titleList, thumbnailList, trailerList)
if len(titleList) > 0:
return {"title": titleList, "thumbnail": thumbnailList, "trailer": trailerList}
|
Java
|
UTF-8
| 824 | 3.609375 | 4 |
[] |
no_license
|
package com.biz.control;
public class Control13 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//급여액이 3000이하이면 6%
//급여액이 3000초과 10000 이하이면 9%
//급여액이 1억을 초과하면 12%
int intPay = 12000;
if(intPay <= 3000) {
System.out.println("세금 : "
+ (intPay * .06));
//이미 intPay가 3000을 초과한 경우이므로 굳이 intPay > 3000을 검사할 필요가 없어져버렸다.
} else if(intPay <= 10000) {
System.out.println("세금 : "
+ (intPay * .09));
//이미 intPay <= 10000 이하인 모든 경우가 사라져 버렸기 때문에 else만으로 나머지 조건을 처리하면 된다.
} else if(intPay > 10000) {
System.out.println("세금 : "
+ (intPay * .12));
}
}
}
|
C++
|
UTF-8
| 1,685 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
#ifndef KERNEL_INTERSECTION_HPP
#define KERNEL_INTERSECTION_HPP
#include "kernel_types/triangle.hpp"
#include "kernels/backend/kernel.hpp"
#include "kernels/backend/vector.hpp"
#include "kernels/matrix.hpp"
#include "kernels/types.hpp"
namespace nova {
// Use woop transformation to transform ray to unit triangle space
// http://www.sven-woop.de/papers/2004-GH-SaarCOR.pdf
DEVICE inline bool
intersects_triangle(const Ray& ray, Intersection& intrs, int tri_index, const TriangleData& tri) {
// Transform ray to unit triangle space
Ray woop_ray = ray;
woop_ray.origin = tri.transform * ray.origin;
woop_ray.direction = make_mat3x3(tri.transform) * ray.direction;
float t = -woop_ray.origin.z / woop_ray.direction.z;
if (t < 0.0f || t >= intrs.length || !isfinite(t)) {
return false;
}
float2 uv = xy<float2>(woop_ray.origin) + t * xy<float2>(woop_ray.direction);
float3 barycentric = make_vector<float3>(1.0f - uv.x - uv.y, uv.x, uv.y);
if (any(isless(barycentric, make_vector<float3>(0.0f)))) {
return false;
}
intrs.length = t;
intrs.barycentric = barycentric;
intrs.tri_index = tri_index;
return true;
}
// AABB fast intersection for BVH
DEVICE inline bool intersects_aabb(const Ray& ray, const float3& top, const float3& bottom) {
// Find slab bounds on AABB
float3 t1 = top * ray.inv_direction + ray.nio;
float3 t2 = bottom * ray.inv_direction + ray.nio;
float3 tvmin = min(t1, t2);
float3 tvmax = max(t1, t2);
// Find tightest components of min and max
float tmin = max(tvmin.x, max(tvmin.y, tvmin.z));
float tmax = min(tvmax.x, min(tvmax.y, tvmax.z));
return tmin <= tmax;
}
}
#endif // KERNEL_INTERSECTION_HPP
|
PHP
|
UTF-8
| 758 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait CurlTrait
{
protected function rapidapiCurl(array $data)
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $data['rapidapiUrl'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"x-rapidapi-host: ".$data['rapidapiHost'],
"x-rapidapi-key: ".$data['rapidapiKey']
],
]);
return $curl;
}
}
|
Java
|
UTF-8
| 2,308 | 2.625 | 3 |
[] |
no_license
|
package com.kamoulcup.mobile.addict.config;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import android.content.Context;
import android.content.res.AssetManager;
public final class Configuration
{
/**
* Nom du fichier de conf.
*/
private static final String CONFIG_FILENAME = "kamoulcup.properties";
/**
* Instance du singleton.
*/
private static Configuration INSTANCE;
/**
* Propriétés lues dans le fichier de conf.
*/
private Properties _properties;
private Configuration(Context ctx)
{
loadProperties(ctx);
}
/**
* Charge les propriétés trouvées dans le fichier.
*/
private void loadProperties(Context ctx)
{
AssetManager assetManager = ctx.getResources().getAssets();
try
{
InputStream inputStream = assetManager.open(CONFIG_FILENAME);
_properties = new Properties();
_properties.load(inputStream);
}
catch (IOException e)
{
System.err.println("Failed to open config file '" + CONFIG_FILENAME + "'");
e.printStackTrace();
}
}
/**
* Pour obtenir l'adresse du serveur de l'édition du jeu en cours.
*/
public static synchronized String getServerHost(Context ctx)
{
if (INSTANCE == null)
{
INSTANCE = new Configuration(ctx);
}
return INSTANCE._properties.getProperty("server.host");
}
/**
* Ce terminal se trouve-t-il derrière un proxy pour se connecter au réseau ? Emulator oui.
*/
public static synchronized boolean connectionUseProxy(Context ctx)
{
if (INSTANCE == null)
{
INSTANCE = new Configuration(ctx);
}
return Boolean.parseBoolean(INSTANCE._properties.getProperty("useProxy"));
}
/**
* Proxy host.
*/
public static synchronized String getProxyHost(Context ctx)
{
if (INSTANCE == null)
{
INSTANCE = new Configuration(ctx);
}
return INSTANCE._properties.getProperty("proxy.host");
}
/**
* Proxy port.
*/
public static synchronized String getProxyPort(Context ctx)
{
if (INSTANCE == null)
{
INSTANCE = new Configuration(ctx);
}
return INSTANCE._properties.getProperty("proxy.port");
}
}
|
Markdown
|
UTF-8
| 1,013 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
# FromJson
TODO: Write a gem description
## Requirements
ORMs:
- ActiveRecord
ODMs:
- Mongoid
## Installation
Add this line to your application's Gemfile:
gem 'from_json'
And then execute:
$ bundle
Or install it yourself as:
$ gem install from_json
## Usage
To use `from_json`, FromJson needs basic information about your models to be available.
The minimum required method is:
```ruby
class MyModel < ActiveRecord::Base
# unique_keys: Define whichever keys in your hash can be matched to existing records.
def self.unique_keys
['id','post_slug']
end
end
```
This would correspond to a model with two unique keys: `id` and `post_slug`, or a SQL table like this:
```sql
CREATE TABLE `posts` (id INTEGER, post_slug varchar(255));
```
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
|
Java
|
UTF-8
| 492 | 2.375 | 2 |
[] |
no_license
|
package com.sample.stockexchange.adapter;
import com.sample.stockexchange.entity.BuyOrderSet;
import com.sample.stockexchange.entity.SellOrderSet;
import com.sample.stockexchange.entity.Stock;
import java.util.Map;
/**
* Interface for persisting incoming orders based stock. For simplicity's sake,
* just a map for this implementation
*/
public interface IOrderSetStore {
public Map<Stock, BuyOrderSet> getBuyOrderStore();
public Map<Stock, SellOrderSet> getSellOrderStore();
}
|
SQL
|
UTF-8
| 857 | 2.546875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
-- phpMyAdmin SQL Dump
-- version 3.1.4
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Aug 02, 2011 at 01:03 AM
-- Server version: 5.5.14
-- PHP Version: 5.3.4
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `brise`
--
-- --------------------------------------------------------
--
-- Table structure for table `brise_settings`
--
CREATE TABLE IF NOT EXISTS `brise_settings` (
`index` varchar(100) NOT NULL,
`value` varchar(255) DEFAULT NULL,
PRIMARY KEY (`index`),
UNIQUE KEY `index` (`index`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Dumping data for table `brise_settings`
--
|
C++
|
WINDOWS-1251
| 1,999 | 3.375 | 3 |
[] |
no_license
|
/*
.
*/
#include<iostream>
#include<Windows.h>
using namespace std;
void main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
int a, b, p, q, r, s;
int S, s1, s2;//S(), s1(.1), s2(.2)
cout << " a: ";
cin >> a;
cout << " b: ";
cin >> b;
cout << " p: ";
cin >> p;
cout << " q: ";
cin >> q;
if ((p <= a) && (p <= b) && (q <= a) && (q <= b))
{
cout << " r: ";
cin >> r;
cout << " s: ";
cin >> s;
if ((r <= a) && (r <= b) && (s <= a) && (s <= b))
{
if ((q + p <= a) && (q + p <= b) && (p + r <= a) && (p + r <= b))//
{
S = a * b;
s1 = p * q;
s2 = r * s;
if (S - s1 - s2 >= 0)//
{
cout << " " << endl;
}
else
{
cout << " " << endl;
}
}
else
{
cout << " " << endl;
}
}
else
{
cout << " 2 " << endl;
}
}
else
{
cout << " 1 " << endl;
}
system("pause");
return;
}
|
Java
|
UTF-8
| 699 | 3.640625 | 4 |
[] |
no_license
|
package exercise11;
/**
*
* @author Ibrahim Olanigan
*/
public class Factory extends FactoryBuilder{
@Override
public Dog CreateDog(String number) {
if(number.equals("2"))
return new Breed2();
else if(number.equals("3"))
return new Breed3();
return new Breed1(); //Default Breed
}
public static void main(String[] args) {
Factory fact = new Factory();
Dog dog1 = fact.CreateDog("1");
Dog dog2 = fact.CreateDog("2");
Dog dog3 = fact.CreateDog("3");
Dog dog4 = fact.CreateDog("0");
dog1.bark();
dog2.bark();
dog3.bark();
dog4.bark();
}
}
|
C++
|
UTF-8
| 942 | 3.390625 | 3 |
[] |
no_license
|
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct Interval
{
int start, end;
};
bool compare(Interval i1, Interval i2)
{
return (i1.start < i2.start);
}
int main()
{
int n, a, b;
cout << "Enter no of values: ";
cin >> n;
Interval arr[n];
cout << "Enter Values: \n";
for (int i = 0; i < n; i++)
{
cin >> arr[i].start >> arr[i].end;
}
sort(arr, arr + n, compare);
stack<Interval> st;
st.push(arr[0]);
for (int i = 1; i < n; i++)
{
Interval top = st.top();
if (top.end < arr[i].start)
{
st.push(arr[i]);
}
else if (top.end < arr[i].end)
{
top.end = arr[i].end;
st.pop();
st.push(top);
}
}
while (!st.empty())
{
Interval t = st.top();
cout << t.start << " " << t.end << endl;
st.pop();
}
return 0;
}
|
C++
|
UTF-8
| 4,594 | 3.515625 | 4 |
[
"MIT"
] |
permissive
|
#include <iostream>
using namespace std;
template <class T>
class Node
{
public:
Node<T> *lchild;
int data;
int height;
Node<T> *rchild;
};
template <class T>
class Tree
{
public:
Node<int> *root = NULL;
int NodeHeight(Node<T> *p)
{
int hl, hr;
hl = p && p->lchild ? p->lchild->height : 0;
hr = p && p->rchild ? p->rchild->height : 0;
return hl > hr ? hl + 1 : hr + 1;
}
int BalanceFactor(Node<T> *p)
{
int hl, hr;
hl = p && p->lchild ? p->lchild->height : 0;
hr = p && p->rchild ? p->rchild->height : 0;
return hl - hr;
}
Node<T> *LLRotation(Node<T> *p)
{
Node<T> *pl = p->lchild;
Node<T> *plr = pl->rchild;
pl->rchild = p;
p->lchild = plr;
p->height = NodeHeight(p);
pl->height = NodeHeight(pl);
if (root == p)
root = pl;
return pl;
}
Node<T> *LRRotation(Node<T> *p)
{
Node<T> *pl = p->lchild;
Node<T> *plr = pl->rchild;
pl->rchild = plr->lchild;
p->lchild = plr->rchild;
plr->lchild = pl;
plr->rchild = p;
pl->height = NodeHeight(pl);
p->height = NodeHeight(p);
plr->height = NodeHeight(plr);
if (root == p)
root = plr;
return plr;
}
Node<T> *RRRotation(Node<T> *p)
{
return NULL;
}
Node<T> *RLRotation(Node<T> *p)
{
return NULL;
}
Node<T> *RInsert(Node<T> *p, int key)
{
Node<T> *t = NULL;
if (p == NULL)
{
t = new Node<T>;
t->data = key;
t->height = 1;
t->lchild = t->rchild = NULL;
return t;
}
if (key < p->data)
p->lchild = RInsert(p->lchild, key);
else if (key > p->data)
p->rchild = RInsert(p->rchild, key);
p->height = NodeHeight(p);
if (BalanceFactor(p) == 2 && BalanceFactor(p->lchild) == 1)
return LLRotation(p);
else if (BalanceFactor(p) == 2 && BalanceFactor(p->lchild) == -1)
return LRRotation(p);
else if (BalanceFactor(p) == -2 && BalanceFactor(p->rchild) == -1)
return RRRotation(p);
else if (BalanceFactor(p) == -2 && BalanceFactor(p->rchild) == 1)
return RLRotation(p);
return p;
}
Node<T> *Search(int key)
{
Node<T> *t = root;
while (t != NULL)
{
if (key == t->data)
return t;
else if (key < t->data)
t = t->lchild;
else
t = t->rchild;
}
return t;
}
void Inorder(Node<T> *p)
{
if (p)
{
Inorder(p->lchild);
cout << p->data << " ";
Inorder(p->rchild);
}
}
};
int main()
{
Tree<int> tree;
int choice;
while (1)
{
cout << "\nOptions";
cout << "\n\n1. Insert in Binary Search Tree";
cout << "\n2. Search Node";
cout << "\n3. Delete Node";
cout << "\n4. Display Tree in Inorder";
cout << "\n5. Exit";
cout << "\nEnter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
{
cout << "\nEnter The Leaf Element: ";
int n;
cin >> n;
if (!tree.root)
{
tree.root = tree.RInsert(tree.root, n);
}
else
{
tree.RInsert(tree.root, n);
}
break;
}
case 2:
{
cout << "\nEnter The Element you Have To Search: ";
int n;
cin >> n;
Node<int> *temp = tree.Search(n);
if (temp)
cout << "\nElement Found ";
else
{
cout << "\nElement Not Found ";
}
break;
}
case 3:
{
cout << "Enter Element To Delete ";
int ele;
cin >> ele;
break;
}
case 4:
{
cout << "Tree Print In Inorder ";
tree.Inorder();
}
case 5:
exit(1);
default:
cout << "\nWrong Option ";
break;
}
}
return 0;
}
|
Java
|
UTF-8
| 3,070 | 2.90625 | 3 |
[] |
no_license
|
package chord;
import peersim.core.Node;
import peersim.core.CommonState;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
//clase que representa el comportamiento del usuario
public class Usuario{
long id;
ListaTareas lista;
ListaTareas colaAgregar;
int actual;
boolean experto;
double peso;
boolean etiquetando;
Queue<Object> colaEspera;
Queue<Object> colaAgregacion;
boolean ejecutando;
boolean agregando;
Node sig;
public Usuario(long id){
this.id = id;
lista = null;
colaAgregar = new ListaTareas();
this.peso = 1.0;
this.etiquetando = false;
float num = CommonState.r.nextFloat();
this.experto = num <=Constantes.PROB_EXPERTO;
if(experto){
this.peso = Constantes.PESO_EXPERTO;
//System.out.println("{"+this.id+"}:EXPERTO ("+num+"<="+Constantes.PROB_EXPERTO+") con peso :"+this.peso);
}
//else{
// System.out.println("{"+this.id+"}:NORMAL("+num+">"+Constantes.PROB_EXPERTO+") con peso :"+this.peso);
//}
this.colaEspera = new LinkedList<>();
this.colaAgregacion = new LinkedList<>();
this.ejecutando = false;
this.agregando = false;
}
public void encolar(Object o){
this.colaEspera.add(o);
}
public Object desencolar(){
return this.colaEspera.poll();
}
public void encolarAgg(Object o){
this.colaAgregacion.add(o);
}
public Object desencolarAgg(){
return this.colaAgregacion.poll();
}
public void setTareas(ListaTareas t){
lista = t;
actual = 0;
}
public void setSiguiente(Node s){
this.sig = s;
}
public Node getSiguiente(){
return this.sig;
}
public void setEtiquetando(boolean e){
etiquetando = e;
}
public boolean getEtiquetando(){
return etiquetando;
}
public ListaTareas getTareas(){
return lista;
}
public void addTareas(ArrayList<Tarea> t){
lista.addAll(t);
}
public boolean hayTareas(){
return actual<lista.tareas.size();
}
public Tarea getActual(){
return lista.tareas.get(actual);
}
public void responderActual(){
if((lista.tareas.size()-1)>=actual){
Tarea aux = lista.tareas.get(actual);
aux.mostrarTarea();
int opcion = -1;
if(this.experto){
if(CommonState.r.nextFloat()<Constantes.EXPERTO_CORRECTA){
opcion = aux.posCorrecta;
}
else{
opcion = CommonState.r.nextInt(aux.opciones.length);
}
}
else{
if(CommonState.r.nextFloat()<Constantes.NORMAL_CORRECTA){
opcion = aux.posCorrecta;
}
else{
opcion = CommonState.r.nextInt(aux.opciones.length);
}
}
if(!aux.setRespuesta(opcion, this.id, this.peso)){
System.out.println("HORROR!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
//Utils.holder.hold(Utils.taskDelay());
}
actual++;
}
}
|
Python
|
UTF-8
| 2,097 | 3.703125 | 4 |
[] |
no_license
|
# school = "Digital School"
# print(school)
"Good Morning"
student1 = "Andrea"
student2 = "Zach"
student3 = "Michael"
student4 = "Rick"
# formatting = "Good Morning: {2} {3} {0} {0}".format(student1, student2, student3, student4)
# print(formatting)
# formatting = "Good mor\ning: {Andrea} {Zach} ".format(Andrea = student1, Zach = student2)
# print(formatting)
# f- strings
# day = "wednesday"
# tomorrow = "thursday"
# currentDay= (f"Today is {day}")
# currentDay1= (f"Today is {tomorrow}")
# print(currentDay)
# print(currentDay1)
# print(type(True))
# a_string = '1'
# an_int = '2'
# print(a_string + an_int)
# print (isinstance(a_string, int))
# one = "one1"
# two = "two1"
# three = "three1"
# print(one,two,three)
# print("""Lorem ipsum is a\v pseudo-Latin \ntext \b\b\bused \nin web design, typography, layout, and printing in place of English to emphasise design elements over content. It's also called placeholder (or filler) text. It's a convenient tool for mock-ups. It helps to outline the visual elements of a document or presentation, eg typography, font, or layout. Lorem ipsum is mostly a part of a Latin text by the classical author and philosopher Cicero. Its words and letters have been changed by addition or removal, so to deliberately render its content nonsensical; it's not genuine, correct, or comprehensible Latin anymore. While lorem ipsum's still resembles classical Latin, it actually has no meaning whatsoever. As Cicero's text doesn't contain the letters K, W, or Z, alien to latin, these, and others are often inserted randomly to mimic the typographic appearence of European languages, as are digraphs not to be found in the
# """)
# one_str = "1"
# two =2
# one = int(one_str)
# print(one + two)
# one_int = 1 cd
# one_str = str(one_int)
# print(one_str + 2
# .format( {} ,
# name = input("What is your name\n")
# age = int(input("How old are you?\n"))
# yearOfBirth = 2020 - age
# print(f"my user entered:\n{name}")
# print(f"Year of birth is:\n{yearOfBirth}")
# print(type(name))
# print(type(yearOfBirth))
print( 5 > 4)
|
Markdown
|
UTF-8
| 9,239 | 2.796875 | 3 |
[] |
no_license
|
---
layout: post
title: "The future paradise of programming thanks to AWS Lambda functions : let's send a newsletter for a Jekyll github pages site with a Lambda"
date: 2015-12-26 23:00:51
categories: cloud
---
# Introduction
[AWS Lambda](http://docs.aws.amazon.com/lambda) is the future of programming :
- no more administration of servers by the developers, a complete serenity : no more worry about how you'll deploy the code into production
- all computing power and required memory is now managed by the cloud provider
- scalability : the cloud provider scales the power in function of the traffic
- cost : low usage will lead to reduced costs in computing power
All this has a very important consequence, a new way of architecturing information systems, in an **event-driven fashion** rather than our traditional **REST architectures**. It is still possible to create a REST API above the event-oriented architecture, with an API endpoint that will translate HTTP and HTTPS requests (GET, POST, ...) into events, thanks to AWS Gateway.
But the scope of possible sources of events, that will produce events for the lambda functions, is now much wider :
- API Gateway (HTTP, HTTPS, ...)
- scheduled events
- AWS services (S3, Cloudwatch logs, SNS...)
And events can be delivered/propagated on faster and safer protocol than HTTP.
This event-oriented architecture simplifies the development and the organization of information systems into what is now defined as **micro-services** : services with a narrow scope, that are independent, scalable, reliable and easy to communicate with for other parts of the organization :
- services can be updated independently
- services do not require the knowledge of other services' context (see Domain Driven Design - by Eric Evans)
Microservices at Netflix :
<iframe width="560" height="315" src="https://www.youtube.com/embed/5qJ_BibbMLw" frameborder="0" allowfullscreen></iframe>
# Example : let us send a newsletter for a Jekyll Gihub Pages blog with an AWS Lambda function
This example works for any website with a RSS or ATOM feed or equivalent, listing the articles by dates, such as a blog, a news website, ...
I'll create a lambda function to fetch the latest articles from the RSS feed, and send them in a newsletter to our readers.
I'll take the case of a free of cost [Jekyll blog](https://jekyllrb.com/) - [hosted by Github](https://pages.github.com/).
Subscription can be integrated very easily into the website with [MailChimp Sign-up Form builder](http://kb.mailchimp.com/lists/signup-forms/create-signup-forms-and-response-emails) or [Mailjet Subscription widget](https://www.mailjet.com/docs/widget) : such forms collect emails into contact lists and have API to send newsletters to these contact lists later on.
# Script development and local testing
Let us create a lambda function in Javascript using [MailJet NodeJS Wrapper](https://github.com/mailjet/mailjet-apiv3-nodejs) :
```
mkdir mylambda
cd mylambda
npm install node-mailjet
npm install xml2js
vi send_newsletter.js
```
and write the following javascript module, named *send_newsletter.js*, with the mission to get all articles being published the last week, and send their titles with their links in a newsletter :
```javascript
var Mailjet = require('node-mailjet').connect('API KEY', 'API SECRET');
var blog_hostname = 'YOUR BLOG HOSTNAME';
var blog_path: '/feed.xml';
var newsletter_infos = {
"Locale":"en_US",
"Sender":"SENDERNAME",
"SenderEmail":"SENDER EMAIL",
"Subject":"NEWSLETTER SUBJECT",
"ContactsListID":"CONTACTLIST ID",
"Title":"NEWSLETTER TITLE",
} ;
var date1weekago = new Date();
date1weekago.setDate(date1weekago.getDate() - 7);
var http = require('http');
var parseString = require('xml2js').parseString;
exports.handler = function(event, context) {
var html_part = "";
var text_part = "";
var req = http.request({
hostname: blog_hostname,
path: blog_path,
port: 80,
method: 'GET',
headers: {"user-agent" : "NodeJS HTTP Client"}
}, function(res) {
var body = '';
console.log('Status:', res.statusCode);
console.log('Headers:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
console.log('Successfully processed HTTPS response');
parseString(body, function (err, result) {
body = result.rss.channel[0].item;
var nb_articles = 0;
for(i in body)
if( new Date( body[i].pubDate[0]) > date1weekago )
{
nb_articles ++;
html_part += "<p><a href=" + body[i].link[0] + ">" + body[i].title[0] + "</a></p>";
text_part += body[i].title[0] + " : " + body[i].link[0] + "\n";
}
html_part = "<strong>Hello!</strong><p>Here are my new articles :</p>" + html_part + "<p>MY NAME</p>";
text_part = "Hello!\nHere are my new articles:\n" + text_part + "MY NAME";
if(nb_articles)
Mailjet.post('newsletter')
.request(newsletter_infos)
.on('success', function(res) {
var id = res.body.Data[0].ID;
Mailjet.post('newsletter/' + id + '/detailcontent')
.request({
"Html-part":html_part,
"Text-part":text_part
})
.on('success', function() {
Mailjet.post('newsletter/' + id + '/send')
.request({}).on('success', context.succeed).on('error', context.fail);
})
.on('error', context.fail);
})
.on('error', context.fail);
});
});
});
req.on('error', context.fail);
req.end();
};
```
In order to test our script **locally on the computer**, let's write the following *test.js* script :
```javascript
var send_newsletter = require('./send_newsletter.js');
var event = {};
var context = {};
context.fail = function (err) {
console.log(err);
}
context.succeed = function( res) {
console.log(res)
}
send_newsletter.handler(event,context)
```
and try it :
```
node test.js
```
If everything works fine, let's upload it to AWS.
# Upload to AWS and configure events for tests and production weekly execution
Since I used node modules, I need to package everything in a zip *mylambda.zip* :
```
zip -r mylambda *
```
that I can directly upload to the console :

or with AWS CLI, provided you attached a Lambda:CreateFunction policy to your current AWS CLI user:
```
aws lambda update-function-code --function-name sendNewsletter \
--zip-file fileb://mylambda.zip
```
Provided you have already created the `lambda_basic_execution` role for your lambdas, or know which IAM/EC2 role to use, you can also directly create it from command line :
```
aws lambda create-function --function-name test --runtime nodejs \
--role arn:aws:iam::ACCOUNT_ID:role/lambda_basic_execution \
--handler send_newsletter.handler --timeout 80 \
--zip-file fileb://mylambda.zip
```
Configure the correct **module name, memory, and execution time** :

It's now time to verify everything works well, by creating an *test event* :

and execute it :

Have a look at the **max used memory** to check if you selected the right memory range. You can also check the **duration** and billed duration to ensure you are not charged for a too long timeout setting and an unterminated process.
You can also invoke your lambda with AWS CLI :
```
aws lambda invoke --function-name sendNewsletter results.json
```
Meanwhile, you'll certainly received the result in your mail box :

Now that everything works well, let's add a scheduled event as event source to **execute our lambda function every tuesday at 10AM UTC time** :

# Conclusion
We created a newsletter in less than an hour... You can now create thousands of such services, for whatever you feel like!
As soon as the libraries are compiled for the [lambda execution environment](https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html) and included into the ZIP file, and execution time is not more than 5 minutes (have a look at [lambda limits](http://docs.aws.amazon.com/lambda/latest/dg/limits.html)), you can execute any code on AWS Lambda...
And for the [AWS lambda costs](https://aws.amazon.com/fr/lambda/pricing/) ? computation of the 5 newsletters per month taking 3200 ms of AWS lambda 128Mo costs about **0,00003334 US$** per month. Free of charge.
**Well done !**
|
Python
|
UTF-8
| 780 | 4.40625 | 4 |
[
"Apache-2.0"
] |
permissive
|
# Paul Caulfield, 2019
# My program takes a user input string and outputs every second word.
x=input("Please enter a sentence: ")
# x is the string input by the user.
secondword = (' '.join(x.split()[::2]))
# splits sentence "x" into words using whitespace as the delimiter - reference https://www.geeksforgeeks.org/python-string-split/
# [::2] extracts every second word in the list beginning with the first word- reference https://docs.python.org/2.3/whatsnew/section-slices.html
# join every second word with whitespace between each word to form new sentence - adapted from https://stackoverflow.com/a/17645386
# Adapted code from https://stackoverflow.com/a/17645629
print(secondword)
# Output new sentence containing every second word of the original sentence
|
Java
|
UTF-8
| 1,966 | 2.671875 | 3 |
[] |
no_license
|
package com.test.testNG;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class TestNGBasics {
//Pre-Conditions Annotations: starting with @Before
//Every Annotation should associated with one method
@BeforeSuite //Executed 1st
public void setUp() {
System.out.println("SetUp method");
}
@BeforeTest //Executed 2nd
public void launchBrowser() {
System.out.println("Launch Chrome Browser");
}
@BeforeClass//Executed 3rd
public void login() {
System.out.println("Login to App");
}
@BeforeMethod//Executed 4th
public void enterURL() {
System.out.println("URL entered");
}
/*
* Sequence will be-
* @BeforeMethod
* @Test(1)
* @AfterMethod
*
* BeforeMethod
* @Test(2)
* @AfterMethod
*/
//Test Case - starting with @Test Annotation
@Test //Executed 5th
public void googleTitleTest() {
System.out.println("Google title Verified");
}
/* while executing test it create pair of @Before - @Test -@After annotation
Hence,same pair will execute with all test available */
@Test
public void searchTest() {
System.out.println("Search method");
}
//Post-Conditions Annotations - Starting with @After
@AfterMethod//Executed 6th
public void logout() {
System.out.println("Logout to App");
}
@AfterTest //Executed 7th
public void deleteAllCookies() {
System.out.println("Delete All Cookies");
}
@AfterClass //Executed 8th
public void closeBrowser() {
System.out.println("Browser Closed");
}
@AfterSuite //Executed 9th
public void generateTestReport() {
System.out.println("Test Report generated");
}
}
|
JavaScript
|
UTF-8
| 646 | 3.625 | 4 |
[] |
no_license
|
/*
Al presionar el botón pedir números hasta que el usuario quiera,
sumar los que son positivos y multiplicar los negativos.*/
function mostrar()
{
var respuesta;
var sumaPositivos;
var multiplicacionNegativos;
sumaPositivos=0;
multiplicacionNegativos=1;
respuesta=true;
var numero;
do{
numero = parseInt(prompt("Ingrese un numero"));
if(!isNaN(numero)){
if(numero > 0){
sumaPositivos += numero;
}else{
multiplicacionNegativos *= numero;
}
}
respuesta = confirm("Desea continuar?");
}while(respuesta);
txtIdSuma.value=sumaPositivos;
txtIdProducto.value=multiplicacionNegativos;
}//FIN DE LA FUNCIÓN
|
Java
|
UTF-8
| 997 | 2.640625 | 3 |
[] |
no_license
|
package dbiadun.MultiplexApp.helpers;
import java.time.LocalDateTime;
public class ReservationOutputData {
private int reservationId;
private double price;
private LocalDateTime expirationTime;
public ReservationOutputData() {
}
public ReservationOutputData(int reservationId, double price, LocalDateTime expirationTime) {
this.reservationId = reservationId;
this.price = price;
this.expirationTime = expirationTime;
}
public int getReservationId() {
return reservationId;
}
public void setReservationId(int reservationId) {
this.reservationId = reservationId;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public LocalDateTime getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(LocalDateTime expirationTime) {
this.expirationTime = expirationTime;
}
}
|
Java
|
UTF-8
| 13,378 | 1.640625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.versioning.diff;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import javax.swing.AbstractListModel;
import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.netbeans.api.progress.ProgressUtils;
import org.netbeans.modules.versioning.util.CollectionUtils;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.Mnemonics;
import org.openide.cookies.SaveCookie;
import org.openide.util.Exceptions;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import static org.openide.NotifyDescriptor.CANCEL_OPTION;
import static org.openide.NotifyDescriptor.DEFAULT_OPTION;
import static org.openide.NotifyDescriptor.ERROR_MESSAGE;
import static org.openide.NotifyDescriptor.OK_OPTION;
/**
*
* @author Marian Petras
* @since 1.9.1
*/
public class FilesModifiedConfirmation {
private static final Object PROTOTYPE_LIST_CELL_VALUE
= "Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; //NOI18N
protected final JComponent mainComponent;
protected final JList list;
private final Listener listener = new Listener();
private DialogDescriptor descriptor;
protected final JButton btnSave;
protected final JButton btnSaveAll;
private ArrayListModel<SaveCookie> listModel;
private Dialog dialog;
public FilesModifiedConfirmation(SaveCookie[] saveCookies) {
btnSaveAll = createSaveAllButton();
btnSave = createSaveButton();
Mnemonics.setLocalizedText(btnSaveAll, getInitialSaveAllButtonText());
Mnemonics.setLocalizedText(btnSave, getInitialSaveButtonText());
JScrollPane scrollPane
= new JScrollPane(list = createFilesList(saveCookies));
if (!listModel.isEmpty()) {
list.setSelectedIndex(0);
} else {
updateSaveButtonState();
}
JComponent panel = new JPanel(new GridLayout(1, 1));
panel.add(scrollPane);
panel.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
mainComponent = panel;
}
protected JButton createSaveAllButton() {
return new JButton();
}
protected JButton createSaveButton() {
return new JButton();
}
private JList createFilesList(SaveCookie[] saveCookies) {
JList filesList = new JList(
listModel = new ArrayListModel<SaveCookie>(saveCookies));
filesList.setVisibleRowCount(8);
filesList.setPrototypeCellValue(PROTOTYPE_LIST_CELL_VALUE);
filesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
filesList.addListSelectionListener(listener);
filesList.setCellRenderer(new ListCellRenderer());
return filesList;
}
protected String getInitialSaveAllButtonText() {
return getMessage("LBL_SaveAll"); //NOI18N
}
protected String getInitialSaveButtonText() {
return getMessage("LBL_Save"); //NOI18N
}
private DialogDescriptor createDialogDescriptor() {
DialogDescriptor desc = new DialogDescriptor(
getMainDialogComponent(),
getDialogTitle(),
true, //modal
getDialogOptions(),
null, //no initial value
DialogDescriptor.RIGHT_ALIGN,
(HelpCtx) null,
listener);
desc.setAdditionalOptions(getAdditionalOptions());
desc.setClosingOptions(getDialogClosingOptions());
return desc;
}
protected Object[] getDialogOptions() {
return new Object[] { btnSaveAll, btnSave };
}
protected Object[] getAdditionalOptions() {
return new Object[] { CANCEL_OPTION };
}
protected Object[] getDialogClosingOptions() {
return new Object[] { CANCEL_OPTION };
}
protected Object getMainDialogComponent() {
return mainComponent;
}
protected String getDialogTitle() {
return getMessage("MSG_Title_UnsavedFiles"); //NOI18N
}
protected void tuneDialogDescriptor(DialogDescriptor descriptor) {}
protected Dialog createDialog(DialogDescriptor descriptor) {
return DialogDisplayer.getDefault().createDialog(descriptor);
}
public final Object displayDialog() {
if (descriptor == null) {
descriptor = createDialogDescriptor();
}
dialog = createDialog(descriptor);
dialog.setVisible(true);
dialog.dispose();
return descriptor.getValue();
}
class Listener implements ActionListener, ListSelectionListener {
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == btnSaveAll) {
pressedSaveAll();
} else if (source == btnSave) {
pressedSave();
} else {
anotherActionPerformed(source);
}
}
public void valueChanged(ListSelectionEvent e) {
assert e.getSource() == list;
listSelectionChanged();
}
}
protected void listSelectionChanged() {
updateSaveButtonState();
}
private void updateSaveButtonState() {
btnSave.setEnabled(list.getSelectedIndex() != -1);
}
protected void pressedSaveAll() {
Collection<String> errMsgs = saveAll();
if (errMsgs == null) {
handleSaveAllSucceeded();
} else {
handleSaveAllFailed(errMsgs);
}
}
protected void pressedSave() {
String errMsg = save();
if (errMsg != null) {
handleSaveFailed(errMsg);
}
if (listModel.isEmpty()) {
savedLastFile();
}
}
protected Collection<String> saveAll() {
List<String> errMsgs = null;
for (int i = 0; i < listModel.getSize(); i++) {
String itemErrMsg = save(i, false);
if (itemErrMsg != null) {
if (errMsgs == null) {
errMsgs = new ArrayList<String>(listModel.getSize());
}
errMsgs.add(itemErrMsg);
}
}
listModel.removeAll();
return errMsgs;
}
protected String save() {
return save(list.getSelectedIndex(), true);
}
protected void handleSaveAllSucceeded() {
closeDialog(btnSaveAll);
}
protected void handleSaveAllFailed(Collection<String> errMsgs) {
JButton btnShowMoreInfo = new JButton();
DialogDescriptor errDescr = new DialogDescriptor(
new ExpandableMessage(
"MSG_ExceptionWhileSavingMoreFiles_Intro", //NOI18N
errMsgs,
null,
btnShowMoreInfo),
getMessage("MSG_Title_SavingError"), //NOI18N
true, //modal
DEFAULT_OPTION,
OK_OPTION,
null); //no button listener
errDescr.setMessageType(ERROR_MESSAGE);
errDescr.setOptions(new Object[] { OK_OPTION });
errDescr.setAdditionalOptions(new Object[] { btnShowMoreInfo });
errDescr.setClosingOptions(new Object[] { OK_OPTION });
DialogDisplayer.getDefault().notify(errDescr);
closeDialog(btnSaveAll);
}
protected void handleSaveFailed(String errMsg) {
showSaveError(errMsg);
}
protected void showSaveError(String errMsg) {
NotifyDescriptor errDialog
= new NotifyDescriptor.Message(errMsg, ERROR_MESSAGE);
errDialog.setTitle(getMessage("MSG_Title_SavingError")); //NOI18N
DialogDisplayer.getDefault().notify(errDialog);
}
@NbBundle.Messages({
"# {0} - file name", "MSG_SavingFile=Saving {0}"
})
private String save(int index, boolean removeSavedFromList) {
final SaveCookie saveCookie = listModel.getElementAt(index);
final AtomicReference<String> errMsg = new AtomicReference<String>();
ProgressUtils.showProgressDialogAndRun(new Runnable() {
@Override
public void run () {
try {
saveCookie.save();
} catch (IOException ex) {
String msg = Exceptions.findLocalizedMessage(ex);
errMsg.set(msg);
if (msg == null) {
msg = getMessage("MSG_exception_while_saving", //NOI18N
saveCookie.toString());
ex = Exceptions.attachLocalizedMessage(ex, msg);
}
Exceptions.printStackTrace(ex);
}
}
}, Bundle.MSG_SavingFile(saveCookie.toString()));
// only remove the object if the save succeeded
if (errMsg.get() == null && removeSavedFromList) {
listModel.removeItem(index);
}
return errMsg.get();
}
protected void anotherActionPerformed(Object source) {}
protected final void closeDialog(Object value) {
descriptor.setValue(value);
dialog.setVisible(false);
}
protected void savedLastFile() {
handleSaveAllSucceeded();
}
protected String getMessage(String msgKey, Object... params) {
return getMessage(getClass(), msgKey, params);
}
protected static String getMessage(Class<?> clazz,
String msgKey,
Object... params) {
return NbBundle.getMessage(clazz, msgKey, params);
}
private static class ArrayListModel<T> extends AbstractListModel {
private T[] array;
ArrayListModel(T[] array) {
if (array == null) {
throw new IllegalArgumentException("null"); //NOI18N
}
this.array = array;
}
public boolean isEmpty() {
return array.length == 0;
}
public int getSize() {
return array.length;
}
public T getElementAt(int index) {
return array[index];
}
void removeItem(int index) {
array = CollectionUtils.removeItem(array, index);
fireIntervalRemoved(this, index, index);
}
void removeAll() {
int size = getSize();
if (size != 0) {
array = CollectionUtils.shortenArray(array, 0);
fireIntervalRemoved(this, 0, size - 1);
}
}
}
class ListCellRenderer extends DefaultListCellRenderer {
public ListCellRenderer() {
setOpaque(true);
}
@Override
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
super.getListCellRendererComponent(list,
value,
index,
isSelected,
cellHasFocus);
if (isSelected){
setBackground(UIManager.getColor("List.selectionBackground")); //NOI18N
setForeground(UIManager.getColor("List.selectionForeground")); //NOI18N
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
return this;
}
}
}
|
C#
|
UTF-8
| 394 | 3.390625 | 3 |
[] |
no_license
|
using System;
namespace NavData
{
class Circle : Shape
{
private double r;
public Circle(double r)
{
Console.WriteLine("Init a Circle object");
this.r = r;
}
public override double Area()
{
Console.WriteLine("Calling Area defined in Circle");
return pi * r * r;
}
}
}
|
JavaScript
|
UTF-8
| 720 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
'use strict';
const paramNameMap = Object.freeze({
_: 'title',
y: 'year'
});
const normalizeName = name => {
const nameList = name.split(' ');
let normalizedList = nameList.map(currName => {
return encodeURI(currName);
});
normalizedList = normalizedList.join('+');
return normalizedList.toString();
};
const buildQuery = params => {
return Object
.keys(params)
.map(key => {
let value = params[key];
if (key === 'title') {
value = normalizeName(value.join(' '));
}
const param = paramNameMap[key] || key;
return `${param.charAt(0)}=${value}`;
})
.join('&');
};
const helpers = {
normalizeName,
buildQuery
};
module.exports = helpers;
|
C
|
UTF-8
| 18,235 | 2.90625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include "hashtable.h"
#include "string.h"
const string hashtable_stack = "hashtable.c";
HashTable * getHT(int len)
{
if(len <= 0)
{
char buf[200];
sprintf_s(buf, "Out of bounds Error while trying to create a HashTable; negative length! Inputted length: %d", len);
return propagateError(getStringPtr(buf),
strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::getHT")), true);
}
HashTable * ht = (HashTable *)malloc(sizeof(HashTable));
if (ht != NULL)
{
ht->size = 0;
ht->len = len;
ht->keys = getLL();
if (ht->keys == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::getHT")), false);
ht->hashTable = (kvPair **)malloc(sizeof(kvPair *) * len);
if (ht->hashTable != NULL)
{
for (int loop = 0; loop < len; loop++)
{
*(ht->hashTable + loop) = NULL;
}
}
else
{
return propagateError(getStringPtr("Allocation error! Are you out of memeory?"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::getHT")), true);
}
}
else
{
return propagateError(getStringPtr("Allocation error! Are you out of memeory?"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::getHT")), true);
}
return ht;
}
Error * HTinsert(HashTable * table, String * key, void * data)
{
if (table == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::Htinsert")), false);
if (!table) return propagateError(getStringPtr("NullPointerError! Trying to insert item into NULL HashTable!"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::Htinsert")), true);
if (key == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::Htinsert")), false);
if (!key) return propagateError(getStringPtr("NullPointerError! Trying to insert NULL-keyed item into HashTable!"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::Htinsert")), true);
//Get hash code for item
uint32_t hashed = SuperFastHash(key->data, key->len);
//Creating insert
kvPair * in = (kvPair *)malloc(sizeof(kvPair));
if (in == NULL) return propagateError(getStringPtr("Allocation error! Are you out of memeory?"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTinsert")), true);
//Initializing insert
in->str = key;
in->key = hashed;
in->data = data;
in->next = NULL;
//Searching set of keys for item current key
bool inKeys = false;
kvPair ** keys = LLgetAll(table->keys);
if (keys == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::Htinsert")), false);
LinkedList * list = table->keys;
for (int loop = 0; loop < list->iLen; loop++)
{
if (keys[loop]->key == in->key && strequals(keys[loop]->str, key))
{
bool bReplaced = LLreplaceItem(list, (*stdEquals), &(keys[loop]), &(in));
if (bReplaced == error) return propagateError(getStringPtr("Allocation error! Are you out of memeory?"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTinsert")), true);
inKeys = true;
break;
}
}
if (!inKeys)
{
Error * e = LLprepend(table->keys, in);
if (e == error) return propagateError(getStringPtr("Allocation error! Are you out of memeory?"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTinsert")), true);
}
//Incrementing size of table
table->size += 1;
//If new size of the table is greater than the capacity of the table
// (table len ^ 2)
// Then resize the table then insert, otherwise, just insert
if (table->size >= table->len * table->len)
{
//If resizing:
// - create new hashtable with 2x the indices of the old one
// - take all items in old hash table and put them into a linked list
// - for every item in above LL, add to new, larger hash table
kvPair ** tb = table->hashTable;
////Adding all items of old hash table to single LL, called start
kvPair * start = NULL;
kvPair * endPtr = NULL;
for (int loop = 0; loop < table->len; loop++)
{
//If kvp LL exists at index,
// add LL to complete LL
if (tb[loop])
{
kvPair * LL = tb[loop];
kvPair * ptr = NULL;
kvPair * prev = NULL;
//If first iteration of loop, set start to head of cur LL
// set ptr to start
if (start == NULL)
{
start = LL;
ptr = start;
}
//else, add cur LL to end of total LL,
// set ptr to endPtr
else
{
endPtr->next = LL;
ptr = endPtr;
}
//Find new endPtr
while (ptr)
{
prev = ptr;
ptr = ptr->next;
}
//reset end ptr
endPtr = prev;
}
}
//Shoving inserted item into beginning of full hashtable LL
in->next = start;
start = in;
//Free the old hashtable
free(table->hashTable);
//Create new ht of twice the len
table->len *= 2;
table->hashTable = (kvPair **)malloc(sizeof(kvPair *) * table->len);
if (table->hashTable == NULL) return propagateError(getStringPtr("Allocation error! Are you out of memeory?"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTinsert")), true);
for (int loop = 0; loop < table->len; loop++)
{
(table->hashTable)[loop] = NULL;
}
if (table->hashTable)
{
//Outer pointer to beginning of total LL
kvPair * pointer = start;
while (pointer)
{
//Finding index
int index = pointer->key % table->len;
//Getting item at index
kvPair * target = (table->hashTable)[index];
//If current loop item has the same key as
// inserted item, yet it is not the
// inserted item, skip adding it to LL
// reduce size of ht because it is a duplicate
if (pointer->key == in->key && pointer != in)
{
kvPair * replace = pointer;
pointer = replace->next;
table->size -= 1;
continue;
}
//If inserting first item at this index
if (!target)
{
(table->hashTable)[index] = pointer;
pointer = pointer->next;
((table->hashTable)[index])->next = NULL;
}
else
{
//If other items already exist at this index
//Search LL of kvp's for end
kvPair * ptr = (table->hashTable)[index];
kvPair * prev = NULL;
while (ptr)
{
prev = ptr;
ptr = ptr->next;
}
if (prev && pointer)
{
//At end, place current item
prev->next = pointer;
//Advance outer LL
pointer = pointer->next;
//Set current item's next to NULL
prev->next->next = NULL;
}
}
}
}
}
//If there is no need to resize the ht, simply insert the new item in normally
else
{
//Finding index in hash table of inserted item
int index = hashed % table->len;
//Storing target for placement
kvPair * target = (table->hashTable)[index];
//If inserted item is the first item at its index in the ht
if (!target)
{
//Simply set item at index in hashed table to inserted item
(table->hashTable)[index] = in;
}
else
{
//Else search for end of kvp LL at index and insert the new item there
kvPair * ptr = target;
kvPair * prev = NULL;
while (ptr)
{
//If the key of the current item in LL == key of insert,
// overwrite old key data, decrement table size, and return
if (ptr->key == in->key)
{
table->size -= 1;
ptr->data = in->data;
return;
}
prev = ptr;
ptr = ptr->next;
}
//insert item as end's next
prev->next = in;
}
}
return NULL;
}
//Searches through hash table for keyed item
// if found, return that kvp
// else, return NULL
kvPair * HTgetItem(HashTable * table, String * key)
{
if (table == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HtgetItem")), false);
if (!table) return propagateError(getStringPtr("NullPointerError! Trying to insert item into NULL HashTable!"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HtgetItem")), true);
if (key == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HtgetItem")), false);
if (!key) return propagateError(getStringPtr("NullPointerError! Trying to insert NULL-keyed item into HashTable!"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HtgetItem")), true);
//Getting key's hash
uint32_t target = SuperFastHash(key->data, key->len);
//Getting index that the item should be in
int index = target % table->len;
//Searching through LL at index for a kvp with the
// same key as the target
kvPair * ptr = (table->hashTable)[index];
if(ptr != NULL)
{
while (ptr)
{
if (target == ptr->key)
{
return ptr;
}
ptr = ptr->next;
}
//if not found, return NULL
return NULL;
}
else
{
return NULL;
}
}
HashTable * HTgroupLLBy(LinkedList * linkedlist, GetGroupingElement getGrouping)
{
if (linkedlist == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTgroupLLBy")), false);
if (!linkedlist) return propagateError(getStringPtr("NullPointerError! Trying to insert item into NULL HashTable!"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTgroupLLBy")), true);
if (linkedlist->iLen == 0)
{
// If LL is empty, then return an empty HashTable
HashTable * ht = getHT(2);
if (ht == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTgroupLLBy")), false);
return ht;
}
// Create HT
HashTable * ht = getHT(linkedlist->iLen);
if (ht == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTgroupLLBy")), false);
for (LLNode* llnPtr = linkedlist->front; llnPtr; llnPtr = llnPtr->next)
{
// For every item in the LL:
void * item = llnPtr->data;
// Get bucket that the item fits in
String * targetBucket = getGrouping(item);
// Check if that item fits in any of the existing buckets of the HT
kvPair * kvp = HTgetItem(ht, targetBucket);
if (kvp != NULL)
{
// If the item does fit into a bucket,
// add that item to the bucket
LinkedList * bucket = (LinkedList *) kvp->data;
Error * e = LLappend(bucket, item);
if (e == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTgroupLLBy")), false);
}
else
{
// else,
// create a new bucket for that item
// Create an empty LinkedList
LinkedList * insert = getLL();
if (insert == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTgroupLLBy")), false);
// Insert current item into LL
Error * e = LLappend(insert, item);
if (e == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTgroupLLBy")), false);
// insert into HT
e = HTinsert(ht, targetBucket, insert);
if (e == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTgroupLLBy")), false);
}
}
// return HT
return ht;
}
//Searches through hash table for keyed item
// returns a boolean indicating whther or not the item was found
bool HTsearch(HashTable* table, String* key)
{
if (table == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTsearch")), false);
if (!table) return propagateError(getStringPtr("NullPointerError! Trying to insert item into NULL HashTable!"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTsearch")), true);
if (key == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTsearch")), false);
if (!key) return propagateError(getStringPtr("NullPointerError! Trying to insert NULL-keyed item into HashTable!"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTsearch")), true);
//Getting target kvp's hash
uint32_t target = SuperFastHash(key->data, key->len);
//Getting index that the target kvp should exist at
int index = target % table->len;
//Searching through LL at index for kvp with the
// same key as the target
kvPair * ptr = (table->hashTable)[index];
if (ptr != NULL)
{
while (ptr)
{
if (target == ptr->key)
{
return true;
}
ptr = ptr->next;
}
//if not found return false
return false;
}
else
{
return false;
}
}
uint32_t SuperFastHash(const char * data, int len)
{
uint32_t hash = len, tmp;
int rem;
if (len <= 0 || data == NULL) return 0;
rem = len & 3;
len >>= 2;
/* Main loop */
for (;len > 0; len--) {
hash += get16bits (data);
tmp = (get16bits (data+2) << 11) ^ hash;
hash = (hash << 16) ^ tmp;
data += 2*sizeof (uint16_t);
hash += hash >> 11;
}
/* Handle end cases */
switch (rem)
{
case 3: hash += get16bits (data);
hash ^= hash << 16;
hash ^= ((signed char)data[sizeof (uint16_t)]) << 18;
hash += hash >> 11;
break;
case 2: hash += get16bits (data);
hash ^= hash << 11;
hash += hash >> 17;
break;
case 1: hash += (signed char)*data;
hash ^= hash << 10;
hash += hash >> 1;
}
/* Force "avalanching" of final 127 bits */
hash ^= hash << 3;
hash += hash >> 5;
hash ^= hash << 4;
hash += hash >> 17;
hash ^= hash << 25;
hash += hash >> 6;
return hash;
}
kvPair ** HTgetAll(HashTable * table)
{
if (table == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTgetAll")), false);
if (!table) return propagateError(getStringPtr("NullPointerError! Trying to insert NULL-keyed item into HashTable!"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTgetAll")), true);
kvPair ** kvps = LLgetAll(table->keys);
if (kvps == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::HTgetAll")), false);
return kvps;
}
Error * printHT(HashTable * hashtable, PrintFunc pf)
{
if (hashtable == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::printHT")), false);
if (!hashtable) return propagateError(getStringPtr("NullPointerError! Trying to insert NULL-keyed item into HashTable!"), strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::printHT")), true);
LLNode * llnHTPtr = hashtable->keys->front;
while (llnHTPtr)
{
kvPair * k = llnHTPtr->data;
String * str = k->data;
kvPair * data = HTgetItem(hashtable, ((kvPair *) llnHTPtr->data)->str);
if (data == error) return propagateError(NULL, strAddStringFreeBoth(getStringPtr(hashtable_stack), getStringPtr("::printHT")), false);
printf("'%s' -> ", ((kvPair *) llnHTPtr->data)->str->data);
pf(data->data);
printf("\n");
llnHTPtr = llnHTPtr->next;
}
return NULL;
}
/*
struct _kvp
{
String * str;
uint32_t key;
void * data;
struct _kvp * next;
};
struct _ht
{
int size;
int len;
kvPair ** hashTable;
LinkedList * keys;
};
*/
void freeHashTable(HashTable* ht)
{
freeLinkedList(ht->keys);
for (int iLoop = 0; iLoop < ht->size; iLoop++)
{
kvPair * ptr = ht->hashTable;
while (ptr)
{
kvPair * next = ptr->next;
freeString(ptr->str);
free(ptr);
ptr = next;
}
}
free(ht->hashTable);
free(ht);
}
|
JavaScript
|
UTF-8
| 3,933 | 2.8125 | 3 |
[] |
no_license
|
import React, { useState, useEffect } from 'react';
import Axios from 'axios';
function ControlPannel() {
const [file,setFile] = useState(null)
const [listeTitle,setlisteTitle] = useState([])
const [listeEp, setlisteEp] = useState([])
const [adder, setAdder] = useState(false)
const [titreDatabase, setTitreDatabase] = useState("")
useEffect(()=>{
async function refresh(){
await Axios.get('http://localhost:8000/animeName').then((res)=>{
console.log(res);
setlisteTitle(res.data)}
)}
refresh()
},[]);
function envoyer(e){
let f = file
var formData = new FormData();
formData.append("text",f);
formData.append('title_database',titreDatabase);
//var options = {contenu: formData};
Axios({
method: 'post',
url: "http://localhost:8000/addLink",
data: formData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
}
function HandleClickTitle(lien){
console.log(lien)
Axios.get("http://localhost:8000/episode/"+lien).then((res)=>{
console.log(res.data)
setlisteEp(res.data.sort(compare))
})
}
function compare(a, b){
return a.episode - b.episode;
}
function deleteEpisode(serie,episode){
console.log("ca rentre")
Axios.delete("http://localhost:8000/del/"+serie+"/"+episode)
.then(function (response) {
listeEp.map((s,i)=>{
if(s.episode === episode){
setlisteEp(listeEp.filter(item => item.episode !== episode));
}
})
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
}
function addEpisode(serie){
const res = "<div><input type = 'text'></input><button>Envoyer</button></div>";
const container = document.getElementById("button");
container.append(res);
}
function deleteSerie(serie){
Axios.delete("http://localhost:8000/del/"+serie)
.then(function (response) {
setlisteEp([]);
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
}
return(
<div>
<div>
Créer une série :<br />
Titre database : <input type = "text" onChange={e => setTitreDatabase(e.target.value)}></input>
</div>
<div>
Liste de liens (fichier json de type : id:[episode(str(INT)),lien(String)])<input type="file" onChange={e => setFile(e.target.files[0])}></input>
</div>
<button onClick={(e)=>envoyer(e)}>Envoyer !</button>
<div>
{listeTitle.map((s,i)=><button key={i} onClick = {HandleClickTitle.bind(this,s.lien)}>{s.titre}</button>)}
</div>
<div>
{listeEp.map((s,i)=>{if(i===0){
return <div key={i}>
<div id="button">
<button onClick={()=>addEpisode(s.titre_anime)}>Ajouter</button>
<button onClick={()=>deleteSerie(s.titre_anime)}>Tout Effacer</button>
</div>
<div key={i}>{s.titre_anime} episode {s.episode} VOSTFR
<button onClick={()=>deleteEpisode(s.titre_anime,s.episode)}>effacer</button></div></div>
}
return <div key={i}>{s.titre_anime} episode {s.episode} VOSTFR <button onClick={()=>deleteEpisode(s.titre_anime,s.episode)}>effacer</button></div>})
}
</div>
</div>
);
}
export default ControlPannel;
|
C++
|
UTF-8
| 927 | 3.140625 | 3 |
[] |
no_license
|
class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, string> w_str_map;
vector<string> str_vec = split_str(str);
if (pattern.length() != str_vec.size()) return false;
set<string> occur_set;
for (int i = 0; i < pattern.size(); i++) {
if (w_str_map.find(pattern[i]) == w_str_map.end()) {
w_str_map[pattern[i]] = str_vec[i];
if (occur_set.find(str_vec[i]) != occur_set.end())
return false;
occur_set.insert(str_vec[i]);
} else {
if (w_str_map[pattern[i]] != str_vec[i])
return false;
}
}
return true;
}
private:
vector<string> split_str(string str) {
vector<string> ret;
int last_index = 0;
for(int i = 0; i < str.length(); i++) {
if (str[i] == ' ') {
ret.push_back(str.substr(last_index, i-last_index));
last_index = i+1;
}
}
ret.push_back(str.substr(last_index, str.length()-last_index));
return ret;
}
};
|
Markdown
|
UTF-8
| 29,014 | 3.21875 | 3 |
[] |
no_license
|
# PT Master Mandiri v Yamazaki Construction (S) Pte Ltd
**Case Number** :Suit 155/
**Decision Date** :06 May 2000
**Tribunal/Court** :High Court
**Coram** :Judith Prakash J
**Counsel Name(s)** :Jeffrey Beh and Kelvin Tan (Lee Bon Leong & Co) for the plaintiffs; Thomas Lei (Chor Pee & Partners) for the defendants
**Parties** :PT Master Mandiri — Yamazaki Construction (S) Pte Ltd
_Contract_ – _Remedies_ – _Damages for breach of contract_ – _Assessment of damages_ – _Loss of profit from sub-sales effected after original contract_ – _Whether damages too remote_ – _Duty to mitigate loss_
: This appeal arises out of an assessment, which the assistant registrar made of the damages, which the plaintiffs had suffered by reason of the defendants` breach of contract. There are two issues to be considered in the appeal: the first is whether the damages claimed by the plaintiffs are too remote and therefore not recoverable and the second is whether the plaintiffs failed to discharge their obligation to mitigate their loss.
The facts can be stated briefly. The defendant company operates a granite quarry on the island of Karimun, Indonesia. The quarry is owned by an Indonesian company called PT Karimun Granite (`PTKG`). The plaintiff is a company incorporated in Indonesia which carries on two types of business. It acts as a contractor and also as a supplier of spare parts and lubricants. Prior to the transaction in question it had supplied goods to the defendants for the operation of the quarry.
On 7 November 1998, the plaintiffs sent a fax to PTKG offering to buy 24 units of heavy machinery from them. This letter detailed the individual prices which the plaintiffs were prepared to pay for each machine and set out the total consideration as being S$428,000. Subsequently, it appeared that the owners of the machines were in fact the defendants rather than PTKG and negotiations continued between the plaintiffs and the defendants. Agreement was reached as was evidenced by the defendants` tax invoice dated 26 November 1998, specifying that they would sell the plaintiffs the same 24 machines at a total price of S$438,000. No breakdown of the individual prices was given in the invoice. The terms of payment provided for 50% of the price to be paid on receipt of the invoice and the balance 50% to be paid on approval of the export permit for the machines. The plaintiffs` acceptance of this contract was evidenced by their payment of 50% of the purchase price being S$219,000.
The plaintiffs, according to their managing director, had at the material time been supplying other quarries in Indonesia with plant and machinery. Several contractors had visited Karimun to look for scrap and upon seeing the machinery at the defendants` quarry, had expressed an interest in purchasing some units. The plaintiffs had negotiations with five such parties and concluded sub-sale contracts with them covering all 24 units.
On 14 December 1998, the defendants wrote to the plaintiffs telling them that they wanted to cancel the contract. On 18 December, the plaintiffs` solicitors wrote to the defendants stating that the plaintiffs accepted the repudiation of the contract by the defendants and demanded the sum of S$2.6m as damages in respect of loss of profit arising from the breach of the agreement.
On 28 December 1998, the parties met to try and resolve the matter. At the meeting the defendants
told the plaintiffs that they could only deliver 18 units. The plaintiffs did not accept this offer. Instead they laid down various conditions for accepting a change in the contract terms among which were a demand that the defendants bear the plaintiffs` legal costs and that they pay plaintiffs compensation of $150,000. No agreement was reached then.
In the meantime the defendants had written the plaintiffs a letter dated 24 December in which they stated that they could deliver all 24 units. The plaintiffs only received this letter after the meeting on 28 December and were confused by it because it was at odds with what they had been told at the meeting. The plaintiffs wrote asking for clarification on exactly how many units were being discussed.
On 29 December the defendants replied to say that they needed approval from PTKG in order to get an export permit to complete the sale of the machines and that they were now able to get approval for only 18 units. The implication was that PTKG wanted the remaining six units for itself and the defendants offered to act as middleman in the sale of the six units to PTKG and to pay the plaintiffs all the proceeds from such sale. On the same day, PTKG sent a letter to the plaintiffs telling them that they were interested in buying eight units of the machines from the defendants.
On 16 January 1999, the plaintiffs` solicitors wrote to the defendants stating that the defendants had not made any concrete proposal to settle the plaintiffs` claim but that the plaintiffs were willing to accept $1m as damages in order to expedite the resolution of the matter even though their actual damages amounted to $2.6m.
The defendants` solicitors replied on 27 January to deny liability but stating that their clients were prepared, able and willing to transfer 18 units to the plaintiffs. They reiterated the defendants` readiness and offer to deliver the 18 machines to the plaintiffs and asked to be informed when the plaintiffs would take delivery of the same. They stated that the defendants would then arrange for an immediate delivery. On the same day, the plaintiffs` solicitors replied to say that they had just started legal proceedings against the defendants but that they would take instructions on the defendants` solicitors` letter.
On 29 January, the defendants` solicitors sent a chaser on the issue of the delivery of the 18 machines. Another chaser was sent on 2 February. This was replied to by the plaintiffs` solicitors on 3 February. They stated that the contract was a lump sum contract for purchase of 24 units of equipment. After the contract was entered into the plaintiffs had procured buyers for all 24 units but had to abort the sub-sales when the defendants repudiated the contract. The plaintiffs were therefore not obliged to take delivery of any machines.
Interlocutory judgment in this action was entered against the defendants on 31 March 1999. The assessment of damages took place in February this year. The plaintiffs claimed for the loss of profits that they had suffered by reason of the cancellation of the sale contract and produced representatives of their five subpurchasers who testified as to the various sub-sales. According to this evidence, the total amount which the plaintiffs would have earned from the sub-sales was $1,056,000 and this meant that their profit from the sub-sales was $618,000 (ie after deduction of the purchase price of $438,000). The learned assistant registrar conducting the assessment deducted $6,000 to cover the costs that the plaintiffs would have incurred in transporting the machines to Singapore. This meant that the plaintiffs` net profit from the sub-sales would have been $612, and this is the amount the assistant registrar awarded the plaintiffs as damages. The defendants have appealed.
**_Are the damages too remote?_**
Not all damages that an injured party sustains by reason of a breach of contract are legally recoverable. The basic rule for assessing the damages payable to a party who has been injured by a breach of contract was set out in 1854 in **Hadley v Baxendale** [1854] 9 Ex 341. Damages which do not fall within the rule established by that case are regarded as too remote and thus irrecoverable. As far as damages for non-delivery of goods are concerned, the first part of the **_Hadley v Baxendale_** rule has been enacted as s 51(2) of the Sale of Goods (Cap 393) (`the Act`). That section provides that a purchaser of goods who has not received those goods due to non-delivery by the seller may recover the estimated loss directly and naturally resulting, in the ordinary course of events, from the seller`s breach of contract. By sub-s (3) where there is an available market for the goods in question, the measure of damages is, prima facie, the difference between the contract price and the market price of the goods at the date when they should have been delivered.
The second part of the rule in **_Hadley v Baxendale_** which is that the injured party may recover such damages as may reasonably be supposed to have been contemplated by both parties, at the time the contract was made, to result from its breach, has not been specifically enacted in the Act. The right of the plaintiffs to claim such damages has, however, been preserved by s 54 of the Act which states that nothing in the Act affects the right of a party to recover interest or special damages in any case where by law such interest or special damages may be recovered.
The plaintiffs in this case did not seek to have their damages assessed under s 51(3). If there had been an available market for the goods concerned, the plaintiffs would have had no choice but to resort to s 51(3) because the usual consequence of a seller`s failure to deliver goods is that the prospective buyer will go out and buy replacement goods. In this case, however, the goods were distinctive in character in being second hand machines used in quarrying work and no evidence was given by the defendants that there was an available market to which the plaintiffs could have had recourse to make up for the defendants` breach.
The plaintiffs, having on-sold the machines, sought instead to recover their loss of profits from the resale contracts which had, necessarily, to be aborted. **_McGregor on Damages_** (17th Ed, 1997) has the following passages on when such loss of profits are recoverable:
844(i) Loss of profit on a resale. The earlier cases did not allow the buyer to recover the loss of profit on a resale, whether made before or after the purchase, where all the seller knew was that the buyer had bought with a general intention to resell, as in Thol v Henderson , or even where it was the practice, known to the seller, for buyers to resell before delivery, as in Williams v Reynolds. Later cases however have shown a more liberal tendency and allowed loss of such profit where the defendant knew the buyer would resell, or even where it was probable that the buyer would resell. ...
846 Where damages are allowed for loss of profit on a resale of which the seller knew the actuality or the probability, he will not be liable for an exceptional loss of profits unless he has been informed of the details of the sub-contracts and only then if he can be said to have taken the risk of such loss on his shoulders. This appears from the speeches in Hall v Pim. Lord Dunedin said: The contracts ... must be contracts in accordance with the market, not extravagant and unusual bargains. And Lord Shaw said: It is not suggested that these prices were out of the ordinary course of business. Had this been so, different considerations might quite well have arisen. Thus in Household Machines v Cosmos Exporters , where the seller knew of the plaintiffs intention to resell but did not know the details of the sub-contract, Lewis J did not award the plaintiff the 12 per cent by which the sub-contract price was higher than the contract price, but gave only ten per cent. Similarly, in Coastal International Trading v Maroil where the sub-contract, of which the
defendants were fully aware, contained unusual terms rendering the plaintiffs profit under it unreasonable and such as would not have been within the contemplation of the parties, the profits awarded to the plaintiffs was arrived at after eliminating the extravagant effect of the unusual terms.
The above passages show that it is settled law that in appropriate circumstances a purchaser may recover the loss of profits that he has sustained by reason of the seller`s failure to deliver the goods.
In his submissions before me, counsel for the defendants contended that two grounds strongly militated against the plaintiffs` claim. These were:
(1) the absence of any special knowledge on the defendants before or at the time they entered into the contract with the plaintiffs; and
(2) the sub-sales by the plaintiffs, or at least four out of five of them, came only after the sales contract was entered into by the parties here. These subsequent sub-sales could not have been in the defendants` contemplation so as to expose them for liability when the plaintiffs had to abort the sub-sales since being unable to know deals which would come after their contract, the defendants did not assume any such risk when they entered into the contract with the plaintiffs.
Taking the second point first, the defendants relied on the case of **Teck Tai Hardware (S) Pte Ltd v Corten Furniture Pte Ltd** <span class="citation">[1998] 2 SLR 244</span> and in particular the following observation by Justice Lai Kew Chai (at [para ] 20):
Further, if the sub-sale is formed after the sale contract in question, any consequential losses suffered by a buyer in respect of the sub-sale contract by reason of the sellers breach of the sale contract cannot be recovered from the seller because such loss could not have been within the contemplation of the parties at the time of the sale contract.
I do not agree that it is a basic precondition for liability for loss of profits arising from a sub-sale that the sub-sale concerned must have been entered into before the main contract. In the **_Teck Tai Hardware_** case, Justice Lai Kew Chai was not dealing with a claim for loss of profits on a sub-sale. He was dealing with a claim for consequential damage arising out of the supply of defective locks by the defendant sellers to the plaintiff buyers who were manufacturers of furniture. Both the plaintiffs and defendants were companies incorporated and operated in Singapore but the plaintiffs had installed some of the defective locks in furniture which was shipped abroad. As a result of the defects, the plaintiffs had to replace the exported items and incurred costs in so doing. The defendants` evidence was that the sellers knew that the locks would be used for the purpose of installing them into furniture and that the buyers were manufacturers of such furniture. But it was stated in the evidence that at the time the contract was made the sellers did not know the locks would be fitted into furniture which would then be exported. The learned judge`s conclusion was that there was nothing material known to the sellers before and at the formation of the contract for sale of the locks that justified a finding that the sellers had realised that losses in respect of overseas sales were likely to result from their breach. He therefore held that the sellers were not liable for these losses. His Honour`s judgment therefore turned on the absence of specific knowledge of overseas sales rather than on the fact that the sub-sales were made after the original contract was concluded. If there had been specific knowledge on the part of the sellers that the locks were likely to be exported either alone or as components of furniture, I think the decision in the case would have
been different.
It is also worth noting that the case of **Patrick v Russo-British Grain Export Co** [1927] 2 KB 535 was not cited to Justice Lai Kew Chai. That case has stood for more than 70 years as an authority that loss of profits on sub-sales effected after the original contract is made can be recovered. There, wheat was bought and resold at a higher price. The seller failed to deliver, and there was no market available to the buyer at the time of the breach or subsequently. The parties contemplated that the wheat would probably be resold. Salter J awarded the plaintiffs the resale price less the contract price (ie their gross profit) as damages. He stated:
The arbitrators [this was an appeal from an arbitration decision] find that both parties contemplated that the buyer would probably resell. ... Hammond v Bussey is authority for holding that it is not necessary, in order to entitle the buyer to recover loss of profit on resale, that the seller should have known, when he sold, that the buyer was buying to implement a contract already made, or that the buyer would certainly resell; it is enough if both parties contemplate that the buyer will probably resell and the seller is content to take the risk. I think, therefore, that the arbitrators finding is sufficient to support a claim for loss of profit on resale. It might well have been insufficient to support a claim for costs incurred in litigation with a sub-buyer or for penalties or damages paid to him.
I next consider the plaintiffs` first ground which was that the defendants did not have any special knowledge before or at the time they entered into the contract with the plaintiffs of the probable resale of the machinery.
The defendants submitted that in 1998 the plaintiffs were not in the business of trading in second hand machinery but were carrying on the businesses of supplying lubricants and spare parts and of acting as contractors. The defendants` witnesses had said in their affidavit of evidence-in-chief that they were aware only of the contracting business. Further, there was no evidence that the plaintiffs had communicated details of any of the sub-sales to the defendants and it was not put to the defendants` managing director that he knew or ought to have known anything about the plaintiffs` sub-sales.
The plaintiffs, on the other hand, pointed out that under cross-examination, the defendants` managing director, Mr Matsunaga, when asked about the nature of the dealings between the plaintiffs and the defendants, had stated that the defendants had procured and the plaintiffs had supplied them with lubricants, construction materials and machinery and other requirements for their project. When he was asked whether it was correct to say that the plaintiffs were supplying spare parts and whatever the defendants required for their quarry, his reply was that he had to clarify that the general items supplied were in relation to items required for construction equipment. When asked what he thought the plaintiffs would have done with the machines, his reply was that he thought the plaintiffs wanted them for their own quarry works or for civil engineering works. Mr Matsunaga indicated that he did not assume that the machines were wanted for resale purposes as the pricing had been made on `FOB Karimun` terms. He then conceded, however, that the machines had to be exported (and this would have been at the plaintiffs` cost) and that he knew that the plaintiffs had no operations in Singapore. He also confirmed that the defendants had previously sold some machinery to the plaintiffs though he was quick to add that this had been sold as scrap.
The learned assistant registrar who had the advantage of seeing the witnesses obviously made a finding of fact that the defendants were aware that the machines would probably be resold. There is
material in the evidence to support this finding. Quite apart from the fact that even on paper Mr Matsunaga does not appear to have been a satisfactory witness in that his answers were often reluctant and evasive, it was clear that since the defendants knew that the plaintiffs did not operate any quarries in Indonesia or in Singapore but had bought these machines on the basis that they would be exported from Karimun, it was probable they were being bought for resale. Further, the chairman of the plaintiffs gave evidence that the defendants were made aware at an early stage that the plaintiffs intended to resell the machines. The quantity of machines bought was also significant. If you need 24 machines you must have a reasonably large project. But the defendants were well aware that the plaintiffs were not a large operation and that they did not operate any quarries. Finally, when the defendants were unable to deliver six of the machines, they offered to act as middleman for the plaintiffs in the sale of these six machines to PTKG and to pass on all proceeds from the sale to the plaintiffs. The fact that they thought that such an offer would help compensate the plaintiffs for their loss indicates that they knew that the plaintiffs` intention was to sell the machines and considered that the plaintiffs` intended resale could be replaced by the resale to PTKG.
In the result, since the defendants were probably aware of the plaintiffs` intention to resell the machines, and since there was no available market where substitute machines could be purchased to fulfil the sub-sale contracts, the damages awarded are not too remote and the first ground of appeal must fail.
**_Did the plaintiffs mitigate their loss?_**
It is well known that the innocent party in a breach of contract case is required by law to take reasonable steps to try and minimise the damages that he will suffer as a result of the breach. **_McGregor on Damages_** sets out the position succinctly:
295 The extent of the damage resulting from a wrongful act, whether tort or breach of contract, can often be considerably lessened by well-advised action on the part of the person wronged. In such circumstances the law requires him to take all reasonable steps to mitigate the loss consequent on the defendants wrong, and refuses to allow him damages in respect of any part of the loss which is due to his neglect to take such steps. Even persons against whom wrongs have been committed are not entitled to sit back and suffer loss which could have been avoided by reasonable efforts or to continue an activity unreasonably so as to increase the loss. This well-established rule finds its most authoritative expression in the speech of Viscount Haldane LC in the leading case of British Westinghouse Co v Underground Ry where he said:
The fundamental basis is thus compensation for pecuniary loss naturally flowing from the breach; but this first principle is qualified by a second, which imposes on a plaintiff the duty of taking all reasonable steps to mitigate the loss consequent on the breach, and debars him from claiming any part of the damage which is due to his neglect to take such steps.
The defendants` submission was that they were willing to deliver 18 of the 24 machines to the plaintiffs and that if the plaintiffs had taken these machines, they would have been able to satisfy most of the sub-sales. They would have made a profit from the 18 machines and would have only lost the profit on the six machines which the defendants were unable to supply.
The plaintiffs rejected this contention. They argued that the defendants had initially totally repudiated the contract and only when threatened with legal action did they come forward and offer
to deliver 18 machines. They also cast doubt on the authenticity of the offer to deliver 18 machines pointing out that the letter from PTKG had indicated that that company was interested in eight machines rather than six as maintained by the defendants. The plaintiffs had no confidence in obtaining any unit at all at the material time because the defendants` position was that they could not get an export permit and it was clear that unless PTKG was prepared to release the machinery, the defendants would not be able to get it out of Karimun. Subsequent events showed the plaintiffs had been right to be doubtful because PTKG ended up buying nine machines rather than only six.
The plaintiffs` submissions on the issue of mitigation are not easy to accept. The defendants made several offers to the plaintiffs to try and reduce the losses that the latter would incur by reason of the defendants` inability to comply fully with the sale terms. They offered to sell the machines on the same terms and conditions as previously, they offered to make arrangements for the plaintiffs to inspect the machines again and they offered to act as brokers for the plaintiffs in respect of the six machines which PTKG wanted. The defendants were so keen to conciliate the plaintiffs that even after proceedings were commenced, they did not proceed with the sale to PTKG but held it back until April 1999 when it was clear that there could be no compromise. In my view the fact that PTKG eventually bought nine machines does not detract from the genuineness of the defendants` offer since there was evidence that the defendants had export permits for all 18 machines and the sale of the three additional machines was not effected until after it was clear that the plaintiffs had no intention of taking any of the remaining machines.
The defendants` offer to supply the 18 machines was not made only once. It was made several times starting from December 1998, first in the defendants` own letters and subsequently in several open letters from the defendants` solicitors to the plaintiffs` solicitors. If the plaintiffs had taken up this offer, they could have fulfilled some of the sub-sales as the evidence of at least two of the subpurchasers was that they could price the machines individually and sell them separately. One of them expressly agreed that even if the plaintiffs could not deliver one out of the five units which he had contracted to purchase, he would have accepted the other four.
The evidence supports the inference that the real reason why the plaintiffs did not take up the defendants` offer was that they not only wanted the 18 machines but also wanted the defendants to agree to their other terms for a negotiated settlement. This included payment of monetary compensation and settlement of their legal fees. As their managing director stated, actually it was not that the plaintiffs did not want to accept the machines (and in fact they wanted those machines) but they had already set down their terms for such acceptance and the defendants did not agree to those conditions. The defendants` failure to agree to the plaintiffs` conditions should not have been a stumbling block. The plaintiffs could easily have replied to the defendants` various offers by stating that they were willing to accept 18 machines without prejudice to their right to claim for the other damages inflicted by the breach.
In my judgment, it was unreasonable on the part of the plaintiffs to refuse to accept delivery of the 18 machines. These were the exact machines they had agreed to buy originally, not substitute machines, and they had agreed to sell these same machines to their sub-purchasers. These were independent machines and there was no evidence that any of the 18 units could not have functioned without the presence of one or more of the six units which the defendants were withholding. Neither was there any evidence that any of the sub-purchasers could reasonably reject the tender of any of the machines on the basis that not all the machines they had contracted to buy were being delivered. There were also two sub-sales which were wholly unaffected by the defendants` breach in that none of the machines which the plaintiffs had agreed to sell under those two sub-sales were among the machines which the defendants would not be delivering. Further, the defendants were offering an immediate delivery so that there was no significant delay which could have altered the plaintiffs`
position vis-.-vis their sub-contractors.
In the result, the plaintiffs having failed to mitigate their loss in respect of 18 machines are not able to recover those losses from the defendants. They are, however, able to recover the loss of profits which they incurred by reason of the defendants` inability to deliver six machines to them. They did not have to accept the defendants` offer to act as a broker in the sale of those machines to PTKG because that would mean accepting that sale and its proceeds in place of the sub-sales the plaintiffs themselves had arranged. They are entitled to recover their full loss in respect of those six machines and not simply the difference between the price at which they bought them from the defendants and the defendants sold them to PTKG.
**_Conclusion_**
In the result, I allow the defendants` appeal and set aside the assessment below which was based on non-delivery of 24 machines. I am remitting the case back to the registrar to assess the plaintiffs` loss of profits in respect of the six machines which could not have been delivered. In considering this point, the registrar would also have to consider whether the plaintiffs` profits on those machines were excessive and if so, make the necessary adjustments. As for costs, I will hear arguments from parties on how the costs here and below should be apportioned in the light of the partial success of the defendants.
## Outcome:
Appeal allowed.
Copyright © Government of Singapore.
Source: [link](https://www.singaporelawwatch.sg/Portals/0/Docs/Judgments/[2000] SGHC 80.pdf)
|
C++
|
UTF-8
| 7,357 | 3.0625 | 3 |
[] |
no_license
|
#ifndef WAITQUEUE_H
#define WAITQUEUE_H
#include "abstractqueue.h"
#include <QMap>
#include <QMutex>
#include <QWaitCondition>
#define WAIT_DEFAULT_QUEUE_MAX_SIZE 20
/**
* if buffer overflow, will wait.
*/
template <typename T>
class WaitQueue: public AbstractQueue<T>{
typedef typename AbstractQueue<T>::QueueNode Node;
public:
explicit WaitQueue();
explicit WaitQueue(unsigned long maxSize);
~WaitQueue();
virtual T * peekReadable(unsigned long timeout) override;
virtual void next(T * data) override;
virtual QList<T*> peekAllReadable(unsigned long timeout) override;
virtual void nextAll(const QList<T*> &list) override;
virtual T * peekWriteable() override;
virtual void push(T * data) override;
virtual QList<T*> peekAllWriteable() override;
virtual void pushAll(const QList<T*> &list) override;
virtual void abort() override;
virtual bool isAbort() override;
private:
Node * m_wIdx;
Node * m_rIdx;
unsigned int m_maxSize;
bool m_abort;
QMap<T*,Node*> m_map;
QMutex m_mutex;
QWaitCondition m_cond;
};
template<typename T>
WaitQueue<T>::WaitQueue()
:m_wIdx(nullptr),
m_rIdx(nullptr),
m_maxSize(WAIT_DEFAULT_QUEUE_MAX_SIZE),
m_abort(false)
{
m_wIdx = new Node();
m_rIdx = new Node();
m_wIdx->pre = m_rIdx;
m_wIdx->next = m_rIdx;
m_rIdx->next = m_wIdx;
m_rIdx->pre = m_wIdx;
m_map.insert(&m_wIdx->data,m_wIdx);
m_map.insert(&m_rIdx->data,m_rIdx);
Node * node = nullptr;
for(unsigned int i = 0;i< m_maxSize;i++){
node = new Node();
node->pre = m_wIdx;
node->next = m_wIdx->next;
node->pre->next = node;
node->next->pre = node;
m_map.insert(&node->data,node);
}
}
template<typename T>
WaitQueue<T>::WaitQueue(unsigned long maxSize)
:m_wIdx(nullptr),
m_rIdx(nullptr),
m_maxSize(maxSize),
m_abort(false)
{
m_wIdx = new Node();
m_rIdx = new Node();
m_wIdx->pre = m_rIdx;
m_wIdx->next = m_rIdx;
m_rIdx->next = m_wIdx;
m_rIdx->pre = m_wIdx;
m_map.insert(&m_wIdx->data,m_wIdx);
m_map.insert(&m_rIdx->data,m_rIdx);
Node * node = nullptr;
for(unsigned int i = 0;i< m_maxSize;i++){
node = new Node();
node->pre = m_wIdx;
node->next = m_wIdx->next;
node->pre->next = node;
node->next->pre = node;
m_map.insert(&node->data,node);
}
}
template<typename T>
WaitQueue<T>::~WaitQueue()
{
while(m_rIdx->next != m_wIdx){
Node *readNode = m_rIdx->next;
readNode->pre->next = readNode->next;
readNode->next->pre = readNode->pre;
readNode->next = nullptr;
readNode->pre = nullptr;
delete readNode;
}
while(m_wIdx->next != m_rIdx){
Node * writeNode = m_wIdx->next;
writeNode->pre->next = writeNode->next;
writeNode->next->pre = writeNode->pre;
writeNode->pre = nullptr;
writeNode->next = nullptr;
delete writeNode;
}
delete m_rIdx;
delete m_wIdx;
}
template<typename T>
T *WaitQueue<T>::peekReadable(unsigned long timeout)
{
QMutexLocker locker(&m_mutex);
while(m_rIdx->next == m_wIdx && !m_abort){
if(!m_cond.wait(&m_mutex,timeout)){
// timeout
return nullptr;
}
}
if(m_abort){
return nullptr;
}
// detach read node
Node *readNode = m_rIdx->next;
readNode->pre->next = readNode->next;
readNode->next->pre = readNode->pre;
readNode->next = nullptr;
readNode->pre = nullptr;
return &readNode->data;
}
template<typename T>
void WaitQueue<T>::next(T *data)
{
if(!m_map.contains(data)){
return;
}
m_mutex.lock();
// insert read node
Node *readNode = m_map.value(data);
readNode->pre = m_rIdx->pre;
readNode->next = m_rIdx;
readNode->pre->next = readNode;
readNode->next->pre = readNode;
readNode = nullptr;
m_cond.wakeOne();
m_mutex.unlock();
}
template<typename T>
QList<T *> WaitQueue<T>::peekAllReadable(unsigned long timeout)
{
QList<T*> list;
QMutexLocker locker(&m_mutex);
while(m_rIdx->next == m_wIdx && !m_abort){
if(!m_cond.wait(&m_mutex,timeout)){
// timeout
return list;
}
}
if(m_abort){
return list;
}
while(m_rIdx->next != m_wIdx){
// detach read node
Node *readNode = m_rIdx->next;
readNode->pre->next = readNode->next;
readNode->next->pre = readNode->pre;
readNode->next = nullptr;
readNode->pre = nullptr;
list.append(&readNode->data);
}
return list;
}
template<typename T>
void WaitQueue<T>::nextAll(const QList<T *> &list)
{
m_mutex.lock();
for(auto data : list){
if(!m_map.contains(data)){
continue;
}
// insert read node
Node *readNode = m_map[data];
readNode->pre = m_rIdx->pre;
readNode->next = m_rIdx;
readNode->pre->next = readNode;
readNode->next->pre = readNode;
readNode = nullptr;
}
m_cond.wakeAll();
m_mutex.unlock();
}
template<typename T>
T *WaitQueue<T>::peekWriteable()
{
QMutexLocker locker(&m_mutex);
while(m_wIdx->next == m_rIdx && !m_abort){
m_cond.wait(&m_mutex);
}
if(m_abort){
return nullptr;
}
// detach write node
Node * writeNode = m_wIdx->next;
writeNode->pre->next = writeNode->next;
writeNode->next->pre = writeNode->pre;
writeNode->pre = nullptr;
writeNode->next = nullptr;
return &writeNode->data;
}
template<typename T>
void WaitQueue<T>::push(T *data)
{
if(!m_map.contains(data)){
return;
}
m_mutex.lock();
// insert write node
Node * writeNode = m_map[data];
writeNode->pre = m_wIdx->pre;
writeNode->next = m_wIdx;
writeNode->pre->next = writeNode;
writeNode->next->pre = writeNode;
writeNode = nullptr;
m_cond.wakeOne();
m_mutex.unlock();
}
template<typename T>
QList<T *> WaitQueue<T>::peekAllWriteable()
{
QList<T*> list;
QMutexLocker locker(&m_mutex);
while(m_wIdx->next == m_rIdx && !m_abort){
m_cond.wait(&m_mutex);
}
if(m_abort){
return list;
}
while(m_wIdx->next != m_rIdx){
// detach write node
Node * writeNode = m_wIdx->next;
writeNode->pre->next = writeNode->next;
writeNode->next->pre = writeNode->pre;
writeNode->pre = nullptr;
writeNode->next = nullptr;
list.append(&writeNode->data);
}
return list;
}
template<typename T>
void WaitQueue<T>::pushAll(const QList<T *> &list)
{
m_mutex.lock();
for(auto data : list){
// insert write node
Node * writeNode = m_map[data];
writeNode->pre = m_wIdx->pre;
writeNode->next = m_wIdx;
writeNode->pre->next = writeNode;
writeNode->next->pre = writeNode;
writeNode = nullptr;
}
m_cond.wakeAll();
m_mutex.unlock();
}
template<typename T>
void WaitQueue<T>::abort()
{
m_mutex.lock();
m_abort = true;
m_cond.wakeAll();
m_mutex.unlock();
}
template<typename T>
bool WaitQueue<T>::isAbort()
{
QMutexLocker locker(&m_mutex);
return m_abort;
}
#endif // WAITQUEUE_H
|
Java
|
UTF-8
| 1,722 | 2.40625 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cardholders;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Администратор
*/
public class ChsCfg {
private String GRhost;
private String AShost;
public ChsCfg(){
FileInputStream fileInput = null;
Properties prop = new Properties();
try {
File file = new File("/opt/wso2/appconf/cardholders.cfg");
if (!file.exists()){
file = new File("C:/opt/wso2/appconf/cardholders.cfg");
if (!file.exists()){
return;
}
}
fileInput = new FileInputStream(file);
prop.loadFromXML(fileInput);
this.GRhost = prop.getProperty("GRhost");
this.AShost = prop.getProperty("AShost");
} catch (IOException ex) {
Logger.getLogger(ChsCfg.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fileInput.close();
} catch (IOException ex) {
Logger.getLogger(ChsCfg.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* @return the GRhost
*/
public String getGRhost() {
return GRhost;
}
/**
* @return the AShost
*/
public String getAShost() {
return AShost;
}
}
|
C++
|
UTF-8
| 1,731 | 2.640625 | 3 |
[] |
no_license
|
#ifndef __AZURITE__INNER__STATE_MACHINE
#define __AZURITE__INNER__STATE_MACHINE
#include <stack>
#include <queue>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <optional>
namespace Azurite {
class Game;
class AState;
struct Event;
// State Manager Class
class StateMachine {
Game &m_owner;
std::stack<std::unique_ptr<AState>> m_states;
public:
// This method should only be called by the Owner of the state machine
void update();
// This class should only be built by game class
StateMachine(Game &owner);
~StateMachine();
// Control Methods
void setState(std::unique_ptr<AState>);
void stackState(std::unique_ptr<AState>);
void leaveCurrentState();
std::optional<std::reference_wrapper<AState>> getCurrentState() const;
};
// State abstract parent
class AState {
static unsigned statesCount;
const unsigned m_id;
protected:
std::queue<Event> m_events;
public:
AState();
virtual ~AState();
// Control Methods
unsigned getId() const;
void sendEvent(const Event event);
std::optional<Event> readEvent();
// State Logic Methods
virtual void onStart(Game &instance) = 0;
virtual void onTick(Game &instance) = 0;
virtual void onPause(Game &instance) = 0;
virtual void onResume(Game &instance) = 0;
virtual void onStop(Game &instance) = 0;
};
// Struct used to system-state communication
struct Event {
std::string name;
};
}
#endif
/*
** DEPENDENCIES
*/
#ifndef __AZURITE__INNER__GAME
#include "Azurite/Game.hpp"
#endif
|
Python
|
UTF-8
| 2,840 | 3.25 | 3 |
[
"Apache-2.0"
] |
permissive
|
'''Functions that are generic enough to not belong in any class'''
import numpy as np
def read(filelist):
'''Read in and concatenate a list of numpy files'''
data = []
for f in sorted(filelist):
x = np.load(f)
if len(data) == 0: data = x.copy()
else: data = np.concatenate([data, x])
return data
def to_unit_vector(ra, dec):
'''Convert location on unit sphere to rectangular coordinates'''
return np.array([np.cos(ra)*np.cos(dec),
np.sin(ra)*np.cos(dec),
np.sin(dec)])
def angular_distance(ra_A, dec_A, ra_B, dec_B):
'''Calculate the angle between two points on the unit sphere'''
unit_A = to_unit_vector(ra_A, dec_A)
unit_B = to_unit_vector(ra_B, dec_B)
if len(unit_A.shape) != 1:
return np.arccos(np.dot(unit_A.T, unit_B))
else:
return np.arccos(np.dot(unit_A, unit_B))
def rotate(ra1, dec1, ra2, dec2, ra3, dec3):
'''Rotation matrix for rotation of (ra1, dec1) onto (ra2, dec2).
The rotation is performed on (ra3, dec3).
'''
def cross_matrix(x):
'''Calculate cross product matrix
A[ij] = x_i * y_j - y_i * x_j
'''
skv = np.roll(np.roll(np.diag(x.ravel()), 1, 1), -1, 0)
return skv - skv.T
ra1 = np.atleast_1d(ra1)
dec1 = np.atleast_1d(dec1)
ra2 = np.atleast_1d(ra2)
dec2 = np.atleast_1d(dec2)
ra3 = np.atleast_1d(ra3)
dec3 = np.atleast_1d(dec3)
assert(
len(ra1) == len(dec1) == len(ra2) == len(dec2) == len(ra3) == len(dec3)
)
cos_alpha = np.cos(ra2 - ra1) * np.cos(dec1) * np.cos(dec2) \
+ np.sin(dec1) * np.sin(dec2)
# correct rounding errors
cos_alpha[cos_alpha > 1] = 1
cos_alpha[cos_alpha < -1] = -1
alpha = np.arccos(cos_alpha)
vec1 = np.vstack([np.cos(ra1) * np.cos(dec1),
np.sin(ra1) * np.cos(dec1),
np.sin(dec1)]).T
vec2 = np.vstack([np.cos(ra2) * np.cos(dec2),
np.sin(ra2) * np.cos(dec2),
np.sin(dec2)]).T
vec3 = np.vstack([np.cos(ra3) * np.cos(dec3),
np.sin(ra3) * np.cos(dec3),
np.sin(dec3)]).T
nvec = np.cross(vec1, vec2)
norm = np.sqrt(np.sum(nvec**2, axis=1))
nvec[norm > 0] /= norm[np.newaxis, norm > 0].T
one = np.diagflat(np.ones(3))
nTn = np.array([np.outer(nv, nv) for nv in nvec])
nx = np.array([cross_matrix(nv) for nv in nvec])
R = np.array([(1. - np.cos(a)) * nTn_i + np.cos(a) * one + np.sin(a) * nx_i
for a, nTn_i, nx_i in zip(alpha, nTn, nx)])
vec = np.array([np.dot(R_i, vec_i.T) for R_i, vec_i in zip(R, vec3)])
ra = np.arctan2(vec[:, 1], vec[:, 0])
dec = np.arcsin(vec[:, 2])
ra += np.where(ra < 0., 2. * np.pi, 0.)
return ra, dec
|
Markdown
|
UTF-8
| 2,589 | 2.796875 | 3 |
[] |
no_license
|
Action planning
## Motivation
- We are going to die.
- Knowing your "Why"
## Discipline
You will never stay in same motivation.
> "Amateurs sit and wait for inspiration, the rest of us just get up and go to work."
> "We are what we repeatedly do."
Productivity is doing the right things consistently.
Momentum and inertia are the key determinants of consistent productivity.
Choose solutions over distractions.(distractions, when you meet problem, choose the things make you forget the problem temporarilly)
## Busy vs Productive
## Minimize the distraction
Do as hard as possible.
## Multitask.
## Social work kill your productivity.
Consume Attention.
We check about 150 times phone daily.
Just try QUIT for 30 days.
## Take charge of your time.
Do not live on others scheduels.
## Meeting
Minimize the meeting time.
## Eliminating you personal procrastination triggers.
Create an environment where you can go to be reliably productive.
## Information overload
Make sure apply what you learn.(What am doing now.)
## Identify your peak performance time
Try the morning. No distractions. No ego depletion(willpower charged).
Planning & Reflection.
Morning give your day momentum.
Accomplish more in you first three hours than most people accomplish in their entire day.(Think about it)
## How to be a morning person
1. Go to bed when your are too tired to stay up
2. Set an alarm to wake up at a fixed time everyday.
3. Don't hesitate to get up!
## Only two thing to focus on to achieve goals
1. Your overall version and goals.
2. Actionable tasks.
Sum of tasks = long term version.
## Conducting an annual review
Set a fix time to do review without any distaction.
(Chrisguillebeau.com)
1. what went well
2. what did not go well
5~10 answers each question.
## Use a task manager to plan and organize your work.
todoist.
## Conducting a weekly review
Set 30 minutes.
1. Process inboxes.
2. Brain dump. (Add to todoist.
3. Review completed items.
4. Review the long-term goal.
5. Answers:
- what went well
- what didn't go well
- what should stop doing
- what should start doing
- what should I continue doing
6. Schedule priority tasks
## Developing a work ethic
No thing in life worth having comes easy.
Compare the feeling when you get things done VS procrastinate.
"Just waiting for ..."
Just get started. try do a tiny bit.
Motivations is reuslt of action.
## Deadline.
Work like a gas.
Be aware of how much time you spend on the task.
Set a strict deadline on the task, and follow it.
## Batch similar tasks.
Create a done list.
|
Shell
|
UTF-8
| 432 | 3.21875 | 3 |
[] |
no_license
|
#! /bin/bash
#cat <<End-of
l="line 3"
read -p "press any key:" k
cat <<End-of-message
-------------------------------------
This is line 1 of the message.
This is line 2 of the message.
This is $l of the message.
This is line 4 of the message.
This is the last line of the message.
$k
-------------------------------------
End-of-message
variable=$(cat <<SETVAR
This variable
runs over multiple lines.
SETVAR
)
echo "$variable"
|
Java
|
UTF-8
| 6,185 | 2.484375 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import Conexion.Conexion;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import modelo.CategoriaDTO;
import modelo.PromocionesDTO;
/**
*
* @author esteb
*/
public class CategoriaDAO {
private static final String SQL_INSERT = "insert into categorias values(?,?,?,?)";
private static final String SQL_DELETE = "delete from categorias where idCategorias=?; delete from promociones where idPromociones=?";
private static final String SQL_UPDATE = "update categorias SET tipo_producto=? where idCategorias=?";
private static final String SQL_READ = "select * from categorias where idCategorias=?";
private static final String SQL_READALL = "select * from categorias";
private static final Conexion conn = Conexion.saberestado();
/**
*
* Metodo que inserta datos en la tabla categorias que se encuentra en la base de datos
* @param c
* @return Metodo que retorna un boolean
*/
public boolean añadircategoria(CategoriaDTO c) {
try {
try {
PreparedStatement ps;
ps=conn.getConn().prepareStatement(SQL_INSERT);
ps.setInt(1, c.getId());
ps.setString(2, c.getTipodeproducto());
ps.setInt(3, c.getIdmenu());
ps.setInt(4, c.getIdpromocion());
if(ps.executeUpdate()>0){
JOptionPane.showMessageDialog(null, "categoria añadida correctamente");
return true;
}
} catch (MySQLIntegrityConstraintViolationException ex) {
JOptionPane.showMessageDialog(null, "codigo ya existe");
}
} catch (SQLException ex) {
Logger.getLogger(CategoriaDAO.class.getName()).log(Level.SEVERE, null, ex);
}finally{
conn.cerrarconexion();
}
JOptionPane.showMessageDialog(null, "error al registrar");
return false;
}
/**
* Metodo que permite eliminar datos dentro de la tabla categorias que se encuentra en la base de datos
* @param c
* @return Metodo que retorna un boolean
*/
public boolean eliminarcategoria(CategoriaDTO c) {
try {
PreparedStatement ps;
ps=conn.getConn().prepareStatement(SQL_DELETE);
ps.setInt(1, c.getId());
if(ps.executeUpdate()>0){
JOptionPane.showMessageDialog(null, "elminado correctamente");
return true;
}
} catch (SQLException ex) {
Logger.getLogger(CategoriaDAO.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(null, "error al eliminar");
return false;
}
/**
* Metodo que modifica los datos dentro de la tabla categorias que se encuentraen la base de datos
* @param c
* @return Metodo que retorna un boolean
*/
public boolean modificarcategoria(CategoriaDTO c){
try {
PreparedStatement ps;
ps=conn.getConn().prepareStatement(SQL_UPDATE);
ps.setString(1, c.getTipodeproducto());
ps.setInt(2, c.getId());
if(ps.executeUpdate()>0){
JOptionPane.showMessageDialog(null, "modificado correctamente");
return true;
}
} catch (SQLException ex) {
Logger.getLogger(CategoriaDAO.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(null, "error al modificar");
return false;
}
/**
* Metodo que permite buscar datos dentro de la tabla categorias de la base de datos
* @param c
* @return Metodo que retorna un objeto de tipo CateogiriaDTO
*/
public CategoriaDTO buscarcategoria(CategoriaDTO c){
PreparedStatement ps;
ResultSet res;
CategoriaDTO cdto=null;
try {
ps=conn.getConn().prepareStatement(SQL_READ);
ps.setInt(1, c.getId());
res= ps.executeQuery();
while (res.next()) {
cdto=new CategoriaDTO(res.getInt(1), res.getString(2), res.getInt(3), res.getInt(4));
}
return cdto;
} catch (SQLException ex) {
Logger.getLogger(CategoriaDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Metodo que almacena un objeto de tipo CategoriaDTO, y permite mostrar todos los datos de la tabla categorias que se encientra en la base de datos
* @return Metodo que retorna un ArrayList
*/
public ArrayList<CategoriaDTO>mostrartodos(){
PreparedStatement ps;
ResultSet res;
ArrayList <CategoriaDTO>arr=new ArrayList();
try {
ps=conn.getConn().prepareStatement(SQL_READALL);
res=ps.executeQuery();
while (res.next()){
arr.add(new CategoriaDTO(res.getInt(1), res.getString(2), res.getInt(3), res.getInt(4)));
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "error vuelva a intentar");
}finally{
conn.cerrarconexion();
}
return arr;
}
}
|
Java
|
UTF-8
| 6,119 | 2.640625 | 3 |
[] |
no_license
|
package com.cg.migrationapp.controller;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.cg.migrationapp.dto.Booking;
import com.cg.migrationapp.dto.Theater;
import com.cg.migrationapp.exception.MovieException;
import com.cg.migrationapp.service.MovieService;
import com.cg.migrationapp.service.MovieServiceImpl;
/**
* Servlet implementation class MovieController
*/
@WebServlet("/MovieController")
public class MovieController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
RequestDispatcher view = null;
MovieService service = new MovieServiceImpl();
// Initial setting the session parameter to false
HttpSession session = request.getSession(false);
// action to fetch movie names available
if (action != null && action.equalsIgnoreCase("fetchName")) {
try {
ArrayList<String> movieNames = service.getMovieNames();
request.setAttribute("movieNames", movieNames);
view = getServletContext().getRequestDispatcher(
"/pages/movieList.jsp");
view.forward(request, response);
} catch (MovieException | SQLException e) {
// dispatching control to error page
request.setAttribute("errMsg", e.getMessage());
view = getServletContext().getRequestDispatcher(
"/pages/error.jsp");
view.forward(request, response);
}
}
// action to search theaters which play selected movie
if (action != null && action.equalsIgnoreCase("Search")) {
String movieName = request.getParameter("movieName");
System.out.println("This is"+movieName);
// if an existing session is not there, then creating a new one.
if (session == null) {
session = request.getSession(true);
}
session.setAttribute("movieName", movieName);
try {
ArrayList<Theater> theaterList = service.searchMovie(movieName);
session.setAttribute("theaterList", theaterList);
view = getServletContext().getRequestDispatcher(
"/pages/showTheaters.jsp");
view.forward(request, response);
} catch (MovieException | SQLException e) {
request.setAttribute("errMsg", e.getMessage());
view = getServletContext().getRequestDispatcher(
"/pages/error.jsp");
view.forward(request, response);
}
}
// action to allow the user to avail booking for a particular movie
if (action != null && action.equalsIgnoreCase("Book")) {
if (session != null) {
int theaterId = Integer.parseInt(request
.getParameter("theaterId"));
ArrayList<Theater> theaterList = (ArrayList<Theater>) session
.getAttribute("theaterList");
for (Theater theaterDetails : theaterList) {
if (theaterId == theaterDetails.getTheaterId()) {
session.setAttribute("theaterDetails", theaterDetails);
}
}
view = getServletContext().getRequestDispatcher(
"/pages/bookNow.jsp");
view.forward(request, response);
} else {
// dispatching control to error page if session is null
request.setAttribute("errMsg", "Invalid Request");
view = getServletContext().getRequestDispatcher(
"/pages/error.jsp");
view.forward(request, response);
}
}
// action to confirm movie booking
if (action != null && action.equalsIgnoreCase("ConfirmBook")) {
if (session != null) {
int quantity = Integer.parseInt(request
.getParameter("quantity"));
Theater theater = (Theater) session
.getAttribute("theaterDetails");
Booking booking = new Booking();
booking.setTheaterName(theater.getTheaterName());
booking.setNoOfTickets(quantity);
float cost = (float) (theater.getTicketPrice() * quantity);
float taxFees = (float) (cost * 10 / 100);
float finalPrice = cost + taxFees;
booking.setTotalPrice(finalPrice);
booking.setMoviePlayTime(theater.getMoviePlayTime());
LocalDate date = LocalDate.now();
booking.setBookingDate(Date.valueOf(date));
session.setAttribute("bookingDetails", booking);
try {
int bookingId = service.makeBooking(booking,
theater.getTheaterId());
if (bookingId != 0) {
session.setAttribute("bookingId", bookingId);
view = getServletContext().getRequestDispatcher(
"/pages/success.jsp");
view.forward(request, response);
} else {
request.setAttribute("errMsg",
"Movie Booking not done.");
view = getServletContext().getRequestDispatcher(
"/pages/error.jsp");
view.forward(request, response);
}
} catch (MovieException | SQLException e) {
request.setAttribute("errMsg", e.getMessage());
view = getServletContext().getRequestDispatcher(
"/pages/error.jsp");
view.forward(request, response);
}
} else {
request.setAttribute("errMsg", "Invalid Request");
view = getServletContext().getRequestDispatcher(
"/pages/error.jsp");
view.forward(request, response);
}
}
// action to logout and invalidate the session
if (action != null && action.equalsIgnoreCase("Logout")) {
if (session != null) {
session.invalidate();
view = getServletContext().getRequestDispatcher("/index.jsp");
view.forward(request, response);
} else {
request.setAttribute("errMsg", "Invalid Request");
view = getServletContext().getRequestDispatcher(
"/pages/error.jsp");
view.forward(request, response);
}
}
}
}
|
C++
|
UTF-8
| 1,567 | 2.78125 | 3 |
[] |
no_license
|
#include "Triangle.h"
Triangle::Triangle()
{
_triangleVertBuffer = 0;
_vertices = 0;
}
Triangle::~Triangle()
{
}
bool Triangle::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext)
{
HRESULT hr;
_indexCount = 3;
//Create the vertex buffer
Vertex v[] =
{
Vertex(0.0f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f),
Vertex(0.5f, -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f),
Vertex(-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f),
};
D3D11_BUFFER_DESC vertexBufferDesc;
ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(Vertex)* _indexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA vertexBufferData;
ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
vertexBufferData.pSysMem = v;
hr = device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &_triangleVertBuffer);
if (FAILED(hr))
{
return false;
}
return true;
}
void Triangle::ReleaseObjects()
{
if (_triangleVertBuffer)
{
_triangleVertBuffer->Release();
_triangleVertBuffer = 0;
}
}
void Triangle::Render(ID3D11DeviceContext* deviceContext)
{
//Set the vertex buffer
UINT stride = sizeof(Vertex);
UINT offset = 0;
deviceContext->IASetVertexBuffers(0, 1, &_triangleVertBuffer, &stride, &offset);
//Set Primitive Topology
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
int Triangle::GetIndexCount()
{
return _indexCount;
}
|
C#
|
UTF-8
| 699 | 2.671875 | 3 |
[] |
no_license
|
using System;
using System.Web;
using AjaxControlToolkit;
public class CombineScriptsHandler : IHttpHandler
{
/// <summary>
/// ProcessRequest implementation outputs the combined script file
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
if (!ToolkitScriptManager.OutputCombinedScriptFile(context))
{
throw new InvalidOperationException("Combined script file output failed unexpectedly.");
}
}
/// <summary>
/// IsReusable implementation returns true since this class is stateless
/// </summary>
public bool IsReusable
{
get { return true; }
}
}
|
Java
|
UTF-8
| 1,048 | 2.265625 | 2 |
[] |
no_license
|
package me.lusu007.lobbysystem.Listener;
import me.lusu007.lobbysystem.System.main;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.potion.PotionEffect;
/**
* Created by Lukas on 25.12.2014.
*/
public class PotionSplashEvent_Listener implements Listener {
private final main plugin;
public PotionSplashEvent_Listener(main main) {
this.plugin = main;
plugin.getServer().getPluginManager().registerEvents(this, main);
}
@EventHandler
public void onSplash(PotionSplashEvent e) {
for(Entity all : e.getAffectedEntities()) {
if(all instanceof Player) {
Player p = (Player) e.getEntity();
for(PotionEffect effect : e.getPotion().getEffects()) {
p.removePotionEffect(effect.getType());
e.setCancelled(true);
}
}
}
}
}
|
Python
|
UTF-8
| 4,001 | 2.953125 | 3 |
[] |
no_license
|
# for a dict of arrays (dd), all same array size, write an arff file, converting complex data to magnitude and phase
""" for complex, had to unroll the loop to write a line of data - slows down about 7x!!
"""
import os
import numpy as np
from numpy.random.mtrand import uniform
# first, arrange a debug one way or another
try:
from debug_ import debug_
except:
def debug_(debug, msg='', *args, **kwargs):
print('attempt to debug ' + msg +
" need boyd's debug_.py to debug properly")
debug=1
# then generate data if there is none
try:
dd.keys()
print('using existing dd dataset')
except:
print('making dummy data')
relation = 'test'
dd = {'f': uniform(size=(10)), 'i': range(10),
'npf':np.linspace(0,10,10),
'c64': np.exp(1j*np.linspace(0,10,10000))}#,'s': ['a','bb']}
def tomagphase(dd, key):
""" This would be happier as class method
given a dictionary of arrays dd, and a key to complex data,
add key and data for the magnitude and another for the phase, then
remove the original key.
This destructive code has the advantage that the write is sped up by
seven times.
"""
dd.update({'mag_'+key: np.abs(dd[key])})
dd.update({'phase_'+key: np.angle(dd[key])})
dd.pop(key)
def split_vectors(dd, newfmts={}): # , keep_scalars=False):
""" pop any vectors and replace them with scalars consecutively numbered
can supply a dictionary of formats for the new names - else use oldkey_0 etc
Alters the dd to contain the items to be saved as scalars
"""
sub_list = []
for k in list(dd.keys()):
order = len(np.shape(dd[k]))
if order==0: # remove scalars - e.g. info
dd.pop(k)
elif order>1:
cols = np.array(dd.pop(k)).T
newks = [] # a list of vector keys and the corresponding split ones
for i in range(len(cols)):
if k in newfmts:
newfmt = newfmts[k]
else:
newfmt = '{k}_{i}'
newk = newfmt.format(k=k, i=i)
dd.update({newk: cols[i]})
newks.append(newk)
sub_list.append([k, newks])
else:
pass # keep column vectors
return(sub_list)
def write_arff(da, filename='tmp.arff', use_keys=[]):
""" use_keys - keys to save, empty list means all
"""
if os.path.exists(filename):os.unlink(filename)
f = open(filename,'w')
dd = da.copyda() # need to copy before vectors are split
# now replace any keys in the key list with their split names
if len(use_keys) == 0: # if empty list, use all
ks = np.sort(dd.keys()).tolist()
else:
ks = use_keys
if 'info' in ks: ks.remove('info') # arff can do info struct.
sub_list = split_vectors(dd)
for key,newks in sub_list:
ks.remove(key)
ks.extend(newks)
f.write("@relation {0}\n".format(relation))
for k in ks:
f.write("@attribute {0} numeric\n".format(k))
f.write('@data'+"\n")
inds = range(len(dd[ks[0]]))
for ind in inds:
f.write(','.join([str(dd[k][ind]) for k in ks]) + "\n")
f.close()
if __name__ == '__main__':
# original primitive code - save the dict in dd
FILE_NAME = 'tmp.arff'
if os.path.exists(FILE_NAME):os.unlink(FILE_NAME)
f = open(FILE_NAME,'w')
ks = np.sort(dd.keys())
f.write("@relation {0}\n".format(relation))
for k in ks:
f.write("@attribute {0} numeric\n".format(k))
f.write('@data'+"\n")
inds = range(len(dd[ks[0]]))
for ind in inds:
f.write(','.join([str(dd[k][ind]) for k in ks]) + "\n")
f.close()
"""
sep14 = nc_storage('sep14.nc')
dd=sep14.restore()
wt=where(abs(dd['time'] -30) < 5)[0]
for k in dd.keys(): exec("dd['{0}']=array(dd['{0}'][wt])".format(k))
x=dd.pop('ne_array')
x=dd.pop('phases')
for coil in 'xyz': tomagphase(dd,'coil_1'+coil)
run -i write_arff.py
"""
|
Java
|
UTF-8
| 406 | 1.78125 | 2 |
[] |
no_license
|
package com.wit.hnxft.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import com.wit.fxp.nxft.domain.model.order.NxftOrder;
import com.wit.hnxft.model.HnxftOrderModel;
@Mapper
public interface HnxftOrderMapper {
HnxftOrderMapper INSTANCE = Mappers.getMapper(HnxftOrderMapper.class);
HnxftOrderModel map(NxftOrder entity, String mealContext, String personMobile);
}
|
C++
|
UTF-8
| 1,719 | 2.59375 | 3 |
[] |
no_license
|
/*----------------------------------------------------------------------------*/
/* */
/* Module: main.cpp */
/* Author: Clara Gehm */
/* Created: Wed Jun 10 2020 */
/* Description: Driver control program for a mecanum drive (H style) */
/* */
/*----------------------------------------------------------------------------*/
// ---- START VEXCODE CONFIGURED DEVICES ----
// Robot Configuration:
// [Name] [Type] [Port(s)]
// Controller1 controller
// frontLeft motor 1
// frontRight motor 2
// backLeft motor 3
// backRight motor 4
// ---- END VEXCODE CONFIGURED DEVICES ----
#include "vex.h"
using namespace vex;
int main()
{
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
while (1==1)
{
int forward = Controller1.Axis3.position(vex::percent);
int sideways = Controller1.Axis4.position(vex::percent);
int turn = Controller1.Axis1.position(vex::percent);
frontRight.spin(vex::forward, forward - sideways + turn, vex::percent);
frontLeft.spin(vex::forward, forward + sideways - turn, vex::percent);
backRight.spin(vex::forward, forward + sideways + turn, vex::percent);
backLeft.spin(vex::forward, forward - sideways - turn, vex::percent);
}
}
|
Java
|
UTF-8
| 4,098 | 2.171875 | 2 |
[] |
no_license
|
//USER INPUTS SHAPE
package com.umbrella.umbrella;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.widget.Toast;
import com.andrognito.patternlockview.PatternLockView;
import com.andrognito.patternlockview.listener.PatternLockViewListener;
import com.andrognito.patternlockview.utils.PatternLockUtils;
import java.util.List;
public class InputPasswordActivity extends AppCompatActivity {
PatternLockView mPatternLockView;
String password;
int passwordAttempts = 0;
CountDownTimer cdt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input_password);
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
password = preferences.getString("password", "0");
cdt = new CountDownTimer(3*60*1000, 1000) {
//Run timer
public void onTick(long millisUntilFinished) {
}
//When timer runs out, send notification that user missed check-in
public void onFinish(){
cdt.cancel();
sendSMS(c.phoneNum, "Your contact missed a check-in! Please ensure her safety.");
returnToTimerPage();
}
}.start();
mPatternLockView = (PatternLockView) findViewById(R.id.pattern_lock_view);
mPatternLockView.addPatternLockListener(new PatternLockViewListener() {
@Override
public void onStarted() {
cdt.cancel();
}
@Override
public void onProgress(List<PatternLockView.Dot> progressPattern) {
}
//Entering in shape
@Override
public void onComplete(List<PatternLockView.Dot> pattern) {
//If correct shape, return to Timer Page
if (password.equals(PatternLockUtils.patternToString(mPatternLockView, pattern))) {
returnToTimerPage();
} else {
Toast.makeText(InputPasswordActivity.this, "Wrong Shape!", Toast.LENGTH_SHORT).show();
mPatternLockView.clearPattern();
passwordAttempts++;
//If incorrect more than three times, notify emergency contact and return to timer page
if (passwordAttempts >= 3) {
sendSMS(c.phoneNum, "Your contact incorrectly inputted their shape. They contact may be in danger! Check up on them!");
returnToTimerPage();
}
}
}
@Override
public void onCleared() {
}
});
}
//Return to timer page
public void returnToTimerPage() {
Intent intent = new Intent(this, TimerPage.class);
intent.putExtra("timeInterval", s.result);
startActivity(intent);
}
//Send SMS
public void sendSMS(String phoneNum, String text){
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNum, null, text, null, null);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage().toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
else{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{android.Manifest.permission.SEND_SMS}, 10);
}
}
}
ChooseContacts c = new ChooseContacts();
TimerPage s = new TimerPage();
}
|
C++
|
UTF-8
| 1,158 | 3.328125 | 3 |
[
"MIT"
] |
permissive
|
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
// 由于1 <= row, col <= 100, 故不需要判断空
int m = grid.size();
int n = grid[0].size();
int area = 0;
int conn = 0; // 每个格子的neighbor数量的总和
for (int y = 0; y < m; y++)
{
for (int x = 0; x < n; x++)
{
if (grid[y][x] == 1)
{
area++;
if (y > 0 && grid[y - 1][x] == 1) conn++; /* 只考虑正上方的格子, 下方的格子根据对称性处理 */
if (x > 0 && grid[y][x - 1] == 1) conn++; /* 正左方的格子, 右方的格子根据对称性处理 */
}
}
}
return area * 4 - conn * 2; /* 只考虑左上, 根据对称性处理 */
}
};
// Test
int main()
{
Solution sol;
vector<vector<int>> grid = {{0, 1, 0, 0}, {1, 1, 1, 0}, {0, 1, 0, 0}, {1, 1, 0, 0}};
auto res = sol.islandPerimeter(grid);
cout << res << endl;
return 0;
}
|
Java
|
UTF-8
| 3,230 | 2.296875 | 2 |
[] |
no_license
|
package util;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.AssertJUnit;
import constants.GeneralComponentIDs;
import constants.PositionComponentIDs;
public class QueryFormUtils {
private WebDriver webDriver;
public QueryFormUtils(WebDriver webDriver) {
this.webDriver = webDriver;
}
public void waitForAutocomplete(String id) {
String valueIn = null;
while (valueIn == null || valueIn == "") {
valueIn = webDriver.findElement(By.id(id)).getAttribute("value");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void insertValue(String id, String i) {
WebElement element = webDriver.findElement(By.id(id));
element.sendKeys(i);
}
public void pressSearchBut() {
WebElement searchBut = webDriver.findElement(By
.id(GeneralComponentIDs.searchButtonId));
searchBut.click();
}
private WebElement getElement(WebDriver driver, String id) {
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement element = webDriver.findElement(By.id(id));
return element;
}
public String extractRAValue() {
WebElement ra = getElement(webDriver, PositionComponentIDs.raId);
return ra.getAttribute("value");
}
public String extractDecValue() {
WebElement dec = getElement(webDriver, PositionComponentIDs.decId);
return dec.getAttribute("value");
}
public String extractRadiusValue() {
WebElement radius = getElement(webDriver,
PositionComponentIDs.searchRadiusId);
return radius.getAttribute("value");
}
public void checkRadiusFieldIsMandatory() {
WebElement radius = getElement(webDriver,
PositionComponentIDs.searchRadiusId);
String radiusAttribute = radius.getAttribute("class");
AssertJUnit.assertTrue("Radius field is mandatory!",
radiusAttribute != null);
}
public void selectOptionInMultiSelectDropDown(String id, String optionText) {
JavascriptExecutor js = (JavascriptExecutor) webDriver;
js.executeScript("document.getElementById('" + id
+ "').style.display='block';");
Select dropdown = new Select(webDriver.findElement(By.id(id)));
dropdown.selectByVisibleText(optionText);
}
public void checkNoResultsMessage() {
WebDriverWait wait = new WebDriverWait(webDriver, 10);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//span[@class='grid-message'][1]")));
WebElement msg = webDriver.findElement(By
.xpath("//span[@class='grid-message'][2]"));
Assert.assertTrue(
msg.getText()
.contains(
"No results were found. Please relax your search criteria and search again"),
"Results were retrieved when they shouldn't");
}
public void clearValue(String fieldId) {
WebElement element = webDriver.findElement(By.id(fieldId));
element.clear();
}
}
|
Markdown
|
UTF-8
| 2,153 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
* * *
本项目是华为2019年软件精英挑战赛的[初赛题目](https://codecraft.huawei.com/Generaldetail)的实现,初赛排名**西北赛区 41 名**
[项目地址:https://github.com/WFrame0224/SDK_python](https://github.com/WFrame0224/SDK_python)
* * *
**目录**
- [1. 运行说明](#1-运行说明)
- [2. 程序数据结构](#2-程序数据结构)
- [3. 程序文档说明](#3-程序文档说明)
- [3.1 程序函数说明](#3-1-程序函数说明)
- [3.2 程序逻辑简要说明](#3-2-程序逻辑简要说明)
* * *
## 1. 运行说明
- 使用语言 python 3.5
- 采用的是 Ubuntu 18.04.2
- 目录结构如下所示:

- 运行时,执行下面任意一条命令即可:
- `python CodeCraft-2019.py ../config/car.txt ../config/road.txt ../config/cross.txt ../config/answer.txt`
- `python dispatcher.py`
## 2. 程序数据结构

上图所示为代码所用的数据结构
## 3. 程序文档说明
### 3.1 程序函数说明
- `strListToIntList(srcStr)` strList转换为intList,方便后面的操作
- `loadData(filePath)` 用于载入数据的函数生成器,调用一次返回一行数据
- `loadRoadData(road_path)` 读取道路的数据
- `loadCarData(car_path)` 用于载入car的数据建立有序的Cars二维列表
- `loadCrossData(cross_path)` 此函数用于读取路口信息,返回
- `getRoadId(head, tail, Crosses)` 函数用于返回两个路口连接的道路标号
- `creatGraph()` 函数用于构建一基本路口道路有向图
- `driveCar2()` 此函数是按照一定的发车方式,上路进行奔跑
### 3.2 程序逻辑简要说明
- _注_:程序并未实现==调度器==,或者是==判题器==,实际上式找了捷径,优化发车策略(调参)进行最大程度地避免死锁现象的发生
- 程序主要执行逻辑如下图所示:

**_注_**:逻辑中,车辆的预处理非常重要,对应于后面的发车策略
|
Java
|
UTF-8
| 1,275 | 1.757813 | 2 |
[] |
no_license
|
import com.tencent.mobileqq.hotpatch.NotVerifyClass;
import com.tencent.mobileqq.utils.HttpDownloadUtil;
import com.tencent.qphone.base.util.QLog;
import cooperation.qzone.font.FontManager;
import java.io.File;
public class ymc
implements Runnable
{
public ymc(FontManager paramFontManager, String paramString, int paramInt)
{
boolean bool = NotVerifyClass.DO_VERIFY_CLASS;
}
public void run()
{
if (QLog.isDevelopLevel()) {
QLog.d("FontManager", 4, "begin to download font file from network, url =" + this.jdField_a_of_type_JavaLangString);
}
if (HttpDownloadUtil.a(null, this.jdField_a_of_type_JavaLangString, new File(FontManager.a(this.jdField_a_of_type_CooperationQzoneFontFontManager, this.jdField_a_of_type_Int)))) {
FontManager.a(this.jdField_a_of_type_CooperationQzoneFontFontManager, this.jdField_a_of_type_Int);
}
for (;;)
{
FontManager.a(this.jdField_a_of_type_CooperationQzoneFontFontManager, this.jdField_a_of_type_Int);
return;
QLog.e("FontManager", 1, "Font Download Failed, font url = " + this.jdField_a_of_type_JavaLangString);
}
}
}
/* Location: E:\apk\QQ_91\classes2-dex2jar.jar!\ymc.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
|
JavaScript
|
UTF-8
| 744 | 2.984375 | 3 |
[] |
no_license
|
exports.trimMobile = (mobile) => {
mobile = mobile.trim()
mobile = mobile.split(" ").join("")
mobile = mobile.split("-").join("")
mobile = mobile.split("(").join("")
mobile = mobile.split(")").join("")
if (mobile.length > 9) {
switch (true) {
case mobile.startsWith('061'):
mobile = mobile.substr(3);
break;
case mobile.startsWith('+61'):
mobile = mobile.substr(3);
break;
case mobile.startsWith('61'):
mobile = mobile.substr(2);
break;
case mobile.startsWith('0'):
mobile = mobile.substr(1);
break;
}
}
return mobile;
}
|
Java
|
UTF-8
| 767 | 2.28125 | 2 |
[] |
no_license
|
package com.kesar.jetpackgank;
import android.annotation.SuppressLint;
import android.content.Context;
/**
* Global
*
* @author andy <br/>
* create time: 2019/2/20 15:08
*/
public class Global {
@SuppressLint("StaticFieldLeak")
private static Global sInstance;
private Context mContext;
private Global() {
}
public static Global getInstance() {
if(sInstance == null) {
synchronized (Global.class) {
if(sInstance == null) {
sInstance = new Global();
}
}
}
return sInstance;
}
public void setContext(Context context) {
this.mContext = context;
}
public Context getContext() {
return mContext;
}
}
|
PHP
|
UTF-8
| 9,514 | 2.765625 | 3 |
[] |
no_license
|
<?php
namespace App\Controllers\Auth;
use Respect\Validation\Validator as v;
use App\Controllers\Controller;
use DB;
use App\Auth\Auth;
use App\Classes\UserActivity;
class AuthController extends Controller
{
/**************************************************************************************************************************************************
*************************************************************(Sign Up Form Get)*******************************************************************
**************************************************************************************************************************************************/
public function getSignUp($request, $response, $args)
{
return $this->view->render($response, 'auth/signup.tpl');
}
/**************************************************************************************************************************************************
*************************************************************(Sign Up Form Post)******************************************************************
**************************************************************************************************************************************************/
public function PostSignUp($request, $response, $args)
{
//validate the registration form fields
$validation = $this->validator->validate($request, [
'email' => v::notEmpty()->email()->EmailAvailable(),
'name' => v::notEmpty(),
'lastname' => v::notEmpty(),
'password' => v::notEmpty()->noWhitespace(),
]);
///check if failed return back with error message and the fields
if ($validation->failed()) {
$this->container->flash->addMessage('error', 'Er is een probleem opgetreden. Probeer het opnieuw of neem contact op met het administratiebureau.');
return $response->withRedirect($this->router->pathFor('auth.signup'));
}
///create the user
$user = new $this->auth;
$user->name = $request->getParam('name');
$user->lastname = $request->getParam('lastname');
$user->email = $request->getParam('email');
$user->password = $request->getParam('password');
$status = $user->create();
//Check if the user is created redirect to home page with a message
if ($status) {
// $check=$this->auth->attempt($request->getParam('email'),$request->getParam('password'));
$this->container->flash->addMessage('info', 'Gebruiker is gemaakt');
UserActivity::Record('Create', $status, 'Auth');
return $response->withRedirect($this->router->pathFor('users.index'));
} else {
//Check if the user is not created return back with variable and error message
$this->container->flash->addMessage('error', 'Er is een probleem opgetreden. Probeer het opnieuw of neem contact op met het administratiebureau.');
return $response->withRedirect($this->router->pathFor('auth.signup'));
}
}
/**************************************************************************************************************************************************
*************************************************************(Sign In Form Get)*******************************************************************
**************************************************************************************************************************************************/
public function getSignIn($request, $response, $args)
{
if (!$this->auth->check()) {
return $this->view->render($response, 'auth/login.tpl');
} else return $response->withRedirect($this->router->pathFor('home'));
}
/**************************************************************************************************************************************************
*************************************************************(Sign In Form Post)******************************************************************
**************************************************************************************************************************************************/
public function postSignIn($request, $response, $args)
{
$auth = $this->auth->attempt(
$request->getParam('email'),
$request->getParam('password')
);
if (!$auth) {
$this->container->flash->addMessage('error', 'De inloggegevens fout zijn !!');
return $response->withRedirect($this->router->pathFor('auth.login'));
} elseif ($auth == 'disable') {
$this->container->flash->addMessage('error', 'Uw account is uitgeschakeld neem contact op met het administratiekantoor !!');
return $response->withRedirect($this->router->pathFor('auth.login'));
}
$this->container->flash->addMessage('success', 'U bent aangemeld');
UserActivity::Record('SignIn', $auth, 'Auth');
if ($_SESSION['trying_to_access'] && $_SESSION['trying_to_access'] != '') {
$tmp = $_SESSION['trying_to_access'];
$_SESSION['trying_to_access'] = '';
unset($_SESSION['trying_to_access']);
return $response->withRedirect($tmp);
} else {
return $response->withRedirect($this->router->pathFor('home'));
}
}
/**************************************************************************************************************************************************
*************************************************************(Sign In Form Get)*******************************************************************
**************************************************************************************************************************************************/
public function getSignOut($request, $response, $args)
{
$id = $this->auth->user_id();
UserActivity::Record('SignOut', $id, 'Auth');
$this->auth->logout();
$this->container->flash->addMessage('info', 'U bent afgemeld ');
return $response->withRedirect($this->router->pathFor('auth.login'));
}
/**************************************************************************************************************************************************
*************************************************************(Change Password Get)****************************************************************
**************************************************************************************************************************************************/
public function getAccount($request, $response, $args)
{
return $this->view->render($response, 'account/index.tpl');
}
/**************************************************************************************************************************************************
*************************************************************(Change Password Post)***************************************************************
**************************************************************************************************************************************************/
public function postAccount($request, $response, $args)
{
$userCurrent = $this->auth->user();//dd($user);
//validate the registration form fields
if ($request->getParam('old_password') && $request->getParam('old_password') != '') {
$validation = $this->validator->validate($request, [
'email' => v::notEmpty()->email(),
'name' => v::notEmpty(),
'lastname' => v::notEmpty(),
'old_password' => v::noWhitespace()->notEmpty()->MatchesPassword($this->auth->GetPassword(), $this->auth->generate_password($request->getParam('old_password'))),
'password' => v::noWhitespace()->notEmpty(),
]);
} else {
$validation = $this->validator->validate($request, [
'email' => v::notEmpty()->email(),
'name' => v::notEmpty(),
'lastname' => v::notEmpty(),
]);
}
///check if failed return back with error message and the fields
if ($validation->failed()) {
$this->container->flash->addMessage('error', 'Er is een probleem opgetreden. Probeer het opnieuw of neem contact op met het administratiebureau.');
} else {
$user = new $this->auth();
$user->id = $request->getParam('id');
$user->name = $request->getParam('name');
$user->lastname = $request->getParam('lastname');
$user->email = $request->getParam('email');
$user->password = $request->getParam('password');
$user->super = $userCurrent['super'];
$status = $user->update();
if ($status) {
$this->container->flash->addMessage('success', 'Uw account is bijgewerkt');
UserActivity::Record('Update', $user->id, 'Auth');
} else {
$this->container->flash->addMessage('error', 'Er is een probleem opgetreden. Probeer het opnieuw of neem contact op met het administratiebureau.');
}
}
return $response->withRedirect($this->router->pathFor('auth.account'));
}
}
|
Markdown
|
UTF-8
| 1,220 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
# _BlackJack counter_
#### _05/10/2019_
#### By _**Olha Wysocky**_
## Description
_This is a web application that helps players of blackjack to count the chances of winning and suggest how much should they bet._
## Known Bugs
_No known bugs._
## Specs
- _Each card has an assigned value._
- _2 through 6 is +1_
- _7 through 9 is 0_
- _10 through Ace is -1_
- _Keep total Running count_
- _Calculate true count: Running count/decks remaining_
- _Standard blackjack has 6 decks_
- _Subtract cards to keep track of how many decks are left_
- _Raise bets when true count raises_
## Installation Requirements
- _Download and install Node.js_
## Setup instructions
- _On GitHub, navigate to the main page of the repository._
- _On the right find the green button "Clone or download", click it._
- _To clone the repository in Desktop choose "Open in Desktop" or download the ZIP file._
- _For more information, see "Cloning a repository from GitHub to GitHub Desktop."_
- _Use Terminal to install the webpack \$ npm install._
- _Use Terminal to run the program with command \$ npm run start._
## Technologies Used
- _React_
- _Redux_
- _.NET_
- _HTML_
- _CSS_
### License
MIT
Copyright (c) 2019 **_Olha Wysocky_**
|
Python
|
UTF-8
| 1,399 | 3.1875 | 3 |
[] |
no_license
|
# nltk & sklearn is used only for one time preprocessing, it does not need to be available in the server
import json
import pickle
from sklearn.metrics import pairwise_distances
from sklearn.feature_extraction.text import TfidfVectorizer
import nltk, string
'''
This script computes similarity for each pair of idioms in our database.
'''
# https://stackoverflow.com/questions/8897593/similarity-between-two-text-documents
# nltk.download('punkt')
stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
def stem_tokens(tokens):
return [stemmer.stem(item) for item in tokens]
'''remove punctuation, lowercase, stem'''
def normalize(text):
return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))
vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english')
def cosine_sim(texts):
tfidfs = vectorizer.fit_transform(texts)
return 1 - pairwise_distances(tfidfs.todense(), metric="cosine")
with open('idioms.json') as f:
data = json.load(f)
idioms = {}
for i in data:
idioms[i["id"]] = {"text": i["text"], "definition": i["definition"]}
dim = max([d['id'] for d in data]) + 1
train_set = []
for i in range(dim):
train_set.append(idioms.get(i, {"definition": ""})["definition"])
matrix = cosine_sim(train_set)
pickle.dump(matrix, open('matrix.pkl', "wb"))
|
SQL
|
UTF-8
| 181 | 3.171875 | 3 |
[] |
no_license
|
/* Problem Statement:
Give the name of the 'Peace' winners since the year 2000, including 2000.
*/
-- Solution:
SELECT winner FROM nobel
WHERE subject = 'Peace' AND yr >= 2000;
|
Java
|
UTF-8
| 443 | 2.015625 | 2 |
[] |
no_license
|
package net.metrosystems.mylibrary3.data.repository;
import net.metrosystems.mylibrary3.data.model.entity.Book;
import net.metrosystems.mylibrary3.data.model.entity.Library;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface LibraryRepository extends CrudRepository<Library, Integer> {
Library findByNameAndAddress (String name, String address);
}
|
C
|
UTF-8
| 1,129 | 3.171875 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
void *runner(void *param);
int sum = 0;
int main(int argc,char** argv)
{
int n = atoi(argv[1]);
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid,&attr,runner,argv[1]);
pthread_join(tid,NULL);
printf("------------Sum usingthreading---------------\n");
printf("| entered Upper limit = %d |\n",n);
printf("| ... |\n");
printf("| ... |\n");
printf("| Summation is = %d |\n",sum);
printf("| THANKYOU!!! |\n");
printf("| |\n");
printf("| |\n");
printf("| |\n");
printf("---------------------------------------------\n");
return 0;
}
void *runner(void *param)
{
int ul = atoi(param);
for(int i = 1;i<=ul;i++)
{
sum += i;
}
pthread_exit(0);
}
|
Markdown
|
UTF-8
| 777 | 2.828125 | 3 |
[] |
no_license
|
Pyg Scroller Demo
=================
Pyg Scroller Demo is an approach to creating a 2D world that can be explored, built on pygcurse and pygame. It features an image converter that creates a CSV map tile file, a shape creator, and an interpreter for hard-coded pixels. Pyg Scroller Demo's greatest strength is the delightful and subtle combinations of foreground and background colours, as well as minimalist ASCII art.
Usage
=====
Requires python 2, pygame, and pygcurse (please get pygcurse from here: https://github.com/asweigart/pygcurse).
python runme.py
History
=======
Pyg Scroller Demo was originally created in early 2013, with two possible project ideas it could lead to. Neither of them came about, but I think it's still a cool demo, if unwieldly to add more to.
|
Java
|
UTF-8
| 2,880 | 2.0625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2019 DeNA Co., Ltd.
*
* 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 packetproxy.gui;
import java.awt.*;
import javax.swing.*;
import packetproxy.common.Binary;
import packetproxy.model.DiffBinary;
import packetproxy.model.DiffSet;
import packetproxy.model.DiffEventAdapter;
public class GUIDiffBinary extends GUIDiffBase
{
@Override
protected DiffSet sortUniq(DiffSet ds) {
String strOrig = "";
String strTarg = "";
try {
strOrig = super.sortUniq(new Binary(ds.getOriginal()).toHexString().toString());
strTarg = super.sortUniq(new Binary(ds.getTarget()).toHexString().toString());
}catch (Exception e){
e.printStackTrace();
}
return new DiffSet(strOrig.getBytes(), strTarg.getBytes());
}
public GUIDiffBinary() throws Exception {}
@Override
public void update() throws Exception {
DiffSet ds;
if (jc.isSelected()) {
ds = sortUniq(DiffBinary.getInstance().getSet());
} else {
ds = DiffBinary.getInstance().getSet();
}
byte[] original = ds.getOriginal();
byte[] target = ds.getTarget();
if (original != null) {
textOrig.setData(new Binary(ds.getOriginal()).toHexString().toString().getBytes(), false);
}
if (target != null) {
textTarg.setData(new Binary(ds.getTarget()).toHexString().toString().getBytes(), false);
}
if (original == null || target == null) {
return;
}
docOrig = textOrig.getStyledDocument();
docTarg = textTarg.getStyledDocument();
docOrig.setCharacterAttributes(0, docOrig.getLength(), defaultAttr, false);
docTarg.setCharacterAttributes(0, docTarg.getLength(), defaultAttr, false);
DiffEventAdapter eventFordocOrig = new DiffEventAdapter() {
public void foundDelDelta(int pos, int length) throws Exception {
docOrig.setCharacterAttributes(pos, length, delAttr, false);
}
public void foundChgDelta(int pos, int length) throws Exception {
docOrig.setCharacterAttributes(pos, length, chgAttr, false);
}
};
DiffEventAdapter eventForTarget = new DiffEventAdapter() {
public void foundInsDelta(int pos, int length) throws Exception {
docTarg.setCharacterAttributes(pos, length, insAttr, false);
}
public void foundChgDelta(int pos, int length) throws Exception {
docTarg.setCharacterAttributes(pos, length, chgAttr, false);
}
};
DiffBinary.diffPerCharacter(ds, eventFordocOrig, eventForTarget);
}
}
|
Java
|
UTF-8
| 172 | 2 | 2 |
[] |
no_license
|
package com.assessment.springboot_exception;
public class TransportNotFound extends RuntimeException{
public TransportNotFound(String msg) {
super(msg);
}
}
|
Python
|
UTF-8
| 331 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
import threading
import time
def run(n):
print("task", n)
time.sleep(1)
print('2s')
time.sleep(1)
print('1s')
time.sleep(1)
print('0s')
time.sleep(1)
if __name__ == '__main__':
# Python 多线程
t1 = threading.Thread(target=run, args=("t1",))
t2 = threading.Thread(target=run, args=("t2",))
t1.start()
t2.start()
|
Python
|
UTF-8
| 1,593 | 2.59375 | 3 |
[] |
no_license
|
from datetime import datetime, timedelta
from app_config import SECONDS_IN_HOUR, HOUR_FOR_CALC, MIDNIGHT, PROXIMITY_COLUMN, COMMENTS_AMOUNT_COLUMN, \
COMMENTS_AMOUNT_KEY, PUBLISH_TIME_KEY
from stories_util import get_top_stories
import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt
import numpy as np
def calc_correlation():
data = _create_data_()
df = pd.DataFrame(data, columns=[PROXIMITY_COLUMN, COMMENTS_AMOUNT_COLUMN])
sn.scatterplot(data=df, x=PROXIMITY_COLUMN, y=COMMENTS_AMOUNT_COLUMN)
plt.show()
return np.corrcoef(data[PROXIMITY_COLUMN], data[COMMENTS_AMOUNT_COLUMN])[0][1]
def _create_data_():
stories = get_top_stories(None)
if stories is not None:
publish_proximity_to_8pm = []
comments_amount = []
for story in stories:
publish_proximity_to_8pm.append(_calc_proximity_(story.get(PUBLISH_TIME_KEY)))
comments_count = story.get(COMMENTS_AMOUNT_KEY)
comments_amount.append(comments_count if comments_count is not None else 0)
return {PROXIMITY_COLUMN: publish_proximity_to_8pm, COMMENTS_AMOUNT_COLUMN: comments_amount}
def _calc_proximity_(epoch_time):
publish_time = datetime.fromtimestamp(epoch_time).time()
delta1 = abs(timedelta(hours=publish_time.hour, minutes=publish_time.minute, seconds=publish_time.second) -
timedelta(hours=HOUR_FOR_CALC))
delta2 = timedelta(hours=MIDNIGHT) - delta1
proximity = min(delta1, delta2)
# convert the delta to a float between 0-1
return proximity.seconds / SECONDS_IN_HOUR
|
Java
|
UTF-8
| 112 | 1.851563 | 2 |
[] |
no_license
|
package com.tcGroup.trainingCenter.domain.enumeration;
public enum IterationUnit {
SECONDS,
QUANTITY
}
|
C++
|
UTF-8
| 549 | 3.140625 | 3 |
[] |
no_license
|
#include <iostream>
#include <iomanip>
int main (int argc, const char * argv[]){
using namespace std;
/*int numeros[10];
for (int i=0; i<10; i++)
numeros[i]= 10 * (i+1);
cout << "Indice\tValor\n------\t------\n";
for (int i=0;i<10;i++)
cout << setw(6) << i << "\t" << setw(5) << numeros[i] << endl;
*/
int numeros[10]={23,7,9,52,41,-4,35,16,0,18};
cout << "Indice\tValor\n------\t------\n";
for (int i=0;i<10;i++){
cout << setw(6) << right << i << "\t" ;
cout << setw(5) << right << numeros[i] << endl;
}
return 0;
}
|
PHP
|
UTF-8
| 363 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace PhpJsonRpc\Server\Stub\ValueObject;
class Name
{
/**
* @var string
*/
private $value;
/**
* @param string $value
*/
public function __construct($value)
{
$this->value = $value;
}
/**
* @return string
*/
public function toNative()
{
return $this->value;
}
}
|
C
|
UTF-8
| 2,438 | 4.0625 | 4 |
[] |
no_license
|
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "ListBaseStack.h"
// 연산자의 우선순위 정보 반환
// 값이 클수록 높은 우선순위
int GetOpPrec(char op)
{
switch(op)
{
case '*':
case '/':
return 5; // 가장 높은 우선순위
case '+':
case '-':
return 3;
case '(':
return 1; // 가장 낮은 우선순위
}
return -1; // 등록되지 않은 연산자
}
// 두 연산자의 우선순위 비교
int WhoPrecOp(char op1, char op2)
{
int op1Prec = GetOpPrec(op1);
int op2Prec = GetOpPrec(op2);
if(op1Prec > op2Prec) // op1 우선순위가 더 높은 경우
return 1;
else if(op1Prec < op2Prec) // op2 우선순위가 더 높은 경우
return -1;
else
return 0; //op1과 op2의 우선순위가 같은 경우
}
// 전위 -> 후위 표기법 수식으로 변환
void ConvToRPNExp(char exp[])
{
Stack stack; // 연산자를 담을 스택(쟁반)
int expLen = strlen(exp);
char * convExp = (char*)malloc(expLen+1); // 변환된 수식을 담을 공간 생성
int i, idx=0;
char tok, popOp;
memset(convExp, 0, sizeof(char)*expLen+1); // 할당된 배열을 0으로 초기화
StackInit(&stack);
for(i=0; i<expLen; i++)
{
tok = exp[i]; // exp로 전달된 수식을 한 문자씩 tok에 저장
if(isdigit(tok)) // tok에 저장된 문자가 숫자인지 확인
{
convExp[idx++] = tok; // 순자인 경우, dst에 바로 저장
}
else
{
switch(tok) // 연산자인 경우
{
case '(':
SPush(&stack, tok); // 스택에 쌓는다.
break;
case ')': // ( 연산자를 만날 때 까지 반복해서 값을 꺼내서 dst에 담는다.
while(1)
{
popOp = SPop(&stack);
if(popOp == '(')
break;
convExp[idx++] = popOp;
}
break;
case '+': case '-':
case '*': case '/':
//스택에 더 높은 우선순위 연산자가 있으면, 스택에서 연산자를 꺼내서 dst에 저장
while(!SIsEmpty(&stack) &&
WhoPrecOp(SPeek(&stack), tok) >= 0)
convExp[idx++] = SPop(&stack);
SPush(&stack, tok);
break;
}
}
}
while(!SIsEmpty(&stack)) // 스택에 남아있는 모든 연산자를
convExp[idx++] = SPop(&stack); // dst(배열 convExp)에 저장
strcpy(exp, convExp); //convExp내용(변환된 수식)을 exp로 복사
free(convExp); //convExp 메모리 해제
}
|
Java
|
UTF-8
| 33,163 | 2.34375 | 2 |
[] |
no_license
|
/*
* ClassicRules.java
*
* Created on July 30, 2005, 9:15 PM
*
*/
package org.invade.rules;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import org.invade.Board;
import org.invade.Card;
import org.invade.PlayableDeck;
import org.invade.CommonBoardEvents;
import org.invade.CommonBoardMethods;
import org.invade.DiceType;
import org.invade.Die;
import org.invade.EndGameException;
import org.invade.Force;
import org.invade.ForcePlacement;
import org.invade.ForceVacuum;
import org.invade.GameAlgorithm;
import org.invade.GameThread;
import org.invade.Player;
import org.invade.SpecialMove;
import org.invade.SpecialUnit;
import org.invade.Territory;
import org.invade.TerritoryDuple;
import org.invade.TerritoryType;
import org.invade.TurnMode;
import org.invade.classic.BonusCard;
/**
*
* @author Jonathan Crosmer
*/
public class ClassicRules extends AbstractRules {
public String toString() {
return "Classic";
}
private int evenDistributionRegular = 1;
private int endYear = -1; // < 0 indicates no end year
private int startingRegularUnits = 40; // for two players
private int startingUnitsSubtrahend = 5; // for each player after the second
private int minStartingUnits = 20;
private int contestedTerritoriesNeeded = 1;
private int maxFreeMovesPerTurn = 1; // < 0 indicates unlimited
private boolean acknowledgeInvasions = false;
private boolean defenderAcknowledgeInvasions = false;
private boolean acknowledgeInvasionOnlyWhenNecessary = true;
private int wildCardCount = 2;
private int bonusValues[] = {4, 6, 8, 12, 15};
private int bonusAddend = 5; // < 0 indicates reset result index
private int maxCardsAtTurnStart = 4; // < 0 indicates unlimited
private int maxCardsAfterCapture = 5; // < 0 indicates unlimited
private int ownTerritoryCardBonus = 2;
private boolean onlyOneOwnTerritoryBonus = true;
private boolean randomTerritoryAssignment = false;
public GameAlgorithm createGameAlgorithm() {
return new ClassicGameAlgorithm();
}
public List<PlayableDeck> getStartingDecks(Board board) {
List<PlayableDeck> result = new ArrayList<PlayableDeck>();
PlayableDeck deck = new PlayableDeck();
deck.setName(BonusCard.DEFAULT_DECK_NAME);
BonusCard.Type types[] = BonusCard.Type.values();
int index = 0;
for(Territory territory : board.getTerritories()) {
if( territory.getType().equals(TerritoryType.LAND) ) {
deck.add(new BonusCard(types[index], territory));
index++;
index %= types.length;
}
}
for( int i = 0; i < getWildCardCount(); ++i ) {
deck.add(new BonusCard());
}
result.add(deck);
return result;
}
public int getEvenDistributionRegular() {
return evenDistributionRegular;
}
public void setEvenDistributionRegular(int evenDistributionRegular) {
this.evenDistributionRegular = evenDistributionRegular;
}
public int getEndYear() {
return endYear;
}
public void setEndYear(int endYear) {
this.endYear = endYear;
}
public int getStartingRegularUnits() {
return startingRegularUnits;
}
public void setStartingRegularUnits(int startingRegularUnits) {
this.startingRegularUnits = startingRegularUnits;
}
public int getStartingUnitsSubtrahend() {
return startingUnitsSubtrahend;
}
public void setStartingUnitsSubtrahend(int startingUnitsSubtrahend) {
this.startingUnitsSubtrahend = startingUnitsSubtrahend;
}
public int getMinStartingUnits() {
return minStartingUnits;
}
public void setMinStartingUnits(int minStartingUnits) {
this.minStartingUnits = minStartingUnits;
}
public int getContestedTerritoriesNeeded() {
return contestedTerritoriesNeeded;
}
public void setContestedTerritoriesNeeded(int contestedTerritoriesNeeded) {
this.contestedTerritoriesNeeded = contestedTerritoriesNeeded;
}
public int getMaxFreeMovesPerTurn() {
return maxFreeMovesPerTurn;
}
public void setMaxFreeMovesPerTurn(int maxFreeMovesPerTurn) {
this.maxFreeMovesPerTurn = maxFreeMovesPerTurn;
}
public boolean isAcknowledgeInvasions() {
return acknowledgeInvasions;
}
public void setAcknowledgeInvasions(boolean acknowledgeInvasions) {
this.acknowledgeInvasions = acknowledgeInvasions;
}
public boolean isDefenderAcknowledgeInvasions() {
return defenderAcknowledgeInvasions;
}
public void setDefenderAcknowledgeInvasions(boolean defenderAcknowledgeInvasions) {
this.defenderAcknowledgeInvasions = defenderAcknowledgeInvasions;
}
public int getWildCardCount() {
return wildCardCount;
}
public void setWildCardCount(int wildCardCount) {
this.wildCardCount = wildCardCount;
}
public int[] getBonusValues() {
return bonusValues;
}
public void setBonusValues(int[] bonusValues) {
this.bonusValues = bonusValues;
}
public int getBonusAddend() {
return bonusAddend;
}
public void setBonusAddend(int bonusAddend) {
this.bonusAddend = bonusAddend;
}
public int getMaxCardsAtTurnStart() {
return maxCardsAtTurnStart;
}
public void setMaxCardsAtTurnStart(int maxCardsAtTurnStart) {
this.maxCardsAtTurnStart = maxCardsAtTurnStart;
}
public int getMaxCardsAfterCapture() {
return maxCardsAfterCapture;
}
public void setMaxCardsAfterCapture(int maxCardsAfterCapture) {
this.maxCardsAfterCapture = maxCardsAfterCapture;
}
public int getOwnTerritoryCardBonus() {
return ownTerritoryCardBonus;
}
public void setOwnTerritoryCardBonus(int ownTerritoryCardBonus) {
this.ownTerritoryCardBonus = ownTerritoryCardBonus;
}
public boolean isOnlyOneOwnTerritoryBonus() {
return onlyOneOwnTerritoryBonus;
}
public void setOnlyOneOwnTerritoryBonus(boolean onlyOneOwnTerritoryBonus) {
this.onlyOneOwnTerritoryBonus = onlyOneOwnTerritoryBonus;
}
public boolean isRandomTerritoryAssignment() {
return randomTerritoryAssignment;
}
public void setRandomTerritoryAssignment(boolean randomTerritoryAssignment) {
this.randomTerritoryAssignment = randomTerritoryAssignment;
}
public boolean isAcknowledgeInvasionOnlyWhenNecessary() {
return acknowledgeInvasionOnlyWhenNecessary;
}
public void setAcknowledgeInvasionOnlyWhenNecessary(boolean acknowledgeInvasionOnlyWhenNecessary) {
this.acknowledgeInvasionOnlyWhenNecessary = acknowledgeInvasionOnlyWhenNecessary;
}
class ClassicGameAlgorithm implements GameAlgorithm {
protected Board board;
protected GameThread gameThread;
private int bonusIndex = 0;
private boolean cardAtEndOfTurn = false;
public void startGame(Board board, GameThread gameThread) throws EndGameException {
this.board = board;
this.gameThread = gameThread;
board.sendMessage(" -- Game start -- ");
board.resetDecks();
receiveStartingRegularUnits();
claimTerritories();
checkAllForElimination();
evenDistribution(getEvenDistributionRegular());
while (CommonBoardMethods.areMultiplePlayersAlive(board)
&& (getEndYear() < 0 || board.getYear() < getEndYear()) ) {
board.setYear(board.getYear() + 1);
for( Player player : board.getPlayers() ) {
board.setTurnMode(TurnMode.TURN_START);
CommonBoardEvents.checkCardsInPlay(board, gameThread);
if( !player.isAlive() ) {
continue;
}
cardAtEndOfTurn = false;
board.setCurrentPlayer(player);
board.setAttackingTerritory(null);
board.setDefendingTerritory(null);
receiveSupplies();
checkAllForElimination();
if( !player.isAlive() ) {
continue;
}
CommonBoardEvents.placeReinforcements(board, gameThread);
if( getMaxCardsAtTurnStart() < 0
|| BonusCard.getBonusCards(player.getCards()).size()
> getMaxCardsAtTurnStart() ) {
forcePlayCard();
}
declareInvasions();
checkAllForElimination();
if( !player.isAlive() ) {
continue;
}
if( cardAtEndOfTurn ) {
drawCard();
}
declareFreeMoves();
checkAllForElimination();
}
}
board.setTurnMode(TurnMode.GAME_OVER);
board.sendMessage(" -- Game over --");
}
public void receiveStartingRegularUnits() throws EndGameException {
int count = getStartingRegularUnits();
count -= (board.getPlayers().size() - 2) * getStartingUnitsSubtrahend();
count = Math.min(Math.max(count, getMinStartingUnits()), getStartingRegularUnits());
CommonBoardEvents.receiveStartingRegularUnits(board, count);
}
public void claimTerritories() throws EndGameException {
Collections.shuffle(board.getPlayers(), board.getRandom());
board.setCurrentPlayer( board.getPlayers().get(0) );
List<Territory> territories = board.getTerritoriesOwned(Player.NEUTRAL, TerritoryType.LAND);
while( ! territories.isEmpty()
&& board.getCurrentPlayer().getReinforcements().getRegularUnits() > 0 ) {
board.setTurnMode(TurnMode.CLAIM_TERRITORIES);
Territory territory;
if( isRandomTerritoryAssignment() ) {
territory = territories.get(board.getRandom().nextInt(territories.size()));
} else {
territory = (Territory)gameThread.take();
}
territory.setOwner(board.getCurrentPlayer());
territories.remove(territory);
//dan added this
board.setAttackingTerritory(territory);
board.getCurrentPlayer().getReinforcements().addRegularUnits(-1);
territory.getForce().addRegularUnits(1);
CommonBoardEvents.checkCardsInPlay(board, gameThread);
board.nextPlayer();
}
//dan added this
board.setAttackingTerritory(null);
}
public void evenDistribution(int number) throws EndGameException {
while(true) {
boolean allPlaced = true;
for( Player player : board.getPlayers() ) {
allPlaced &= player.getReinforcements().isEmpty();
}
if( allPlaced ) {
break;
}
board.setTurnMode(TurnMode.EVEN_REINFORCEMENTS);
board.setNumberToPlace(number);
while( !board.getCurrentPlayer().getReinforcements().isEmpty() &&
board.getNumberToPlace() > 0 ) {
ForcePlacement duple = (ForcePlacement)gameThread.take();
Territory territory = duple.getTerritory();
Force force = duple.getForce();
board.getCurrentPlayer().getReinforcements().subtract(force);
territory.getForce().add(force);
board.setNumberToPlace( board.getNumberToPlace() - force.getSize() );
}
board.nextPlayer();
}
}
public void receiveSupplies() throws EndGameException {
CommonBoardEvents.checkCardsInPlay(board, gameThread);
Player player = board.getCurrentPlayer();
int supply = CommonBoardMethods.getBasicSupply(board, board.getCurrentPlayer())
+ CommonBoardMethods.getContinentBonuses(board, board.getCurrentPlayer());
player.getReinforcements().addRegularUnits(supply);
board.sendMessage(player.getName() + " receives " + supply + " units");
}
public void drawCard() throws EndGameException {
boolean canDraw = false;
for( PlayableDeck deck : board.getDecks() ) {
if( deck.canDraw(board) ) {
canDraw = true;
}
}
if( ! canDraw ) {
return;
}
board.setTurnMode(TurnMode.DRAW_CARD);
Object taken = gameThread.take();
if( taken != SpecialMove.END_MOVE ) {
PlayableDeck deck = (PlayableDeck)taken;
board.sendMessage(board.getCurrentPlayer().getName() + " draws a " + deck);
board.getCurrentPlayer().getCards().add( deck.draw() );
}
}
public void declareInvasions() throws EndGameException {
Player current = board.getCurrentPlayer();
board.setBeforeFirstInvasion(true);
board.setBeforeFirstCard(true);
int contestedTerritoriesTaken = 0;
while(true) {
CommonBoardEvents.checkCardsInPlay(board, gameThread);
board.setCurrentPlayer(current);
board.setTurnMode(TurnMode.DECLARE_INVASIONS);
board.setDefendingTerritory(null);
Object taken = gameThread.take();
if( taken == SpecialMove.END_MOVE ) {
break;
}
if( taken instanceof Card ) {
((Card)taken).play(board, gameThread);
board.setBeforeFirstCard(false);
finishSet();
continue;
}
board.setBeforeFirstInvasion(false);
board.setAttackingTerritory(((TerritoryDuple)taken).getFirst());
board.setDefendingTerritory(((TerritoryDuple)taken).getSecond());
Player defender = board.getDefendingTerritory().getOwner();
board.sendMessage(current.getName() + " invades "
+ board.getDefendingTerritory().getName() + " from "
+ board.getAttackingTerritory().getName() );
boolean contested = (board.getDefendingTerritory().getForce().getMobileIndependentSize() > 0);
if( isAcknowledgeInvasions()
&& board.getDefendingTerritory().getOwner() != Player.NEUTRAL ) {
board.setTurnMode(TurnMode.ACKNOWLEDGE_INVASION);
List<Player> ask = new ArrayList<Player>();
for(Player player : board.getPlayers()) {
if( (player != board.getAttackingTerritory().getOwner())
&& player.isAlive() ) {
if(isAcknowledgeInvasionOnlyWhenNecessary()) {
for(Card card : player.getCards()) {
board.setCurrentPlayer(player);
if(card.canPlay(board)) {
ask.add(player);
break;
}
}
} else if( isDefenderAcknowledgeInvasions() ) {
if( player == board.getDefendingTerritory().getOwner() ) {
ask.add(player);
}
} else {
ask.add(player);
}
}
}
CommonBoardEvents.getAcknowledgements(board, gameThread,
TurnMode.ACKNOWLEDGE_INVASION,
ask);
}
if( CommonBoardMethods.isInvasionBlockedByCard(board, board.getAttackingTerritory(), board.getDefendingTerritory())
|| board.getAttackingTerritory().getForce().getMobileIndependentSize() <= 1 ) {
continue;
}
board.setTurnMode(TurnMode.DECLARE_ATTACK_FORCE);
board.setCurrentPlayer( board.getAttackingTerritory().getOwner() );
Force attackForce = board.getPlayers().contains(board.getCurrentPlayer())
? (Force)gameThread.take()
: board.getAttackingTerritory().getForce().getDefaultAttack(board.getRules());
if(board.getDefendingTerritory().getForce().getMobileIndependentSize() > 0) {
board.setTurnMode(TurnMode.DECLARE_DEFENSE_FORCE);
board.setCurrentPlayer(board.getDefendingTerritory().getOwner());
Force defenseForce = board.getPlayers().contains(board.getCurrentPlayer())
? (Force)gameThread.take()
: board.getDefendingTerritory().getForce().getDefaultDefense(board.getRules());
board.setCurrentPlayer(board.getAttackingTerritory().getOwner());
// Here is where we roll the dice!
battle(attackForce, defenseForce);
board.setCurrentPlayer(board.getAttackingTerritory().getOwner());
}
if( board.getDefendingTerritory().getForce().getMobileIndependentSize() <= 0 ) {
if(contested) {
board.sendMessage(board.getDefendingTerritory().getName()
+ " falls");
}
attackForce = attackForce.getMobileForce();
board.getDefendingTerritory().setOwner(board.getAttackingTerritory().getOwner());
board.getAttackingTerritory().getForce().subtract(attackForce);
board.getDefendingTerritory().getForce().add(attackForce);
for( SpecialUnit special : new ArrayList<SpecialUnit>(board.getDefendingTerritory().getForce().getSpecialUnits()) ) {
if( special.getMaxOwnable() >= 0
&& board.getUnitCount(current, special) > special.getMaxOwnable() ) {
board.getDefendingTerritory().getForce().getSpecialUnits().remove(special);
}
}
if( board.getAttackingTerritory().getForce().getMobileIndependentSize() > 1 ) {
freeMove(board.getAttackingTerritory(), board.getDefendingTerritory());
}
afterConqueringTerritory();
CommonBoardEvents.checkCardsInPlay(board, gameThread);
checkForElimination(defender);
if( contested && board.getDefendingTerritory().getType() != TerritoryType.UNDERWORLD ) {
++contestedTerritoriesTaken;
if( contestedTerritoriesTaken == getContestedTerritoriesNeeded() ) {
receiveContestedTerritoryBonus();
}
}
board.setAttackingTerritory(board.getDefendingTerritory());
board.setDefendingTerritory(null);
}
}
board.setBeforeFirstInvasion(false);
}
public void battle(Force attackForce, Force defenseForce) throws EndGameException {
board.getAttackerDice().clear();
for( DiceType dieType : getAttackDice(attackForce,
board.getAttackingTerritory(), board.getDefendingTerritory()) ) {
board.getAttackerDice().add(new Die(board.getRandom(), dieType));
}
Collections.sort(board.getAttackerDice());
Collections.reverse(board.getAttackerDice());
board.getDefenderDice().clear();
for( DiceType dieType : getDefenseDice(defenseForce,
board.getAttackingTerritory(), board.getDefendingTerritory()) ) {
board.getDefenderDice().add(new Die(board.getRandom(), dieType));
}
Collections.sort(board.getDefenderDice());
Collections.reverse(board.getDefenderDice());
afterRoll(attackForce, defenseForce);
for( int i = 0; i < Math.min(board.getAttackerDice().size(),
board.getDefenderDice().size()); ++i ) {
if( board.getAttackerDice().get(i).getValue()
> board.getDefenderDice().get(i).getValue()
|| (board.getAttackerDice().get(i).getValue()
== board.getDefenderDice().get(i).getValue()
&& attackerWinsTies(attackForce, defenseForce))) {
board.getDefendingTerritory().addNumberToDestroy(1);
} else {
board.getAttackingTerritory().addNumberToDestroy(1);
}
}
board.setTurnMode(TurnMode.BATTLE_RESULTS);
gameThread.take();
beforeRemovingUnits();
CommonBoardEvents.checkForDestroyed(board, gameThread, board.getAttackingTerritory());
CommonBoardEvents.checkForDestroyed(board, gameThread, board.getDefendingTerritory());
}
public void beforeRemovingUnits() throws EndGameException {}
// Can be used in subclasses to reroll certain dice, etc.
public void afterRoll(Force attackForce, Force defenseForce)
throws EndGameException {}
public void afterConqueringTerritory() throws EndGameException {}
public boolean attackerWinsTies(Force attackForce, Force defenseForce) {
return false;
}
public void receiveContestedTerritoryBonus() throws EndGameException {
cardAtEndOfTurn = true;
}
public void declareFreeMoves() throws EndGameException {
board.setTurnMode(TurnMode.DECLARE_FREE_MOVES);
CommonBoardEvents.checkCardsInPlay(board, gameThread);
Player current = board.getCurrentPlayer();
int freeMoves = getMaxFreeMovesPerTurn() + current.getFreeMoves();
current.setFreeMoves(0);
int i = 0;
while(freeMoves < 0 || i < freeMoves) {
board.setCurrentPlayer(current);
board.setTurnMode(TurnMode.DECLARE_FREE_MOVES);
Object taken = gameThread.take();
if( taken == SpecialMove.END_MOVE ) {
break;
} else if( taken instanceof Card ) {
((Card)taken).play(board, gameThread);
} else {
if(freeMove(((TerritoryDuple)taken).getFirst(), ((TerritoryDuple)taken).getSecond())) {
++i;
}
}
if( freeMoves >= 0 ) {
// Player might have used a card that awards an additional free move
freeMoves += current.getFreeMoves();
current.setFreeMoves(0);
}
}
}
public boolean freeMove(Territory from, Territory to) throws EndGameException {
board.setAttackingTerritory(from);
board.setDefendingTerritory(to);
board.setTurnMode(TurnMode.COMPLETE_FREE_MOVE);
Force force = (Force)gameThread.take();
if( force.isEmpty() ) {
return false;
}
from.getForce().subtract(force);
to.getForce().add(force);
board.sendMessage(board.getCurrentPlayer().getName() + " fortifies "
+ to.getName() + " from " + from.getName());
return true;
}
public void checkForElimination(Player player) throws EndGameException {
if( ! player.isAlive() ) {
return;
}
List<Territory> territories = board.getTerritoriesOwned(player);
for( Territory territory : new ArrayList<Territory>(territories) ) {
if( EnumSet.of(TerritoryType.HEAVEN, TerritoryType.UNDERWORLD).contains(territory.getType()) ) {
territories.remove(territory);
}
}
if( territories.isEmpty()
&& board.getPlayers().contains(player) ) {
board.sendMessage("All units under the command of "
+ player.getName() + " have surrendered" );
/* "Bonus" will be -2 for second place, -3 for third, etc.,
* so point system will rank players by reverse order of
* elimination. */
player.setBonusPoints( - board.getLivingPlayers().size() );
player.setAlive(false);
player.setEnergy(0);
player.setReinforcements(new ForceVacuum()); // Goodbye units
player.setFreeMoves(0);
for( Card card : player.getCards() ) {
surrenderCard(card);
}
player.getCards().clear();
afterCardSurrender();
// Remove cards that target this player
for( Card card : board.getCardsInPlay() ) {
if( card.getPlayer() == player ) {
if( card.getDeck() != null ) {
card.getDeck().discard(card);
}
}
}
for( Territory territory : board.getTerritoriesOwned(player, TerritoryType.UNDERWORLD) ) {
territory.getForce().setRegularUnits(0);
territory.setOwner(Player.NEUTRAL);
for( SpecialUnit special : new ArrayList<SpecialUnit>(territory.getForce().getSpecialUnits()) ) {
if( ! special.isNeutral() ) {
territory.getForce().getSpecialUnits().remove(special);
}
}
}
}
}
public void surrenderCard(Card card) {
if( board.getCurrentPlayer() == null ) {
card.getDeck().discard(card);
} else {
board.getCurrentPlayer().getCards().add(card);
}
}
public void afterCardSurrender() throws EndGameException {
while( BonusCard.getBonusCards(board.getCurrentPlayer().getCards()).size()
> getMaxCardsAfterCapture() ) {
forcePlayCard();
finishSet();
}
}
public void checkAllForElimination() throws EndGameException {
for( Player player : board.getPlayers() ) {
checkForElimination(player);
}
}
public void finishSet() throws EndGameException {
checkForSet();
while( isPlayingSet() ) {
forcePlayCard();
checkForSet();
}
}
public boolean isPlayingSet() {
return ! BonusCard.getBonusCards(board.getCardsInPlay()).isEmpty();
}
public void checkForSet() throws EndGameException {
List<BonusCard> cardSet = BonusCard.getBonusCards(board.getCardsInPlay());
if( cardSet.size() == BonusCard.SET_SIZE ) {
receiveBonus(cardSet);
for( Card card : cardSet ) {
board.getCardsInPlay().remove(card);
card.getDeck().discard(card);
}
}
}
public void receiveBonus(List<BonusCard> cardSet) throws EndGameException {
for( BonusCard bonusCard : cardSet ) {
if( bonusCard.getTerritory() != null
&& bonusCard.getTerritory().getOwner()
== board.getCurrentPlayer() ) {
bonusCard.getTerritory().getForce().addRegularUnits(getOwnTerritoryCardBonus());
if( isOnlyOneOwnTerritoryBonus() ) {
break;
}
}
}
int bonus = getCardBonus();
board.sendMessage(board.getCurrentPlayer().getName() + " receives "
+ bonus + " units");
board.getCurrentPlayer().getReinforcements().addRegularUnits(bonus);
CommonBoardEvents.placeReinforcements(board, gameThread);
}
public int getCardBonus() {
if( getBonusValues().length == 0 ) {
if( getBonusAddend() <= 0 ) {
return 0;
}
bonusIndex++;
return bonusIndex * getBonusAddend();
}
int result = 0;
if( bonusIndex < getBonusValues().length ) {
result = getBonusValues()[bonusIndex];
} else if(bonusAddend < 0) {
bonusIndex = 0;
result = getBonusValues()[0];
} else {
result = getBonusValues()[getBonusValues().length - 1]
+ (bonusIndex - (getBonusValues().length - 1)) * bonusAddend;
}
bonusIndex++;
return result;
}
public void forcePlayCard() throws EndGameException {
board.setTurnMode(TurnMode.FORCE_PLAY_CARD);
((Card)gameThread.take()).play(board, gameThread);
finishSet();
}
}
public List<DiceType> getAttackDice(Force force, Territory from, Territory to) {
List<DiceType> result = new ArrayList<DiceType>();
for( SpecialUnit special : force.getSpecialUnits() ) {
if( special.isMobile() && special.isIndependentUnit() ) {
if( hasAttackBonus(special, from.getType()) ||
hasAttackBonus(special, to.getType()) ) {
result.add(DiceType.EIGHT_SIDED);
} else {
result.add(DiceType.SIX_SIDED);
}
}
}
if( force.getRegularUnits() > 0 ) {
for( int i = 0; i < force.getRegularUnits() && result.size() < getMaxAttackDice(); ++i ) {
result.add(DiceType.SIX_SIDED);
}
}
Collections.sort(result);
while( result.size() > getMaxAttackDice() ) {
result.remove(0);
}
return result;
}
public List<DiceType> getDefenseDice(Force force, Territory from, Territory to) {
List<DiceType> result = new ArrayList<DiceType>();
boolean maxPower = false;
for( SpecialUnit special : force.getSpecialUnits() ) {
if( special.isMobile() && special.isIndependentUnit() ) {
result.add(DiceType.EIGHT_SIDED);
}
if( special == DefaultRules.SPACE_STATION
|| special == AmoebaRules.ALIEN_LEADER ) {
maxPower = true;
}
}
if( force.getRegularUnits() > 0 ) {
for( int i = 0; i < force.getRegularUnits() && result.size() < getMaxDefenseDice(); ++i ) {
result.add(DiceType.SIX_SIDED);
}
}
if( maxPower ) {
for( int i = 0; i < result.size(); ++i ) {
result.set(i, DiceType.EIGHT_SIDED);
}
}
Collections.sort(result);
while( result.size() > getMaxDefenseDice() ) {
result.remove(0);
}
return result;
}
public boolean hasAttackBonus(SpecialUnit specialUnit,
TerritoryType territoryType) {
return false;
}
}
|
C++
|
UTF-8
| 1,464 | 2.578125 | 3 |
[] |
no_license
|
#ifndef L_H
#define L_H
//! The Laplace operator class
/*!
This class provides operators for computing the Laplacian
It can be applied on fourier transformed sets of wave functions
means on sets of fourier coefficients of plane wave functions
*/
//#include "checkOperatorSize.h"
#include "main.h"
#include "latexComment.h"
class Lop //: public latexComment
{
public:
latexComment *myLatexClass; //!< public latex class, to be initialized in construction - used to give latex output stream
Lop(const arma::Mat<double> G2inp,const arma::mat G2CompInp,const arma::mat Rinp,const int Numwavfunc,latexComment *ltX);//,checkOperatorSize<T> *chkPointer);
//! The constructor
/*!
\param G2inp a vector of wave vector squared
\param Rinp a 3x3 matrix of system size
\param Numwavfunc number of wavefunctions to compute
\param ltX - pointer to a latex comment class instance */
~Lop();
//! Laplace operator for input of values
/*!
\param input as fourier coefficients of wave functions expanded in plane waves
*/
arma::cx_mat operator*(arma::cx_mat input);
arma::cx_mat operator*(arma::cx_mat* input);
private:
arma::mat _G2i;
arma::mat _Ri;
arma::mat _Faktor;
arma::mat _FaktorComp;
arma::cx_mat _outputM;
int _noActiveIndices;
//checkOperatorSize<T> *_checkPointer;
// std::auto_ptr<arma::mat> Rint;
};
#endif // L_H
|
JavaScript
|
UTF-8
| 898 | 2.515625 | 3 |
[] |
no_license
|
import {
GET_USER_CHAT,
GET_FULL_CHAT,
SEND_MESSAGE,
FILTER_CHAT,
} from "./chat.types";
const INITIALSTATE = {
userChats: [],
chats: [],
filtered: null,
};
const Chat = (state = INITIALSTATE, action) => {
const { type, payload } = action;
switch (type) {
case GET_USER_CHAT:
return {
...state,
userChats: payload,
};
case GET_FULL_CHAT:
return {
...state,
chats: payload.reverse(),
};
case SEND_MESSAGE:
return {
...state,
chats: [...state.chats, payload],
};
case FILTER_CHAT:
return {
...state,
filtered: state.userChats.filter((chat) => {
const regex = new RegExp(`${payload}`, "gi");
return chat.name.match(regex) || chat.lastMessage.match(regex);
}),
};
default:
return state;
}
};
export default Chat;
|
C++
|
UTF-8
| 836 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include "../utils/assets/Resource.h"
#include "../utils/scene/SceneManager.h"
#include "Tile.h"
class Grid {
public:
Grid();
bool loadMap(std::shared_ptr<Resource> data, std::shared_ptr<SceneManager> scene);
//
int getWidth();
int getHeight();
void findPlayer(int& x, int& y);
void findEnemy(int& x, int& y);
bool is_obstacle(int x, int y);
void update_player(int x, int y);
void update_enemy(int x, int y);
void set_tank_lives(bool* pt, bool* et);
void kill_player_tank();
void kill_enemy_tank();
private:
void create_tile(int type, int x, int y, std::shared_ptr<SceneManager> scene);
std::vector<Tile> tiles;
int width;
int height;
int player_x;
int player_y;
int enemy_x;
int enemy_y;
bool* ptank;
bool* etank;
};
|
Java
|
UTF-8
| 523 | 2.140625 | 2 |
[] |
no_license
|
package com.example.demo.controller;
import com.example.demo.dto.SiteInfo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/")
public class SiteInfoController {
@PostMapping("/show")
public String bid( @RequestBody SiteInfo siteInfo ) {
return siteInfo.toString();
}
}
|
Ruby
|
UTF-8
| 594 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
require 'httparty'
class Push
def self.push_indefinitely()
polls_per_second = AppConfig.twitter_polls_per_hour / 60.0 / 60.0
desired_pause = 1.0 / polls_per_second
loop do
time_at_start = Time.now
push_once
poll_duration = Time.now - time_at_start
if desired_pause - poll_duration > 0
actual_pause = desired_pause - poll_duration
else
actual_pause = 0
end
sleep actual_pause
end
end
def self.push_once
puts "sending xml message"
HTTParty.post("http://localhost:3000", :body=>Tweet.pull_next)
end
end
|
SQL
|
UTF-8
| 335 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
CREATE TABLE DELEGATE_INFO(
ID BIGINT NOT NULL,
ASSIGNEE VARCHAR(200),
ATTORNEY VARCHAR(200),
START_TIME DATETIME,
END_TIME DATETIME,
PROCESS_DEFINITION_ID VARCHAR(100),
TASK_DEFINITION_KEY VARCHAR(100),
STATUS INTEGER,
TENANT_ID VARCHAR(64),
CONSTRAINT PK_DELEGATE_INFO PRIMARY KEY(ID)
) ENGINE=INNODB CHARSET=UTF8;
|
Markdown
|
UTF-8
| 3,253 | 3.125 | 3 |
[] |
no_license
|
# 摘要
* 现维护项目中使用的表单验证
>strtus1的xml验证插件 + ActionForm。
>>xml插件验证的问题
>>>得给每一个action的每一个表单属性做配置,现在超过2000多行。根据需求增改页面都要有输入->确认->完成页面。增和改其实是个重复的逻辑。因为这些原因导致配置文件里有两份同样的配置。
>>ActionForm的问题
>>>ActionForm里做的是xml难以实现的验证。比如验证是否同名(需要操作数据库),或者一个表单属性涉及到其他表单属性。经常维护发现,很多都是重复性的代码,而且,遇到几十个表单属性的情况,简直就是灾难。
* spring
>项目里已经导入spring 3.x
>>spring mvc很早就已经能代替struts了。
综上,一是想慢慢摆脱struts1,二是想简化验证过程。
# 表单验证的简化
>方式一: 通过实现spring提供的validator来实现
>>要在controller利用@InitBinder绑定实现validator的类。在该类的isValid方法里提供所有的验证。
>>优点
>>>感觉跟struts1的ActionForm差不多,没感觉到什么优点。
>>缺点
>>>一旦用@InitBinder绑定验证类,会导致Bean里的注解验证(方式二)失效。
>方式二: 用注解验证
>>直接上例子。
```
public class User {
@NotEmpty
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
```
>>>简单粗暴。一个注释就验证了name不能为空。还可以指定自定义错误信息like @NotEmpty(message="登录帐号不能为空"),还可以这样 @NotEmpty(message="{login.account.not.empty}")。除了这个还有很多hibernate-validator提供的。不知道为什么spring只提供接口,没有去实现。所以要用到hibernate-validator。
>>>>问题
>>>>>但是在实际运用中出了点问题。很多message里提供的key的内容是可以格式化的。比如propertis文件里的login.account.not.empty={0}不能为空。而且存在另一个专门指定“登录账号”的key,login.accound=登录账号。所以最终的错误信息是由login.account.not.empty和login.account的内容组成的。但是hibernate-validator似乎不提供这样的结构。有可能我的了解不深。不管怎么说把朕急坏了。差点要放弃。还是度娘谷哥有招。居然可以自定义注解验证。
>方式三: 自定义注解验证
>>有两种(或以上)
>>>适用于类属性级别的
>>>>就像上面的例子,作用于类属性。虽说第一次有点代码量,但是只要定义好了,不管新增多少,都可以用一行注解解决。
>>>适用于整个类的
>>>>作用于整个类。在属性级别做不到的就在这里验证。这个验证的通用性就比较差了。估计只能且只有用在一个类上。
# 参考文章
* [https://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/validator-customconstraints.html#section-cross-parameter-constraints](https://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/validator-customconstraints.html#section-cross-parameter-constraints)
* [https://www.cnblogs.com/ASPNET2008/p/5831766.html](https://www.cnblogs.com/ASPNET2008/p/5831766.html)
|
Markdown
|
UTF-8
| 2,417 | 3.6875 | 4 |
[] |
no_license
|
#### 变量的类型
`undefined`, `number`, `string`, `boolean`属于简单的值类型.函数、数组、对象、null、new Number(10)都是对象。他们都是引用类型。
> 一切引用类型都是对象,对象是属性的集合
```js
typeof "x" //string
typeof 10 //number
typeof true //boolean
typeof x //undefine
typeof null //object
typeof function(){} //function
function(){} instanceof Object //true
```
#### prototype原型
每个函数都有一个属性`prototype`.其属性值是一个对象,对象中默认只有一个`constructor`属性,默认指向函数本身.
#### __proto__隐式原型
1. 每个对象都有一个`__proto__`,可以称之为隐式原型,`__proto__`指向创建该对象函数的`prototype`.
2. `prototype`也是一个对象,那`fn.prototype.__proto__`指向哪里
``` js
fn.prototype.__proto__ === Object.prototype //true
```
3. `Object.prototype.__proto__`指向`null`
4. 函数既是函数也是对象,所以函数既有`prototype`也有`__proto__`
```js
function fn(x, y) {
return x + y
}
var fn1 = new Function('x', 'y', 'return x + y')
console.log(fn1(1+2))
```
5. 依据上述对象的`__proto__`指向创建该对象函数的`prototype`,所以...
```js
Object.__proto__ === Function.prototype //true
Function.__proto__ === Function.prototype //true
Function.prototype.__proto__ === Object.prototype //true
```
#### instanceof
`Instanceof`运算符的第一个变量是一个对象,暂时称为A;第二个变量一般是一个函数,暂时称为B。
Instanceof的判断队则是:沿着A的__proto__这条线来找,同时沿着B的prototype这条线来找,如果两条线能找到同一个引用,即同一个对象,那么就返回true。如果找到终点还未重合,则返回false。
```js
Object instanceof Function //true
Function instanceof Object //true
Funtion instanceof Function //true
```
由上我们可以得出如下关系

#### 继承
1. JavaScript中的继承是通过原型链实现的
2. 访问一个对象的属性时,先在自身的属性中查找,如果没有,再沿着`__proto__`这条链向上找,这就是原型链
3. 可以用`hasOwnProperty`来区分一个属性是自身的还是原型链中的. `for..in..`循环中需要注意
```js
for(item in f1) {
if(f1.hasOwnProperty){
console.log(item)
}
}
```
|
PHP
|
UTF-8
| 653 | 2.515625 | 3 |
[] |
no_license
|
<?php
namespace php_boilerplate\plugins\other;
use \marshall\core\Menu as Menu;
use \marshall\core\MenuItem as MenuItem;
class _plugin extends \marshall\core\BasePlugin {
private $name = "Other Links";
public function getPluginName(){
return $this->name;
}
public function addMenuItems(){
$node = $this->buildMenuItem($this->name, "/other", 'icon-chevron-right', 40);
$node->addMenuItem($this->buildMenuItem("Foo", "/other/foo", '', 10));
$node->addMenuItem($this->buildMenuItem("Bar", "/other/bar", '', 20));
$node->addMenuItem($this->buildMenuItem("Extra", "/other/extra", '', 30));
Menu::addMenu($node);
}
}
?>
|
Markdown
|
UTF-8
| 1,284 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
# README.md
koa2的一个中间件,用于处理vue-router使用history模式返回index.html,让koa2支持SPA应用程序。 \
我只是一个搬运工,让它兼容Koa2而已。详细说明请到原作者项目库查看\
[bripkens作者的connect-history-api-fallback](https://github.com/bripkens/connect-history-api-fallback)
## Install
```bash
$ npm install --save 'koa2-connect-history-api-fallback'
```
## Use
在原作者的使用方法下增加了白名单选项,原作者的插件默认会将所有的请求都指向到index.html,这样可能就会导致项目内其他路由也被指向到index.html
使用方法如下:
``` javascript
const Koa = require('koa');
const historyApiFallback = require('koa2-connect-history-api-fallback');
const app = new Koa();
// handle fallback for HTML5 history API
app.use(historyApiFallback({ whiteList: ['/api'] }));
// other middlewares
app.use(...);
```
## Example
```javascript
const Koa = require('koa');
// require 'koa2-connect-history-api-fallback' middleware
const historyApiFallback = require('koa2-connect-history-api-fallback');
// create app
const app = new Koa();
// use historyApiFallback
app.use(historyApiFallback());
// other middlewares
app.use(...);
```
|
Python
|
UTF-8
| 1,612 | 3.25 | 3 |
[] |
no_license
|
import numpy as np
import matplotlib.pyplot as plt
import csv
category = ["Ecological Well-being", "Health & Human Services", "Arts & Culture", "Community Building", "Environment"]
arr = np.empty((0, 6), str)
moneyGranted = [[0]*5 for _ in range(6)]
moneyRequested = [[0]*5 for _ in range(6)]
perFull = [[0]*5 for _ in range(6)]
def task5(arr): # function definition; be sure to add your task number after 'task'
# Write your code here
for row in arr:
moneyGranted[int(row[1])-2015][int(row[3])-1] += int(row[4])
moneyRequested[int(row[1])-2015][int(row[3])-1] += int(row[5])
for i in range(6):
for j in range(5):
if moneyRequested[i][j] == 0:
print(i+2015,",",category[j],":", "0.0%")
else:
perFull[i][j] = round((moneyGranted[i][j] / moneyRequested[i][j])*100, 2)
print(i+2015,",",category[j],":", perFull[i][j],"%")
for i in range(6):
graphTitle = "Percentage fulfilled for each category in " + str(i+2015)
plt.title(graphTitle)
plt.bar(category, perFull[i])
plt.show()
with open('CEL_HistoricalGrantInformation_2014-7Oct2020_CSV.csv', newline='') as csvfile: # reading the csv file
reader = csv.DictReader(csvfile)
for row in reader:
arr = np.append(arr, np.array([[row['organization_id'], int(row['year_id']), row['process_id'],
int(row['area_id']), int(row['awarded_id']), int(row['requested_id'])]]), axis=0)
#print(arr)
task5(arr)
|
Markdown
|
UTF-8
| 6,911 | 2.875 | 3 |
[] |
no_license
|
# EzDrive: An iOS platform for car-sharing
This repo holds the source code for a project completed for NUS Orbital Program held during the summer of 2018.
Embarassingly, there are no commits for this project because at the time of creating this application, I was not yet
familiar with source control and thus did not use it for this project. However, for the purpose of displaying the
past projects that I have completed and to show the type of code I have written, I decided to put this on GitHub.
## Introduction
EzDrive is an iOS application that aims to provide an easy and simple to use car-sharing platform for car owners in Singapore.
We found that there are many car owners in Singapore, yet not fully utilising the car at times. With cars being notoriously
expensive here, there are also many drivers that do not personally own cars. This application was created with the idea of
connecting these two groups of people to allow car sharing to take place.
There are two main user types in this application, namely car owners and car renters. Car owners can post their cars on the
app when they wish to rent it out, specifying their car type and model, period of loan, photos of the car and some other
general information. Car renters can easily browse through available cars on the application, select whichever one they are
interested in renting and the exchange can happen entirely on the application.
## Information
This project was built entirely in Swift 4.0. The UI was built 100% programmatically with auto layout and constraints, with no storyboards or interface builder. Backend used is Firebase Database and no other third-party libraries were used.
## Features
### Login/Registration
Our app features a simple sign-in and sign-out functionality using Firebase Authentification. Users would have to register using an email and password, and will also login with an email and password. We also chose to take down more information regarding the user such as his name, location, a preferred username and also a profile picture. User is automatically logged in once registration is complete.
<img src="/docs/ezdrive_login.jpg" alt="login" width="200"/>
### Sorting and Filtering of posts
Upon logging in, users are immediately presented with the Browse tab of the application, which displays all the cars that other users have already shared in the app. Users can sort posts via their location, which we have currently limited to just North, South, East, West and Central Singapore for simplicity. Sorting by price and date of post is also possible, as is filtering by car model. We have also limited the car models for simplicity. This can easily be expanded to include all car models in future development.
<img src="/docs/ezdrive_browse.jpg" alt="browse" width="200"/>
### New post
Users can create a new post when they wish to put their car available for sharing through the Share tab. The share tab requires the user to input some basic details regarding their car, including photos, brand and model, location, price, etc. Users are also required to input their car plate number, which is kept private, but used as a primary defense against bogus posts. Invalid car plate numbers will be rejected and the user will not be allowed to proceed with the post. The car plate number is checked against actual Singapore vehicle registration plate checksum. More info on the [wiki page](https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Singapore).
<img src="/docs/ezdrive_share.jpg" alt="share" width="200"/>
### Searching of posts
Users can navigate to the search tab and input a custom search query for their desired car. The search feature works in such a way that as users are inputting their search query, the posts are automatically filtered when whatever term they are searching for appears in the post's title. The following code segment shows how this is done:
<img src="/docs/ezdrive_search1.png" alt="search1" width="200"/> <img src="/docs/ezdrive_search2.png" alt="search2" width="200"/>
##### Implementation
```swift
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
self.filteredPosts = self.posts
} else {
self.filteredPosts = self.posts.filter { (post) -> Bool in
return post.title.lowercased().contains(searchText.lowercased()) || post.description.lowercased().contains(searchText.lowercased())
}
self.filteredPosts = self.filteredPosts.sorted(by: { (post1, post2) -> Bool in
return post1.timestamp > post2.timestamp
})
}
self.collectionView?.reloadData()
}
```
### User-to-user Chat
When a user is interested in a particular post, clicking on the post brings him to the main view of that single post, where
there is an option for the user to initiate a chat. In the chat view, users can send a text message to the owner of the post just like any other messaging application. The owner of the post will then receive the message in his inbox and he can then reply on the spot. The messaging happens in real time.
This was admittedly one of the harder features to implement due to the lack of suitable and up-to-date third party libraries that could provide us with a customisable message controller. We had to do this completely from scratch and encountered a lot of problems with storing the messages in the database, fetching the correct messages for the correct users and post, and rendering out the message in a clean and aesthetic manner.
<img src="/docs/ezdrive_chat.png" alt="chat" width="200"/>
##### Implementation
In the end, on the database side of things, we decided to structure our data in the following manner (Firebase is a NoSQL database):
```
<chatrooms>
|-- <postId>_<user1Uid>_<user2Uid>
|-- <messageId>
|-- <fromUid>
|-- <toUid>
|-- <timestamp>
|-- <content>
|-- <messageId>
|-- <fromUid>
|-- <toUid>
|-- <timestamp>
|-- <content>
```
This allowed us to have a unique chatroom for every single post and between every single unique user.
There was an interesting problem that we had to get around when using this idea - we had to make sure that when pushing the data to the database, the sequence of `user1Uid` and `user2Uid` must always be the same and reproducible. We got around this by putting the lexicographically smaller one in front.
### User Profile page and review
The profile page of the user simply presents the posts belonging to the current user as well as his reviews and other information. The current user is also able to browse the profile pages of other users by navigating through the posts on the main browse page, and can subsequently leave reviews on their pages.
<img src="/docs/ezdrive_profile.jpg" alt="profile" width="200"/>
|
Java
|
UTF-8
| 463 | 2.703125 | 3 |
[] |
no_license
|
@Override public void update(Command command) throws IllegalArgumentException {
if (command instanceof OpenClosedType) {
state=(OpenClosedType)command;
}
else {
final String updatedValue=command.toString();
if (openString.equals(updatedValue)) {
state=OpenClosedType.OPEN;
}
else if (closeString.equals(updatedValue)) {
state=OpenClosedType.CLOSED;
}
else {
state=OpenClosedType.valueOf(updatedValue);
}
}
}
|
Go
|
UTF-8
| 308 | 3.328125 | 3 |
[] |
no_license
|
package cyclelinkedlist
type ListNode struct {
Val int
Next *ListNode
}
func hasCycle(head *ListNode) bool {
slowP := head
fastP := head
for slowP != nil && fastP != nil && fastP.Next != nil {
slowP = slowP.Next
fastP = fastP.Next.Next
if slowP == fastP {
return true
}
}
return false
}
|
JavaScript
|
UTF-8
| 1,947 | 2.625 | 3 |
[] |
no_license
|
import React, { Component } from 'react';
import { connect } from "react-redux";
import './style.css';
import {addTask, chngId} from "../../actions"
const mapDispatchToProps = dispatch => {
return {
addTask: task => dispatch(addTask(task)),
chngId: id => dispatch(chngId(id)),
};
};
const mapStateToProps = state => {
return { toDoList: state.toDoList,
idCounter: state.idCounter,
users: state.users
};
};
class ConnectedAddTask extends Component {
constructor(props) {
super(props);
this.addTask = this.addTask.bind(this);
}
addTask() {
if (this.inputTask.value !== '' && this.props.users.length>0) {
var username=document.getElementById("assigneeSelect").value;//aware that this not being recomended way of getting input value
var selectedUser=this.props.users.filter(user=>user.username==username)[0];
console.log(selectedUser);
var id=this.props.idCounter+1;
var taskArray={
title: this.inputTask.value,
id: id,
completed: false,
userId: selectedUser.id,
};
var users=this.props.users;
console.log(users)
this.inputTask.value = '';
this.props.addTask(taskArray);
this.props.chngId(id);
}
//e.preventDefault()-seems to be unnecessary when button type is defined as "button"
}
render() {
return (
<div id="addTask">
<input ref={(a) => this.inputTask = a}
placeholder="please enter your task" className="inputAddTask">
</input>
<select id="assigneeSelect">
{this.props.users.map((user)=><option
key={user.id}>{user.username}</option>)}
</select>
<button type="button" onClick={this.addTask} className="buttonAddTask">Add to Task List</button>
</div>
);
}
}
const AddTask=connect(mapStateToProps,mapDispatchToProps)(ConnectedAddTask)
export default AddTask;
|
Java
|
UTF-8
| 3,630 | 1.984375 | 2 |
[
"Apache-2.0",
"GPL-2.0-only",
"EPL-2.0",
"CDDL-1.0",
"MIT",
"BSD-3-Clause",
"Classpath-exception-2.0"
] |
permissive
|
package com.commercetools.api.predicates.query.subscription;
import java.util.function.Function;
import com.commercetools.api.predicates.query.*;
public class ResourceUpdatedDeliveryPayloadQueryBuilderDsl {
public ResourceUpdatedDeliveryPayloadQueryBuilderDsl() {
}
public static ResourceUpdatedDeliveryPayloadQueryBuilderDsl of() {
return new ResourceUpdatedDeliveryPayloadQueryBuilderDsl();
}
public StringComparisonPredicateBuilder<ResourceUpdatedDeliveryPayloadQueryBuilderDsl> projectKey() {
return new StringComparisonPredicateBuilder<>(
BinaryQueryPredicate.of().left(new ConstantQueryPredicate("projectKey")),
p -> new CombinationQueryPredicate<>(p, ResourceUpdatedDeliveryPayloadQueryBuilderDsl::of));
}
public StringComparisonPredicateBuilder<ResourceUpdatedDeliveryPayloadQueryBuilderDsl> notificationType() {
return new StringComparisonPredicateBuilder<>(
BinaryQueryPredicate.of().left(new ConstantQueryPredicate("notificationType")),
p -> new CombinationQueryPredicate<>(p, ResourceUpdatedDeliveryPayloadQueryBuilderDsl::of));
}
public CombinationQueryPredicate<ResourceUpdatedDeliveryPayloadQueryBuilderDsl> resource(
Function<com.commercetools.api.predicates.query.common.ReferenceQueryBuilderDsl, CombinationQueryPredicate<com.commercetools.api.predicates.query.common.ReferenceQueryBuilderDsl>> fn) {
return new CombinationQueryPredicate<>(
ContainerQueryPredicate.of()
.parent(ConstantQueryPredicate.of().constant("resource"))
.inner(fn.apply(com.commercetools.api.predicates.query.common.ReferenceQueryBuilderDsl.of())),
ResourceUpdatedDeliveryPayloadQueryBuilderDsl::of);
}
public CombinationQueryPredicate<ResourceUpdatedDeliveryPayloadQueryBuilderDsl> resourceUserProvidedIdentifiers(
Function<com.commercetools.api.predicates.query.message.UserProvidedIdentifiersQueryBuilderDsl, CombinationQueryPredicate<com.commercetools.api.predicates.query.message.UserProvidedIdentifiersQueryBuilderDsl>> fn) {
return new CombinationQueryPredicate<>(
ContainerQueryPredicate.of()
.parent(ConstantQueryPredicate.of().constant("resourceUserProvidedIdentifiers"))
.inner(fn.apply(
com.commercetools.api.predicates.query.message.UserProvidedIdentifiersQueryBuilderDsl.of())),
ResourceUpdatedDeliveryPayloadQueryBuilderDsl::of);
}
public LongComparisonPredicateBuilder<ResourceUpdatedDeliveryPayloadQueryBuilderDsl> version() {
return new LongComparisonPredicateBuilder<>(
BinaryQueryPredicate.of().left(new ConstantQueryPredicate("version")),
p -> new CombinationQueryPredicate<>(p, ResourceUpdatedDeliveryPayloadQueryBuilderDsl::of));
}
public LongComparisonPredicateBuilder<ResourceUpdatedDeliveryPayloadQueryBuilderDsl> oldVersion() {
return new LongComparisonPredicateBuilder<>(
BinaryQueryPredicate.of().left(new ConstantQueryPredicate("oldVersion")),
p -> new CombinationQueryPredicate<>(p, ResourceUpdatedDeliveryPayloadQueryBuilderDsl::of));
}
public DateTimeComparisonPredicateBuilder<ResourceUpdatedDeliveryPayloadQueryBuilderDsl> modifiedAt() {
return new DateTimeComparisonPredicateBuilder<>(
BinaryQueryPredicate.of().left(new ConstantQueryPredicate("modifiedAt")),
p -> new CombinationQueryPredicate<>(p, ResourceUpdatedDeliveryPayloadQueryBuilderDsl::of));
}
}
|
Markdown
|
UTF-8
| 533 | 2.515625 | 3 |
[] |
no_license
|
# This is the front-end of click-stream analysis
The click-stream software a.k.a Divolte collector is going to collect data from this web-site.
# How to use this
- The `environment.yml` file has all dependencies in it
> Use setup the flask environment create a new environment using `environment.yml` file
- Open the root folder and type `python run.py`
> This will start the flask application
- User needs to login, in order to perform any activity
> One can register to the website and start purchaging mobile phones
|
Java
|
UTF-8
| 7,936 | 2.46875 | 2 |
[] |
no_license
|
package com.tminions.app.screenController;
import com.tminions.app.Utils.AlertBox;
import com.tminions.app.controllers.ConflictsController;
import com.tminions.app.models.ConflictModel;
import com.tminions.app.models.ResolvedConflictModel;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import java.util.*;
public class ConflictsScreenController {
// Used to hold current conflict
private ConflictModel conflict;
@FXML private Label conflictsText;
@FXML private ScrollPane scroller;
@FXML private GridPane grid;
@FXML private Button submit;
@FXML private Button copy;
// Called by javafx framework after screen components have been initialized
public void initialize() {
updateScreen();
}
public void updateScreen() {
grid.getChildren().clear();
// Get a conflict
this.conflict = getConflict();
// If conflict does not exist, show that no conflicts found
if (conflict != null) {
conflictsText.setText("Please fix the conflict below in Template: " + conflict.getTemplate_name());
conflictsText.setTextFill(Color.RED);
conflictsText.setFont(Font.font("Verdana", FontWeight.NORMAL, 12));
} else {
conflictsText.setText("All Conflicts Resolved!");
conflictsText.setTextFill(Color.GREEN);
conflictsText.setFont(Font.font("Verdana", FontWeight.BOLD, 25));
}
// Show conflict data if it is not null
if (conflict != null) {
// Get map of column names to values for first person in list
Map<String, String> columnToValues = conflict.getConflicts().get(0);
// Create a list to hold column constraints for how many people there are + 2 columns for padding
ObservableList<ColumnConstraints> constraints = FXCollections.observableArrayList();
// Find number of columns needed + 2 to show values and input
int size = 100/(conflict.getConflicts().size()+2);
for (int i = 0; i < conflict.getConflicts().size() + 2; i++) {
ColumnConstraints col = new ColumnConstraints();
col.setPercentWidth(size);
col.setPrefWidth(size);
constraints.add(col);
}
grid.getColumnConstraints().setAll(constraints);
scroller.setFitToWidth(true);
// Get column names
List<String> columnNames = new ArrayList<>(conflict.getConflicts().get(0).keySet());
// Add key title
int currRow = columnNames.size() - 1;
grid.add(new Label("Field"), 0, 0);
// Loop through each column name adding it first column
for (String name : columnNames) {
grid.add(new Label(name), 0, currRow + 1);
currRow--;
}
int currCol = conflict.getConflicts().size() - 1;
// Loop through each person
for (Map<String, String> person : conflict.getConflicts()) {
currRow = columnNames.size() - 1;
// Add person heading
grid.add(new Label("Person " + Integer.toString(currCol + 1)), currCol + 1, 0);
// Add all their values for the current column
for (String column : columnNames) {
// Add their value for the current column
TextField field = new TextField(person.get(column));
field.setEditable(false);
grid.add(field, currCol + 1, currRow + 1);
currRow--;
}
currCol--;
}
// Add resolved title
currRow = columnNames.size() - 1;
grid.add(new Label("Resolved"), conflict.getConflicts().size() + 1, 0);
// Create array of textfields to hold resolved values
List<TextField> inputs = new ArrayList<TextField>();
int currInput = 0;
// Loop through each column name
for (String name : columnNames) {
// Create textfield
TextField input = new TextField();
input.setPromptText(name + " RESOLVED");
inputs.add(input);
grid.add(input, conflict.getConflicts().size() + 1, currRow + 1);
currRow--;
}
submit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if (submitUpdate(columnNames, inputs)) {
AlertBox.display("Update Successful!", "Update has been sent");
updateScreen();
} else {
AlertBox.display("Update Failed!", "The update was unsuccessful at this time, please try again later.");
}
}
});
copy.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
int i = 0;
for (String column : columnNames) {
//if all the persons.get(column) is the same, then set inputs.get(i) to the value
if (conflict.getConflicts().get(0).get(column).equals(conflict.getConflicts().get(1).get(column))) {
inputs.get(i).setText(conflict.getConflicts().get(0).get(column));
}
i++;
}
}
});
} else {
scroller.setVisible(false);
grid.setVisible(false);
submit.setVisible(false);
copy.setVisible(false);
}
}
/**
* Call this to try and submit data.
* @param columnNames List of column names
* @param fields Array of textfields. The textfield order must correspond to the column names.
* @return True when successful request to server, false otherwise.
*/
private boolean submitUpdate(List<String> columnNames, List<TextField> fields) {
// Create map of resolved columns
Map<String, String> resolvedColumns = new HashMap<String, String>();
// Loop through each column
for (int i = 0; i < columnNames.size(); i++) {
resolvedColumns.put(columnNames.get(i), fields.get(i).getText());
}
ResolvedConflictModel resolved = new ResolvedConflictModel(conflict.get_id(), conflict.getTemplate_name(),
conflict.getUnique_identifier(), resolvedColumns);
return ConflictsController.resolveConflict(resolved);
}
private ConflictModel getConflict() {
// The following below can be uncommented to test the feature
// Map<String, String> vals = new HashMap<String, String>(){
// {
// this.put("col1", "val1");
// this.put("col2", "val2");
// this.put("col3", "val3");
// this.put("col4", "val4");
// }
// };
// Map<String, String> vals2 = new HashMap<String, String>(){
// {
// this.put("col1", "val4");
// this.put("col2", "val5");
// this.put("col3", "val6");
// this.put("col4", "val7");
// }
// };
// ConflictModel a = new ConflictModel("id", "template", "unique id",
// Arrays.asList(vals, vals2));
// return a;
return ConflictsController.getConflict();
}
}
|
Java
|
UTF-8
| 856 | 2.25 | 2 |
[] |
no_license
|
package com.jsd.blibiliclient.di.module;
import com.jess.arms.di.scope.ActivityScope;
import dagger.Module;
import dagger.Provides;
import com.jsd.blibiliclient.mvp.contract.TabCategoryContract;
import com.jsd.blibiliclient.mvp.model.TabCategoryModel;
@Module
public class TabCategoryModule {
private TabCategoryContract.View view;
/**
* 构建TabCategoryModule时,将View的实现类传进来,这样就可以提供View的实现类给presenter
*
* @param view
*/
public TabCategoryModule(TabCategoryContract.View view) {
this.view = view;
}
@ActivityScope
@Provides
TabCategoryContract.View provideTabCategoryView() {
return this.view;
}
@ActivityScope
@Provides
TabCategoryContract.Model provideTabCategoryModel(TabCategoryModel model) {
return model;
}
}
|
Java
|
UTF-8
| 1,030 | 2.171875 | 2 |
[] |
no_license
|
package com.example.smartutor.model;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import java.time.LocalDateTime;
import java.util.List;
@Dao
public interface LessonDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) void insertLesson(Lesson lesson);
@Delete void deleteLesson(Lesson lesson);
@Query("SELECT * FROM Lesson WHERE tutorEmail = :tutorEmail and date = :date Limit 1") LiveData<Lesson> getLessonByTutor(String tutorEmail, LocalDateTime date);
@Query("SELECT * FROM Lesson WHERE studentEmail = :studentEmail and date = :date Limit 1") LiveData<Lesson> getLessonByStudent(String studentEmail, LocalDateTime date);
@Query("SELECT * FROM Lesson WHERE studentEmail = :email") LiveData<List<Lesson>> getLessonsByStudent(String email);
@Query("SELECT * FROM Lesson WHERE tutorEmail = :email") LiveData<List<Lesson>> getLessonsByTutor(String email);
}
|
PHP
|
UTF-8
| 668 | 2.703125 | 3 |
[] |
no_license
|
<?php
class Member{
private $database;
function Member(){
// $this->database = new db();
}
/*根据username取得所有字段的值*/
public function getMemberMsgByUsername($username){
$sql = "select * from ".DBPREFIX."member where username='".$username."'";
return DB::get_all($sql);
}
/*根据数组插入新会员*/
public function insertMemberByArray($mumber_msg){
DB::insert(DBPREFIX."member", $mumber_msg);
}
/*修改密码*/
public function updatePassword($username, $newpassword){
return DB::update(DBPREFIX."member", array("password"=>md5($newpassword)), " username='".$username."'");
}
}
?>
|
Java
|
UTF-8
| 614 | 1.921875 | 2 |
[] |
no_license
|
package org.takeback.util.task.schedule;
import java.io.PrintStream;
import org.joda.time.DateTime;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class Task
implements Job
{
public void execute(JobExecutionContext jobExecutionContext)
throws JobExecutionException
{
System.out.println(new DateTime().toLocalDateTime());
}
}
/* Location: E:\apache-tomcat-8\apache-tomcat-8\webapps\ROOT\WEB-INF\classes\!\org\takeback\util\task\schedule\Task.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/
|
TypeScript
|
UTF-8
| 1,615 | 2.90625 | 3 |
[] |
no_license
|
import { MTask, ITask } from "./task.model";
import { MTag } from "./tag.model";
type stringOrNull = string | null;
export class MListOfTasks {
public listId: number;
public title: string;
public tag: MTag;
public color: stringOrNull;
public isFavorite: boolean;
public isFixed: boolean;
public dateReminder: Date | null;
public dateUpdate: Date;
public dateRegister: Date;
public isDelete: boolean;
public tasks: MTask[];
constructor(thingsToDo: IListOfTasks) {
this.listId = thingsToDo.list_id;
this.title = thingsToDo.title;
this.tag = {
color: thingsToDo.tagColor,
name: thingsToDo.tagName,
tagId: thingsToDo.tag_id
};
this.color = thingsToDo.color;
this.isFavorite = thingsToDo.isFavorite ? true : false;
this.isFixed = thingsToDo.isFixed ? true : false;
this.dateReminder = thingsToDo.date_reminder ? new Date(thingsToDo.date_reminder) : null;
this.dateUpdate = new Date(thingsToDo.date_update);
this.dateRegister = new Date(thingsToDo.date_register);
this.isDelete = thingsToDo.isDelete ? true : false;
this.tasks = thingsToDo.tasks.map(task => new MTask(task));
}
}
export interface IListOfTasks {
list_id: number,
title: string,
tag: stringOrNull,
color: stringOrNull,
isFavorite: 0 | 1,
isFixed: 0 | 1,
date_reminder: stringOrNull,
date_update: string,
date_register: string,
tag_id: number,
tagName: string,
tagColor: string,
isDelete: number,
tasks: ITask[]
}
|
Java
|
UTF-8
| 302 | 1.765625 | 2 |
[] |
no_license
|
package DOMNodes;
public interface IDOMEdgeNode extends IDOMNode {
IDOMClassNode getFrom();
IDOMClassNode getTo();
void addAttribute(String dotAttrName, String property);
String getAttribute(String graphvizKey);
String attributeMapToString();
void set(IDOMClassNode start, IDOMClassNode end);
}
|
Java
|
UTF-8
| 1,905 | 1.59375 | 2 |
[] |
no_license
|
/*
* Copyright (c) 2016 Brett Profitt.
*
* This file is part of the Elgg support plugin for JetBrains PhpStorm IDE.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.elgg.ps.views;
import com.intellij.codeInsight.completion.CompletionContributor;
import com.intellij.codeInsight.completion.CompletionType;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.patterns.PsiElementPattern;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.parser.PhpElementTypes;
import com.jetbrains.php.lang.patterns.PhpPatterns;
import org.jetbrains.annotations.NotNull;
public class ViewsCompletionContributor extends CompletionContributor {
public ViewsCompletionContributor() {
extend(
CompletionType.BASIC,
getViewAttributePatterns(),
new ViewsCompletionProvider());
}
/**
* Function filtering is done in the contributor because it's too messy to do here.
* @return
*/
@NotNull
private static PsiElementPattern.Capture<PsiElement> getViewAttributePatterns() {
return PlatformPatterns.psiElement()
.inside(PlatformPatterns.psiElement(PhpElementTypes.PARAMETER_LIST))
.inside(PlatformPatterns.psiElement(PhpElementTypes.FUNCTION_CALL))
.inFile(PhpPatterns.psiFile());
}
}
|
Java
|
UTF-8
| 403 | 2.859375 | 3 |
[] |
no_license
|
package com.dlh.zambas.executor;
public class WorkerThread implements Runnable{
private String command;
public WorkerThread(String command) {
this.command = command;
}
@Override
public void run(){
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+ " is running **** " + command);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
Java
|
UTF-8
| 3,579 | 2.8125 | 3 |
[] |
no_license
|
package com.ssitcloud.common.util;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.util.StringUtils;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import com.ssitcloud.common.system.MongoInstance;
public class MBeanUtil {
/**
*
* @Description: 检查WriteResult
* @param @param wr
* @param @return
* @return boolean
* @throws
* @author lbh
* @date 2016年3月18日
*/
public static boolean writeResultWasAcknowledged(WriteResult wr) {
if (wr != null && wr.wasAcknowledged()) {
return true;
}
return false;
}
/**
* 把实体bean对象转换成DBObject
*
* @param bean
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static <T> DBObject bean2DBObject(T bean)
throws IllegalArgumentException, IllegalAccessException {
if (bean == null) {
return null;
}
DBObject dbObject = new BasicDBObject();
// 获取对象对应类中的所有属性域
Field[] fields = bean.getClass().getDeclaredFields();
for (Field field : fields) {
// 获取属性名
String varName = field.getName();
// 修改访问控制权限
boolean accessFlag = field.isAccessible();
if (!accessFlag) {
field.setAccessible(true);
}
Object param = field.get(bean);
if (param == null) {
continue;
} else if (param instanceof Integer) {// 判断变量的类型
int value = ((Integer) param).intValue();
dbObject.put(varName, value);
} else if (param instanceof String) {
String value = (String) param;
dbObject.put(varName, value);
} else if (param instanceof Double) {
double value = ((Double) param).doubleValue();
dbObject.put(varName, value);
} else if (param instanceof Float) {
float value = ((Float) param).floatValue();
dbObject.put(varName, value);
} else if (param instanceof Long) {
long value = ((Long) param).longValue();
dbObject.put(varName, value);
} else if (param instanceof Boolean) {
boolean value = ((Boolean) param).booleanValue();
dbObject.put(varName, value);
} else if (param instanceof Date) {
Date value = (Date) param;
dbObject.put(varName, value);
}
// 恢复访问控制权限
field.setAccessible(accessFlag);
}
return dbObject;
}
/**
* 把DBObject转换成bean对象
*
* @param dbObject
* @param bean
* @return
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
*/
public static <T> T dbObject2Bean(DBObject dbObject, T bean)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
if (bean == null) {
return null;
}
Field[] fields = bean.getClass().getDeclaredFields();
for (Field field : fields) {
String varName = field.getName();
Object object = dbObject.get(varName);
if (object != null) {
BeanUtils.setProperty(bean, varName, object);
}
}
return bean;
}
/**
* 检查monodb 实例的值
* @param instance
* @return
*/
public static boolean validationMongoInstance(MongoInstance instance){
if(!StringUtils.hasText(instance.getHost()))
return false;
if(!StringUtils.hasText(instance.getOperDatabase()))
return false;
if(instance.getPort()==0)
return false;
if(!StringUtils.hasText(instance.getPwd()))
return false;
if(!StringUtils.hasText(instance.getUser()))
return false;
return true;
}
}
|
Python
|
UTF-8
| 2,321 | 4.09375 | 4 |
[] |
no_license
|
"""
1156. Swap For Longest Repeated Character Substring (Medium)
Given a string text, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters.
Example 1:
Input: text = "ababa"
Output: 3
Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa", which its length is 3.
Example 2:
Input: text = "aaabaaa"
Output: 6
Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa", which its length is 6.
Example 3:
Input: text = "aaabbaaa"
Output: 4
Example 4:
Input: text = "aaaaa"
Output: 5
Explanation: No need to swap, longest repeated character substring is "aaaaa", length is 5.
Example 5:
Input: text = "abcdef"
Output: 1
"""
class Solution(object):
def maxRepOpt1(self, text):
"""
:type text: str
:rtype: int
"""
memo = []
for i in range(26):
memo.append([])
i = 0
n = len(text)
while i < n:
j = i + 1
while j < n and text[j] == text[i]:
j += 1
ind = ord(text[i]) - ord('a')
memo[ind].append((i, j-1))
i = j
best = 0
for range_list in memo:
for idx, tmptuple in enumerate(range_list):
begin, end = tmptuple
tmplen = end - begin + 1
if len(range_list) > 1:
tmplen += 1
best = max(best, tmplen)
if idx > 0:
lbegin, lend = range_list[idx-1]
if lend + 2 == begin:
tmplen = end-begin+1+lend-lbegin+1
if len(range_list) >= 3:
tmplen += 1
else:
tmplen = end-begin+1+1
best = max(best, tmplen)
return best
if __name__ == "__main__":
a = Solution()
print(a.maxRepOpt1("ababa"))
print(a.maxRepOpt1("aaabaaa"))
print(a.maxRepOpt1("aaabbaaa"))
print(a.maxRepOpt1("aaaaa"))
print(a.maxRepOpt1("abcdef"))
print(a.maxRepOpt1("aabaadefaaa"))
print(a.maxRepOpt1("aaaaabbbbbbaabbaabbaaabbbbab"))
|
PHP
|
UTF-8
| 4,232 | 2.6875 | 3 |
[] |
no_license
|
<?
/**
* The Galleries controller class.
*
* @author Yarick
* @version 0.1
*/
class Controller_Backend_Galleries extends Controller_Backend_Standard
{
/**
* @see parent::getModelName()
*/
protected function getModelName( $method = null )
{
if ( in_array( $method, array('items', 'addi', 'editi', 'deli', 'posi') ) )
{
return 'Gallery_Item';
}
return 'Gallery';
}
/**
* @see parent::getAliasName()
*/
protected function getAliasName( $method = null )
{
if ( in_array( $method, array('items', 'addi', 'editi', 'deli', 'posi') ) )
{
return 'Item';
}
return 'Gallery';
}
/**
* @see parent::getTitle()
*/
public function getTitle()
{
return 'Галереи';
}
/**
* @see parent::haltForm()
*/
protected function haltForm( $Object, $method = 'edit' )
{
if ( $method == 'editi' || $method == 'addi' )
{
return $this->halt( 'items/'.$Object->GalleryId, true );
}
return parent::haltForm( $Object, $method );
}
/**
* The index handler.
*
* @access public
* @return string The HTML code.
*/
public function index()
{
$Gallery = new Gallery();
$params = array();
$params[] = 'Type = '.intval( Request::get('t') );
$this->getView()->set( 'Galleries', $Gallery->findList( $params, 'Position asc' ) );
return $this->getView()->render();
}
/**
* @see parent::add()
*/
public function add()
{
$Gallery = new Gallery();
$Gallery->Type = intval( Request::get('t') );
return $this->initForm( $Gallery, 'add' );
}
/**
* The gallery items hanlder.
*
* @access public
* @param int $id The Gallery id.
* @return string The HTML code.
*/
public function items( $id = null )
{
$Gallery = new Gallery();
$Gallery = $Gallery->findItem( array( 'Id = '.$id ) );
if ( !$Gallery->Id )
{
return $this->halt();
}
$Item = new Gallery_Item();
$this->getView()->set( 'Gallery', $Gallery );
$this->getView()->set( 'Items', $Item->findList( array( 'GalleryId = '.$Gallery->Id ), 'Position desc' ) );
return $this->getView()->render();
}
/**
* The function adds gallery item.
*
* @access public
* @param int $id The gallery id.
* @return string The HTML code.
*/
public function addi( $id = null )
{
$Gallery = new Gallery();
$Gallery = $Gallery->findItem( array( 'Id = '.$id ) );
if ( !$Gallery->Id )
{
return $this->halt();
}
$Item = new Gallery_Item();
$Item->GalleryId = $Gallery->Id;
return parent::initForm( $Item, 'addi' );
}
/**
* The editing gallery item handler.
*
* @access public
* @param int $id The gallery item id.
* @return string The HTML code.
*/
public function editi( $id = null )
{
$Item = new Gallery_Item();
$Item = $Item->findItem( array( 'Id = '.$id ) );
if ( !$Item->Id )
{
return $this->halt();
}
return parent::initForm( $Item, 'editi' );
}
/**
* @see parent::delete()
*/
public function deli( $id = null )
{
return $this->rawDelete('deli', $id);
}
/**
* @see parent::pos()
*/
public function posi()
{
return $this->rawPos('posi');
}
/**
* The upload form handler.
*
* @access public
* @param int $id The Gallery id.
* @return string The HTML code.
*/
public function upload( $id = null )
{
$error = array();
$Gallery = new Gallery();
$Gallery = $Gallery->findItem( array( 'Id = '.$id ) );
if ( !$Gallery->Id )
{
return $this->halt();
}
if ( isset( $_POST['submit'] ) )
{
if ( isset( $_FILES['file'] ) )
{
foreach ( $_FILES['file']['name'] as $id => $value )
{
$file = array(
'name' => $_FILES['file']['name'][ $id ],
'type' => $_FILES['file']['type'][ $id ],
'tmp_name' => $_FILES['file']['tmp_name'][ $id ],
'error' => $_FILES['file']['error'][ $id ],
'size' => $_FILES['file']['size'][ $id ],
);
$Item = new Gallery_Item();
$Item->GalleryId = $Gallery->Id;
if ( $Item->save() )
{
if ( File::upload( $Item, $file ) )
{
$Item->save();
}
}
}
}
return $this->halt( 'items/'.$Gallery->Id );
}
$this->getView()->set( 'Gallery', $Gallery );
$this->getView()->set( 'Error', $error );
return $this->getView()->render();
}
}
|
C
|
GB18030
| 2,495 | 2.6875 | 3 |
[] |
no_license
|
#include "led.h"
#include "beep.h"
#include "delay.h"
#include "usart.h"
extern int time; // ٶ
extern int speed_falg; // ƿƱ־λ
extern int led_speed_num; // ĸ
extern int led_speed_arr_flag[]; // Ƶı־
extern int led_arr_flag[]; // Ƶı־
// תǰҪļҪ
// תʱgofindȻ
void LED_Init(void)
{
// GPIOϢṹ
GPIO_InitTypeDef GPIO_InitStruct;
// ʹʱ
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF|RCC_AHB1Periph_GPIOE, ENABLE); // ʹʱ
GPIO_InitStruct.GPIO_Pin=GPIO_Pin_9|GPIO_Pin_10; //
GPIO_InitStruct.GPIO_Mode=GPIO_Mode_OUT; // ģʽ
GPIO_InitStruct.GPIO_OType=GPIO_OType_PP; // ģʽ
GPIO_InitStruct.GPIO_PuPd=GPIO_PuPd_NOPULL; //
GPIO_InitStruct.GPIO_Speed=GPIO_High_Speed; //
// ʼϢϢдĴ
GPIO_Init(GPIOF,&GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin=GPIO_Pin_13|GPIO_Pin_14;
GPIO_Init(GPIOE,&GPIO_InitStruct);
// ŵĸߵ͵ƽֵ
GPIO_SetBits(GPIOF,GPIO_Pin_9|GPIO_Pin_10); // øߵƽ led
GPIO_SetBits(GPIOE,GPIO_Pin_13|GPIO_Pin_14);
// GPIO_ResetBits(GPIOF,GPIO_Pin_9); // õ͵ƽ led
}
// led
void LED_Open(int i)
{
switch(i){
case 1:
GPIO_ResetBits(GPIOF,GPIO_Pin_9);
break;
case 2:
GPIO_ResetBits(GPIOF,GPIO_Pin_10);
break;
case 3:
GPIO_ResetBits(GPIOE,GPIO_Pin_13);
break;
case 4:
GPIO_ResetBits(GPIOE,GPIO_Pin_14);
break;
}
}
// led
void LED_Close(int i)
{
switch(i){
case 1:
GPIO_SetBits(GPIOF,GPIO_Pin_9);
break;
case 2:
GPIO_SetBits(GPIOF,GPIO_Pin_10);
break;
case 3:
GPIO_SetBits(GPIOE,GPIO_Pin_13);
break;
case 4:
GPIO_SetBits(GPIOE,GPIO_Pin_14);
break;
}
}
// ˮ
void LED_Water(void)
{
int i;
for(i=1;i<=4;i++)
{
LED_Open(i);
delay_ms(200);
LED_Close(i);
}
}
//
void LED_Flash(int i,int times)
{
if(speed_falg)
{
LED_Open(led_speed_num);
delay_ms(times);
LED_Close(led_speed_num);
delay_ms(times);
}
}
void LED_BEEP_Flash(int i,int times)
{
//BEEP_Open();
LED_Open(led_speed_num);
delay_ms(times);
LED_Close(led_speed_num);
//BEEP_Close();
delay_ms(times);
}
// ٶ
void LED_Speed(int flag)
{
if(flag) // flag==1
{
time+=10;
}else{
if(time!=0)
{
time-=10;
}
}
}
|
C++
|
UTF-8
| 482 | 2.71875 | 3 |
[] |
no_license
|
//UVa Problem-11634(Generate random numbers)
//Accepted
//Running time: 0.120 sec
#include<iostream>
#include<set>
using namespace std;
int main(){
int n;
while(cin>>n && n){
set<int>suru;
suru.insert(n);
while(true){
n=n*n;
n/=100;
n%=10000;
if(suru.find(n)!=suru.end())
break;
suru.insert(n);
}
cout<<suru.size()<<endl;
}
return 0;
}
|
Java
|
UTF-8
| 313 | 2.75 | 3 |
[] |
no_license
|
package com.logical;
public class ReturnTest {
//type instance-varibale;
int var=10;
//type methodname(parameter-list) {
//}
public static void main(String[] args) {
boolean t=true;
System.out.println("Before the Return.");
if(t) return;
System.out.println("is this line will execute?");
}
}
|
JavaScript
|
UTF-8
| 1,110 | 3.421875 | 3 |
[] |
no_license
|
export const toRomNum = (num) => {
const numVals = [
["M", 1000],
["D", 500],
["C", 100],
["L", 50],
["X", 10],
["V", 5],
["I", 1],
];
let start;
for (let i = 0; i < numVals.length; i++) {
if (numVals[i][1] < num + 1) {
start = i;
break;
}
}
if (!start && start !== 0) {
throw new Error("Couldn't find a start point.");
}
let romNumsVal = "";
let cont = true;
while (cont) {
if (Math.floor(num / numVals[start][1]) === 4) {
romNumsVal += numVals[start][0] + numVals[start - 1][0];
} else if (num === 9) {
romNumsVal += "IX";
break;
} else if (String(num).startsWith(9)) {
romNumsVal += numVals[start + 1][0] + numVals[start - 1][0];
num = String(num).substring(1);
num = Number(num);
console.log(num);
} else {
for (let i = 0; i < Math.floor(num / numVals[start][1]); i++) {
romNumsVal += numVals[start][0];
}
}
num = num % numVals[start][1];
if (num === 0) {
cont = false;
} else {
start++;
}
}
return romNumsVal;
};
|
Markdown
|
UTF-8
| 3,510 | 4.0625 | 4 |
[] |
no_license
|
自己在写代码时对this的指向总是靠猜的,这里整理一下。
this是什么?
> 在函数内部,有两个特殊的对象:arguments和this。this引用的是函数据以执行的环境对象。this对象是在运行时基于函数的执行环境绑定的。
this有什么用处?
> this用于在js函数调用时指明函数调用上下文,建立函数内部与调用上下文之间的联系。此处尤其需要注意的是,只有当函数调用时,this建立的上下文联系才存在;仅仅定义函数而不调用,this所建立的上下文联系并不存在。并且这种上下文联系的类型,决定于函数调用的方式。
### 函数调用方式
+ 方法调用模式
+ 函数调用模式
+ 构造器调用模式
+ apply/call调用模式
#### 方法调用模式
函数被定义为对象的方法时,以对象的方法形式调用该函数。
```
var o = {
init:function(){
console.log(this);
}
}
o.init();//o
//如果我将这个对象的方法赋给一个变量,再调用,就是函数调用模式
var func = o.init;
func(); //window
```
#### 函数调用模式
当一个函数不是一个对象的属性时,就是被当做一个函数来调用的。此时this被绑定到全局对象。
```
//全局函数
function fuc(){
console.log(this);
}
func();//window
var value = "window";
var obj = {
value:"obj",
init:function(){
function foo(){
console.log(this.value);
}
foo();
}
}
obj.init();//window
//在对象中定义的函数,如果想访问这个对象的变量,可以通过将this的引用复制一份,然后通过这个变量来访问我们想要的。
var value = "window";
var obj = {
value:"obj",
init:function(){
var _this = this;
function foo(){
console.log(_this.value);
}
foo();
}
}
obj.init();//obj
//一种简单的方式区分是方法调用还是函数调用,方法调用是通过 "." 去调用
//函数调用是函数名后面跟() 去调用
//匿名函数的执行环境具有全局性,因此其this对象通常指向window
var name = "window";
var obj = {
name : "MyObject",
getName : function(){
return function(){
return this.name;
}
}
}
console.log(obj.getName()());//window
```
#### 构造器调用模式
这里首先分析一下new一个构造函数的过程。
第一步:创建一个新对象
第二步:将构造函数的作用域赋给新对象,因此this就指向了这个新对象
第三步:执行构造函数代码,为这个新对象添加属性和方法
第四步:返回新对象
```
function Person(){
this.name = "zhangyanwei";
this.sayName();
}
Person.prototype.sayName = function(){
this.age = 22;
console.log(this.name+this.age);
}
function (){
this.age = 22;
console.log(this.name+this.age);
}
var person = new Person();//zhangyanwei22
person.hasOwnProperty("age");//true
```
#### 显示的改变this指向模式
apply(call)方法允许我们构建一个参数数组传递给调用函数,也允许我们选择this的值。它接受两个参数,第一个是要绑定给this的值,第二个是一个参数数组。他们强大之处是能够扩充函数赖以运行的作用域。
```
window.color = "red";
var obj = {
color : "blue"
}
function sayColor(){
console.log(this.color);
}
sayColor();//red
sayColor.call(this);
sayColor.call(window);
sayColor.call(obj);
```
|
PHP
|
UTF-8
| 3,370 | 2.90625 | 3 |
[] |
no_license
|
<?php
/**
* Objeto referente a la tabla de base de datos 'responsabilidad'.
*
* @author Emanuel Carrasco
* @copyright
* @license
*/
namespace Application\Model\Entity;
/**
* Define el objeto Responsabilidad y el intercambio de información con el hydrator.
*/
class Responsabilidad
{
private $rpo_id;
private $car_id;
private $rpo_descripcion;
private $rpo_valor_f;
private $rpo_valor_ga;
private $rpo_val_c;
function __construct()
{}
/**
*
* @return the $rpo_id
*/
public function getRpo_id()
{
return $this->rpo_id;
}
/**
*
* @return the $car_id
*/
public function getCar_id()
{
return $this->car_id;
}
/**
*
* @return the $rpo_descripcion
*/
public function getRpo_descripcion()
{
return $this->rpo_descripcion;
}
/**
*
* @return the $rpo_valor_f
*/
public function getRpo_valor_f()
{
return $this->rpo_valor_f;
}
/**
*
* @return the $rpo_valor_ga
*/
public function getRpo_valor_ga()
{
return $this->rpo_valor_ga;
}
/**
*
* @return the $rpo_val_c
*/
public function getRpo_val_c()
{
return $this->rpo_val_c;
}
/**
*
* @param
* Ambigous <NULL, array> $rpo_id
*/
public function setRpo_id($rpo_id)
{
$this->rpo_id = $rpo_id;
}
/**
*
* @param
* Ambigous <NULL, array> $car_id
*/
public function setCar_id($car_id)
{
$this->car_id = $car_id;
}
/**
*
* @param
* Ambigous <NULL, array> $rpo_descripcion
*/
public function setRpo_descripcion($rpo_descripcion)
{
$this->rpo_descripcion = $rpo_descripcion;
}
/**
*
* @param
* Ambigous <NULL, array> $rpo_valor_f
*/
public function setRpo_valor_f($rpo_valor_f)
{
$this->rpo_valor_f = $rpo_valor_f;
}
/**
*
* @param
* Ambigous <NULL, array> $rpo_valor_ga
*/
public function setRpo_valor_ga($rpo_valor_ga)
{
$this->rpo_valor_ga = $rpo_valor_ga;
}
/**
*
* @param
* Ambigous <NULL, array> $rpo_val_c
*/
public function setRpo_val_c($rpo_val_c)
{
$this->rpo_val_c = $rpo_val_c;
}
/**
* Registra los atributos de clase mediante post o base de datos.
*
* @param array $data
* @return void
*/
public function exchangeArray($data)
{
$this->rpo_id = (isset($data['rpo_id'])) ? $data['rpo_id'] : null;
$this->car_id = (isset($data['car_id'])) ? $data['car_id'] : null;
$this->rpo_descripcion = (isset($data['rpo_descripcion'])) ? $data['rpo_descripcion'] : null;
$this->rpo_valor_f = (isset($data['rpo_valor_f'])) ? $data['rpo_valor_f'] : null;
$this->rpo_valor_ga = (isset($data['rpo_valor_ga'])) ? $data['rpo_valor_ga'] : null;
$this->rpo_val_c = (isset($data['rpo_val_c'])) ? $data['rpo_val_c'] : null;
}
/**
* Obtiene los valores de los atributos de clase para poblar el hydrator.
*
* @return array
*/
public function getArrayCopy()
{
return get_object_vars($this);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.