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
| 800 | 2.71875 | 3 |
[] |
no_license
|
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
class TheArray {
public:
int find(int n, int d, int first, int last) {
int ans = max(first, last);
for (int i = 2; i < n; i++) {
int maxn = first + d * (i - 1);
if (abs(maxn - last) > d * (n - i)) continue;
ans = max(maxn, ans);
}
swap(first, last);
for (int i = 2; i < n; i++) {
int maxn = first + d * (i - 1);
if (abs(maxn - last) > d * (n - i)) continue;
ans = max(maxn, ans);
}
return ans;
}
};
|
C++
|
UTF-8
| 3,966 | 3.109375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
//assume memory size = 1Mb = 2**20b
#define MEMORY_SIZE 20
using namespace std;
//buddy system list
struct block{
int size;
int start;
};
vector < vector<block> > bslist;
block my_malloc(int size);
void init();
void my_free(block blc);
int _power(int val,int pow){
if(pow <= 0)
return 1;
return val * _power(val,pow - 1);
}
int getPower(int N){
if(N == 0)
return -1;
N--;
int count = 0;
while(N > 0){
N = N/2;
count ++;
}
return count;
}
void my_print(){
int count = 0;
for(vector< vector<block> >::iterator ite = bslist.begin();ite != bslist.end();ite++){
if((*ite).size() > 0)
printf("\t%d:\n",count );
count ++;
for(vector<block>::iterator iter = (*ite).begin(); iter != (*ite).end(); iter++){
printf("\t\tstart:%d=%dK size:%d\n",(*iter).start,(*iter).start/1024,(*iter).size);
}
}
}
int main(){
init();
printf("After ini:\n");
my_print();
block A = my_malloc(100*1024);
printf("After Request 100K:\n");
printf("A got memory starting at %dK with the size of 2**%d\n",A.start/1024,A.size);
my_print();
block B = my_malloc(240*1024);
printf("After Request 240K:\n");
printf("B got memory starting at %dK with the size of 2**%d\n",B.start/1024,B.size);
my_print();
block C = my_malloc(64*1024);
printf("After Request 64K:\n");
printf("C got memory starting at %dK with the size of 2**%d\n",C.start/1024,C.size);
my_print();
block D = my_malloc(256*1024);
printf("After Request 256K:\n");
printf("D got memory starting at %dK with the size of 2**%d\n",D.start/1024,D.size);
my_print();
my_free(B);
printf("After FRee B:\n");
my_print();
my_free(A);
printf("After Free A\n");
my_print();
block E = my_malloc(75*1024);
printf("After Request 75K:\n");
printf("E got memory starting at %dK with the size of 2**%d\n",E.start/1024,E.size);
my_print();
my_free(C);
printf("After FRee C:\n");
my_print();
my_free(E);
printf("After Free E\n");
my_print();
my_free(D);
printf("After Free D\n");
my_print();
return 0;
}
void init(){
vector<block> v;
for(int i=0;i<MEMORY_SIZE+1;i++){
bslist.push_back(v);
}
block ini; ini.size = MEMORY_SIZE; ini.start = 0;
bslist[MEMORY_SIZE].push_back(ini);
}
block my_malloc(int size){
int start = -1;
int pow = getPower(size);
// search = collumn to start searching
int search = pow;
while(search <= MEMORY_SIZE){
//printf("search:%d\n", search);
if(bslist[search].size() > 0){
//printf("note\n");
int t_start = -1;
start = bslist[search][0].start;
int t_size = bslist[search][0].size;
(bslist[search]).erase(bslist[search].begin());
//printf("t:%d s:%d\n",t_size,size );
while(t_size > pow){
//printf("test\n");
t_size --;
t_start = start + _power(2,t_size);
vector<block>::iterator pos = bslist[t_size].begin();
while(pos != bslist[t_size].end()){
if(t_start < (*pos).start)
break;
pos ++ ;
}
block bk; bk.start = t_start; bk.size=t_size;
(bslist[t_size]).insert(pos,bk);
}
break;
}
search ++;
}
block forReturn; forReturn.start = start; forReturn.size = pow;
return forReturn;
}
void my_free(block blc){
int start = blc.start;
int size = blc.size;
int toFind;
//printf("start:%d\n",start);
if(start % _power(2,size+1) == 0)
toFind = start + _power(2,size);
else
toFind = start - _power(2,size);
//printf("tofind:%dK\n",toFind/1024 );
if(bslist[size].size() == 0){
printf("insert1\n");
bslist[size].insert(bslist[size].begin(),blc);
return;
}
for(vector<block>::iterator it = bslist[size].begin();it!=bslist[size].end();it++){
if((*it).start > toFind){
printf("insert2\n");
bslist[size].insert(it,blc);
break;
}
else if((*it).start == toFind){
bslist[size].erase(it);
block toFree; toFree.size = size + 1; toFree.start = (start % _power(2,size+1) == 0)?start:toFind;
my_free(toFree);
return;
}
}
}
|
Java
|
UTF-8
| 670 | 2.234375 | 2 |
[] |
no_license
|
package com.rfchina.community.entity;
import java.io.Serializable;
public class AccountLogoutEvent implements Serializable {
private Long passportId;
private Long timestamp;
public AccountLogoutEvent(Long passportId, Long timestamp) {
this.passportId = passportId;
this.timestamp = timestamp;
}
public Long getPassportId() {
return passportId;
}
public Long getTimestamp() {
return timestamp;
}
@Override
public String toString() {
return "AccountLogoutEvent{" +
"passportId=" + passportId +
", timestamp=" + timestamp +
'}';
}
}
|
C#
|
UTF-8
| 912 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
using System;
using CommandDotNet;
using Spectre.Console;
namespace BbGit.ConsoleApp
{
public class TableFormatModel : IArgumentModel
{
public enum TableFormat { c, b, h, m }
[Option('t',
Description = " b: borders\n" +
" c: columns\n" +
" h: header separator\n" +
" m: markdown")]
public TableFormat Table { get; set; } = TableFormat.b;
public TableBorder GetTheme()
{
return Table switch
{
TableFormat.b => TableBorder.Rounded,
TableFormat.c => TableBorder.Minimal,
TableFormat.h => TableBorder.Simple,
TableFormat.m => TableBorder.Markdown,
_ => throw new ArgumentOutOfRangeException($"unknown TableFormat: {Table}")
};
}
}
}
|
Ruby
|
UTF-8
| 182 | 3.28125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def prime?(integer)
if integer < 2
return false
else
[*(2...integer)].each do |x|
if integer % x == 0
return false
end
end
return true
end
end
|
PHP
|
UTF-8
| 2,073 | 2.59375 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
<?php
class User_Model extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function checkpass($pass, $id) {
$query = 'SELECT * FROM p_user WHERE id_user = '.$id.' AND user_password="'.$pass.'" AND is_active=1';
$result = $this->db->query($query);
if ($result) {
return $result;
}else {
return 0;
}
}
public function getUser($id_user) {
if ($id_user != '') {
$query = "SELECT *
FROM p_user u
LEFT JOIN p_profile p on u.id_profile = p.id_profile
WHERE u.is_active=1 AND u.id_user = '".$id_user."'";
}else {
$query = "SELECT *
FROM p_user u
LEFT JOIN p_profile p on u.id_profile = p.id_profile
WHERE u.is_active=1";
}
$result = $this->db->query($query);
if ($result) {
return $result;
}else {
return 0;
}
}
public function getProfile() {
$query = "SELECT * from p_profile where is_active = 1";
return $this->db->query($query);
}
public function checkUser($user) {
$query = "SELECT * FROM p_user WHERE user_email = '".$user."' AND is_active = '1'";
return $this->db->query($query);
}
public function saveUser($data) {
$result = $this->db->insert('p_user', $data);
if ($result) {
return true;
}else{
return false;
}
}
function cek_user($id_user)
{
$query = "
SELECT * FROM p_user WHERE id_user = '".$id_user."' AND is_active = '1'
";
return $this->db->query($query);
}
public function updateUser($id_user, $data) {
$this->db->where('id_user', $id_user);
$result = $this->db->update('p_user', $data);
if ($result) {
return true;
}else{
return false;
}
}
}
|
JavaScript
|
UTF-8
| 3,116 | 2.8125 | 3 |
[] |
no_license
|
function getListeSeries(table){
var xmlHttpSeries = getAjaxRequestObject();
xmlHttpSeries.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var text= this.responseText;
var lesSeries = JSON.parse(text);
lesSeries.sort(function(a, b){
if (a.nom < b.nom){
return -1;
}else if (a.nom > b.nom){
return 1;
}else{
return 0;
}
});
for(var i=0;i<lesSeries.length;i++){
var row = table.insertRow(i);
var cellnom = row.insertCell(0);
var cellannee = row.insertCell(1);
var cellSaisons = row.insertCell(2);
cellnom.innerText = lesSeries[i].nom;
cellannee.innerText = lesSeries[i].anneeparution;
cellSaisons.innerHTML = "<button id='saisons' onclick='voirSaisons("+ lesSeries[i].id +")'>Voir Saisons</button>";
//getNbSaisons(lesSeries[i].id, cellSaisons);
row.setAttribute("tag", lesSeries[i].id);
cellnom.style.textAlign = "left";
cellnom.style.paddingLeft = "10px";
row.onclick = function(){
getSaisons(this.getAttribute("tag"));
}
}
}
};
xmlHttpSeries.open("GET", "../api-netflix/api.php?data=series");
xmlHttpSeries.send();
}
function voirSaisons(id) {
document.getElementById("Saisons").style.display = 'block';
var tableSaisons = document.querySelector("#tbSaisons>tbody");
getSaisons(tableSaisons);
}
function getSaisons(id){
console.log(id);
var xmlHttpSaisons = getAjaxRequestObject();
xmlHttpSaisons.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200){
try{
console.log(JSON.parse(this.responseText));
}catch (e){
console.log('Pas de saisons');
}
var text= this.responseText;
var lesSaisons = JSON.parse(text);
lesSaisons.sort(function(a, b){
if (a.id < b.id){
return -1;
}else if (a.id > b.id){
return 1;
}else{
return 0;
}
});
for(var i=0;i<lesSaisons.length;i++){
var row = table.insertRow(i);
var cellnom = row.insertCell(0);
var cellannee = row.insertCell(1);
var cellSaisons = row.insertCell(2);
cellnom.innerText = lesSaisons[i].nom;
cellannee.innerText = lesSaisons[i].anneeparution;
cellSaisons.innerHTML = "<button id='saisons' value='"+ lesSaisons[i].id +"'>Voir Episode</button>";
//getNbSaisons(lesSeries[i].id, cellSaisons);
row.setAttribute("tag", lesSaisons[i].id);
cellnom.style.textAlign = "left";
cellnom.style.paddingLeft = "10px";
/*row.onclick = function(){
getSaisons(this.getAttribute("tag"));
}*/
}
}
};
xmlHttpSaisons.open("GET", "../api-netflix/api.php?data=saisons&idserie=" + id);
xmlHttpSaisons.send();
}
function getNbSaisons(id, cellule){
var nbSaisons = 0;
var xmlHttpSaisons = getAjaxRequestObject();
xmlHttpSaisons.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200){
try{
nbSaisons = JSON.parse(this.responseText).length;
}catch (e){
nbSaisons = 0;
}
cellule.innerText = nbSaisons;
}
};
xmlHttpSaisons.open("GET", "../api-netflix/api.php?data=saisons&idserie=" + id);
xmlHttpSaisons.send();
}
|
Markdown
|
UTF-8
| 3,335 | 2.78125 | 3 |
[] |
no_license
|
---
title: "Decline of the Dollar"
categories: blog
permalink: blog_decline_dollar.html
tags: [blog]
---
Fifty years ago the US was the world's main creditor nation.
Today it is the world's main debtor nation.
Yanis Varoufakis explains the turnaround in his
[Global Minotaur](https://www.yanisvaroufakis.eu/books/the-global-minotaur/)
book.
The Economist observes that the US *is an unusual borrower* with
[Net Debts, but Big Returns](https://www.economist.com/news/finance-and-economics/21709549-exorbitant-privilege-looks-greater-ever-net-debt-big-returns).
Since 1989 foreigners have owned more assets in America than Americans have
owned overseas, that is the
[Net International Investment Position - NIIP](https://snbchf.com/fx-theory/wealth-niip/net-international-investment-position/)
has been negative - and increasingly so, yet the Americans manage to
increase their net international income receipts:
{% include image.html file="NIIP_Valuation_Effect.jpg" alt="NIIP_Valuation_Effect" %}
The clue seems to be the depriciation of the dollar - some 30% since 2002.
Dollar depreciations increase the dollar value of US claims on foreigners
(denominated in foreign currencies).
A parallel is the increased value (in Norwegian Krone) of the Norwegian
Sovereign Wealth Fund as the Krone depreciated due to falling oil prices.
A further clue is the compostion of the debt.
*Between 2000 and 2010, U.S. investments abroad had an increasing percentage of direct investments and securities, while claims on the U.S. rose particularly by foreign central banks (the dollar as a reserve currency). Since the former had a higher yield than the latter, the Americans managed to increase more and more the net income receipts.*
So - the Minotaur is still alive, even after the 2008 financial crisis.
However, recents signs point to decreased role of the Dollar as the major
reserve currency. Reform or Replacemnet of The Bretton Wood's institutions
are long
[overdue](https://www.project-syndicate.org/onpoint/saving-the-international-economic-order-by-paola-subacchi-2017-09?utm_source=Project+Syndicate+Newsletter&utm_campaign=263bdc8ba9-op_newsletter_2017_9_1&utm_medium=email&utm_term=0_73bad5b7d8-263bdc8ba9-105543865)
So - May be the time finally has come for Ernest Mandel's
vision from the 1960's -
[Decline of the Dollar](https://www.amazon.com/Decline-Dollar-Marxist-Monetary-Crisis/dp/0913460044)
The parallel between the decline of the British Pound as reserve currency
in the 1960's and of the Dollar today is
[striking](https://www.marxists.org/archive/mandel/1968/04/dollar.htm).
As Mandel put it in 1968:
*The dollar’s function as a reserve currency corresponds to the balance-of-trade deficits which most capitalist countries have with the United States.
...”The-Americans-who-are-buying-‘our’-factories-with-the-paper-dollars-they-are-sending-us” is a Gaullist myth. In reality the American monopolies are buying up the European factories with the capital which the European banks advance as loans. And these banks loan them this capital because the American monopolies are richer, more solid, make higher profits, and offer more security than the European monopolies. What must be challenged is the whole logic of the capitalist system, not Wall Street’s diabolical use of the dollar.*
{% include links.html %}
|
Markdown
|
UTF-8
| 1,660 | 2.9375 | 3 |
[] |
no_license
|
# 支持响应式背压
最后一步,我们将探访 UserService.allFriends 查询,它将从数据中获取整个数据集。
**表 17,进化成响应型微服务,第三部分,UserService.allFriends 的背压**

**结果**
- 是的,这很啰嗦。
- …但现在,我们将查询的结果依次流式处理(可能已经通过 SQL 限定分页)。
- `Streams.createWith` 是一个 `PublisherFactory`,它将截断请求,执行启动或停止操作。
- 请求的消费者给出了订阅者准备接收的元素数量。
- 请求的消费者接收一个 `SubscriberWithContext`,它实现了实际订阅者的委托,提供了对共享上下文和取消状态的访问。
- 我们发送了至多同需求相当的独立结果。
- 在读取充分执行后,我们的操作将完结。
- 由于现在数据是独立的,`convertToList`不再需要了,用 `convert` 替换它。
- 数据消费方面,可以使用一些诸如 `capacity(long)` 或 `buffer(int)` 的工具 5 个一组的批量消费请求。
- 这样做的结果是流动可以明显加快,因为不需要在每行读取后打印它。
- 由于批处理可能无法匹配大小,我们还要加上一个时间限制。
>对类似 List<T> 这样的状态化 Iterable<T> 的使用和对独立流化的 T 的使用之间的平衡非常重要。由于创建需要一定的时间,List<T> 可能会导致一些延迟。而且它的恢复性也不好,一旦出错,我们会丢失一整批的数据。最后,流化的 T 数据将使限定尺寸的需求更可预测,因为我们能够发出单个的信号,而不是批量的信号。
|
C++
|
GB18030
| 4,832 | 3.5625 | 4 |
[] |
no_license
|
/************************************************************************/
/* 10. Ҫʵ߾ȵʮƼӷҪʵֺ
void add (const char *num1, const char *num2, char *result)
롿num1ַʽ1Ϊnum1[0]Ϊλ'-'
num2ַʽ2Ϊnum2[0]Ϊλ'-'
resultӷַΪresult[0]Ϊλ
*/
/************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void move(char *str, int length) //Ƴĸǰ"-"
{
if(str[0] != '-')
return;
int i;
for(i = 0; i < length-1; i++)
str[i] = str[i+1];
str[i] = '\0';
}
int remove_zero(char *result, int length)
{
int count = 0;
for(int i = length-1; i > 0; i--) //ʼƳ0ֱ0ֻ֣λϵ0ж
{
if(result[i] == '0')
{
result[i] = '\0';
count++;
}else
return length-count;
}
return length - count;
}
void reverse(char *result, int length) //ַת
{
char temp;
for(int i = 0; i <= (length-1)/2; i++)
{
temp = result[i];
result[i] = result[length-1-i];
result[length-1-i] = temp;
}
}
int real_add(char *str1, char *str2, char *result, const bool flag)
{
int len1 = strlen(str1);
int len2 = strlen(str2);
int n1, n2, another = 0; //anotherʾλ
int cur_rs = 0; //ʾresultĵǰλ
int i, j;
int curSum;
for(i = len1-1, j = len2-1; i >= 0 && j >= 0; i--, j--)
{
n1 = str1[i] - '0';
n2 = str2[j] - '0';
curSum = n1 + n2 + another;
result[cur_rs++] = curSum % 10 + '0';
another = curSum / 10;
}
if(j < 0)
{
while(i >= 0) //str1ʣλ
{
n1 = str1[i--] - '0';
curSum = n1 + another;
result[cur_rs++] = curSum % 10 + '0';
another = curSum / 10;
}
if(another != 0) //нλδ
result[cur_rs++] = another + '0';
}
else
{
while(j >= 0)
{
n2 = str2[j--] - '0';
curSum = n2 + another;
result[cur_rs++] = curSum % 10 + '0';
another = curSum / 10;
}
if(another != 0)
result[cur_rs++] = another + '0';
}
result[cur_rs] = '\0';
cur_rs = remove_zero(result, cur_rs);
if(!flag)
{
result[cur_rs++] = '-';
result[cur_rs] = '\0';
}
reverse(result, strlen(result));
return cur_rs;
}
int real_minus(char *str1, char *str2, char *result) //ʹstr1ȥstr2
{
char big[100], small[100];
int big_len, sml_len;
int len1 = strlen(str1);
int len2 = strlen(str2);
bool flag = false; //ڱstr2Ƿstr1
if(len1 < len2)
flag = true;
else if(len1 == len2)
{
if(strcmp(str1, str2) == 0)
{
result[0] = '0';
result[1] = '\0';
return 1;
}else if(strcmp(str1,str2) < 0)
flag = true;
}
if(flag) //str1str2ȷstr1ֵָнϴߣͨflagȷҪҪǰ-
{
char *temp = str1;
str1 = str2;
str2 = temp;
len1 = strlen(str1);
len2 = strlen(str2);
}
int n1, n2, another = 0; //anotherʾǷнλ
int i, j;
int cur_rs = 0;
int curMinus;
for(i = len1-1, j = len2-1; i>=0 && j>=0; i--,j--)
{
n1 = str1[i] - '0';
n2 = str2[j] - '0';
if(n1 >= n2+another)
{
result[cur_rs++] = (n1-n2-another) +'0';
another = 0;
}
else
{
result[cur_rs++] = (n1+10-n2-another) + '0';
another = 1;
}
}
while(i >= 0)
{
n1 = str1[i--] - '0';
if(another != 0)
{
n1 -= another;
another = 0;
}
result[cur_rs++] = n1 + '0';
}
result[cur_rs] = '\0';
cur_rs = remove_zero(result, cur_rs);
if(flag)
{
result[cur_rs++] = '-';
result[cur_rs] = '\0';
}
reverse(result, cur_rs);
return cur_rs;
}
void addi(const char *num1, const char *num2, char *result)
{
int len1 = strlen(num1);
int len2 = strlen(num2);
int rs_len;
if(!len1 || !len2)
return;
char str1[100], str2[100];
strncpy(str1, num1, len1);
str1[len1] = '\0';
strncpy(str2, num2, len2);
str2[len2] = '\0';
if(str1[0] == '-' && str2[0] == '-')
{
move(str1, len1);
move(str2, len2);
rs_len = real_add(str1, str2, result, false);
}else if(str1[0] == '-')
{
move(str1, len1);
rs_len = real_minus(str2, str1, result);
}
else if(str2[0] == '-')
{
move(str2, len2);
rs_len = real_minus(str1, str2, result);
}else
rs_len = real_add(str1, str2, result, true);
}
//int main(int argc, char *argv[])
int main()
{
char num1[100],num2[100];
printf("ݣ\n");
scanf("%s%s",num1,num2);
char result[100];
memset(result, 0, 100);
addi(num1,num2, result);
printf("%s\n", result);
return 0;
}
|
Markdown
|
UTF-8
| 14,234 | 2.859375 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: SignupCustomer Service Operation - Customer Management
ms.service: bing-ads-customer-management-service
ms.topic: article
author: eric-urban
ms.author: eur
description: Creates a new customer and account that rolls up to your reseller payment method.
dev_langs:
- csharp
- java
- php
- python
---
# SignupCustomer Service Operation - Customer Management
Creates a new customer and account that rolls up to your reseller payment method.
> [!NOTE]
> You must be a reseller with aggregator user permissions to call this operation. For more details see [Management Model for Resellers](../guides/management-model-resellers.md).
Pass both [Customer](customer.md) and [AdvertiserAccount](advertiseraccount.md) objects in the request. The customer object includes the customer's name, the address where the customer is located, the market in which the customer operates, and the industry in which the customer participates. Although it is possible to add multiple customers with the same details, you should use unique customer names so that users can easily distinguish between customers in a user interface.
The account object must specify the name of the account; the type of currency to use to settle the account; and the payment method identifier, which must be set to null. The operation generates an invoice account and sets the payment method identifier to the identifier associated with the reseller's invoice. You are invoiced for all charges incurred by the customers that you manage.
If the operation succeeds, a new managed customer is created outside of the reseller customer and an account is created within the managed customer.
## <a name="request"></a>Request Elements
The *SignupCustomerRequest* object defines the [body](#request-body) and [header](#request-header) elements of the service operation request. The elements must be in the same order as shown in the [Request SOAP](#request-soap).
> [!NOTE]
> Unless otherwise noted below, all request elements are required.
### <a name="request-body"></a>Request Body Elements
|Element|Description|Data Type|
|-----------|---------------|-------------|
|<a name="account"></a>Account|An [AdvertiserAccount](advertiseraccount.md) that specifies the details of the customer's primary account.|[AdvertiserAccount](advertiseraccount.md)|
|<a name="customer"></a>Customer|A [Customer](customer.md) that specifies the details of the customer that you are adding.|[Customer](customer.md)|
|<a name="parentcustomerid"></a>ParentCustomerId|The customer identifier of the reseller that will manage this customer.|**long**|
### <a name="request-header"></a>Request Header Elements
[!INCLUDE[request-header](./includes/request-header.md)]
## <a name="response"></a>Response Elements
The *SignupCustomerResponse* object defines the [body](#response-body) and [header](#response-header) elements of the service operation response. The elements are returned in the same order as shown in the [Response SOAP](#response-soap).
### <a name="response-body"></a>Response Body Elements
|Element|Description|Data Type|
|-----------|---------------|-------------|
|<a name="accountid"></a>AccountId|A system-generated account identifier corresponding to the new account specified in the request.<br/><br/>Use this identifier with operation requests that require an *AccountId* element and a *CustomerAccountId* SOAP header element.|**long**|
|<a name="accountnumber"></a>AccountNumber|A system-generated account number that is used to identify the account in the Microsoft Advertising web application. The account number has the form, X*nnnnnnn*, where *nnnnnnn* is a series of digits.|**string**|
|<a name="createtime"></a>CreateTime|The date and time that the account was added. The date and time value reflects the date and time at the server, not the client. For information about the format of the date and time, see the dateTime entry in [Primitive XML Data Types](https://go.microsoft.com/fwlink/?linkid=859198).|**dateTime**|
|<a name="customerid"></a>CustomerId|A system-generated customer identifier corresponding to the new customer specified in the request.<br/><br/>Use this identifier with operation requests that require a *CustomerId* SOAP header element.|**long**|
|<a name="customernumber"></a>CustomerNumber|A system-generated customer number that is used in the Microsoft Advertising web application. The customer number is of the form, C*nnnnnnn*, where *nnnnnnn* is a series of digits.|**string**|
### <a name="response-header"></a>Response Header Elements
[!INCLUDE[response-header](./includes/response-header.md)]
## <a name="request-soap"></a>Request SOAP
This template was generated by a tool to show the [order](../guides/services-protocol.md#element-order) of the [body](#request-body) and [header](#request-header) elements for the SOAP request. For supported types that you can use with this service operation, see the [Request Body Elements](#request-header) reference above.
```xml
<s:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header xmlns="https://bingads.microsoft.com/Customer/v13">
<Action mustUnderstand="1">SignupCustomer</Action>
<AuthenticationToken i:nil="false">ValueHere</AuthenticationToken>
<DeveloperToken i:nil="false">ValueHere</DeveloperToken>
</s:Header>
<s:Body>
<SignupCustomerRequest xmlns="https://bingads.microsoft.com/Customer/v13">
<Customer xmlns:e1056="https://bingads.microsoft.com/Customer/v13/Entities" i:nil="false">
<e1056:CustomerFinancialStatus i:nil="false">ValueHere</e1056:CustomerFinancialStatus>
<e1056:Id i:nil="false">ValueHere</e1056:Id>
<e1056:Industry i:nil="false">ValueHere</e1056:Industry>
<e1056:LastModifiedByUserId i:nil="false">ValueHere</e1056:LastModifiedByUserId>
<e1056:LastModifiedTime i:nil="false">ValueHere</e1056:LastModifiedTime>
<e1056:MarketCountry i:nil="false">ValueHere</e1056:MarketCountry>
<e1056:ForwardCompatibilityMap xmlns:e1057="http://schemas.datacontract.org/2004/07/System.Collections.Generic" i:nil="false">
<e1057:KeyValuePairOfstringstring>
<e1057:key i:nil="false">ValueHere</e1057:key>
<e1057:value i:nil="false">ValueHere</e1057:value>
</e1057:KeyValuePairOfstringstring>
</e1056:ForwardCompatibilityMap>
<e1056:MarketLanguage i:nil="false">ValueHere</e1056:MarketLanguage>
<e1056:Name i:nil="false">ValueHere</e1056:Name>
<e1056:ServiceLevel i:nil="false">ValueHere</e1056:ServiceLevel>
<e1056:CustomerLifeCycleStatus i:nil="false">ValueHere</e1056:CustomerLifeCycleStatus>
<e1056:TimeStamp i:nil="false">ValueHere</e1056:TimeStamp>
<e1056:Number i:nil="false">ValueHere</e1056:Number>
<e1056:CustomerAddress i:nil="false">
<e1056:City i:nil="false">ValueHere</e1056:City>
<e1056:CountryCode i:nil="false">ValueHere</e1056:CountryCode>
<e1056:Id i:nil="false">ValueHere</e1056:Id>
<e1056:Line1 i:nil="false">ValueHere</e1056:Line1>
<e1056:Line2 i:nil="false">ValueHere</e1056:Line2>
<e1056:Line3 i:nil="false">ValueHere</e1056:Line3>
<e1056:Line4 i:nil="false">ValueHere</e1056:Line4>
<e1056:PostalCode i:nil="false">ValueHere</e1056:PostalCode>
<e1056:StateOrProvince i:nil="false">ValueHere</e1056:StateOrProvince>
<e1056:TimeStamp i:nil="false">ValueHere</e1056:TimeStamp>
<e1056:BusinessName i:nil="false">ValueHere</e1056:BusinessName>
</e1056:CustomerAddress>
</Customer>
<Account xmlns:e1058="https://bingads.microsoft.com/Customer/v13/Entities" i:nil="false">
<e1058:BillToCustomerId i:nil="false">ValueHere</e1058:BillToCustomerId>
<e1058:CurrencyCode i:nil="false">ValueHere</e1058:CurrencyCode>
<e1058:AccountFinancialStatus i:nil="false">ValueHere</e1058:AccountFinancialStatus>
<e1058:Id i:nil="false">ValueHere</e1058:Id>
<e1058:Language i:nil="false">ValueHere</e1058:Language>
<e1058:LastModifiedByUserId i:nil="false">ValueHere</e1058:LastModifiedByUserId>
<e1058:LastModifiedTime i:nil="false">ValueHere</e1058:LastModifiedTime>
<e1058:Name i:nil="false">ValueHere</e1058:Name>
<e1058:Number i:nil="false">ValueHere</e1058:Number>
<e1058:ParentCustomerId>ValueHere</e1058:ParentCustomerId>
<e1058:PaymentMethodId i:nil="false">ValueHere</e1058:PaymentMethodId>
<e1058:PaymentMethodType i:nil="false">ValueHere</e1058:PaymentMethodType>
<e1058:PrimaryUserId i:nil="false">ValueHere</e1058:PrimaryUserId>
<e1058:AccountLifeCycleStatus i:nil="false">ValueHere</e1058:AccountLifeCycleStatus>
<e1058:TimeStamp i:nil="false">ValueHere</e1058:TimeStamp>
<e1058:TimeZone i:nil="false">ValueHere</e1058:TimeZone>
<e1058:PauseReason i:nil="false">ValueHere</e1058:PauseReason>
<e1058:ForwardCompatibilityMap xmlns:e1059="http://schemas.datacontract.org/2004/07/System.Collections.Generic" i:nil="false">
<e1059:KeyValuePairOfstringstring>
<e1059:key i:nil="false">ValueHere</e1059:key>
<e1059:value i:nil="false">ValueHere</e1059:value>
</e1059:KeyValuePairOfstringstring>
</e1058:ForwardCompatibilityMap>
<e1058:LinkedAgencies i:nil="false">
<e1058:CustomerInfo>
<e1058:Id i:nil="false">ValueHere</e1058:Id>
<e1058:Name i:nil="false">ValueHere</e1058:Name>
</e1058:CustomerInfo>
</e1058:LinkedAgencies>
<e1058:SalesHouseCustomerId i:nil="false">ValueHere</e1058:SalesHouseCustomerId>
<e1058:TaxInformation xmlns:e1060="http://schemas.datacontract.org/2004/07/System.Collections.Generic" i:nil="false">
<e1060:KeyValuePairOfstringstring>
<e1060:key i:nil="false">ValueHere</e1060:key>
<e1060:value i:nil="false">ValueHere</e1060:value>
</e1060:KeyValuePairOfstringstring>
</e1058:TaxInformation>
<e1058:BackUpPaymentInstrumentId i:nil="false">ValueHere</e1058:BackUpPaymentInstrumentId>
<e1058:BillingThresholdAmount i:nil="false">ValueHere</e1058:BillingThresholdAmount>
<e1058:BusinessAddress i:nil="false">
<e1058:City i:nil="false">ValueHere</e1058:City>
<e1058:CountryCode i:nil="false">ValueHere</e1058:CountryCode>
<e1058:Id i:nil="false">ValueHere</e1058:Id>
<e1058:Line1 i:nil="false">ValueHere</e1058:Line1>
<e1058:Line2 i:nil="false">ValueHere</e1058:Line2>
<e1058:Line3 i:nil="false">ValueHere</e1058:Line3>
<e1058:Line4 i:nil="false">ValueHere</e1058:Line4>
<e1058:PostalCode i:nil="false">ValueHere</e1058:PostalCode>
<e1058:StateOrProvince i:nil="false">ValueHere</e1058:StateOrProvince>
<e1058:TimeStamp i:nil="false">ValueHere</e1058:TimeStamp>
<e1058:BusinessName i:nil="false">ValueHere</e1058:BusinessName>
</e1058:BusinessAddress>
<e1058:AutoTagType i:nil="false">ValueHere</e1058:AutoTagType>
<e1058:SoldToPaymentInstrumentId i:nil="false">ValueHere</e1058:SoldToPaymentInstrumentId>
</Account>
<ParentCustomerId i:nil="false">ValueHere</ParentCustomerId>
</SignupCustomerRequest>
</s:Body>
</s:Envelope>
```
## <a name="response-soap"></a>Response SOAP
This template was generated by a tool to show the order of the [body](#response-body) and [header](#response-header) elements for the SOAP response.
```xml
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header xmlns="https://bingads.microsoft.com/Customer/v13">
<TrackingId d3p1:nil="false" xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance">ValueHere</TrackingId>
</s:Header>
<s:Body>
<SignupCustomerResponse xmlns="https://bingads.microsoft.com/Customer/v13">
<CustomerId>ValueHere</CustomerId>
<CustomerNumber d4p1:nil="false" xmlns:d4p1="http://www.w3.org/2001/XMLSchema-instance">ValueHere</CustomerNumber>
<AccountId d4p1:nil="false" xmlns:d4p1="http://www.w3.org/2001/XMLSchema-instance">ValueHere</AccountId>
<AccountNumber d4p1:nil="false" xmlns:d4p1="http://www.w3.org/2001/XMLSchema-instance">ValueHere</AccountNumber>
<CreateTime>ValueHere</CreateTime>
</SignupCustomerResponse>
</s:Body>
</s:Envelope>
```
## <a name="example"></a>Code Syntax
The example syntax can be used with [Bing Ads SDKs](../guides/client-libraries.md). See [Bing Ads API Code Examples](../guides/code-examples.md) for more examples.
```csharp
public async Task<SignupCustomerResponse> SignupCustomerAsync(
Customer customer,
AdvertiserAccount account,
long? parentCustomerId)
{
var request = new SignupCustomerRequest
{
Customer = customer,
Account = account,
ParentCustomerId = parentCustomerId
};
return (await CustomerManagementService.CallAsync((s, r) => s.SignupCustomerAsync(r), request));
}
```
```java
static SignupCustomerResponse signupCustomer(
Customer customer,
AdvertiserAccount account,
java.lang.Long parentCustomerId) throws RemoteException, Exception
{
SignupCustomerRequest request = new SignupCustomerRequest();
request.setCustomer(customer);
request.setAccount(account);
request.setParentCustomerId(parentCustomerId);
return CustomerManagementService.getService().signupCustomer(request);
}
```
```php
static function SignupCustomer(
$customer,
$account,
$parentCustomerId)
{
$GLOBALS['Proxy'] = $GLOBALS['CustomerManagementProxy'];
$request = new SignupCustomerRequest();
$request->Customer = $customer;
$request->Account = $account;
$request->ParentCustomerId = $parentCustomerId;
return $GLOBALS['CustomerManagementProxy']->GetService()->SignupCustomer($request);
}
```
```python
response=customermanagement_service.SignupCustomer(
Customer=Customer,
Account=Account,
ParentCustomerId=ParentCustomerId)
```
## Requirements
Service: [CustomerManagementService.svc v13](https://clientcenter.api.bingads.microsoft.com/Api/CustomerManagement/v13/CustomerManagementService.svc)
Namespace: https\://bingads.microsoft.com/Customer/v13
|
C++
|
UTF-8
| 2,403 | 2.953125 | 3 |
[] |
no_license
|
#include "gamecomponents.h"
#include "eventhandler.h"
#include "box.h"
#include <map>
#include <sstream>
#include <algorithm>
#include <SDL2/SDL.h>
bool GameComponents::updated = false;
SDL_Window* GameComponents::window = nullptr;
SDL_Renderer* GameComponents::renderer = nullptr;
Box* GameComponents::box = nullptr;
std::map<std::string, Box*> GameComponents::other_boxes;
ClientSocket const * const * GameComponents::socket = nullptr;
void GameComponents::init(SDL_Window* w, SDL_Renderer* r, ClientSocket** s, std::string n, float x, float y){
window = w;
renderer = r;
socket = (ClientSocket const * const *)s;
box = new Box(n, x, y, renderer);
}
void GameComponents::update(){
//reset update state
updated = false;
//update local player
if(EventHandler::keyPressed(EventHandler::W)){
box->moveY(-0.001f);
updated = true;
}else;
if(EventHandler::keyPressed(EventHandler::A)){
box->moveX(-0.001f);
updated = true;
}else;
if(EventHandler::keyPressed(EventHandler::S)){
box->moveY(0.001f);
updated = true;
}else;
if(EventHandler::keyPressed(EventHandler::D)){
box->moveX(0.001f);
updated = true;
}else;
//update other players
std::stringstream new_msg_ss((*socket)->getCurrentMessage());
std::string b("");
while(new_msg_ss>>b){
//b should be in the format of "playername:x,y", transform it into "playername x y"
replace(b.begin(), b.end(), ':', ' ');
replace(b.begin(), b.end(), ',', ' ');
//parse b into 3 parts
std::string name("");
float x = 0.0f;
float y = 0.0f;
std::stringstream(b)>>name>>x>>y;
//assign new values to proper boxes
if(name==box->getName()){
//do nothing
}else if(other_boxes.find(name)!=other_boxes.end()){
other_boxes.find(name)->second->setX(x);
other_boxes.find(name)->second->setY(y);
}else{
other_boxes.insert(std::make_pair(name, new Box(name, x, y, renderer)));
}
}
}
void GameComponents::render(){
SDL_RenderClear(renderer);
box->render(renderer);
for(std::map<std::string, Box*>::iterator i=other_boxes.begin(); i!=other_boxes.end(); ++i){
i->second->render(renderer);
}
SDL_RenderPresent(renderer);
}
void GameComponents::destroy(){
delete box;
for(std::map<std::string, Box*>::iterator i=other_boxes.begin(); i!=other_boxes.end(); ++i){
delete i->second;
}
}
bool GameComponents::isUpdated(){
return updated;
}
Box const * GameComponents::getMyBox(){
return box;
}
|
Python
|
UTF-8
| 4,148 | 2.71875 | 3 |
[] |
no_license
|
from json_parser import JSONParser
import psycopg2
from psycopg2 import sql
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import os
import json
class StdOutListener(StreamListener):
def on_data(self, data):
parser = JSONParser(data)
try:
conn = psycopg2.connect(database="twitterdb", user="postgres", password="admin",port=5433)
except:
print("I am unable to connect to the database")
cur = conn.cursor()
try:
for tweet in parser.createTweets(parser.data):
try:
insert_user_row(tweet.user, cur)
except:
pass
try:
insert_tweet_row(tweet, cur)
for mentioned_user in tweet.mentioned_users:
insert_mentioned_user_row(mentioned_user, cur)
for hashtag in tweet.hashtags:
try:
insert_hashtag_row(hashtag, cur)
hashtag_id = fetch_hashtag_id(hashtag, cur)
insert_row_to_intersection_table(hashtag_id, tweet.id, cur)
except:
pass
conn.commit()
except:
pass
except:
pass
conn.commit()
conn.close()
return True
def on_error(self, status):
print(status)
def insert_user_row(user, cur):
table_name = 'public.users(id, followers_count, location, name, screen_name, tweets_count, language)'
cur.execute("insert into %s values (%%s, %%s, %%s, %%s, %%s, %%s, %%s)" % table_name,
[user.id, user.followers_count, user.location, user.name, user.screen_name, user.tweets_count
, user.language])
def insert_tweet_row(tweet, cur):
table_name = 'public.tweets(id, user_id, created_at, text, in_reply_tweet_id, in_reply_user_id, retweets_count)'
cur.execute("insert into %s values (%%s, %%s, %%s, %%s, %%s, %%s, %%s)" % table_name,
[tweet.id, tweet.user.id, tweet.created_at, tweet.text, tweet.in_reply_tweet_id, tweet.in_reply_user_id
, tweet.retweets_count])
def insert_mentioned_user_row(mentioned_user, cur):
table_name = 'public.mentioned_users(tweet_id, user_id)'
cur.execute("insert into %s values (%%s, %%s)" % table_name, [mentioned_user.tweet_id, mentioned_user.user_id])
def insert_hashtag_row(hashtag, cur):
table_name = 'public.hashtags(name)'
cur.execute("insert into %s values (%%s)" % table_name, [hashtag.name])
def fetch_hashtag_id(hashtag, cur):
table_name = 'public.hashtags'
cur.execute("select id from %s where name = %%s" % table_name, [hashtag.name])
fetched_row = cur.fetchone()
return fetched_row[0]
def insert_row_to_intersection_table(hashtag_id, tweet_id, cur):
table_name = 'public.tweets_hashtags(hashtag_id, tweet_id)'
cur.execute("insert into %s values (%%s, %%s)" % table_name, [hashtag_id, tweet_id])
def main():
file = open('private_file_not_to_publish.passwords', 'r')
security_data = file.readlines()
access_token = security_data[0].strip()
access_token_secret = security_data[1].strip()
consumer_key = security_data[2].strip()
consumer_secret = security_data[3].strip()
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
#This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby'
stream.filter(track=['catalonia', 'catalunya',
'catalanindependence', 'catalonianreferendum'
'catalanreferendum2017', 'helpcatalonia'
'puigdemont', 'rajoy', 'savecatalonia',
'independenciaesp' , 'spanishdictatorship',
'KRLS', 'jcuixart', 'jordisanchezp'],async=True)
if __name__ == '__main__':
main()
|
Java
|
UTF-8
| 2,731 | 1.789063 | 2 |
[] |
no_license
|
package th.co.pt.pcca.pccaapp.entities.member;
import java.util.List;
public class WorkOutIntraObj {
public String emp_id;
public String company;
public String objective;
public String place_flag;
public String place;
public String isprivate_car;
public String start_company;
public String start_date;
public String end_company;
public String end_date;
public int day_night;
public String doc_no;
public String cancel_user;
public String cancel_flag;
public String approve_flag;
public String getApprove_flag() {
return approve_flag;
}
public void setApprove_flag(String approve_flag) {
this.approve_flag = approve_flag;
}
public String getApprove_user() {
return approve_user;
}
public void setApprove_user(String approve_user) {
this.approve_user = approve_user;
}
public String approve_user;
public String getEmp_id() {
return emp_id;
}
public void setEmp_id(String emp_id) {
this.emp_id = emp_id;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getObjective() {
return objective;
}
public void setObjective(String objective) {
this.objective = objective;
}
public String getPlace_flag() {
return place_flag;
}
public void setPlace_flag(String place_flag) {
this.place_flag = place_flag;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getIsprivate_car() {
return isprivate_car;
}
public void setIsprivate_car(String isprivate_car) {
this.isprivate_car = isprivate_car;
}
public String getStart_company() {
return start_company;
}
public void setStart_company(String start_company) {
this.start_company = start_company;
}
public String getStart_date() {
return start_date;
}
public void setStart_date(String start_date) {
this.start_date = start_date;
}
public String getEnd_company() {
return end_company;
}
public void setEnd_company(String end_company) {
this.end_company = end_company;
}
public String getEnd_date() {
return end_date;
}
public void setEnd_date(String end_date) {
this.end_date = end_date;
}
public int getDay_night() {
return day_night;
}
public void setDay_night(int day_night) {
this.day_night = day_night;
}
public String getDoc_no() {
return doc_no;
}
public void setDoc_no(String doc_no) {
this.doc_no = doc_no;
}
public String getCancel_user() {
return cancel_user;
}
public void setCancel_user(String cancel_user) {
this.cancel_user = cancel_user;
}
public String getCancel_flag() {
return cancel_flag;
}
public void setCancel_flag(String cancel_flag) {
this.cancel_flag = cancel_flag;
}
}
|
Markdown
|
UTF-8
| 2,471 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
# Tevana
Project Name: Tevana
20.05.2021
Developed By :
Gayathri Chennakrishnam Sharma & Divyansh Sharma
Overview :
Tevana(meaning a beautiful garden,in Sanskrit) is a fully-fledged home garden application with various features wherein the users can register themselves as members and take a look at all the home garden packages available , go through the package description and user experiences about the same , choose one or more packages from the available or can customize their home garden for themselves and find all the necessary information regarding the package(s) from the my gardens section. The website has been designed dynamically to cater to all the needs of a potential home garden without compromising on the security aspect of the user data.
Approach flowchart:
Visit https://sketchboard.me/zCH9dOWNGYca#/ for a better view.
Goals:
New users can Sign-up to create an account with us.
User can sign-up through third-party applications.
User login and logout using JWT.
Registered members can add profile details and a profile picture in the profile.
Users can navigate and search for the packages available on the application.
User can book one or multiple packages based on his/her liking and other considerations.
User can navigate to the my bookings section to keep track of all the bookings made.
Integrating a payment gateway for successful completion of the booking.
A successful booking email to be sent to the user on successful completion of the booking and delivery details.
Technologies used:
JavaScript for performing various array operations and making functions etc.
Node js as a backend language for the project
Express js, a node js framework to create a server and make API’s
MongoDB to store the user and garden packages data.
Mongoose, a MongoDB framework to get more functionalities to retrieve and manipulate data.
JWT library for user authentication
HTML/CSS for designing the front end part
Bootstrap to add some styles to our existing front end section
Pug /Handlebars template engine for rendering views from the backend
Multer for handling image data
Tools used :
✴Technical:
VS Code
Github
✴Non-Technical:
Monday.com
Sketchboard
Keynote
Future Scope :
Integrating a blog space for members’ interactions.
Track your garden progress by uploading weekly/bi-weekly progress and consulting a team of garden experts.
Extending the home garden workflow to bigger farms.
THANK YOU.
|
Ruby
|
UTF-8
| 311 | 2.703125 | 3 |
[] |
no_license
|
class Trip < ApplicationRecord
belongs_to :driver
belongs_to :passenger
def self.new_trip(passenger_id, driver)
trip = Trip.new(
driver_id: driver.id,
passenger_id: passenger_id,
date: Date.today.strftime("%Y-%d-%m"),
cost: (500..10000).to_a.sample
)
return trip
end
end
|
PHP
|
UTF-8
| 1,303 | 2.578125 | 3 |
[] |
no_license
|
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\SearchRepository")
*/
class Search
{
/*
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/*
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $search;
/*
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $localisation;
/*
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $category;
public function getId()
{
return $this->id;
}
public function getSearch(): ?string
{
return $this->search;
}
public function setSearch(?string $search): self
{
$this->search = $search;
return $this;
}
public function getLocalisation(): ?string
{
return $this->localisation;
}
public function setLocalisation(?string $localisation): self
{
$this->localisation = $localisation;
return $this;
}
public function getCategory(): ?string
{
return $this->category;
}
public function setCategory(?string $category): self
{
$this->category = $category;
return $this;
}
}
|
Java
|
GB18030
| 853 | 2.96875 | 3 |
[] |
no_license
|
package Payroll;
public abstract class AddEmployeeTransaction extends Transaction {
private int empid;
private String name;
private String address;
public AddEmployeeTransaction( int id ,String n,String a,PayrollDatebase database){
super(database);
this.empid = id;
this.name=n;
this.address=a;
}
protected abstract PaymentClassification makeClassification();
protected abstract PaymentSchedule makeSchedule();
//Աӵݿ
public void execute(){
PaymentClassification pc=makeClassification();
PaymentSchedule ps=makeSchedule();
//ĬdzԱ֧Ʊ
HoldMethod pm =new HoldMethod();
Employee e=new Employee(empid,name,address,database);
e.setClassification(pc);
e.setSchedule(ps);
e.setMethod(pm);
database.AddEmployee(empid, e);
}
}
|
C++
|
UTF-8
| 474 | 2.828125 | 3 |
[] |
no_license
|
#include "procedure.h"
Call_Table* Call_Table::create(){
if(_instance == NULL){
_instance = new Call_Table;
}
return _instance;
}
int Call_Table::add_procedure(int id, Procedure pro){
table[id] = pro;
return 1;
}
int Call_Table::del_procedure(int id){
table.erase(id);
}
int Call_Table::find_procedure(Procedure &p, int id){
if(table.count(id)){
p = table[id];
return 1;
}
return 0;
}
|
Java
|
UTF-8
| 1,858 | 2.1875 | 2 |
[] |
no_license
|
package e.aqibqureshi.imci.activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import e.aqibqureshi.imci.R;
public class MainActivity extends AppCompatActivity {
public Button intro1;
public Button button;
public Button treat;
public Button followup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intro1=(Button) findViewById(R.id.buttonintro);
intro1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent into= new Intent(MainActivity.this, Introduction.class);
startActivity(into);
}
});
button=(Button) findViewById(R.id.buttonage5);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent toy= new Intent(MainActivity.this, age51.class);
startActivity(toy);
}
});
treat=(Button) findViewById(R.id.bttreat);
treat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent trt= new Intent(MainActivity.this, treatchild1.class);
startActivity(trt);
}
});
followup=(Button) findViewById(R.id.btfollowup);
followup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent flp= new Intent(MainActivity.this, followupcare1.class);
startActivity(flp);
}
});
}
}
|
PHP
|
UTF-8
| 809 | 2.65625 | 3 |
[] |
no_license
|
<?php
declare(strict_types=1);
namespace Raxos\Router\Attribute;
use Attribute;
use Raxos\Router\Controller\Controller;
use Raxos\Router\Error\RegisterException;
/**
* Class SubController
*
* @author Bas Milius <bas@mili.us>
* @package Raxos\Router\Attribute
* @since 1.0.0
*/
#[Attribute(Attribute::TARGET_METHOD)]
readonly class SubController
{
/**
* SubController constructor.
*
* @param string $class
*
* @throws RegisterException
* @author Bas Milius <bas@mili.us>
* @since 1.0.0
*/
public function __construct(public string $class)
{
if (!is_subclass_of($class, Controller::class)) {
throw new RegisterException(sprintf('Controller class must extend %s.', Controller::class), RegisterException::ERR_NOT_A_CONTROLLER);
}
}
}
|
JavaScript
|
UTF-8
| 6,256 | 2.703125 | 3 |
[] |
no_license
|
function CreatFlyBird(options) {
this.bgMusic=bgMusic;
this.dieMusic=dieMusic;
this.jumpMusic=jumpMusic;
this.container = options.container;
this.imgSrc = options.imgSrc;
//检查是否狗带
this.Die = false;
// 检测是否按了作弊按钮
this.isOn = false;
// 所有对象的整合
this.roles = {
skyArr: [],
pipeArr: [],
landArr: [],
timeArr: [],
birdArr: [],
};
this.BirdwidthFrame=options.BirdwidthFrame||3;
this.BirdheightFrame=options.BirdheightFrame||1;
this.Birddirection=options.Birddirection||0;
// 背景音乐
this.bgMusic=options.bgMusic||0;
}
CreatFlyBird.prototype = {
// 运行 渲染js 渲染游戏
run: function () {
imgLoad(this.imgSrc, function (objImg) {
// 获取对应图片
this.ctx = until.getCtx(this.container, objImg.sky.width, objImg.sky.height);
this.ctxW = this.ctx.canvas.width;
this.ctxH = this.ctx.canvas.height;
this.objImg = objImg;
// 加入相应的公共属性 生成相应的工厂函数
this.factory = factory({
ctx: this.ctx
});
// 创建对应 实例
this.initRole();
// 刷新 帧 更新每个实例的相应状态 重新渲染画面
this.loop();
// 注册相应事件
this.bind();
}.bind(this));
},
// 检查 是否 狗带
godie: function () {
var roles = this.roles;
var bird = roles.birdArr[0];
var bX = bird.x + bird.w / 2;
var bY = bird.y + bird.h / 2;
var ctx = this.ctx;
if (bY <= 0 || bY >= roles.landArr[0].y - 10) {
// clearInterval(loop);
this.isDie = true;
} else if (ctx.isPointInPath(bX, bY)) {
// clearInterval(loop);
console.log('in');
this.isDie = true;
} else {
this.isDie = false;
}
},
// 求需要图片的数量,给下面 主渲染画面的函数
getNum: function (ctxW, landW) {
return Math.ceil(ctxW / landW) + 1
},
// 计算出对应 对象的位置,并且创建对应的 对象实例
initRole: function () {
var objImg = this.objImg;
var ctx = this.ctx;
var ctxW = ctx.canvas.width;
var ctxH = ctx.canvas.height;
var roles = this.roles;
var getNum = this.getNum;
var BirdwidthFrame=this.BirdwidthFrame;
var BirdheightFrame=this.BirdheightFrame;
var Birddirection=this.Birddirection;
// 获取land数量
var landLength = getNum(ctxW, objImg.earth.width);
// 获取sky数量
var skyLength = getNum(ctxW, objImg.sky.width);
// 获取pipe数量
var pipeLength = getNum(ctxW, objImg.pipeDown.width + 150);
// 应用工厂函数创建相应的 实例:::
var factory = this.factory;
// 创建 地板实例
for (var i = 0; i < landLength; i++) {
roles.landArr.push(factory("Earth", {
// ctx: ctx,
img: objImg.earth,
y: objImg.sky.height - objImg.earth.height,
x: objImg.earth.width * i
}))
}
// 创建 背景实例
for (var i = 0; i < landLength; i++) {
roles.skyArr.push(factory("Sky", {
// ctx: ctx,
img: objImg.sky,
x: objImg.sky.width * i
}))
}
// 创建 管道实例
for (var i = 0; i < pipeLength; i++) {
roles.pipeArr.push(factory("Pipe", {
// ctx: ctx,
imgUp: objImg.pipeUp,
imgDown: objImg.pipeDown,
LRSpace: 250,
TBSpace: 125,
x: 250 + (objImg.pipeUp.width + 250) * i,
}))
}
// 创建 时间 实例
roles.timeArr.push(factory("Timer"))
// 创建 小鸟实例
roles.birdArr.push(factory("Bird", {
// ctx: ctx,
img: objImg.bird,
widthFrame: 4,
heightFrame: 4,
direction :2
}))
},
// 注册相应事件
bind: function () {
var ctx = this.ctx;
var roles = this.roles;
var jumpMusic=this.jumpMusic;
// var isDie = this.isDie;
// var isOn = this.isOn;
ctx.canvas.addEventListener('click', function () {
roles.birdArr[0].flappyUp();
// jumpMusic.play();
// console.log(111);
})
window.onkeydown = function (e) {
if (e.keyCode == 86) {
// console.log('vvv');
this.isDie = false;
this.isOn = true;
}
window.onkeyup = function () {
this.isOn = false;
// isDie = true;
}.bind(this);
}.bind(this);
},
// 重新渲染画面 在里面判断是否死亡,是否需要继续执行 渲染
loop: function () {
var ctx = this.ctx;
var roles = this.roles;
var godie = this.godie;
var isDie = this.isDie;
var isOn = this.isOn;
var loop = this.loop;
var ctxW = this.ctxW;
var ctxH = this.ctxH;
var self = this;
requestAnimationFrame(function () {
ctx.clearRect(0, 0, ctxW, ctxH);
ctx.beginPath();
// 检测是否狗带
// 更新每个实例 相应的状态
for (var key in roles) {
roles[key].forEach(function (key, i) {
// 计算相应对象的相应状态
key.draw();
})
}
//判断是否按下,按下不判断 刷新死亡判断
if (!isOn) {
self.godie();
}
// 判断是否死了,死了不刷新
if (!isDie) {
self.loop();
}
else{
bgMusic.pause();
dieMusic.play();
}
});
}
}
|
C#
|
UTF-8
| 1,402 | 2.671875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using Inbox2.Framework.Interfaces;
namespace Inbox2.Framework.Threading.AsyncUpdate
{
public static class AsyncUpdateQueue
{
private static Thread readerThread;
private static Queue<IEntityBase> queue;
private static AutoResetEvent signal;
private static object synclock;
static AsyncUpdateQueue()
{
signal = new AutoResetEvent(false);
queue = new Queue<IEntityBase>();
synclock = new object();
readerThread = new Thread(HeartBeat)
{
Name = "Background Entity Update Thread",
IsBackground = true,
Priority = ThreadPriority.BelowNormal
};
readerThread.Start();
}
static void HeartBeat()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
do
{
// Wait for the signal to be set
signal.WaitOne();
IEntityBase entry;
lock (synclock)
entry = queue.Count > 0 ? queue.Dequeue() : null;
while (entry != null)
{
ClientState.Current.DataService.Update(entry);
lock (synclock)
{
entry = queue.Count > 0 ? queue.Dequeue() : null;
}
}
}
while (true);
}
public static void Enqueue(IEntityBase entity)
{
lock(synclock)
queue.Enqueue(entity);
signal.Set();
}
}
}
|
Java
|
UTF-8
| 8,459 | 2.859375 | 3 |
[] |
no_license
|
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
// 매출 관리
public class SalesManage extends JFrame{
private String[] yearData = { "2020", "2021", "2022" };
private String[] monthData = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" };
MyCalendarModel model = new MyCalendarModel();
DefaultTableModel dTable = new DefaultTableModel();
JTable cal = new JTable(dTable) {
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
Component comp = super.prepareRenderer(renderer, row, col);
Object value = getModel().getValueAt(row, col);
if (value == null) {
comp.setBackground(Color.LIGHT_GRAY);
comp.setEnabled(false);
comp.setFocusable(false);
} else {
comp.setBackground(Color.white);
comp.setEnabled(true);
}
return comp;
}
public boolean isCellEditable (int rowIndex, int colIndex) {
return false; // 셀 편집 금지
}
};
private int year_, month_;
Object data;
private ImageIcon icon;
public SalesManage() {
setTitle("매출 관리");
setResizable(false);
icon = new ImageIcon("image/payment.png");
icon = imageSetSize(icon, 620, 610);
JPanel background = new JPanel() {
public void paintComponent(Graphics g) {
g.drawImage(icon.getImage(),0,0,null);
}
};
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int height = screenSize.height;
int width = screenSize.width;
setPreferredSize(new Dimension(630, 640));
setSize(new Dimension(630, 640));
setResizable(false);
setLocation(width/2-this.getWidth()/2, height/2-this.getHeight()/2);
JPanel selectJp = new JPanel(new GridLayout(1, 2));
selectJp.setBorder(BorderFactory.createEmptyBorder(50, 30, 0, 200));
selectJp.setOpaque(false);
JPanel calendarJp = new JPanel();
calendarJp.setOpaque(false);
JPanel salesJp = new JPanel(new GridLayout(1, 2));
salesJp.setOpaque(false);
salesJp.setBorder(BorderFactory.createEmptyBorder(0, 30, 50, 50));
JPanel allJp = new JPanel(new BorderLayout());
allJp.setOpaque(false);
JComboBox<String> year = new JComboBox<String>(yearData);
year.setSize(62, 35);
selectJp.add(year);
Calendar c = Calendar.getInstance();
JComboBox<String> month = new JComboBox<String>(monthData);
month.setSize(62, 35);
month.setSelectedIndex(c.get(Calendar.MONTH));
selectJp.add(month);
JLabel daySales = new JLabel("매출 : " + " 원");
daySales.setFont(new Font("굴림", Font.BOLD, 22));
daySales.setSize(50, 50);
salesJp.add(daySales);
year_ = year.getSelectedIndex() + 2020;
month_ = month.getSelectedIndex() + 1;
CoffeePosDAO dao = new CoffeePosDAO();
int sales = dao.sumMonth(year_, (c.get(Calendar.MONTH) + 1));
JLabel totalSales = new JLabel();
totalSales.setText((c.get(Calendar.MONTH) + 1) + "월 총매출 : " + String.format("%,d", sales) +"원");
totalSales.setFont(new Font("굴림", Font.BOLD, 22));
totalSales.setOpaque(false);
totalSales.setSize(50, 50);
salesJp.add(totalSales);
dTable = model.setMonth(year.getSelectedIndex() + 2020, month.getSelectedIndex());
cal.setModel(dTable);
JScrollPane jsp = new JScrollPane(cal, JScrollPane.VERTICAL_SCROLLBAR_NEVER , JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setPreferredSize(new Dimension(520, 382));
jsp.setSize(new Dimension(520, 382));
//jsp.seth
myCalendar(cal);
calendarJp.add(jsp);
allJp.add(selectJp, BorderLayout.NORTH);
allJp.add(calendarJp, BorderLayout.CENTER);
allJp.add(salesJp, BorderLayout.SOUTH);
background.add(allJp);
add(background);
setVisible(true);
year.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
CoffeePosDAO dao = new CoffeePosDAO();
dTable = model.setMonth(year.getSelectedIndex() + 2020, month.getSelectedIndex());
year_ = year.getSelectedIndex() + 2020;
int sales = dao.sumMonth(year_, month_);
totalSales.setText(month_ + "월 총매출 : " + String.format("%,d", sales) + "원");
cal.repaint();
}
});
month.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
CoffeePosDAO dao = new CoffeePosDAO();
dTable = model.setMonth(year.getSelectedIndex() + 2020, month.getSelectedIndex());
month_ = month.getSelectedIndex() + 1;
int sales = dao.sumMonth(year_, month_);
totalSales.setText(month_ + "월 총매출 : " + String.format("%,d", sales) + "원");
cal.repaint();
}
});
cal.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
CoffeePosDAO dao = new CoffeePosDAO();
int row = cal.getSelectedRow();
int col = cal.getSelectedColumn();
data = model.getValueAt(row, col);
String date = data.toString();
if(0 < Integer.parseInt(date) && Integer.parseInt(date) < 10) {
date = 0 + date;
}
try {
int sales = dao.sumDay(year_,month_,date);
String dayNum = null;
dayNum = data.toString() + "일 ";
daySales.setText(dayNum + "매출 : " + String.format("%,d", sales) +"원");
}catch(NullPointerException ex) {
}
}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseClicked(MouseEvent e) {}
});
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) { new Menu(); }
});
}
// table 모델 class
class MyCalendarModel extends AbstractTableModel {
String[] days = { "일", "월", "화", "수", "목", "금", "토" };
int[] lastDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 날짜 들어가는 배열
String[][] calendar = new String[6][7];
DefaultTableModel dModel = new DefaultTableModel(days, 6);
// 초기화
public MyCalendarModel() {
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 7; ++j) {
dModel.setValueAt(null, i, j);
}
}
}
@Override
public int getColumnCount() {
return 7;
}
@Override
public int getRowCount() {
return 6;
}
@Override
public Object getValueAt(int row, int column) {
return dModel.getValueAt(row, column);
}
@Override
public void setValueAt(Object value, int row, int column) {
dModel.setValueAt(value, row, column);
}
// 달마다 날짜 설정
public DefaultTableModel setMonth(int year, int month) {
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 7; ++j) {
dModel.setValueAt(null, i, j);
}
}
GregorianCalendar cal = new GregorianCalendar();
cal.set(year, month, 1);
int offset = cal.get(GregorianCalendar.DAY_OF_WEEK) - 1;
offset += 7;
// 달 마지막 날짜
int num = daysInMonth(year, month);
for (int i = 0; i < num; ++i) {
dModel.setValueAt(i + 1, (offset / 7)-1, offset % 7);
++offset;
}
return dModel;
}
// 윤년
public boolean isLeapYear(int year) {
if (year % 4 == 0)
return true;
return false;
}
public int daysInMonth(int year, int month) {
int days = lastDays[month];
if (month == 1 && isLeapYear(year)) {
++days;
}
return days;
}
public boolean isCellEditable(int row, int column){
return false;
}
}
// 캘린더 설정
public void myCalendar(JTable table) {
table.setGridColor(Color.DARK_GRAY);
table.setSize(600, 600);
table.setRowHeight(60);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setCellSelectionEnabled(true); // 셀 하나만 선택
table.setSelectionBackground(Color.gray);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
for (int i = 0; i < 7; i++) {
table.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
}
}
public ImageIcon imageSetSize(ImageIcon icon, int i, int j) {
Image ximg = icon.getImage();
Image yimg = ximg.getScaledInstance(i, j, java.awt.Image.SCALE_SMOOTH);
ImageIcon xyimg = new ImageIcon(yimg);
return xyimg;
}
}
|
JavaScript
|
UTF-8
| 4,304 | 2.515625 | 3 |
[] |
no_license
|
import React from 'react';
import { kebabCase } from 'lodash';
import "./sidenav.scss";
class SideNav extends React.Component {
constructor(props) {
super(props)
this.hideLabelsTimer = null;
this.showActiveLabelTimer = null;
this.observer = null;
this.observed = [];
this.triggerRender = true;
this.state = {
pages: this.props.pages
}
this.addObservers = this.addObservers.bind(this);
}
componentDidMount() {
this.observer = new IntersectionObserver(this.observerCallback, { threshold: 0.7 });
setTimeout(this.addObservers, 200);
}
componentWillUnmount() {
clearTimeout(this.addObservers);
clearTimeout(this.hideLabelsTimer);
}
addObservers() {
this.addObserverToTargets();
this.showLabel();
}
observerCallback = (entries, _observer) => {
const activeTargets = entries.map((entry) => {
if (entry.intersectionRatio > 0) {
return entry.target.id;
}
return entry.target
});
if (activeTargets.length !== this.props.pages.length) {
const activeHash = activeTargets[0];
const page = this.state.pages.find(obj => {
return obj.hash === activeHash
})
this.observed = [...this.observed, page]
if (this.triggerRender) {
this.triggerRender = false;
this.showLabel();
}
this.addObserverToTargets();
}
}
addObserverToTargets = () => {
const pages = this.state.pages.map((anc) => {
const target = document.getElementById(anc.hash);
if (target && !anc.isObserved) {
this.observer.observe(target);
return { ...anc, isObserved: true }
}
return anc;
});
this.setState({ pages })
}
showLabel = () => {
this.showActiveLabelTimer = setTimeout(() => {
this.triggerRender = true;
const active = this.observed[this.observed.length - 1]
const pages = this.state.pages.map((obj, page) => {
return page === this.props.currentPage
? { ...obj, isActive: true, isActiveBar: true } : { ...obj, isActive: false, isActiveBar: false };
});
this.setState({ pages });
this.hideLabels();
}, 200);
}
hideLabels() {
this.hideLabelsTimer = setTimeout(() => {
const pages = this.state.pages.map(obj => {
return { ...obj, isActive: false };
});
this.setState({ pages });
}, 2500);
}
handleClick = (pageNumber) => (event) => {
this.props.goToPage(pageNumber);
event.preventDefault();
}
render() {
const theme = this.state.pages[this.props.currentPage].theme;
return (
<div className={`side-bar side-bar--${theme}`}>
<ul>
{
this.state.pages.map((anc, index) => (
<li className="side-bar-item" key={kebabCase(anc.title)}>
<div className={`side-bar-tab
${anc.isActiveBar ? "side-bar-tab-active"
: "side-bar-tab-hidden"
}`}>
</div>
<a style={{ width: `${anc.title.length * 8}px` }}
className={`side-bar-label font-weight-bold
${anc.isActive ? "side-bar-label-active"
: "side-bar-label-hidden"}`}
href={`#${kebabCase(anc.title)}`}
data-value={kebabCase(anc.title)}
onClick={this.handleClick(index)}
>
{anc.title}
</a>
</li>
))
}
</ul>
</div>
);
}
}
export default SideNav;
|
Python
|
UTF-8
| 874 | 2.953125 | 3 |
[] |
no_license
|
#The purpose of this program is to learn the friendship between pygame and nxt python!
#Author: Guillermo Ochoa
import pygame, sys
from pygame.locals import *
import nxt.locator
from nxt.motor import *
pygame.init()
b = nxt.locator.find_one_brick()
m_b = Motor(b, PORT_B)
m_a = Motor(b, PORT_A)
m_c = Motor(b, PORT_C)
#Window Set up.
pygame.display.set_mode((1, 1), NOFRAME)
#Write the variables..
while True:
for event in pygame.event.get(KEYDOWN):
if event.key == (K_UP):
m_b.run(-50, True)
m_a.run(-50, True)
m_c.run(-50, True)
elif event.key == (K_ESCAPE):
pygame.quit()
sys.exit()
for event in pygame.event.get(KEYUP):
if event.key == (K_UP):
m_b.idle()
m_c.idle()
m_a.idle()
|
JavaScript
|
UTF-8
| 193 | 3.1875 | 3 |
[] |
no_license
|
let input=prompt("문자열 입력")
//레전드 문제 나는 머리가 안좋은가봄 코드 깔쌈하네
for (let i=0; i<input.length-1; i++){
console.log(input[i], input[i+1]);
}
|
Python
|
UTF-8
| 373 | 2.890625 | 3 |
[] |
no_license
|
def lagrange(x,y,find):
ans=0
for i in range(0,len(x)):
mult=y[i]
main1=1
main2=1
for j in range(0,len(x)):
if(i!=j):
main1*=(find-x[j])
main2*=(x[i]-x[j])
ans+=(mult*(main1/main2))
return(ans)
x=[0,1,4,5,6,7,8]
y=[170,168,172,169,168,165,167]
find=9
lagrange(x,y,find)
|
C++
|
UTF-8
| 1,374 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
/*
LloydSample.hpp
the "points" (in the jargon of [Balzer et al. SIGGRAPH 2009])
Li-Yi Wei
07/15/2009
*/
#ifndef _LLOYD_SAMPLE_HPP
#define _LLOYD_SAMPLE_HPP
#include <vector>
using namespace std;
#include "Sample.hpp"
#include "LloydIndex.hpp"
class LloydSample
{
public:
LloydSample(void);
LloydSample(const int dimension, const LloydIndex & index);
~LloydSample(void);
class Index // index to the site/owner for each class
{
public:
Index(const LloydIndex & index);
Index(void);
~Index(void);
int NumClass(void) const;
void Clear(void);
void Clear(const int num_class);
// return 1 if successful, 0 else
int Set(const int which_class, const int lord, const float dist);
int Get(const int which_class, int & lord, float & dist) const;
int Set(const vector<int> & class_combo, const int lord, const float dist);
int Get(const vector<int> & class_combo, int & lord, float & dist) const;
// find the lord id with minimum dist under a given class combination
int Get(const vector<int> & class_combo) const;
Index(const Index & rhs);
Index & operator=(const Index & rhs);
protected:
LloydIndex * _index;
};
public:
Sample sample;
float density;
Index index;
};
#endif
|
Python
|
UTF-8
| 166 | 3.65625 | 4 |
[] |
no_license
|
palavra1 = input()
palavra2 = input()
reverso = palavra1[::-1]
if(reverso == palavra2):
print("palíndromas mútuas")
else:
print("não são palíndromas")
|
Markdown
|
UTF-8
| 1,010 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
<img src="https://freepngimg.com/thumb/terminator/21148-9-terminator-picture.png" width="200" title="Bot" alt="Bot" />
# Bot-InstaAutoLike
A Javascript Bot to Auto Like all pictures in an Instagram profile.
It bypasses Instagram spam protection and keeps retrying upon encountering the limits (limits of like frequency / limits of likes).
**Usage :**
**(1).** Open the Instagram profile whose pic you want to like in the browser.
**(2).** Copy-Paste the code from **Bot-InstaAutoLike.js** in Browser Console or save the code as a bookmark (click it to run).
After liking all the pics, it just refreshes the page.
That's all folks!
**CAUTION :**
1. More than 2 hours of continuous usage will give you a **'suspicious activity message' from Instagram** where you'll be asked to **reset your password**.
Give breaks while using it, if you do not want to be forced to reset you password.
2. Continuous usage of this tool for hours will get you temporarily banned from liking any pictures.
|
Java
|
UTF-8
| 334 | 1.828125 | 2 |
[
"MIT"
] |
permissive
|
package com.zjmeow.bboard.dao;
import com.zjmeow.bboard.model.po.Singer;
import java.util.List;
public interface SingerMapper {
Singer selectByPrimaryKey(Integer id);
List<Singer> selectSingerBySongId(Integer songId);
List<Singer> selectSingerByName(String name);
List<Singer> selectSingerByBorn(String born);
}
|
Markdown
|
UTF-8
| 4,147 | 3.015625 | 3 |
[] |
no_license
|
# DNS : sistema de nombre de dominios
La configuración de los DNS es una etapa crucial para que tu servidor esté accesible. En efecto, si tus DNS están mal configurados, con mucha certeza tendrás problemas de conexión a tu servidor vía tu nombre de dominio.
*Aunque esta etapa de documentación parezca larga y compleja, sigue siendo muy importante si quieres entender correctamente las implicaciones de la denominación en Internet vía los nombres de dominio, que son necesarios para el funcionamiento de tu servidor YunoHost.*
### ¿ Qué es ?
DNS significa « Domain Name Server » en inglés, y está frecuentemente empleado para designar la configuración de tus nombres de dominio. Tu nombre de dominio debe apuntar hacia algo (en general, una dirección IP).
**Por ejemplo** : `yunohost.org` apunta hacia `88.191.153.110`.
Este sistema fue creado para poder memorizar más fácilmente las direcciones de servidores. Existen registros DNS en los cuales hay que apuntarse. Esto se hace con **registrars** que te alquilarán estos nombres de dominio a cambio de cierto importe (entre cinco y algunas centenas de euros). Estos [registrars](/registrar) son entidades privadas autorizadas por el [ICANN](https://es.wikipedia.org/wiki/Corporaci%C3%B3n_de_Internet_para_la_Asignaci%C3%B3n_de_Nombres_y_N%C3%BAmeros), tales como [Gandi](http://gandi.net), [OVH](http://ovh.com) o [BookMyName](http://bookmyname.com).
Es importante notar que los subdominios no necesariamente apuntan al dominio principal.
Si `yunohost.org` apunta hacia `88.191.153.110`, no quiere decir que `backup.yunohost.org` apunte hacia la misma IP. Tienes que configurar **todos** los dominios y subdominios que deseas utilizar.
También existen **tipos** de registros DNS, lo que significa que un dominio puede apuntar hacia otra cosa que una dirección IP.
**Por ejemplo** : `www.yunohost.org` apunta hacia `yunohost.org`
### ¿ Cómo (bien) hacer la configuración ?
Tienes varias opciones. Nota que puedes cumular estas soluciones si posees varios dominios : por ejemplo, puedes tener `mi-servidor.nohost.me` utilizando la solución **1.**, et `mi-servidor.org` utilizando la solución **2.**, redirigiéndolos hacia el mismo servidor YunoHost.
1. Puedes utilizar [el servicio DNS de YunoHost](/dns_nohost_me), que configurará él mismo los DNS de tu instancia YunoHost. Pero en este caso, tienes que elegir un dominio terminando por `.nohost.me`, `.noho.st` o `.ynh.fr`, lo que puede tener inconvenientes (tendrás direcciones email tales como `juan@mi-servidor.noho.st`).
**Es el método recomendado si estás debutando.**
2. Puedes utilizar el servicio de DNS de tu **registrar** (Gandi, OVH, BookMyName u otro) para configurar tus nombres de dominio. Ésta es la [configuración DNS estándar](/dns_config). También es posible utilizar una redirección DNS local, más información sobre cómo [Acceder a su servidor desde la red local](/dns_local_network).
También puedes consultar las documentaciones específicas a estas varias [oficinas de registro](/registrar) : [Gandi](http://gandi.net), [OVH](/OVH) o [BookMyName](http://bookmyname.com).
**Atención** : Si eliges este modo de funcionamiento, tendrás más flexibilidad, pero nada será automático. Por ejemplo si quieres utilizar `webmail.mi-servidor.org`, tendrás que añadirlo manualmente en la interfaz de tu registrar.
3. (Advanced, not 100% supported, do this only if you know what you're doing) Tu instancia tiene un servicio DNS, lo que quiere decir que configura automáticamente sus registros DNS y que es posible delegarle la administración de estos registros. Por eso, tienes que indicar al **registrar** que es tu instancia YunoHost que es el servidor DNS de tu nombre de dominio creando un registro glue (a menudo denominado **glue record**) apuntando hacia la IP de tu instancia YunoHost.
<br><br>**Atención** : Si eliges este modo de funcionamiento, todas las configuraciones serán automatizadas, tendrás mucha flexibilidad pero la pérdida de tu servidor potencialmente traerá muchos problemas. **Elige este método si estás muy seguro de los que estás haciendo.**
|
Java
|
UTF-8
| 923 | 2.859375 | 3 |
[] |
no_license
|
public class DrawAvoidingBridges {
public static void main(String[] args) {
double q = 0.999999;
double k = 0;
int N = 20;
int T = 20;
int S = 10;
SimulateQR qr = new SimulateQR(q, k, N, T, S);
Tiling tile = qr.sample();
int[][] pos = tile.getParticles();
double[][] bb2 = new double[N][T];
double slope = 1.0 * S / T;
for (int i = 0; i < N; i++) {
for (int j = 0; j < T; j++) {
bb2[i][j] = pos[i][j] - slope * j - i;
}
}
tile.drawLines();
// draw the trajectories
/*StdDraw.setXscale(-100, 600);
StdDraw.setYscale(-100, 100);
for (int i = 0; i < N; i++) {
for (int j = 0; j < T - 1; j++) {
StdDraw.line(j, bb2[i][j], j + 1, bb2[i][j + 1]);
}
}*/
}
}
|
JavaScript
|
ISO-8859-1
| 817 | 2.578125 | 3 |
[] |
no_license
|
function alterarTipo(){
var t = jQuery(".tipo").get();
var c = jQuery(".cod").get();
var cods = Array();
var tipos = Array();
if(c != null){
for(i=0; i<c.length; i++){
cods.push(c[i].value);
tipos.push(t[i].value);
}
}
if(cods.length == 0 || tipos.length == 0){
alert("Por favor, selecione um registro.");
return;
}
jQuery.post("../ctrl/CtrlCadAtividade.php", { acao: "Alterar", "tipos[]": tipos, "cods[]": cods },
function(data) {
if(data.sucesso == "true"){
alert("Alterao realizada com sucesso")
}
else{
alert("Alterao no realizada")
}
},"json"
);
}
|
C++
|
UTF-8
| 2,751 | 2.734375 | 3 |
[] |
no_license
|
#include <cmath>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <GL/glut.h>
#include "common.h"
#include "math.h"
using namespace std;
namespace morph {
static const int samples = 80;
static long frame;
struct point {
const float x, y, z;
point(float x_, float y_, float z_) :
x(x_), y(y_), z(z_) {
}
};
//find a fix for floating point errors when s is very close to R
point sphere_(float s, float t) {
//return point(s,t,0);
float R = 0.5;
s = (s * 2 - 1) * R;
t = t * 2 * PI;
if (s > R)
return point(NAN, NAN, NAN);
float r = sqrt((R + s) * (R - s)); //written like this it is numerically more stable
return point(cos(t) * r, sin(t) * r, s);
}
point blob(float s, float t) {
float time = frame * 0.06;
s = PI * s;
t = PI * t * 2;
float R = 0.55 + 0.45*sin(time) * sin(4*s) * sin(4*t);
float r = R * sin (s) ;
return point(
r * cos(t),
r * sin(t),
R * cos(s) );
}
point melc(float s, float t) {
float time = frame * 0.02 ;
float cut = sin(time) ;
s = PI * ( (0.5 - cut) + s * ( 2 * cut));
t = PI * t * 4;
float R = t/PI/4;
float r = R * sin (s) ;
return point(
r * cos(t),
r * sin(t),
R * cos(s) );
}
//s,t in [0..1]
point func(float s, float t) {
return melc(t, s);
}
void print_point(point p) {
//cout << "[" << p.x << "," << p.y << "," << p.z << "]" << endl;
}
// for (float t = 0; t <= 1; t += step) {
// is *not* splitting 0..1 evenly but some 0..k, k>1 .
// 1 will never be reached
// floating point rounding makes step slightly bigger
// Fix: use integers for interval division; do floating point operations per dot
// 0..1 the divisions will not be equal as above but 1 will be reached
void drawGeometry(long frame_) {
glPushMatrix();
frame = frame_;
glRotatef(-frame*3,0,0,1);
const float interval_width = 1;
for (int sdot = 0; sdot < samples; sdot += 1) {
float s = (float) interval_width * sdot / (float) samples;
glBegin(GL_TRIANGLE_STRIP);
for (int tdot = 0; tdot <= samples; tdot += 1) {
float t = (float) interval_width * tdot / (float) samples;
point fl = func(s, t);
if (fl.x != NAN) { //test if function is defined here
print_point(fl);
glColor3f(1 - t, s, t); //parametric colors
glVertex3f(fl.x, fl.y, fl.z);
}
float next_s = (float) interval_width * (sdot + 1) / (float)samples;
point fr = func(next_s, t);
if (fr.x != NAN) {
print_point(fr);
glColor3f(1 - t, next_s, t); //parametric colors
glVertex3f(fr.x, fr.y, fr.z);
}
}
glEnd();
}
glPopMatrix();
}
}
int _main(int argc, char* argv[]) {
srand(time(NULL));
renderSettings settings;
settings.fps = 20;
settings.drawGeometry = morph::drawGeometry;
return render_run(settings, argc, argv);
}
|
Markdown
|
UTF-8
| 2,996 | 3.578125 | 4 |
[] |
no_license
|
# [1582. 二进制矩阵中的特殊位置](https://leetcode-cn.com/problems/special-positions-in-a-binary-matrix/)
---
## Description
<section>
<p>给你一个大小为 <code>rows x cols</code> 的矩阵 <code>mat</code>,其中 <code>mat[i][j]</code> 是 <code>0</code> 或 <code>1</code>,请返回 <strong>矩阵 <em><code>mat</code></em> 中特殊位置的数目</strong> 。</p>
<p><strong>特殊位置</strong> 定义:如果 <code>mat[i][j] == 1</code> 并且第 <code>i</code> 行和第 <code>j</code> 列中的所有其他元素均为 <code>0</code>(行和列的下标均 <strong>从 0 开始</strong> ),则位置 <code>(i, j)</code> 被称为特殊位置。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong>mat = [[1,0,0],
[0,0,<strong>1</strong>],
[1,0,0]]
<strong>输出:</strong>1
<strong>解释:</strong>(1,2) 是一个特殊位置,因为 mat[1][2] == 1 且所处的行和列上所有其他元素都是 0
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong>mat = [[<strong>1</strong>,0,0],
[0,<strong>1</strong>,0],
[0,0,<strong>1</strong>]]
<strong>输出:</strong>3
<strong>解释:</strong>(0,0), (1,1) 和 (2,2) 都是特殊位置
</pre>
<p><strong>示例 3:</strong></p>
<pre><strong>输入:</strong>mat = [[0,0,0,<strong>1</strong>],
[<strong>1</strong>,0,0,0],
[0,1,1,0],
[0,0,0,0]]
<strong>输出:</strong>2
</pre>
<p><strong>示例 4:</strong></p>
<pre><strong>输入:</strong>mat = [[0,0,0,0,0],
[<strong>1</strong>,0,0,0,0],
[0,<strong>1</strong>,0,0,0],
[0,0,<strong>1</strong>,0,0],
[0,0,0,1,1]]
<strong>输出:</strong>3
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>rows == mat.length</code></li>
<li><code>cols == mat[i].length</code></li>
<li><code>1 <= rows, cols <= 100</code></li>
<li><code>mat[i][j]</code> 是 <code>0</code> 或 <code>1</code></li>
</ul>
</section>
## My Solution
```cpp
class Solution {
public:
int numSpecial(vector<vector<int>>& mat) {
vector<int> colCount(mat[0].size(), 0);
for(int i = 0; i < mat.size(); ++i){
for(int j = 0; j < mat[0].size(); ++j){
if(mat[i][j] == 1)++colCount[j];
}
}
int result = 0;
for(int i = 0; i < mat.size(); ++i){
for(int j = 0; j < colCount.size(); ++j){
if(mat[i][j] == 1){
if(colCount[j] == 1){
int k = j + 1;
while(k < colCount.size() && mat[i][k] == 0)++k;
if(k == colCount.size())++result;
break;
}else{
break;
}
}
}
}
return result;
}
};
```
|
Markdown
|
UTF-8
| 1,632 | 2.53125 | 3 |
[] |
no_license
|
## John's ERC-721 NFT Token
Howdy, this is my repository for my very own ERC-721 non-fungible token. What's it for? Find out soon.
#### What is ERC-721?
[ERC-721](http://erc721.org/) is a free, open standard that describes how to build non-fungible or unique tokens on the [Ethereum](https://www.ethereum.org/) blockchain. While most tokens are fungible (every token is the same as every other token), ERC-721 tokens are all unique.
Think of them like rare, one-of-a-kind collectables.
Non-Fungible tokens allow developers to tokenize ownership of any arbitrary data, drastically increasing the design space of what can be represented as a token on the Ethereum blockchain.
#### Current Deployment
The token contract is currently deployed on the Rinkelby testnet at the address `0xf04Ab4810b2DA6eCd6b67e9Cb929Ca38A5D12a34`. You can check it out on etherscan [here](https://rinkeby.etherscan.io/token/0xf04ab4810b2da6ecd6b67e9cb929ca38a5d12a34).
As soon as I finish up development, I'll deploy it to mainnet Ethereum.
## Install
```
yarn
// then create a .env file that looks like this:
TRUFFLE_MNEMONIC=candy maple cake sugar pudding cream honey rich smooth crumble sweet treat
GANACHE_MNEMONIC=grid voyage cream cry fence load stove sort grief fuel room save
TESTNET_MNEMONIC=a twelve word mnemonic phrase that works with some test network buddy
INFURA_API_KEY=yOUrInfURaKEy
```
## Run
```
yarn lint:watch
```
## Test
```
truffle develop
yarn test
```
## Deploy
```
truffle develop
yarn deploy --network develop
// this just runs truffle migrate --reset --compile-all
```
## Prior Art
Project boilerplate based off of [truffle-shavings](https://github.com/okwme/truffle-shavings/).
|
Java
|
UTF-8
| 1,892 | 2.234375 | 2 |
[] |
no_license
|
package com.tiancaibao.pojo.system;
import java.io.Serializable;
import java.util.Date;
public class SystemAppCodeEdition implements Serializable {
private Integer id;
private String name;
private Byte numbers;
private Date deletedAt;
private Date createdAt;
private Date updatedAt;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Byte getNumbers() {
return numbers;
}
public void setNumbers(Byte numbers) {
this.numbers = numbers;
}
public Date getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(Date deletedAt) {
this.deletedAt = deletedAt;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", numbers=").append(numbers);
sb.append(", deletedAt=").append(deletedAt);
sb.append(", createdAt=").append(createdAt);
sb.append(", updatedAt=").append(updatedAt);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
C#
|
UTF-8
| 3,502 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
// Licensed under the MIT License. See LICENSE in the repository root for license information.
using System.Linq;
namespace Common
{
/// <summary>
/// Class with label and score.
/// </summary>
public class FileDataLabel
{
/// <summary>
/// Gets or sets the filename.
/// </summary>
public string File { get; set; }
/// <summary>
/// Gets or sets the title.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the 1st subtitle.
/// </summary>
public string Subtitle1 { get; set; }
/// <summary>
/// Gets or sets the 2nd subtitle.
/// </summary>
public string Subtitle2 { get; set; }
/// <summary>
/// Gets or sets the 3rd subtitle.
/// </summary>
public string Subtitle3 { get; set; }
/// <summary>
/// Gets or sets the 4th subtitle.
/// </summary>
public string Subtitle4 { get; set; }
/// <summary>
/// Gets or sets the 5th subtitle.
/// </summary>
public string Subtitle5 { get; set; }
/// <summary>
/// Gets or sets the word count.
/// </summary>
public int WordCount { get; set; }
/// <summary>
/// Gets or sets the reading time.
/// </summary>
public string ReadingTime { get; set; }
/// <summary>
/// Gets or sets the top 20 words.
/// </summary>
public string Top20Words { get; set; }
/// <summary>
/// Gets or sets the predicted label.
/// </summary>
public uint PredictedLabel { get; set; }
/// <summary>
/// Gets or sets the score.
/// </summary>
public float[] Score { get; set; }
/// <summary>
/// Gets the headers.
/// </summary>
public string Headers =>
Row(string.Join(",", new[]
{
nameof(File),
nameof(Title),
nameof(Subtitle1),
nameof(Subtitle2),
nameof(Subtitle3),
nameof(Subtitle4),
nameof(Subtitle5),
nameof(WordCount),
nameof(ReadingTime),
nameof(Top20Words),
nameof(PredictedLabel),
}.Select(h => $"\"{h}\"")
.ToArray()));
/// <summary>
/// Gets the row data.
/// </summary>
public string Data =>
Row(string.Join(
",",
new[]
{
File,
Title,
Subtitle1,
Subtitle2,
Subtitle3,
Subtitle4,
Subtitle5,
}.Select(val => val.StartsWith("\"") ? val : $"\"{val}\"")
.Append(WordCount.ToString())
.Append(ReadingTime.StartsWith("\"") ? ReadingTime : $"\"{ReadingTime}\"")
.Append(Top20Words.StartsWith("\"") ? Top20Words : $"\"{Top20Words}\"")
.Append(PredictedLabel.ToString())
.ToArray()));
/// <summary>
/// Wraps the row with a newline.
/// </summary>
/// <param name="src">The source.</param>
/// <returns>The source with a new line.</returns>
private string Row(string src) => $"{src}\r\n";
}
}
|
PHP
|
UTF-8
| 1,530 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* Project Entity
*
* @property int $id
* @property string $name
* @property int $status
* @property int|null $project_manager
* @property int|null $tech_lead
* @property int|null $process_manager
* @property int|null $tech_dir
* @property int|null $reviewer
* @property int|null $warning_problem
* @property int|null $warning_alarm
* @property string|null $slack_name
* @property string|null $emoji
*
* @property \App\Model\Entity\Post[] $post
* @property \App\Model\Entity\ProjectNotification[] $project_notification
* @property \App\Model\Entity\ProjectToUser[] $project_to_user
*/
class Project extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* @var array
*/
protected $_accessible = [
'name' => true,
'status' => true,
'project_manager' => true,
'tech_lead' => true,
'process_manager' => true,
'tech_dir' => true,
'reviewer' => true,
'warning_problem' => true,
'warning_alarm' => true,
'slack_name' => true,
'emoji' => true,
'post' => true,
'project_notification' => true,
'project_to_user' => true
];
}
|
Markdown
|
UTF-8
| 4,627 | 2.703125 | 3 |
[
"MIT-0"
] |
permissive
|
## Getting started with RPA using AWS Step Functions and Amazon Textract
[AWS Step
Functions](https://aws.amazon.com/step-functions/) is a serverless function
orchestrator and workflow automation tool. [Amazon Textract](https://aws.amazon.com/textract/)
is a fully managed machine learning service that automatically extracts text
and data from scanned documents. Combining these services, you can create an RPA bot
to automate the processing of documents.
See [Getting started with RPA using AWS Step Functions and Amazon Textract blog post](https://aws.amazon.com/blogs/compute/getting-started-with-rpa-using-aws-step-functions-and-amazon-textract/).
## Security
See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.
## License
This library is licensed under the MIT-0 License. See the LICENSE file.
## Prerequisites
Before you get started with deploying the solution, you must install the
following prerequisites:
1. [Python](https://www.python.org/)
2. [AWS Command Line Interface (AWS CLI)](https://aws.amazon.com/cli/)
-- for instructions, see [Installing the AWS
CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html)
3. [AWS Serverless Application Model Command Line Interface (AWS
SAM CLI)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-command-reference.html)
-- for instructions, see [Installing the AWS SAM
CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
## Deploying the solution
The solution will create the following three Amazon Simple Storage
Service (S3) buckets with names suffixed by your AWS Account ID to
prevent a global namespace collision of your S3 bucket names:
- scanned-invoices-\<YOUR AWS ACCOUNT ID\>
- invoice-analyses-\<YOUR AWS ACCOUNT ID\>
- processed-invoices-\<YOUR AWS ACCOUNT ID\>
The below steps deploy the reference implementation in your AWS account.
The solution deploys several components including an AWS Step Functions
state machine, AWS Lambda functions, Amazon Simple Storage Service (S3)
buckets, an Amazon DynamoDB table for payment information, and AWS
Simple Notification Service (SNS) topics. You will need an Amazon S3
bucket to be used by AWS CloudFormation for deploying the solution. You
will also need a stack name, e.g., Getting-Started-with-RPA, for
deploying the solution. To deploy run the following commands from a
terminal session:
1. Download code from GitHub repo
(<https://github.com/aws-samples/aws-step-functions-rpa>).
2. Run the following command to build the artifacts locally on your
workstation:
sam build
3. Run the following command to create a CloudFormation stack and
deploy your resources:
sam deploy --guided --capabilities CAPABILITY_NAMED_IAM
Monitor the progress and wait for the completion of the stack creation
process from the [AWS CloudFormation
console](https://console.aws.amazon.com/cloudformation/home) before
proceeding.
## Testing the solution
To test the solution, upload the .PDF test invoices from the invoices
folder of the downloaded solution to the S3 bucket named
scanned-invoices-\<Your AWS Account ID\> created during deployment.
An AWS Step Functions state machine with the name \<YOUR STACK
NAME\>-ProcessedScannedInvoiceWorkflow will execute the workflow. Amazon
Textract document analyses will be stored in the S3 bucket named
invoice-analyses-\<YOUR AWS ACCOUNT ID\>, and processed invoices will be
stored in the S3 bucket named processed-invoices-\<YOUR AWS ACCOUNT
ID\>. Processed payments will be found in the DynamoDB table named
\<YOUR STACK NAME\>-invoices.
You can monitor the execution status of the workflows from the [AWS Step
Functions console](https://console.aws.amazon.com/states/home).
Upon completion of the workflow executions, review the items added to
DynamoDB from the [Amazon DynamoDB
console](https://console.aws.amazon.com/dynamodb/home).
## Cleanup
To avoid ongoing charges for resources you created,
follow the below steps which will delete the stack of resources
deployed:
1. Empty the three S3 buckets created during deployment using the
[Amazon S3 Console](https://s3.console.aws.amazon.com/s3/home):
- scanned-invoices-\<YOUR AWS ACCOUNT ID\>
- invoice-analyses-\<YOUR AWS ACCOUNT ID\>
- processed-invoices-\<YOUR AWS ACCOUNT ID\>
2. Delete the CloudFormation stack created during deployment using the
[AWS CloudFormation
console](https://console.aws.amazon.com/cloudformation/home).
|
JavaScript
|
UTF-8
| 150 | 2.640625 | 3 |
[] |
no_license
|
function setup() {
// put setup code here
}
function draw() {
// put drawing code here
text("x = " + mouseX + ", y = " + mouseY, 40, 40) ;
}
|
Java
|
UTF-8
| 5,417 | 2.828125 | 3 |
[] |
no_license
|
package com.ge;
import java.beans.Introspector;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import com.ge.auditapi.Audit;
public class MainClass {
private Object[][] getMatrix(List<Object> obj, int rowNum){
List<Method> getterMethods = getMethodList(obj);
String propertyName = "";
Object [][] newArr = new Object[rowNum][getterMethods.size()];
try {
for(int i = 0; i<rowNum-1; i++) {
for(int j = 0; j<getterMethods.size();j++) {
if(!getterMethods.get(j).invoke(obj.get(i)).equals(getterMethods.get(j).invoke(obj.get(i+1)))) {
if(!getterMethods.get(j).invoke(obj.get(i)).getClass().getName().startsWith("java.lang")) {
Method[] methods = getterMethods.get(j).invoke(obj.get(i)).getClass().getDeclaredMethods();
List<ResultObject> resultList = new ArrayList<ResultObject>();
if(null != methods) {
resultList = this.compareFields(methods, (Object)getterMethods.get(j).invoke(obj.get(i)), (Object)getterMethods.get(j).invoke(obj.get(i+1)));
String changedObject = "";
propertyName = "";
int specialChar = 0;
for(ResultObject result : resultList) {
if(specialChar == 0) {
propertyName = Introspector.decapitalize(result.getFieldName().substring(result.getFieldName().startsWith("is")?2:3));
changedObject = (Object)result.getOldObjectValue() + " to " +(Object)result.getNewObjectValue();
}else {
propertyName = propertyName + ", " + Introspector.decapitalize(result.getFieldName().substring(result.getFieldName().startsWith("is")?2:3));
changedObject = changedObject + " & " + (Object)result.getOldObjectValue() + " to " +(Object)result.getNewObjectValue();
}
specialChar++;
}
newArr[i][j] = "The " + propertyName + " has been changed from " + changedObject;
}
}else {
propertyName = Introspector.decapitalize(getterMethods.get(j).getName().substring(getterMethods.get(j).getName().startsWith("is")?2:3));
newArr[i][j] = "The " + propertyName + " has been changed from " + (Object)getterMethods.get(j).invoke(obj.get(i)) + " to " + (Object)getterMethods.get(j).invoke(obj.get(i+1));
}
}
}
}
}catch(Exception e) {
System.out.println(e.getMessage());
}
return newArr;
}
private List<Method> getMethodList(List<Object> obj) {
List<Method> getterMethods = new ArrayList<>();
for(Method method : obj.get(0).getClass().getMethods()) {
if((method.getName().startsWith("get") || method.getName().startsWith("is"))&& method.getParameterCount() == 0) {
getterMethods.add(method);
}
}
return getterMethods;
}
public List<ResultObject> compareFields(Method[] methods, Object obj1, Object obj2) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
List<ResultObject> resultList = new ArrayList<ResultObject>();
for(Method method : methods) {
if((method.getName().startsWith("get") || method.getName().startsWith("is"))&& method.getParameterCount() == 0) {
if(!Objects.equals(method.invoke(obj1),method.invoke(obj2))) {
ResultObject resultObject = new ResultObject();
resultObject.setFieldName(method.getName());
resultObject.setOldObjectValue((Object)method.invoke(obj1));
resultObject.setNewObjectValue((Object)method.invoke(obj2));
resultList.add(resultObject);
}
}
}
return resultList;
}
public static void main(String[] args) {
List<Student> studentList = new ArrayList<>();
Student student1 = new Student();
student1.setId(1L);
student1.setFirstName("Vandit");
student1.setLastName("V");
student1.setRollNo("A001");
student1.setResult("Pass");
student1.setStatus(true);
Subject subject1 = new Subject();
subject1.setId(1L);
subject1.setMaths("Pass");
subject1.setScience("Pass");
subject1.setComputer("Fail");
subject1.setEnglish("Fail");
student1.setSubject(subject1);
Student student2 = new Student();
student2.setId(2L);
student2.setFirstName("Vandit");
student2.setLastName("J");
student2.setRollNo("A001");
student2.setResult("Fail");
student2.setStatus(true);
Subject subject2 = new Subject();
subject2.setId(1L);
subject2.setMaths("Fail");
subject2.setScience("Pass");
subject2.setComputer("Pass");
subject2.setEnglish("Fail");
student2.setSubject(subject2);
Student student3 = new Student();
student3.setId(3L);
student3.setFirstName("Prince");
student3.setLastName("G");
student3.setRollNo("A002");
student3.setResult("Pass");
student3.setStatus(false);
Subject subject3 = new Subject();
subject3.setId(2L);
subject3.setMaths("Pass");
subject3.setScience("Pass");
subject3.setComputer("Pass");
subject3.setEnglish("Pass");
student3.setSubject(subject3);
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
MainClass mainClass = new MainClass();
Audit audit = new Audit();
@SuppressWarnings("unchecked")
Object [][] finalMatrix = mainClass.getMatrix((List<Object>)(Object)studentList,3);
for(int i = 0; i<finalMatrix.length-1; i++) {
for(int j= 0 ; j<7;j++) {
//if(null!=finalMatrix[i][j])
System.out.println( i + " " + j + " " + finalMatrix[i][j]);
}
}
}
}
|
Python
|
UTF-8
| 1,420 | 3.953125 | 4 |
[] |
no_license
|
class Empty(Exception):
pass
class queue_using_linkedlist:
class node:
__slots__ = 'element', 'next'
def __init__(self,element,next):
self.element = element
self.next = next
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def __len__(self):
return self.size
def is_empty(self):
return self.size==0
def enqueue(self,element):
new_node = self.node(element,None)
if self.is_empty():
self.head= new_node
else:
self.tail.next= new_node
self.tail = new_node
self.size += 1
def dequeue(self):
if self.is_empty():
raise Empty("queue is empty")
value = self.head.element
self.head = self.head.next
self.size -=1
if self.is_empty:
self.tail= None
return value
def first(self):
if self.is_empty():
raise Empty("queue is empty")
return self.head.element
def display(self):
temp = self.head
while temp:
print(temp.element, end = '-->')
temp =temp.next
print()
# q= queue_using_linkedlist()
# q.enqueue(10)
# q.enqueue(20)
# q.enqueue(30)
# q.display()
# print('length', q.len())
# q.dequeue()
# print('length', q.len())
# q.display()
# print(q.first())
|
JavaScript
|
UTF-8
| 4,166 | 3.171875 | 3 |
[] |
no_license
|
function Node(id, x, y) {
/*
nodes are created by the importData.js file
x and y are coordinates on the map image
id is a unique identifier
like a primary key
adjIds is an array of ints,
each int represents the id
of an adjacent node.
i.e. you can travel from this point to that one
*/
"use strict";
var error = false;
try {
this.id = parseInt(id);
if (isNaN(this.id)) {
error = true;
throw new TypeError("Node id must be an integer");
}
} catch (idError) {
console.log(idError.stack);
}
try {
this.x = parseFloat(x);
this.y = parseFloat(y);
if (isNaN(this.x) || isNaN(this.y)) {
error = true;
throw new TypeError("X and Y must be numbers");
}
} catch (latLngError) {
console.log(latLngError);
}
this.adjIds = [];
this.buildings = [];
this.rooms = [];
this.classes = [];
this.connectionImages = {};
}
// Methods
Node.prototype = {
loadAdj: function (nodeDB) {
/*
Creates an array of Nodes,
the array contains all the
Nodes adjacent to this one.
Has to be invoked after
initializing all Nodes,
otherwise you will reference
nonexistant variables.
automatically invoked by importNodeData
*/
"use strict";
this.adj = [];
for (var i = 0; i < this.adjIds.length; i++) {
var check = nodeDB.getNode(this.adjIds[i]);
if (check) {
this.adj.push(check);
}
}
},
distanceFrom: function (n2) {
"use strict";
return Math.sqrt(
Math.pow(this.x - n2.x, 2) + Math.pow(this.y - n2.y, 2)
);
},
addAdjId : function(id){
"use strict";
this.adjIds.push(id);
},
addBuilding : function(buildingName){
"use strict";
this.buildings.push(buildingName.toString().toUpperCase());
},
isAdjToBuilding : function(buildingName){
"use strict";
return (this.buildings.indexOf(buildingName.toString().toUpperCase()) !== -1);
},
addRoom : function(roomName){
"use strict";
this.rooms.push(roomName.toString().toUpperCase());
},
isAdjToRoom : function(roomName){
"use strict";
return (this.rooms.indexOf(roomName.toString().toUpperCase()) !== -1);
},
addClass : function(classNum){
"use strict";
this.classes.push(parseInt(classNum));
},
isAdjToClass : function(classNum){
"use strict";
return (this.classes.indexOf(parseInt(classNum)) !== -1);
},
setConnectionImage: function (id, url) {
// invoked by importImages in import data file
// sets the image going from this node to node with id equal to the id passed
"use strict";
this.connectionImages[id] = url;
},
getHasImage: function (id) {
// returns whether or not an image has been given showing the area
//between this node and node with id equal to the id passed
"use strict";
return this.connectionImages.hasOwnProperty(id);
},
getImageTo: function (id) {
// returns the image of going from this node to node with id equal to the id passed
"use strict";
return this.connectionImages[id];
},
draw : function (canvas) {
"use strict";
canvas.setColor("red");
canvas.rect(this.x, this.y, 5, 5);
},
drawId : function(canvas){
"use strict";
canvas.setColor("red");
canvas.text(this.id, this.x, this.y);
},
drawLinks: function (canvas) {
// draws lines connecting this node to its adjacent nodes
"use strict";
canvas.setColor("red");
this.drawId(canvas);
for (var j = 0; j < this.adj.length; j++) {
this.adj[j].draw(canvas);
canvas.line(this.x, this.y, this.adj[j].x, this.adj[j].y);
}
},
generateDiv: function (main) {
// used for testing
"use strict";
var node = this;
var canvas = main.getCanvas();
var f = function () {
node.draw(canvas);
node.drawLinks(canvas);
};
var f2 = function (){
canvas.clear();
var path = main.getPath();
if (path !== undefined) {
path.draw(canvas);
}
main.getNodeDB().generateDivs(main);
};
var f3 = function(){
console.log(node);
};
node.drawId(canvas);
canvas.rect(this.x, this.y, 10, 10).mouseover(f).mouseout(f2).click(f3);
}
};
|
PHP
|
UTF-8
| 6,630 | 2.515625 | 3 |
[] |
no_license
|
<?php
namespace App\Http\Controllers\Admin\Property;
use App\CustomServices\ImageService;
use App\Property;
use App\PropertyFloorPlan;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Session;
class PropertyFloorPlanController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index($propertyId)
{
//
$property = Property::findOrFail($propertyId);
$propertyFloors = PropertyFloorPlan::where('property_id',$property->id)->latest()->get();
dd($propertyFloors);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
return redirect('/admin');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request,$propertyId)
{
$validator = Validator::make($request->all(), [
'floor_title' =>'required|max:191',
'floor_description'=>'required',
'floor_price' => 'required|integer',
'floor_area_size' => 'required|integer',
'floor_area_size_postfix' => 'required|max:191',
'floor_bedrooms' => 'required',
'floor_bathrooms' => 'required',
'floor_image' =>'sometimes|nullable|image',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput()
->with('tabName','floor_plan');
}
$property = Property::findOrFail($propertyId);
//continue if only property exists
$floor = new PropertyFloorPlan();
$floor->floor_title = ucwords(strtolower($request->floor_title));
$floor->property_id = $property->id;
$floor->floor_description = $request->floor_description;
$floor->floor_price = $request->floor_price;
$floor->floor_price_postfix = $request->floor_price_postfix;
$floor->floor_area_size = $request->floor_area_size;
$floor->floor_area_size_postfix = $request->floor_area_size_postfix;
$floor->floor_bedrooms = $request->floor_bedrooms;
$floor->floor_bathrooms = $request->floor_bathrooms;
//save floor Image
if ($request->hasFile('floor_image')) {
$filenameToStore=ImageService::saveImage($request->file('floor_image'));
$floor->floor_image=$filenameToStore;
}
$floor->save();
Session::flash('success', 'New Floor Has Been Added!');
return redirect()->back()->with('tabName','floor_plan');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
return redirect('/admin');
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Request $request,$propertyId,$id)
{
$property = Property::findOrFail($propertyId);
$floor = PropertyFloorPlan::where('property_id',$property->id)->where('id',$id)->first();
if ($request->ajax()) {
return view('admin.pages.property.property.floor.floor-edit-ajax', compact('floor','property'))->render();
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request,$propertyId,$id)
{
$validator = Validator::make($request->all(), [
'floor_title' =>'required|max:191',
'floor_description'=>'required',
'floor_price' => 'required|integer',
'floor_area_size' => 'required|integer',
'floor_area_size_postfix' => 'required|max:191',
'floor_bedrooms' => 'required',
'floor_bathrooms' => 'required',
'floor_image' =>'sometimes|nullable|image',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
$property = Property::findOrFail($propertyId);
//continue if only property exists
$floor = PropertyFloorPlan::where('property_id',$property->id)->where('id',$id)->first();
$floor->floor_title = $request->floor_title;
$floor->property_id = $property->id;
$floor->floor_description = $request->floor_description;
$floor->floor_price = $request->floor_price;
$floor->floor_price_postfix = $request->floor_price_postfix;
$floor->floor_area_size = $request->floor_area_size;
$floor->floor_area_size_postfix = $request->floor_area_size_postfix;
$floor->floor_bedrooms = $request->floor_bedrooms;
$floor->floor_bathrooms = $request->floor_bathrooms;
//save floor Image
if ($request->hasFile('floor_image')) {
$filenameToStore=ImageService::saveImage($request->file('floor_image'));
$oldFileName=$floor->floor_image;
$floor->floor_image=$filenameToStore;
//delete image from Server
if (!empty($oldFileName) && $floor->floor_image == $filenameToStore) {
//delete the old photo
ImageService::deleteImage($oldFileName);
}
}
$floor->save();
Session::flash('success', 'Floor Has Been Updated!');
return redirect()->back()->with('tabName','floor_plan');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($propertyId,$id)
{
$property = Property::findOrFail($propertyId);
//continue if only property exists
$floor = PropertyFloorPlan::where('property_id',$property->id)->where('id',$id)->first();
$imageToBeDeleted=$floor->floor_image;
//delete floor image
ImageService::deleteImage($imageToBeDeleted);
$floor->delete();
Session::flash('success', 'Floor Has Been Deleted!');
//redirect
return redirect()->route('property.edit',$property->id)->with('tabName','floor_plan');
}
}
|
Java
|
UTF-8
| 1,909 | 2.03125 | 2 |
[] |
no_license
|
package com.hiramexpress.controller;
import com.alibaba.druid.util.StringUtils;
import com.hiramexpress.domain.Result;
import com.hiramexpress.domain.enums.ResultEnum;
import com.hiramexpress.service.AnalysisExpress;
import com.hiramexpress.service.CheckExpress;
import com.hiramexpress.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class ExpressController {
private final CheckExpress checkExpress;
private final AnalysisExpress analysisExpress;
@Autowired
public ExpressController(CheckExpress checkExpress, AnalysisExpress analysisExpress) {
this.checkExpress = checkExpress;
this.analysisExpress = analysisExpress;
}
@PostMapping("/check")
public Result<?> checkExpressWithCode(String shipperCode, String logisticCode, boolean useAnalysis, String analysisPlatform) throws Exception {
if (StringUtils.isEmpty(shipperCode) || StringUtils.isEmpty(logisticCode)) {
return ResultUtil.error(ResultEnum.ERROR);
}
return checkExpress.checkExpress(shipperCode, logisticCode, useAnalysis, analysisPlatform);
}
@GetMapping("/count")
public Result<?> getCount() {
return checkExpress.getCount();
}
@GetMapping("/list")
public Result<?> getExpressList() {
return checkExpress.getExpressList();
}
@GetMapping("/analysis")
public Result<?> analysisExpress(@RequestParam("logisticCode") String logisticCode) {
return analysisExpress.analysis(logisticCode);
}
@PostMapping("/rate")
public Result<?> rate(String message, String email, int stars) {
return checkExpress.rate(message, email, stars);
}
@GetMapping("/statistics")
public Result<?> statistics() {
return checkExpress.statistics();
}
}
|
Python
|
UTF-8
| 834 | 4.25 | 4 |
[] |
no_license
|
# Pairs with Specific Difference
# Given an array arr of distinct integers and a nonnegative integer k, write a function findPairsWithGivenDifference
# that returns an array of all pairs [x,y] in arr, such that x - y = k. If no such pairs exist, return an empty array.
# Note: the order of the pairs in the output array should maintain the order of the y element in the original array.
# Examples:
# input: arr = [0, -1, -2, 2, 1], k = 1
# output: [[1, 0], [0, -1], [-1, -2], [2, 1]]
# input: arr = [1, 7, 5, 3, 32, 17, 12], k = 17
# output: []
# Time
# O(n)
# n = len(arr)
# Space
# O(n)
# n = len(arr)
def find_pairs_with_given_difference(arr, k):
elementsSet = set(arr)
answer = []
for num in arr:
if num + k != num and num + k in elementsSet:
answer.append([num + k, num])
return answer
|
C++
|
UTF-8
| 2,486 | 2.625 | 3 |
[] |
no_license
|
// Setup the server to receive data over WiFi
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
// Configuration parameters for Access Point
char * ssid_ap = "Tazer Tag";
char * password_ap = "TazerTag";
IPAddress ip(192,168,11,4); // arbitrary IP address (doesn't conflict w/ local network)
IPAddress gateway(192,168,11,1);
IPAddress subnet(255,255,255,0);
// Set up the server object
ESP8266WebServer server;
// Keep track of the sensor data that's going to be sent by the client
String tmpString = "";
unsigned int temp = 0;
int tag = 0;
//Set HTML
//HTML
String html_1 = R"=====(
<!DOCTYPE html>
<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1.0'/>
<meta charset='utf-8'>
<meta http-equiv='refresh' content='5'>
<style>
body {font-size:110%;}
#main {display: table; margin: auto; padding: 0 12px 0 12px; }
#temp {display:table; margin auto; padding: 0 8px 0 8px; }
h2 {text-align:center; }
p { text-align:center; }
</style>
<title>Tazer Tag Score Board</title>
</head>
<body>
<div id='main'>
<h2>Tazer Tag Score</h2>
<div id='temp'>
<p>Temp = %temp%</p>
</div>
</div>
</body>
</html>
)=====";
void setup() {
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(ip,gateway,subnet);
WiFi.softAP(ssid_ap,password_ap);
// Print IP Address as a sanity check
Serial.begin(115200);
Serial.println();
Serial.print("IP Address: "); Serial.println(WiFi.localIP());
// Configure the server's routes
server.on("/",handleIndex); // use the top root path to report the last sensor value
server.on("/update",handleUpdate); // use this route to update the sensor value
server.begin();
}
void loop() {
// put your main code here, to run repeatedly:
server.handleClient();
//tmpString = html_1;
html_1.replace("%temp%", String(temp));
html_1.replace("%tag%", String(tag) );
//Serial.println(String(temp));
temp = String(temp).toFloat();
Serial.print("Tag = ");Serial.println(tag);
delay(1000);
Serial.print("Temp = "); Serial.println(temp);
}
void handleIndex() {
server.send(200,"text/html", html_1); // we'll need to refresh the page for getting the latest value
}
void handleUpdate() {
// The value will be passed as a URL argument
temp = server.arg("value").toFloat();
//Serial.println(temp);
//server.send(200,"text/plain","Updated");
}
|
Markdown
|
UTF-8
| 537 | 3.125 | 3 |
[] |
no_license
|
# Typed Array
## Syntax
---
From a length:
```js
let int8 = new Int8Array(2);
int8[0] = 42;
console.log(int8[0]); // 42
console.log(int8.length); // 2
console.log(int8.BYTES_PER_ELEMENT); // 1
```
From an array:
```js
let arr = new Int8Array([21, 31]);
console.log(arr[1]); // 31
```
## Reference
---
- [Typed Array Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
- [Array Literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Array_literals)
|
Java
|
UTF-8
| 537 | 3.28125 | 3 |
[] |
no_license
|
import java.util.*;
public class Solution {
public int strStr(String haystack, String needle) {
int ans = 0;
if(needle.equals("")) return ans;
int l = needle.length();
for(int i=0;i<=haystack.length()-l;i++){
for(int j = 0;j<l;j++){
if(haystack.charAt(i+j) != needle.charAt(j)) break;
if((j == l-1) && haystack.charAt(i+j) == needle.charAt(j)){
return i;
}
}
}
return -1;
}
public static void main(String [] args) {
Solution obj = new Solution();
System.out.println(obj.strStr("aa","aa"));
}
}
|
PHP
|
UTF-8
| 4,440 | 2.609375 | 3 |
[] |
no_license
|
<?php
// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
//345678901234567890123456789012345678901234567890123456789012345678901234567890
/**
* Holder of {@link tgif_compiler_library}
*
* @package tgiframework
* @subpackage ui
* @copyright c.2010 terry chay
* @license GNU Lesser General Public License <http://www.gnu.org/licenses/lgpl.html>
*/
// {{{ tgif_compiler_library
/**
* Interface for an external compiler library.
*
* Implement these static methods to extend the functionality of a compiler.
*
* @package tgiframework
* @subpackage ui
* @author terry chay <tychay@php.net>
*/
interface tgif_compiler_library
{
// SIGNATURE METHODS:
// {{{ - generateSignature($fileName,$compileObj)
/**
* Figure a way of making a signature unique
*
* @param string $fileName the name of the library file
* @param tgif_compiler $compilerObj for introspection as needed (for
* instance, you want to recursively call generate signature.
* @return string the signature
*/
public function generateSignature($fileName, $compileObj);
// }}}
// {{{ - generateFileData($fileName,$compileObj)
/**
* Turn a file name into file data
*
* @param string $fileName the name of the library file
* @param tgif_compiler $compilerObj for introspection as needed (for
* instance, you want to recursively call generate signature.
* @return array The library file's filedata, empty if no match
*/
public function generateFileData($fileName,$compileObj);
// }}}
// {{{ - compileFile($sourceFileData,$targetFileName,$targetFilePath,$compilerObj)
/**
* Turn a file name into file data
*
* @param array $sourceFileData The file data of the resource. This will
* be modified to the target file data if successful.
* @param string $targetFileName The file name of the destination file
* @param string $targetFilePath The path to a physically unique file to
* place the destination file.
* @param tgif_compiler $compilerObj for introspection as needed. For
* instance it may be useful to call {@link
* tgif_compiler::compileFileInternal() compileFileInternal()} to further
* compress a file.
* @return boolean success or failure
*/
public function compileFile(&$sourceFileData, $targetFileName, $targetFilePath, $compilerObj);
// }}}
// {{{ - compileFileService($sourceFileData,$targetFileName,$targetFilePath,$compilerObj)
/**
* Turn a file name into file data via a "service" (delayed call).
*
* Note that if service is on, then even if the result is instanteous,
* it is always assumed to have "failed".
*
* @param array $sourceFileData The file data of the resource. This will
* be modified to the target file data if successful.
* @param string $targetFileName The file name of the destination file
* @param string $targetFilePath The path to a physically unique file to
* place the destination file.
* @param tgif_compiler $compilerObj for introspection as needed
* @return boolean success or failure
*/
public function compileFileService(&$sourceFileData, $targetFileName, $targetFilePath, $compilerObj);
// }}}
// {{{ - catFiles(&$fileDatas,$compilerObj)
/**
* Allow you to catenate files at the front (or in place).
*
* @param array $fileDatas a list of file data to catenate together. You
* can manipulate this result set however you want. But be warned, if you
* do no purge all library instances, this will get ugly.
* @param tgif_compiler $compilerObj for introspection as needed (for
* instance, you are replacing the object in place with a local file
* version)
* @return array a list of file data that is separate from regular file
* catenation.
*/
public function catFiles(&$fileDatas, $compilerObj);
// }}}
// {{{ - generateUrl($fileData)
/**
* Turn a file data into a full URL.
*
* Note if the resource is really a local file. then it is suggested you
* modify {@link cat_files()} to remove the 'library' property for these
* files and let the automated routine handle it.
*
* @param string $fileData The data to extract the URL for
* @return string the url
*/
public function generateUrl($fileData);
// }}}
}
// }}}
?>
|
Markdown
|
UTF-8
| 3,106 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
# bacterial-analysis
## The project has been deployed: https://knishina-otu-bacteria.herokuapp.com/
<br />
### Summary.
The [Dunn Lab](http://robdunnlab.com/projects/belly-button-biodiversity/) performed a survey study to assess the diversity of bacteria in in participants' belly buttons. The samples were subjected to PCR for the 16S rRNA gene, sequenced, and analysed for the type of bacterial strain. The bacterial strain is listed as its operational taxonomic unit (OTU). The data was made public and was ripe for analysis and visualization. Consequently, this project was to take the data, clean it, and build an interactive web-based dashboard. The following were used: `Pandas, Numpy, SQLAlchemy` for `Plotly` for data visualization, and `Flask, JavaScript, HTML/CSS/Bootstrap` for front-end and deployment.

<br />
### Features.
The navigation block is in the upper left part of the page. Samples are selected by this drop-down menu and the corresponding data is visualized in the three plots.

<br />
#### Data Block: Sample MetaData.
The Data Block contains data associated with the selected sample. The data displayed includes the participant's age, belly button type, ethnicity, gender, location, and sample ID.

<br />
#### Plot: Pie Chart.
The first plot is a pie chart. This chart displays a maximum of the top ten bacteria found in each sample. The legend indicates the identification number of the bacteria species seen in the chart. For more information about the bacteria, over the pie chart. A text box will display the species ID of the bacteria, the full classification of the bacteria, the number of bacteria in the sample, and the percent of the whole sample.

<br />
#### Plot: Gauge.
The second plot is a gauge. The gauge indicates the freqeuncy of belly button washes performed by the participant. It is interesting to observe if there is a correlation between bacterial type/quantity and the number of belly button washes.

<br />
#### Plot: Bubble Chart.
The third plot is a bubble plot. This chart displays all bacteria found per sample. The size of the bubble indicates the quantity of the bacterial strain found, which is also represented by the y-axis. The x-axis of the plot is the bacterial species ID. A text box will display the species ID of the bacteria, the quantity of that bacteria found, and the full classification of the bacteria.

<br />
### License.
This project is licensed under the MIT License - see the [LICENSE](https://github.com/knishina/bacterial-analysis/blob/master/LICENSE) file for details.
|
Markdown
|
UTF-8
| 5,507 | 2.828125 | 3 |
[] |
no_license
|
# Information Handling Policy
There are many types of confidential and sensitive information passing through Made Tech at any given moment. It is important that we as a company ensure that we are handling this information responsibly and in a secure way. If sensitive information is communicated to an unauthorised, and potentially malicious, party - there could be severe consequences.
An Information Handling policy encourages seucre working practices amongst our team, both in our offices and whilst working remotely. It also helps us remain ISO 27001 compliant.
## General Guidelines:
All sensitive information (anything other than Public) is subject to the following information handling and disposal procedures:
- Passwords which provide access to sensitive information must not be given to any unauthorised person See our [Password and 2FA policy](password_and_2fa.md) for more details
- Device screens should be locked with a password when not in use and not left unattended for any reason. See our [Clear Desk/Clear Screen Policy](clear_desk_clear_screen.md) for more details.
- Devices used to handle Made Tech or client related information should not be misused or placed at risk of theft, damage or misuse. See our [Device Security Policy](device_security.md) for more information.
- Users shall not try to disable or alter the antivirus software settings on their device
## When not at the Made Tech offices
When not at Made Tech offices you should ensure and hard copies of Made Tech information are
- Supervised during printing and removed from the printer immediately when complete.
- Not left unattended on a desk at any time.
- Stored in a secured cupboard / drawer when not in use.
- Mass storage devices (such as USB drives etc.) containing internal information should not be left unattended and should be stored securely.
- When Internal information is no longer required (either in hard or electronic copy) it is destroyed and/or deleted appropriately
- Information should not be stored locally, but on the backed up to an appropraite Made Tech tool. For more information, see below.
## Store data in Made Tech tools
Made Tech data should be stored in Made Tech tools. Check what your team is using.
Sensitive data (personal information for example user research, or commercial information for example contracts) can be stored on the Google Team Drive for your team, unless the data subject or owner has requested that the data does not go ‘off-shore’ (where data is processed or stored outside of the UK) for example, to the US.
Regardless of where it’s stored, you should ensure data is appropriately secured and backed up. Made Tech’s G Suite is backed up by automatically, but data on your Made Tech laptop is not.
If you can’t work on a Made Tech tool, make a local copy instead. Make sure you update the Made Tech tool version when possible, and then delete your local copy in a way that the files can’t be recovered.
Information should always be stored on the Made Tech provided services such as GitHub and G Suite. Information should never be downloaded onto a laptop unless there is a specific business need for the information to be available remotely and there is no suitable network connection available. When this is the case the information should be uploaded back to the server as soon as is practicable and the information on the laptop securely erased.
## What happens if an unauthorised party gains access to Made Tech information?
Any event which involves an unauthorised party gaining of access to any Made Tech information (other than information classified as Public) will be handled in accordance with our event logging procedure.
This includes, but is not limited to:
- Loss, theft, or unauthorised release of information in electronic or hard copy form, or equipment upon which the data is stored.
- Virus infection.
- Evidence of unauthorised access or use of your laptop, PC or passwords.
## Social Engineering
Leaving sensitive and confidential information in easy to access places is not the only way attackers can gain unauthorised access. Social engineering also makes us vulnerable. Attackers will use techniques to gain your trust, take advantage of inattention, or capitalise on your desire to be helpful to obtain information.
### Remain vigilant for anyone asking you to:
- Provide sensitive information about any aspect of our business, (contact numbers, username / password combos)
- Perform an action that is unusual or costly, (close down a customer system ‘immediately’)
- Download and opening a file you weren’t expecting
- Click on a link in an email or message that you don’t recognize, e.g. an invoice from iTunes or any other familiar supplier)
- Do something that ‘just doesn’t feel right’, particularly if you’re put under a lot of pressure.
### It is always ok to:
- Be sceptical of unusual requests
- Challenge (politely) any request from an unexpected or unfamiliar source
- Verify the identity of a requester before sharing information
- When in doubt, do not respond!
### Finally:
It's always better to be safe than sorry. Always check with the IMS Manager or CSO if you think something is amiss.
# Related Standards, Policies and Processes
- [Acceptable Use Policy](aup.md)
- [Password and 2FA Policy](password_and_2fa.md)
- [Clear Desk/Clear Screen Policy](clear_desk_clear_screen.md)
- [How to report an incident](link)
- [Device Security Policy](device_security.md)
|
Java
|
UTF-8
| 2,050 | 4 | 4 |
[] |
no_license
|
import java.util.*;
/**
* @author yangxing
* @version 1.0
* @date 2020/8/24 0024 17:18
* 98. 验证二叉搜索树
* 给定一个二叉树,判断其是否是一个有效的二叉搜索树。
*
* 假设一个二叉搜索树具有如下特征:
*
* 节点的左子树只包含小于当前节点的数。
* 节点的右子树只包含大于当前节点的数。
* 所有左子树和右子树自身必须也是二叉搜索树。
* 示例 1:
*
* 输入:
* 2
* / \
* 1 3
* 输出: true
* 示例 2:
*
* 输入:
* 5
* / \
* 1 4
* / \
* 3 6
* 输出: false
* 解释: 输入为: [5,1,4,null,null,3,6]。
* 根节点的值为 5 ,但是其右子节点值为 4 。
*/
public class IsValidBST {
public static void main(String[] args) {
TreeNode root = new TreeNode(7);
TreeNode right = new TreeNode(1);
root.right = right;
System.out.println(isValidBST2(root));
}
public static boolean isValidBST(TreeNode root) {
if (root == null) return true;
TreeNode cur = root;
double last = - Double.MAX_VALUE;
int curNum = root.val;
Deque<TreeNode> deque = new ArrayDeque<>();
while(cur != null || !deque.isEmpty()){
while (cur != null){
deque.push(cur);
cur = cur.left;
}
cur = deque.pop();
if (cur.val <= last) return false;
last = cur.val;
cur = cur.right;
}
return true;
}
public static boolean isValidBST2(TreeNode root) {
return helper(root,null,null);
}
private static boolean helper(TreeNode root, Integer lower, Integer upper) {
if (root == null) return true;
int cur = root.val;
if (lower != null && cur <= lower) return false;
if (upper != null && cur >= upper) return false;
if(!helper(root.left,lower,cur)) return false;
if(!helper(root.right,cur,upper)) return false;
return true;
}
}
|
C#
|
UTF-8
| 344 | 2.609375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnTheFly.Helpers
{
public static class StringHelpers
{
public static string PrettyArray<T>(this IEnumerable<T> items)
{
return $"[{string.Join(", ", items)}]";
}
}
}
|
Python
|
UTF-8
| 285 | 2.875 | 3 |
[] |
no_license
|
import bisect
n = int(input())
A = sorted(list(map(int, input().split())))
B = sorted(list(map(int, input().split())))
C = sorted(list(map(int, input().split())))
ans = 0
for b in B:
a = bisect.bisect_left(A, b)
c = bisect.bisect_right(C, b)
ans += a * (n - c)
print(ans)
|
Java
|
UTF-8
| 1,041 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
package io.eyolas.http.query.collection;
/**
* Type of QueryList
*
* @author eyolas
*/
public enum QueryListType {
/**
* <p>
* No bracket and no index.</p>
*
* <p>
* Example:<br>
* With list : Arrays.asList("asse", "psg", "om"); and key club<br>
* result: ?club=asse&club=psg&club=om
* </p>
*/
NONE,
/**
* <p>
* With bracket.</p>
*
* <p>
* Example:<br>
* With list : Arrays.asList("asse", "psg", "om"); and key club<br>
* result: ?club[]=asse&club[]=psg&club[]=om
* </p>
*/
BRACKET,
/**
* <p>
* Indexed</p>
* <p>
* Example:<br>
* With list : Arrays.asList("asse", "psg", "om"); and key club<br>
* result: ?club[0]=asse&club[1]=psg&club[2]=om
* </p>
*/
INDEXED,
/**
* <p>
* Semicolon</p>
*
* <p>
* Example:<br>
* With list : Arrays.asList("asse", "psg", "om"); and key club<br>
* result: ?club=asse;psg;om
* </p>
*/
SEMICOLON;
}
|
SQL
|
UTF-8
| 1,711 | 3.21875 | 3 |
[
"Apache-2.0"
] |
permissive
|
--
-- Name: v_analysis_request_jobs_list_report; Type: VIEW; Schema: public; Owner: d3l243
--
CREATE VIEW public.v_analysis_request_jobs_list_report AS
SELECT j.job,
j.priority,
js.job_state AS state,
tool.analysis_tool AS tool_name,
ds.dataset,
j.param_file_name AS param_file,
j.settings_file_name AS settings_file,
org.organism,
j.organism_db_name AS organism_db,
j.protein_collection_list,
j.protein_options_list AS protein_options,
j.comment,
j.created,
j.start AS started,
j.finish AS finished,
(j.progress)::numeric(9,2) AS job_progress,
(j.eta_minutes)::numeric(18,1) AS job_eta_minutes,
j.batch_id AS batch,
j.request_id,
(((dfp.dataset_folder_path)::text || '\'::text) || (j.results_folder_name)::text) AS results_folder,
(j.processing_time_minutes)::numeric(9,2) AS runtime_minutes,
ds.dataset_id
FROM (((((public.t_analysis_job j
JOIN public.t_dataset ds ON ((j.dataset_id = ds.dataset_id)))
JOIN public.t_organisms org ON ((j.organism_id = org.organism_id)))
JOIN public.t_analysis_tool tool ON ((j.analysis_tool_id = tool.analysis_tool_id)))
JOIN public.t_analysis_job_state js ON ((j.job_state_id = js.job_state_id)))
LEFT JOIN public.v_dataset_folder_paths dfp ON ((j.dataset_id = dfp.dataset_id)));
ALTER TABLE public.v_analysis_request_jobs_list_report OWNER TO d3l243;
--
-- Name: TABLE v_analysis_request_jobs_list_report; Type: ACL; Schema: public; Owner: d3l243
--
GRANT SELECT ON TABLE public.v_analysis_request_jobs_list_report TO readaccess;
GRANT SELECT ON TABLE public.v_analysis_request_jobs_list_report TO writeaccess;
|
Java
|
UTF-8
| 2,089 | 2.078125 | 2 |
[] |
no_license
|
package org.iesalixar.jmoreno.proyecto.controller;
import java.util.Optional;
import org.iesalixar.jmoreno.proyecto.model.Orders;
import org.iesalixar.jmoreno.proyecto.service.OrdersService;
import org.iesalixar.jmoreno.proyecto.service.ProvidersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class OrdersController {
@Autowired
private OrdersService ordersService;
@Autowired
private ProvidersService providersService;
@GetMapping("/administracionArea/listorders")
public String listOrders(Model model) {
model.addAttribute("listorders", ordersService.findAll());
return "listorders";
}
@GetMapping("/administracionArea/ordersmodify/{id}")
public String modifyOrders(@PathVariable("id")Long id, Model model) {
Optional<Orders> orders = ordersService.getId(id);
model.addAttribute("orders", orders.get());
return "modifyOrder";
}
@PostMapping("/administracionArea/ordersmodify/submit")
public String modifyOrdersSubmit(@ModelAttribute Orders orderm) {
ordersService.modifyOrders(orderm);
return "redirect:/administracionArea/listorders";
}
@GetMapping("/administracionArea/ordersdelete/{id}")
public String deleteOrders(@PathVariable("id") Long id) {
ordersService.eliminar(id);
return "redirect:/administracionArea/listorders";
}
@GetMapping("/administracionArea/ordersnew")
public String orderNew(Model model) {
model.addAttribute("orders", new Orders());
model.addAttribute("providers", providersService.findAll());
return "formOrders";
}
@PostMapping("/administracionArea/ordersnew/submit")
public String orderNewSubmit(@ModelAttribute Orders orders) {
ordersService.save(orders);
return "redirect:/administracionArea";
}
}
|
JavaScript
|
UTF-8
| 3,758 | 2.78125 | 3 |
[] |
no_license
|
////// DATA ////////////////////////////////////////////////////////////////////
/// Current data
let slaveName = ""; // This comes from the cloud save data and retrieved with "getSlaveDetailStorage()"
let masterName = ""; // This comes from the cloud saved data and retrieved with "getMasterDetailStorage()"
let foundSlaveJsonArrayIndex = 0; // This comes from an API Search
let slaveCSSObject = {}; // This comes from the API to be sent to the content.JS
/// Server URLS
const SLAVE_URL = "https://prnkstrserver.herokuapp.com/users.json";
const MASTER_URL = "https://prnkstrserver.herokuapp.com/masters.json";
////// FUNCTIONS ///////////////////////////////////////////////////////////////
/// Retrieving slave name from cloud storage
const getSlaveDetailStorage = function() {
chrome.storage.sync.get( "slaveName", function( result ) {
slaveName = ( result.slaveName );
} );
}
/// Retrieving master name from cloud storage
const getMasterDetailStorage = function() {
chrome.storage.sync.get( "masterName", function( result ) {
masterName = ( result.masterName );
} );
}
/// Iterating through the API to find a slave match. It then returns the ID number to 'foundSlaveJsonArrayIndex'
const slaveDataGetter = function() {
$.getJSON( SLAVE_URL )
.done( ( response ) => {
for ( let i = 0; i < response.length; i += 1 ) {
// Iterating over Users.json response looking for match against local storage 'slaveName'
if ( slaveName === '"' + response[ i ].name + '"' ) {
// console.log( "Match found! Array possition " + response[ i ] );
foundSlaveJsonArrayIndex = [ i ] // this remebers the ID of the slave found
}
}
} )
.done( ( response ) => {
console.log( response );
slaveCSSObject = {
"fill_murray": response[ foundSlaveJsonArrayIndex ].fill_murray,
"place_cage": response[ foundSlaveJsonArrayIndex ].place_cage,
"custom_header": response[ foundSlaveJsonArrayIndex ].custom_header,
"custom_header_text": response[ foundSlaveJsonArrayIndex ].custom_header_text,
"paragraph_background": response[ foundSlaveJsonArrayIndex ].paragraph_background,
"paragraph_color": response[ foundSlaveJsonArrayIndex ].paragraph_color,
"snap": response[ foundSlaveJsonArrayIndex ].snap,
"stranger_things": response[ foundSlaveJsonArrayIndex ].stranger_things,
"page_flip": response[ foundSlaveJsonArrayIndex ].page_flip,
"otherside": response[ foundSlaveJsonArrayIndex ].otherside,
"marquee": response[ foundSlaveJsonArrayIndex ].marquee,
"marquee_element": response[ foundSlaveJsonArrayIndex ].marquee_element,
"marquee_speed": response[ foundSlaveJsonArrayIndex ].marquee_speed,
"unicorn_mode": response[ foundSlaveJsonArrayIndex ].unicorn_mode,
"word_swapper": response[ foundSlaveJsonArrayIndex ].word_swapper,
"existing_word": response[ foundSlaveJsonArrayIndex ].existing_word,
"new_word": response[ foundSlaveJsonArrayIndex ].new_word,
"hidden_video": response[ foundSlaveJsonArrayIndex ].hidden_video,
"hidden_video_url": response[ foundSlaveJsonArrayIndex ].hidden_video_url,
"hidden_video_element": response[ foundSlaveJsonArrayIndex ].hidden_video_element
,
}
})
}
/// This function is fired on page reload
chrome.tabs.onUpdated.addListener( function( tabId, changeInfo, tab ) {
console.log( changeInfo );
getSlaveDetailStorage(); // Getting the Slave Data from Storage
getMasterDetailStorage() // Getting the Masters details from storage
if ( tab.status === "loading" ) {
slaveDataGetter() // Ping API for values for DOM manipulation object.
} else if ( tab.status === "complete" ) {
chrome.tabs.query( { active: true }, function( tabs ) {
chrome.tabs.sendMessage( tabs[ 0 ].id, slaveCSSObject );
} );
}
} )
|
C++
|
UTF-8
| 2,657 | 3.125 | 3 |
[] |
no_license
|
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
class NGUOI
{
private:
char ht[30];
char scm[10];
char gt[4];
public:
NGUOI()
{
}
NGUOI(char *ht,char *scm,char *gt)
{
strcpy(this->ht,ht);
strcpy(this->scm,scm);
strcpy(this->gt,gt);
}
void set()
{
cout<<"Ho Ten :";
cin.ignore();
cin.getline(ht,30);
cout<<"So chung minh :";
cin.getline(scm,10);
cout<<"Gioi tinh :";
cin.getline(gt,4);
}
void get()
{
cout<<left<<setw(32)<<ht;
cout<<left<<setw(12)<<scm;
cout<<left<<setw(5)<<gt;
}
};
class CN : public NGUOI
{
private:
char cv[20];
float sn;
public:
CN()
{
}
CN(char *ht, char* scm, char* gt , char* cv,float sn):NGUOI(ht,scm,gt)
{
strcpy(this->cv,cv);
this->sn,sn;
}
~CN()
{
}
friend istream& operator >> (istream& is, CN &cn)
{
cn.set();
cin.ignore();
cout<<"Cong viec :";
is.getline(cn.cv,20);
cout<<"So nam lam viec :";
is>>cn.sn;
return is;
}
friend ostream& operator << (ostream& os, CN &cn)
{
cn.get();
cout<<left<<setw(25)<<cn.cv;
cout<<left<<setw(5)<<cn.sn<<endl;
}
float getsn()
{
return float (sn);
}
void xeploai_CN()
{
if(sn >=0.0 || sn<=2.9)
{
cout<<"So cap";
}
else if(sn >=3.0 || sn<=9.9)
{
cout<<"Trung cap";
}
else
{
cout<<"Cao cap";
}
}
friend bool operator >= (CN cn1, CN cn2)
{
return cn1.getsn() > cn2.getsn();
}
void sort_sn(CN cn[],int n)
{
for(int i=0; i<n; i++)
{
for(int j=i+1; j<n; j++)
{
if(cn[i].sn > cn[j].sn)
{
CN temp= cn[i];
cn[i]= cn[j];
cn[j]=temp;
}
}
cout<<cn[i]<<endl;
}
}
};
void title()
{
cout<<left<<setw(5)<<"STT";
cout<<left<<setw(32)<<"Ho Va Ten";
cout<<left<<setw(12)<<"SCM";
cout<<left<<setw(5)<<"Gioi tinh"<<endl;
}
void title2()
{
cout<<left<<setw(5)<<"STT";
cout<<left<<setw(32)<<"Ho Va Ten";
cout<<left<<setw(12)<<"SCM";
cout<<left<<setw(15)<<"Gioi tinh";
cout<<left<<setw(25)<<"Chuyen Nganh";
cout<<left<<setw(10)<<"Tich Luy";
cout<<left<<setw(10)<<"Xep loai"<<endl;
}
main()
{
int n,stt=0,stt1=0;
cout<<"So luong nguoi :";
cin>>n;
NGUOI *ng = new NGUOI[n];
for(int i=0; i<n; i++)
{
ng[i].set();
}
title();
for(int i=0; i<n; i++)
{
ng[i].get();
}
CN *cn= new CN[n];
for(int i=0; i<n; i++)
{
cin>>cn[i];
}
title2();
for(int i=0; i<n; i++)
{
cout<<cn[i];
}
cout<<"Danh sach sap xep tang dan :"<<endl;
for(int i=0; i<n; i++)
{
cn[i].sort_sn(cn,n);
}
}
|
Markdown
|
UTF-8
| 1,140 | 3.359375 | 3 |
[] |
no_license
|
---
layout: post
title: "Handling strings containing quotes in SQL"
date: 2010-02-26
category: vba
tags:
- access
- quote
- sql
- string
- vba
---
Everyone is aware that quotes in strings used in SQL cause all sorts of
problems. As developers, it is our duty to ensure that an end user
never sees an SQL error because we didn't handle his input
appropriately!
But how the heck do you ensure that quotes are handled
correctly? The following function will take a string and return it
enclosed with quotes and all instances of quotes in the string will be
doubled up.
For example if I call QuotedString("This is a "string" example") then it
will return:
"This is ""a string"" example"
```vb
Public Function QuotedString( _
strText As String) As String
Const conQuoteChar = """"
QuotedString = conQuoteChar _
& Replace$(strText, conQuoteChar, conQuoteChar & conQuoteChar) _
& conQuoteChar
End Function
```
NOTE: you should always check for specific methods designed to escape
strings in whatever framework you are using. I had to roll my own
because Microsoft Access.
|
Java
|
UTF-8
| 970 | 3.328125 | 3 |
[] |
no_license
|
package com.javarush.task.task04.task0413;
/*
День недели
*/
import java.io.*;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws Exception {
//напишите тут ваш код
String s = "";
int i = new Scanner(new InputStreamReader(System.in)).nextInt();
switch(i){
case 1: s = "понедельник";
break;
case 2: s = "вторник";
break;
case 3: s = "среда";
break;
case 4: s = "четверг";
break;
case 5: s = "пятница";
break;
case 6: s = "суббота";
break;
case 7: s = "воскресенье";
break;
default: s = "такого дня недели не существует";
break;
}
System.out.println(s);
}
}
|
Java
|
UTF-8
| 20,718 | 2.078125 | 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 userinterface.StudentRole;
import Business.AccomodationData.SellAccomodation;
import Business.AccomodationData.SellAccomodationDirectory;
import Business.Enterprise.Enterprise;
import Business.HouseholdData.Household;
import Business.HouseholdData.HouseholdDirectory;
import Business.Logging.MyLogging;
import Business.Organization.AssisstantManagerOrganization;
import Business.Organization.ManagerOrganization;
import Business.Organization.Organization;
import Business.Organization.StudentOrganization;
import Business.UserAccount.UserAccount;
import Business.WorkQueue.AccomodationAssisstantManagerWorkRequest;
import Business.WorkQueue.BookstoreAssisstantManagerWorkRequest;
import Business.WorkQueue.HouseholdAssisstantManagerWorkRequest;
import Business.WorkQueue.HouseholdWorkRequest;
import Business.WorkQueue.WorkRequest;
import java.awt.CardLayout;
import java.awt.Component;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
import userinterface.AssistantManagerRole.AssistantAccomodationManagerWorkAreaJPanel;
/**
*
* @author Jaynee
*/
public class SellHouseholdJPanel extends javax.swing.JPanel {
/**
* Creates new form SellAccomodationJPanel
*/
HouseholdDirectory householdDir;
JPanel userProcessContainer;
Enterprise enterprise;
UserAccount userAccount;
Organization organization;
public SellHouseholdJPanel(JPanel userProcessContainer, Enterprise enterprise, UserAccount userAccount,Organization organization) {
initComponents();
this.householdDir = new HouseholdDirectory();
this.userProcessContainer=userProcessContainer;
this.enterprise=enterprise;
this.userAccount=userAccount;
this.organization=(StudentOrganization)organization;
firstNameText.setText(userAccount.getUsername()+"");
populateData();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
quantityComboBox = new javax.swing.JComboBox();
costText = new javax.swing.JTextField();
filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0));
createButton = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
firstNameText = new javax.swing.JTextField();
jScrollPane2 = new javax.swing.JScrollPane();
sellHouseholdTable = new javax.swing.JTable();
furnitureTypeText = new javax.swing.JTextField();
viewSoldRequestsButton = new javax.swing.JButton();
backJButton = new javax.swing.JButton();
chatButton = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
setBackground(new java.awt.Color(0, 153, 153));
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel1.setText("Furniture type");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setText("Quantity");
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setText("Cost");
quantityComboBox.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
quantityComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));
costText.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
createButton.setBackground(new java.awt.Color(102, 102, 102));
createButton.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
createButton.setText("SELL");
createButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createButtonActionPerformed(evt);
}
});
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel7.setText("Username");
firstNameText.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
firstNameText.setEnabled(false);
sellHouseholdTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null}
},
new String [] {
"Username", "Furniture Type", "Quantity", "Cost", "Status", "Result"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(sellHouseholdTable);
if (sellHouseholdTable.getColumnModel().getColumnCount() > 0) {
sellHouseholdTable.getColumnModel().getColumn(0).setResizable(false);
sellHouseholdTable.getColumnModel().getColumn(1).setResizable(false);
sellHouseholdTable.getColumnModel().getColumn(2).setResizable(false);
sellHouseholdTable.getColumnModel().getColumn(3).setResizable(false);
sellHouseholdTable.getColumnModel().getColumn(4).setResizable(false);
sellHouseholdTable.getColumnModel().getColumn(5).setResizable(false);
}
furnitureTypeText.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
viewSoldRequestsButton.setBackground(new java.awt.Color(102, 102, 102));
viewSoldRequestsButton.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
viewSoldRequestsButton.setText("VIEW SOLD REQUESTS");
viewSoldRequestsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewSoldRequestsButtonActionPerformed(evt);
}
});
backJButton.setBackground(new java.awt.Color(102, 102, 102));
backJButton.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
backJButton.setText("BACK");
backJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backJButtonActionPerformed(evt);
}
});
chatButton.setBackground(new java.awt.Color(102, 102, 102));
chatButton.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
chatButton.setText("CHAT");
chatButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chatButtonActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel3.setText("HOUSEHOLD SELLING WORK AREA");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(396, 396, 396)
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(100, 100, 100)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(backJButton)
.addGap(26, 26, 26)
.addComponent(jLabel3))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(46, 46, 46)
.addComponent(firstNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel2)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(furnitureTypeText, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
.addComponent(quantityComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(costText)))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 541, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(141, 141, 141)
.addComponent(createButton, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(53, 53, 53)
.addComponent(viewSoldRequestsButton)
.addGap(45, 45, 45)
.addComponent(chatButton)))
.addGap(195, 195, 195))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(backJButton)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(firstNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(furnitureTypeText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(quantityComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(82, 82, 82)
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(costText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(createButton, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
.addComponent(viewSoldRequestsButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(chatButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
}// </editor-fold>//GEN-END:initComponents
public void populateData()
{
DefaultTableModel model = (DefaultTableModel) sellHouseholdTable.getModel();
model.setRowCount(0);
// for(Household household: householdDir.getHouseholdDataList())
// {
// Object row[] = new Object[10];
// row[0]=household.getfName();
// row[1]=household.getFurnitureType();
// row[2]=household.getQuantity();
// row[3]=household.getCost();
// row[4] = household.getStatus();
// String result = household.getResult();
// row[5] = result == null ? "Waiting" : result;
// ((DefaultTableModel) sellHouseholdTable.getModel()).addRow(row);
// }
for(HouseholdWorkRequest request : userAccount.getWorkQueue().getHouseholdWorkRequests()){
Object[] row = new Object[6];
row[0] = request.getfName();
row[1] = request.getFurnitureType();
row[2]=request.getQuantity();
row[3]=request.getCost();
row[4]=request.getStatus();
String result = ((HouseholdAssisstantManagerWorkRequest) request).getTestResult();
row[5] = result == null ? "Waiting" : result;
model.addRow(row);
}
}
private void createButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createButtonActionPerformed
double cost =0.0;
int quantity = Integer.parseInt(quantityComboBox.getSelectedItem()+"");
try{
cost =Double.parseDouble(costText.getText());
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Enter a valid number for the cost of furniture");
return;
}
String furnitureType =furnitureTypeText.getText();
String fname= userAccount.getUsername();
String status = "Pending";
if(fname != null && fname.trim().length()>0 &&
furnitureType != null && furnitureType.trim().length()>0)
{
householdDir.sellHouseholdInformation(furnitureType, cost, quantity, fname,status);
populateData();
//code to generate the sell request of student in the queue of Manager
HouseholdAssisstantManagerWorkRequest request = new HouseholdAssisstantManagerWorkRequest();
request.setFurnitureType(furnitureType);
request.setQuantity(quantity);
request.setCost(cost);
request.setfName(fname);
request.setStatus("Pending");
Organization managerOrg = null;
Organization studentOrg =null;
Organization assistantManagerOrg=null;
for (Organization organization : enterprise.getOrganizationDirectory().getOrganizationList()){
if (organization instanceof ManagerOrganization){
managerOrg = organization;
break;
}
}
for (Organization organization : enterprise.getOrganizationDirectory().getOrganizationList()){
if (organization instanceof StudentOrganization){
studentOrg = organization;
break;
}
}
for (Organization organization : enterprise.getOrganizationDirectory().getOrganizationList()){
if (organization instanceof AssisstantManagerOrganization){
assistantManagerOrg = organization;
break;
}
}
if (managerOrg!=null && studentOrg!=null && assistantManagerOrg!=null ){
managerOrg.getWorkQueue().getHouseholdWorkRequests().add(request);
//adding student request only to current student's account so that when other students log in they cant see current students request
userAccount.getWorkQueue().getHouseholdWorkRequests().add(request);
assistantManagerOrg.getWorkQueue().getHouseholdWorkRequests().add(request);
}
populateData();
}
else
{
JOptionPane.showMessageDialog(null, "Please enter all the value.");
}
MyLogging.log(Level.INFO, userAccount.getUsername()+ " from " + enterprise +" Enterprise posted a sell request on dashboard");
}//GEN-LAST:event_createButtonActionPerformed
private void viewSoldRequestsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewSoldRequestsButtonActionPerformed
SoldHouseholdJPanel soldhouse = new SoldHouseholdJPanel(userProcessContainer,enterprise,userAccount,organization);
userProcessContainer.add("SoldHouseholdJPanel", soldhouse);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}//GEN-LAST:event_viewSoldRequestsButtonActionPerformed
private void backJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backJButtonActionPerformed
userProcessContainer.remove(this);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.previous(userProcessContainer);
}//GEN-LAST:event_backJButtonActionPerformed
private void chatButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chatButtonActionPerformed
// TODO add your handling code here:
System.out.println("2");
TestChat_Client cc = new TestChat_Client();
//chat_client cc = new chat_client();
cc.setVisible(true);
System.out.println("21");
}//GEN-LAST:event_chatButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton backJButton;
private javax.swing.JButton chatButton;
private javax.swing.JTextField costText;
private javax.swing.JButton createButton;
private javax.swing.Box.Filler filler1;
private javax.swing.JTextField firstNameText;
private javax.swing.JTextField furnitureTypeText;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel7;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JComboBox quantityComboBox;
private javax.swing.JTable sellHouseholdTable;
private javax.swing.JButton viewSoldRequestsButton;
// End of variables declaration//GEN-END:variables
}
|
Markdown
|
UTF-8
| 8,102 | 3.046875 | 3 |
[] |
no_license
|
# Galactic Index (planetary trade simulation data)
## Overview
### What is this site for?
This site is a tool to view data pulled from a planetary trading simulation, involving buying/selling of minerals, and companies trying to profit from the available simulated market.
### What does it do?
This site will allow people to view data on individual planets, their names, climate, amounts of resources and the prices those are bought and sold at, as well as companies, with names and locations.
### How does it work?
The front end of the site will make extensive use of D3, DC and crossfilter for visualisation of the data, the backend will run on a Flask framwork. It will also use a snapshot of data from a MongoDB database.
The graphs will allow the users to view detailed info on both companies and planets and about what minerals they own/sell. These pages will implement a feature to switch on-page between individual planet data for quick browsing between them. The front page will feature graphs which cover more broad data about the subject and make more use of crossfilter and DC to allow users to see how the different data relates.
### Design Choices
For this project I was interested in creating my own dataset for the project that would create quite a few different statistics to measure. I created a Python Project that Uploaded data to a mongoDB database, which can be found [here](https://github.com/kaiforward/GalacticIndex). It's a simulation of planets and companies interacting by buying and selling minerals from each other and all the data associated with them.
I was interested in trying MongoDb to see how it worked differently than MySQL, I found it was difficult to access the data from the simulation which was heavily nested, but managed to find a good working solution.
To show all this data I knew I wanted to make use of crossfilter and DC for some of the broader data. It would allow the user to crossfilter data on planets and companies, comparing data between the individuals in each.
To show data for individual planets and companies, I decided to dedicate the full page to graphs and information on one company/planet and allow the user to switch between them on-page, which would let them see new information much more quickly. As there is a lot of data that needed to be shown this was the best approach I could think of.
I had lots of issues designing the UI for this as it was hard to have the graphs resizable for different screen sizes.
### Existing Features
- Homepage that lets users crossfilter and view data about companies and planets.
- Planets Page that lets users view and interact with more detailed information about planets.
- Company Page that lets users view and interact with more detailed information about companies.
## Tech Used
### Some of the tech used includes:
- [Bootstrap](http://getbootstrap.com/)
- I use **Bootstrap** to include some useful layout functionality like tabs.
- [JQuery](https://jquery.com/)
- **JQuery** is used for extra front-end functionality.
- [D3](https://d3js.org/)
- **D3** is used along with other graphic libraries to visualise the data.
- [Crossfilter](https://github.com/square/crossfilter)
- **Crossfilter** is used to refine the data for use in our D3 and DC graphs.
- [DC](https://dc-js.github.io/dc.js/)
- **DC** is used to extend my graphs functionality and improve user experience.
- [MONGODB](https://www.mongodb.com/)
- **MongoDB** was used to store the snapshot of data the site uses for the graphs and other information.
- [FLASK](http://flask.pocoo.org/)
- **FLASK** is used as the framwork for this project.
## Contributing
Firstly you will need to clone this repository by running the git clone <project's Github URL> command
Then make sure you have downloaded and installed pycharm, there is a free community edition that works fine for this set-up.
- [Pycharm](https://www.jetbrains.com/pycharm/)
This project uses Python version 2.7.14
- [Python 2.7.14](https://www.python.org/downloads/)
### Set up a virtual environment
- Open the project Root folder in Pycharm and in the menu navigate to file > settings.
- Then in the menu look for project:Galactic-index > ProjectInterpreter.
- Using the Wheel icon select CreateVirtualEn to create virtual environment for this project.
- Then using the + symbol, add the dependencies found in the requirements.txt files in the project root folder.
Now everything should be working correctly you can use the play button at the top right of the pycharm screen to run the local server.
Just choose myrouting.py from the dropdown and click the http link in the console window when the server has loaded.
## My Deployment
After signing up to [Heroku](https://signup.heroku.com/) and [installing](https://devcenter.heroku.com/articles/heroku-cli) it, I created a new Heroku app from the Heroku dashboard.
I then installed gunicorn using the Project settigns in Pycharm, but could also install to the command line using:
```
pip install gunicorn
```
to create a requirements file I navigated to the folder where my virtual environments are stored and saved the requirements using:
```
pip freeze --local > requirements.txt
```
or if already running the chosen ENV in the command line.
```
pip freeze > requirements.txt
```
To tell Heroku what to do when opening the website, I created a new file and named it Profcile and inside it include:
```
web: gunicorn school_donations:app
```
Because I am using windows I also added a Procfile.windows which included:
```
web: python school_donations.py
```
To test the server locally after these changes use, for windows:
```
heroku local -f Procfile.windows
```
On Mac/Linux
```
heroku local
```
After pushing these changes to github. we tell heroku to start a 'worker' by typing into the command line:
```
heroku ps:scale web=1
```
The next step was to connect the server to some data from mongoDB.
- After installing MLab MongoDB from the Hroku Add-ons page I created a user with the name root.
- I then copied the commands to connect to mongo shell using my DBuser and DBpassword. I was then able to create a collection for my data.
- Then I input this command using my personal db user settings, hostname, dbname and my datafile:
```
mongoimport -h <hostname> -d <dbname> -c <collectionname> -u <dbuser> -p <dbpassword> --file opendata_projects_clean.csv --type csv --headerline
```
Then I could check in Mongo Management studio wether the data had been sucessfully uploaded.
### Modify routing.py
After checking the data was sucessfully uploaded, the names in my .py files needed to be changed from my local database to the data stored on the server, by changing from MONGODB_HOST, PORT AND NAME to the MONGO_URI given by heroku in the settings tab.
Then push the changes to heroku/git with:
```
git push heroku master
```
The project is ready to be opened with
```
heroku open
```
or can be opened through the heroku dashboard.
### References
Lot's of the code was influenced by learning on the LMS as well as asking questions or finding solutions to them found on stack overflow and it was a great help in completing this project.
### Issues and testing
So the main issues I faced when doing this project was overcoming the learning curve of crossfilter, DC and D3. The site still has styling issues caused by misunderstanding of the different values associated with the different graphs. I also had a lot fo trouble styling the site because of the graphs static nature, having them be resizable would have helped a lot during the process of making the site and i wish i could have spent more time on perfecting it.
I found that cases where I tried to use the graphs differently that the standard, it was hard to modify them to suit the exact needs that I had and perhaps in future would have found it more useful to look more closely at D3 instead of DC. As a user i would prefer clear, readable graphs rather than quite buggy responsive ones. Without fully understanding the way DC works it is definitely hard to get the best out of it.
|
Shell
|
UTF-8
| 749 | 4.21875 | 4 |
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env bash
gitPull(){
echo "git pull"
git pull
}
function getDir(){
echo "path: "$1
for fileName in `ls -a $1`
do
current_path=$1"/"${fileName}
if [ ${fileName} == ".git" ];then
gitPull
elif [ -d ${current_path} ] && [ ${fileName} != "." -a ${fileName} != ".." ];then
getDir ${current_path}
fi
done
}
read -p "Please input a path: " path
ask_yes_or_no() {
read -p "$1 ([Y / y] yes or [N / n] no): "
case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
Y|y|yes) echo "yes" ;;
*) echo "no" ;;
esac
}
if [ "yes" != $(ask_yes_or_no "Do you want to continue? ") ]; then
exit
else
getDir ${path}
fi
|
Go
|
UTF-8
| 1,144 | 2.625 | 3 |
[] |
no_license
|
package main
import (
"fmt"
"net"
)
func main() {
// 创建监听
socket, err := net.ListenUDP("udp4", &net.UDPAddr{
IP: net.IPv4(127, 0, 0, 1),
Port: 2222,
})
if err != nil {
fmt.Println("监听失败!", err)
return
} else {
fmt.Println("监听成功!", err)
}
defer socket.Close()
for {
// 读取数据
data := make([]byte, 2048)
read, remoteAddr, err := socket.ReadFromUDP(data)
if err != nil {
fmt.Println("读取数据失败!", err)
continue
}
fmt.Println(read, remoteAddr)
fmt.Printf("%s\n", data)
// 发送数据
senddata := []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?><cjstudio type=\"CS_REPLY\" seq=\"0\"><From><IPAddress>127.0.0.1</IPAddress><Port>3333</Port><UserID>1001</UserID><Name>cjstudio</Name></From><To><IPAddress>127.0.0.1</IPAddress><Port>2222</Port><UserID>10000</UserID><Name>server</Name></To><Data><Text>hello serverPC</Text></Data><Hash>DBA1C38D01372E18CE34C24695215270</Hash></cjstudio>")
_, err = socket.WriteToUDP(senddata, remoteAddr)
if err != nil {
return
fmt.Println("发送数据失败!", err)
}
}
}
|
JavaScript
|
UTF-8
| 4,314 | 2.84375 | 3 |
[] |
no_license
|
;(function($){
var sortAnimate = {
list: '.unsorted-list',
btnCreateList: '.btn-create-list',
btnSortList: '.btn-sort-list',
arrRandom: [],
textSort: '.text-sort',
sortInfo: '.sort-info',
init: function(){
this.showListClick( this.btnCreateList, this.list );
this.showSortListClick( this.btnSortList, this.list );
},
//----------------------------generate random arr
randomArr: function(length){
var arr = [];
for (var i = 0; i < length; i++){
arr.push( Math.round( Math.random() * 10 ));
}
return arr;
},
//------------------------------create list from random arr
createList: function(arr, list){
$(list).empty().removeClass('in');
for (var i = 0; i < arr.length; i++){
$(list).append('<li data-num="' + arr[i] +'">' + arr[i] + '</li>');
}
setTimeout(function() { $(list).addClass('in') },200);
},
//------------------------------sort list from random arr
sortList: function(arr, list){
var tmp;
var tmpY;
var that = this;
that.startSorting();
for (var i = arr.length - 1, time = 1; i > 0; i--) {
for (var j = 0; j < i; j++) { //--обход массива каждым элемнетом
setTimeout( showSort(j, i) , 500 * (++time) ); //таймаут для каждого обхода - для визуализации обхода
function showSort(j, i){
return function(){
$(list + ' li').eq(j).addClass('active');
if (arr[j] > arr[j+1]) {
tmp = arr[j];
tmpY = parseInt( $(list + ' li').eq(j).css('transform').split(',')[5] );
$(list + ' li').eq(j).css('transform', 'translate(0,' + parseInt( $(list + ' li').eq(j+1).css('transform').split(',')[5]) + 'px)');
arr[j] = arr[j+1];
$(list + ' li').eq(j+1).css('transform', 'translate(0,' + tmpY + 'px)');
arr[j+1] = tmp;
setTimeout(callbackInsert(j), 300);
//------------изменение порядка li в dom
function callbackInsert(j){
return function(){
$(list + ' li').eq(j).insertAfter( $(list + ' li').eq(j+1) );
}
}
}
setTimeout(function(){ $(list + ' li.active').removeClass('active'); }, 400);
if ( i == 1) {that.endSorting();}
}
}
}
}
},
//--------------------------------start sort status
startSorting: function(){
$(this.textSort).text('list sorting...');
$(this.btnCreateList).prop('disabled', true);
$(this.btnSortList).prop('disabled', true);
$(this.sortInfo).css('display', 'none');
$(this.sortInfo).find('div').eq(0).html( 'Before sort: ' + this.arrRandom);
},
//---------------------------------end sort status
endSorting: function(){
$(this.textSort).text('list sorting ended');
$(this.btnCreateList).prop('disabled', false);
$(this.btnSortList).prop('disabled', false);
$(this.sortInfo).css('display', 'block');
$(this.sortInfo).find('div').eq(1).html('After sort: ' + this.arrRandom);
},
//-------------------------------show list from random arr
showListClick: function(btn, list){
var that = this;
$('body').on('click', btn, function(){
that.arrRandom = that.randomArr(9);
that.createList(that.arrRandom, list);
$(that.btnSortList).prop('disabled', false);
});
},
//---------------------------------show sort list
showSortListClick: function(btn, list){
var that = this;
$('body').on('click', btn, function(){
that.sortList(that.arrRandom, list);
});
}
};
sortAnimate.init();
}(jQuery));
|
Java
|
UTF-8
| 947 | 2.421875 | 2 |
[] |
no_license
|
package cn.mh.springboottest.sharding;
import java.util.Collection;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
public class AdminPreciseAlgorithm implements PreciseShardingAlgorithm<Integer> {
@Override
public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Integer> shardingValue) {
String tmp = "";
System.out.println(availableTargetNames);
System.out.println(shardingValue);
if (!shardingValue.getLogicTableName().equalsIgnoreCase("student")) {
return "ds0";
}
for (String tableName : availableTargetNames) {
if (shardingValue.getValue() < 5) {
if (tableName.endsWith("0")) {
tmp = tableName;
break;
}
} else {
if (tableName.endsWith("1")) {
tmp = tableName;
break;
}
}
}
System.out.println(tmp);
return tmp;
}
}
|
Markdown
|
UTF-8
| 5,146 | 2.625 | 3 |
[] |
no_license
|
[![LinkedIn][linkedin-shield]][linkedin-url]
[![Twitter][twitter-shield]][twitter-url]
<a href="https://discord.gg/3tHHD4VUKW"><img src="https://img.shields.io/discord/733027681184251937.svg?style=flat&label=Join%20Community&color=7289DA" alt="Join Community Badge"/></a>
<img src="assets/composable-logo.png" alt="Composable Finance logo" title="Composable Finance logo" width="400" height="400">
## Reimagining Parachain Auctions with an Ethereum Vault Strategy
Amidst all of the hype in the DeFi space over parachains, Composable Finance is introducing a new solution which allows for participation in our parachain with ETH or any ERC-20 token asset, rather than purchasing DOT/KSM and leaving it to sit. With our novel approach, we expand our ability to stake DOT/KSM and allow for users to continue to gain profits on their staked assets.
Parachain vault strategies [details](https://composablefi.medium.com/reimagining-parachain-auctions-with-an-ethereum-vault-strategy-a0dcc3481759).
Users participating through our strategies get:
- Exposure to Composable Tokens
- Exposure to Polkadot parachain auction
- Exposure to DOT/KSM
- Yield on staking
- Minting our cross-layer stablecoin, Equal Cash off the receipt token from the vault
In addition to its direct benefits to users, this strategy fits into our overall mission as a platform; one of our main goals is connecting the spaces of Ethereum and Polkadot, and that begins even at the parachain auction level.
## Parachain Auction Tokens
Parachain Auction Tokens (or pAT) are the receipt token minted for participation in our parachain vault strategy, representing a user’s stake in the vault. Whenever someone deposits in our vault strategies, they get back pAT in an amount depending upon their investment and strategy type.
If we take for example the Harvest stablecoins strategies, whenever you invest Token (Dai/Usdc/Usdt), you’ll get back fToken (fDai/fUsdc/fUsdt). The value of fToken is usually a bit lower than the amount of Token you invested.
For example, investing $100 in DAI in the Harvest DAI strategy, will get you around 95 fDai and the amount of pAT you’ll receive is equal to the amount of fDai, which is 95 in this case.
Each strategy has its own pAT token, similar to how an AMM transfers LP tokens once you add liquidity. One of the use cases for pAT is to mint EQLC (our stablecoin). This provides additional capital efficiency by having a stablecoin collateralized by locked funds. This will be released at a later date.
## Risks
Parachain vault strategies provide an annual percentage yield (APY) for users who invest and at the same time gives ETH or stable coin holders exposure to KSM/DOT auctions, opening gates that were chained shut in the past.
Opportunities for yield farming have inherent risks associated with them. Please take note of the following risk associated with our solution:
#### Smart Contract Related Risks
Even though smart contracts are known for being a stable and a secure way of processing data, bugs can still be discovered.
Attempted remediation for this risk includes the following:
- Trail of Bits audited our solution and changes have been reviewed by Stela Labs.
- Our cap for the vault will slowly be increased over time.
- Composable’s contracts themselves don’t keep user’s funds, rather re-routing them to yield farms that have several thousand users associated with them.
#### Market Related Risks
The fluctuation of assets is also an obvious market-related concern. Our strategies, depending on the one you chose to invest into, might swap your initial asset to another. In case of a withdrawal, that asset is swapped back to your initial one. The amount you receive back plus the APY depends on the price variation between the initial asset and the under the hood asset.
Remediation for this risk includes the following:
- We tackle this risk by providing a boosted APY generated by Composable Tokens, which are distributed at the token generation event (TGE) and after the launch event.
- Each strategy will illustrate exactly what happens under the hood in order for users to determine for themselves if they are comfortable taking on a given level of risk.
- To further mitigate market risk, all the strategies supported through Composable use assets with high liquidity in most AMMs, making it harder for people to manipulate them.
#### Yield Farms' Related Risks
All the risks associated with any dApp are also available in the case of yield farming through Composable.
Remediation for this risk includes the following:
- In order to have a high APY and a higher degree of stability, we chose to connect to farms that were proven to be strong performers so far.
<!-- MARKDOWN LINKS & IMAGES -->
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?logo=linkedin&colorB=555
[linkedin-url]: https://www.linkedin.com/company/composable-finance
[twitter-shield]: https://img.shields.io/twitter/follow/ComposableFin?style=social
[twitter-url]: https://twitter.com/ComposableFin
|
Python
|
UTF-8
| 1,551 | 3.25 | 3 |
[] |
no_license
|
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
self.solution2(nums)
def solution1(self, nums):
non_zero = 0
zero = 0
# 迴圈終點
while non_zero < len(nums) and zero < len(nums):
# 找到第1個0的位置
while zero < len(nums) and nums[zero] != 0:
zero += 1
non_zero = zero + 1
# 找到第1個非0的位置
while non_zero < len(nums) and nums[non_zero] == 0:
non_zero += 1
# 互換位置
if zero < len(nums) and non_zero < len(nums):
nums[zero], nums[non_zero] = nums[non_zero], nums[zero]
# 下一個尋找的起始點
zero += 1
def solution2(self, nums):
zero_counter = 0
i = 0
while i < len(nums)-zero_counter:
if nums[i] == 0:
# 如果遇到0就往前shift
nums[i:-zero_counter-1] = nums[i+1:len(nums)-zero_counter]
# 紀錄尾巴的地方要塞幾個零,len(nums)-zero_counter也是新的邊界所在
zero_counter += 1
else:
# 如果非0的話就要繼續看一下一個
i += 1
# 用0把尾巴填滿
nums[-zero_counter:] = [0 for i in range(zero_counter)] if zero_counter > 0 else nums
|
JavaScript
|
UTF-8
| 1,155 | 2.625 | 3 |
[] |
no_license
|
export default class Sprite {
constructor(data,z) {
this.z = z
this.sx = data.sx
this.sy = data.sy
this.dxOffsetX = data.dxOffsetX || 0
this.dxOffsetY = data.dxOffsetY || 0
this.width = data.width
this.height = data.height
this.frames = data.frames
this.currentFrame = 0
this.animationSpeed = data.speed || 1
this.flip = false
this.loop = true
this.frozen = false
this.rotation = 0
this.tick = 0
}
set(data) {
this.sx = data.sx
this.sy = data.sy
this.width = data.width
this.height = data.height
this.frames = data.frames
this.loop = true
this.animationSpeed = data.speed || 1
this.frozen = false
this.tick = 0
this.currentFrame = 0
}
animate() {
if (this.frames > 1 && !this.frozen) {
if (!this.loop && this.tick / (this.frames - 1) > 1) {
return
}
this.currentFrame = Math.floor(this.tick % this.frames)
this.tick += this.animationSpeed
}
}
}
|
JavaScript
|
UTF-8
| 1,843 | 2.515625 | 3 |
[] |
no_license
|
ig.module(
'game.entities.girl'
)
.requires(
'impact.entity'
)
.defines(function() {
EntityGirl = ig.Entity.extend({
SIGHT_RANGE_SQUARED: 90000,
SIGHT_ANGLE: 10,
animSheet: new ig.AnimationSheet('media/girl.png', 667, 337),
size: { x: 180, y: 180 },
offset: { x: 200, y: 10 },
direction: { x: 0, y: 0 },
directionAngleSpeed: 0.5,
clockwise: true,
init: function(x, y, settings) {
this.parent(x, y, settings);
this.addAnim('idle', 1.0 / 30.0, ig.Utils.getNumberRangeArray(0, 59));
this.canSeePlayer = window.canSeePlayerFunction.bind(this);
},
update: function() {
this.updateDirection();
if (!ig.game.gamePlaying) {
this.parent();
return;
}
if (this.canSeePlayer()) {
ig.game.lose('player seen by girl');
} else {
var player = ig.game.getPlayer();
if (player) {
if (this.touches(player)) {
ig.game.win();
}
}
}
this.parent();
},
updateDirection: function() {
var percentage = this.currentAnim.frame / 30.0;
var directionAngle;
if (percentage > 1) {
percentage -= 1;
directionAngle = ig.Utils.lerp(Math.PI * 0.85, Math.PI * 0.1, percentage);
} else {
directionAngle = ig.Utils.lerp(Math.PI * 0.1, Math.PI * 0.85, percentage);
}
this.direction = {
x: Math.cos(directionAngle),
y: Math.sin(directionAngle)
};
this.direction = ig.Utils.normalize(this.direction);
},
center: function() {
var center = {
x: this.pos.x + (this.size.x / 2),
y: this.pos.y + (this.size.y / 2)
};
return {
x: center.x + 10,
y: center.y - 60
};
},
canSeePlayer: function() { return false; }
});
});
|
JavaScript
|
UTF-8
| 2,096 | 2.640625 | 3 |
[] |
no_license
|
const fs = require('fs')
const axios = require('axios')
const crypto = require('crypto')
var https = require('follow-redirects').https;
axios.get ('https://api.codenation.dev/v1/challenge/dev-ps/generate-data?token=d33ff9445b219ec0d37ad83ce1a73fbc9ba218f9')
.then(res => {
let cifrado = res.data.cifrado
console.log(decode(cifrado));
res.data.decifrado = decode(cifrado)
const hash = crypto.createHash('sha1')
.update('microsoft is not the answer. microsoft is the question. "no" is the answer. unknown')
.digest('hex');
console.log(hash);
res.data.resumo_criptografico = hash
fs.appendFile('answer.json', JSON.stringify(res.data), 'utf-8', error => console.log(error))
console.log(res.data);
})
const decode = str => {
return str.toLowerCase().split('').map(letter => {
if (/[a-z]/g.test(letter)) {
let decifrarCode = letter.charCodeAt(0) - 12
if (decifrarCode < 97)
{
return String.fromCharCode(decifrarCode + 26)
} else {
return String.fromCharCode(decifrarCode)
} ;
}
return letter
}).join('')
}
var options = {
'method': 'POST',
'hostname': 'api.codenation.dev',
'path': '/v1/challenge/dev-ps/submit-solution?token=d33ff9445b219ec0d37ad83ce1a73fbc9ba218f9',
'headers': {
},
'maxRedirects': 20
};
var req = https.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function (chunk) {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
res.on("error", function (error) {
console.error(error);
});
});
var postData = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"answer\"; filename=\"answer.json\"\r\nContent-Type: \"{Insert_File_Content_Type}\"\r\n\r\n" + fs.readFileSync('/Users/Thiago/Desktop/desafio-codenation/answer.json') + "\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--";
req.setHeader('content-type', 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW');
req.write(postData);
req.end();
|
C++
|
UTF-8
| 1,074 | 3.734375 | 4 |
[] |
no_license
|
// InsertionSort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
/*
* The insertion sorting algorithm is not the efficient algorithm compared to selection sort
* the best case timecomplexity of this algorithm is O(n) and the worst case time compolexity
* of this algorithm is O(nPower2).
* Both the insertion and selection sorting algorithm have the same timecomplexity for the average and worst case
* the number of assignments and other operations involved in the insertion sort makes this algorithm even more infficient
* compare to the selection sort
*/
void InsertionSort(int *A, int size)
{
for (int i = 1; i < size; i++)
{
int hole = i;
int value = A[i];
while (hole > 0 && A[hole - 1] > value) {
A[hole] = A[hole - 1];
hole = hole - 1;
}
A[hole] = value;
}
}
int main()
{
int A[] = { 5, 2, 7, 1, 3, 8 };
InsertionSort(A, 6);
for (int i = 0; i < 6; i++) {
cout << A[i] << " ";
}
cout << endl;
return 0;
}
|
Markdown
|
UTF-8
| 383 | 3.34375 | 3 |
[] |
no_license
|
# Letter-Guessing-Game
A simple guessing game built with HTML5, CSS3, and vanilla Javascript/ES5.
* You are greeted by the computer who is “thinking” of a letter.
* Press any character on the keyboard to take a guess.
* After seven incorrect guesses, you lose.
* The computer will keep track of your score.
* To see what letter the computer is thinking of, open the console!
|
C#
|
UTF-8
| 525 | 2.9375 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* This component destroys object whenever it triggers a collider with the given tag.
*/
public class DestroyOnTrigger : MonoBehaviour {
[Tooltip("Every object tagged with this tag will trigger the destruction of this object")]
[SerializeField] string triggeringTag;
private void OnTriggerEnter(Collider collision) {
if (collision.tag == triggeringTag) {
Destroy(collision.gameObject);
}
}
}
|
C++
|
UTF-8
| 3,055 | 3.171875 | 3 |
[] |
no_license
|
#include <string>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "FragTrap.class.hpp"
FragTrap::FragTrap(void) : _name("Unamed minion") {
return;
}
FragTrap::FragTrap(std::string name) : _name(name), _hp(100), _maxHp(100), _ep(100), _maxEp(100), _lvl(1), _meleeDamage(30), _rangeDamage(20), _armor(5) {
(void)this->_lvl;
(void)this->_maxEp;
std::cout << "Jack: Claptrap -- start bootup sequence." << std::endl << "Claptrap: Directive one: Protect humanity! Directive two: Obey Jack at all costs. Directive three: Dance!" << std::endl;
return;
}
FragTrap::~FragTrap() {
std::cout << "Claptrap: I'M DEAD I'M DEAD OHMYGOD I'M DEAD!" << std::endl;
return;
}
FragTrap::FragTrap( FragTrap const & src ) {
// std::cout << "Copy constructor called" << std::endl;
*this = src;
return;
}
FragTrap & FragTrap::operator=( FragTrap const & rhs ) {
// std::cout << "Assignation operator called" << std::endl;
if (this != &rhs)
*this = rhs;
return *this;
}
void FragTrap::rangedAttack(std::string const & target) {
std::cout << "FR4G-TP " << this->_name << " attacks " << target << " at range, causing " << this->_rangeDamage << " points of damage !" << std::endl;
return;
}
void FragTrap::meleeAttack(std::string const & target) {
std::cout << "FR4G-TP " << this->_name << " attacks " << target << " at melee, causing " << this->_meleeDamage << " points of damage !" << std::endl;
return;
}
void FragTrap::takeDamage(unsigned int amount) {
if (amount - this->_armor > this->_hp) {
this->_hp = 0;
std::cout << "FR4G-TP " << this->_name << " takes too much damage and his hp falls to 0" << std::endl;
} else {
this->_hp = this->_hp - amount + this->_armor;
std::cout << "FR4G-TP " << this->_name << " takes damage and his hp are now " << this->_hp << std::endl;
}
return;
}
void FragTrap::beRepaired(unsigned int amount) {
if (amount > this->_maxHp - this->_hp) {
this->_hp = this->_maxHp;
std::cout << "FR4G-TP " << this->_name << " gets heal to max hp" << std::endl;
} else {
this->_hp += amount;
std::cout << "FR4G-TP " << this->_name << " gets heal and his hp are now " << this->_hp << std::endl;
}
return;
}
void FragTrap::vaulthunter_dot_exe(std::string const & target) {
if (this->_ep >= 25) {
this->_ep -= 25;
int randomInt = rand();
if (randomInt % 5 == 0) {
std::cout << "Hey " << target << " ! Step right up, to the Bulletnator 9000!" << std::endl;
} else if (randomInt % 5 == 1) {
std::cout << "Hey " << target << " ! I am a tornado of death and bullets!" << std::endl;
} else if (randomInt % 5 == 2) {
std::cout << "Hey " << target << " ! Fall before your robot overlord!" << std::endl;
} else if (randomInt % 5 == 3) {
std::cout << "Hey " << target << " ! Yo momma's so dumb, she couldn't think of a good ending for this 'yo momma' joke!" << std::endl;
} else if (randomInt % 5 == 4) {
std::cout << "Hey " << target << " ! Get ready for some Fragtrap face time!" << std::endl;
}
} else {
std::cout << "No more energy :(" << std::endl;
}
return;
}
|
C++
|
UTF-8
| 1,083 | 2.578125 | 3 |
[] |
no_license
|
#ifndef DISPLAYBRIDGE_H
#define DISPLAYBRIDGE_H
#include "../objects/DBTransform.h"
#include "../as3/ColorTransform.h"
#include "../glm/glm.hpp"
#include "../as3/Object.h"
class Texture;
namespace DragonBones {
class Image;
class DisplayObject;
class DisplayObjectContainer;
class DisplayBridge {
private:
DisplayObject* _display;
Image* _imageBackup;
Texture* _textureBackup;
float _pivotXBackup;
float _pivotYBackup;
public:
bool getVisible();
void setVisible(bool value);
Object* getDisplay();
void setDisplay(Object* value);
DisplayBridge();
~DisplayBridge();
void updateTransform(glm::mat4 matrix, DBTransform* transform);
void updateColor(
float aOffset,
float rOffset,
float gOffset,
float bOffset,
float aMultiplier,
float rMultiplier,
float gMultiplier,
float bMultiplier);
//Adds the original display object to another display object.
void addDisplay(DisplayObjectContainer* container, int index=-1);
//remove the original display object from its parent.
void removeDisplay();
};
}
#endif
|
Java
|
UTF-8
| 2,520 | 2.671875 | 3 |
[] |
no_license
|
package com.githubtools.githubtools.beantest;
import com.crossoverjie.distributed.lock.redis.RedisLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import javax.annotation.PostConstruct;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Configuration
public class BeansConfig {
@Autowired
private RedisLock redisLock ;
@PostConstruct
public void use() {
String key = "key";
String request = UUID.randomUUID().toString();
try {
boolean locktest = redisLock.tryLock(key, request);
if (!locktest) {
System.out.println("locked error");
return;
}
//do something
System.out.println("get lock and wait!");
} finally {
redisLock.unlock(key,request) ;
}
}
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 10, 50, TimeUnit.SECONDS, new ArrayBlockingQueue<>(90));
for (int i = 0; i <= 50; i++) {
pool.execute(new Runnable(){
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
pool.shutdown();
while (!pool.awaitTermination(1, TimeUnit.SECONDS)) {
System.out.println("still ... ");
}
long end = System.currentTimeMillis();
System.out.println("一共处理了【{}】" + (end - start));
}
@Bean
public RedisLock build(){
RedisLock redisLock = new RedisLock() ;
// HostAndPort hostAndPort = new HostAndPort("127.0.0.1",6379) ;
// JedisCluster jedisCluster = new JedisCluster(hostAndPort) ;
Jedis jedis = new Jedis("127.0.0.1", 6379);
// Jedis 或 JedisCluster 都可以
// redisLock.setJedisCluster(jedisCluster) ;
redisLock.setJedis(jedis);
return redisLock ;
}
}
|
C++
|
UTF-8
| 1,355 | 2.78125 | 3 |
[] |
no_license
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "RecursiveDivisionMaze.h"
#include <random>
#include "Random.h"
void RecursiveDivisionMaze::Init(int width, int height, bool isConneccted, bool InitAsMaze)
{
Grid::Init(width, height, isConneccted, InitAsMaze);
std::mt19937 RandomInt;
GenerateMaze(RandomInt, Point(0, 0), width, height, false);
}
void RecursiveDivisionMaze::GenerateMaze(std::mt19937& RandomInt, const Point& Origin, const int UsingWidth, const int UsingHeight, bool HorizontalCut)
{
if (UsingWidth < 2 || UsingHeight < 2) return;
int WallIdx = (HorizontalCut) ? Random::NextInt(UsingHeight - 1, 0) : Random::NextInt(UsingWidth - 1, 0);
int DoorIdx = (HorizontalCut) ? Random::NextInt(UsingWidth, 0) : Random::NextInt(UsingHeight, 0);
if (HorizontalCut)
{
DisconnectRow(Origin, WallIdx, UsingWidth, DoorIdx);
GenerateMaze(RandomInt, Origin, UsingWidth, WallIdx + 1, !HorizontalCut);
GenerateMaze(RandomInt, Point(Origin.X, Origin.Y + WallIdx + 1), UsingWidth, UsingHeight - WallIdx - 1, !HorizontalCut);
}
else
{
DisconnectCol(Origin, WallIdx, UsingHeight, DoorIdx);
GenerateMaze(RandomInt, Origin, WallIdx + 1, UsingHeight, !HorizontalCut);
GenerateMaze(RandomInt, Point(Origin.X + WallIdx + 1, Origin.Y), UsingWidth - WallIdx - 1, UsingHeight, !HorizontalCut);
}
}
|
JavaScript
|
UTF-8
| 2,436 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
/**
* @desc 组件库 Component.js
* @author yijie
* @date 2020-11-03 22:00
* @logs[0] 2020-11-03 22:00 yijie 创建了Component.js文件
*/
import deepDefine from '~/lib/tool/deepDefine'
const getComponentInstance = async (componentName: String) => {
const autoWiringComponents = deepDefine(global, [{
name: '$Quick-D',
default: {}
}, {
name: 'autoWiringComponents',
default: {}
}])
let waitTimes = 10
const getComponent = async (componentName) => {
const autoWiringComponent = autoWiringComponents[componentName]
if (autoWiringComponent === undefined || autoWiringComponent.status === 'wiring') {
return new Promise((resolve, reject) => {
setTimeout(_ => {
if (waitTimes === 0) {
reject(new Error('Component not found'))
return
}
waitTimes-=1
getComponent(componentName)
.then(resolve)
.catch(reject)
}, 500)
})
}
if (autoWiringComponent.status === 'wired') {
return autoWiringComponents[componentName]
} else {
throw new Error('Unknown Wiring status')
}
}
const Component = (await getComponent(
componentName.toLowerCase()
)).value
return new Component()
}
const QComponent = (componentName: String): ClassDecorator => {
return (originClass: Function): Function | void => {
const autoWiringComponents = deepDefine(global, [{
name: '$Quick-D',
default: {}
}, {
name: 'autoWiringComponents',
default: {}
}])
componentName = (componentName ?? originClass.name).toLowerCase()
autoWiringComponents[componentName] = {
status: 'wiring'
}
autoWiringComponents[componentName].value = originClass
autoWiringComponents[componentName].status = 'wired'
}
}
const QService = QComponent
const QModel = QComponent
const AutoWired = (componentName: String): PropertyDecorator => {
return (originClass: Object, propertyKey: String | Symbol): void => {
deepDefine(global, [{
name: '$Quick-D',
default: {}
}, {
name: 'components',
default: {}
}])
getComponentInstance(componentName ?? propertyKey)
.then(component => {
Object.assign(originClass.prototype, {
[propertyKey]: component
})
originClass[propertyKey] = component
})
}
}
export {
QService, QModel, QComponent,
AutoWired
}
|
Java
|
UTF-8
| 142 | 1.84375 | 2 |
[] |
no_license
|
package test2;
import test1.text.A;
public class B {
public static void main(String args[]){
A a = new A();
a.printA();
}
}
|
C++
|
UTF-8
| 2,760 | 3.375 | 3 |
[] |
no_license
|
#include "Generator.h"
#include <time.h>
#include <stdlib.h>
using namespace std;
Generator::Generator()
{
sectionTotalLenght = getRandRange (SECTION_MIN,SECTION_MAX);
sectionRemaingingLenght = sectionTotalLenght;
floorCurrent = getRandRange(FLOOR_MIN, FLOOR_MAX);
ceilingCurrent = getRandRange(CEILING_MIN, CEILING_MAX);
floorNext = getRandRange(FLOOR_MIN, FLOOR_MAX);
ceilingNext = getRandRange(CEILING_MIN, CEILING_MAX);
initBag();
}
Generator::~Generator()
{
}
void Generator::getNext (array<Square, WINDOW_H>& nextColumn )
{
generateWalls (nextColumn);
for (int i = floorCurrent + 1; i < ceilingCurrent; ++i)
{
nextColumn[i].setType(getFromBag());
}
}
void Generator::generateWalls(std::array<Square, WINDOW_H>& nextColumn)
{
if (sectionRemaingingLenght > 0)
{
nextColumn[floorCurrent].setType(WALL);
nextColumn[ceilingCurrent].setType(WALL);
--sectionRemaingingLenght;
}
else if (sectionRemaingingLenght == 0)
{
bool wallsUpToDate = true;
if (floorCurrent < floorNext)
{
++floorCurrent;
if (floorCurrent == floorNext)
{
nextColumn[floorCurrent].setType(WALL);
}
else
{
nextColumn[floorCurrent].setType(WALL_RIGHT);
wallsUpToDate = false;
}
}
else if (floorCurrent > floorNext)
{
--floorCurrent;
if (floorCurrent == floorNext)
{
nextColumn[floorCurrent].setType(WALL);
}
else
{
nextColumn[floorCurrent].setType(WALL_LEFT);
wallsUpToDate = false;
}
}
if (ceilingCurrent < ceilingNext)
{
++ceilingCurrent;
if (ceilingCurrent == ceilingNext)
{
nextColumn[ceilingCurrent].setType(WALL);
}
else
{
nextColumn[ceilingCurrent].setType(WALL_LEFT);
wallsUpToDate = false;
}
}
else if (ceilingCurrent > ceilingNext)
{
--ceilingCurrent;
if (ceilingCurrent == ceilingNext)
{
nextColumn[ceilingCurrent].setType(WALL);
}
else
{
nextColumn[ceilingCurrent].setType(WALL_RIGHT);
wallsUpToDate = false;
}
}
if (wallsUpToDate)
{
sectionRemaingingLenght = getRandRange(SECTION_MIN, SECTION_MAX);
floorNext = getRandRange(FLOOR_MIN, FLOOR_MAX);
ceilingNext = getRandRange(CEILING_MIN, CEILING_MAX);
}
}
}
SquareType Generator::getFromBag()
{
if (typeBag.empty())
{
initBag();
}
int index = getRandRange(0, typeBag.size());
SquareType type = typeBag[index];
typeBag.erase(typeBag.begin()+index);
return type;
}
int Generator::getRandRange(int min, int max)
{
srand((unsigned)time(0));
int range = (max - min);
return min + int((range * rand()) / (RAND_MAX + 1.0));
}
void Generator::initBag()
{
for (int i = 0; i < BAG_SIZE; ++i)
{
if (i < BAG_ENEMY)
{
typeBag.push_back(ENEMY);
}
else
{
typeBag.push_back(EMPTY);
}
}
}
|
C#
|
UTF-8
| 632 | 2.5625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.SQLite;
namespace WindowsFormsApplication1
{
class Db
{
public static SQLiteConnection getConnection()
{
if (!Directory.Exists("DataBase"))
{
Directory.CreateDirectory("DataBase");
}
if (!File.Exists("DataBase/dbDodger.db"))
{
SQLiteConnection.CreateFile("DataBase/dbDodger.db");
}
return new SQLiteConnection("Data Source = DataBase/dbDodger.db");
}
}
}
|
Python
|
UTF-8
| 2,342 | 3.296875 | 3 |
[] |
no_license
|
#
# @lc app=leetcode id=82 lang=python3
#
# [82] Remove Duplicates from Sorted List II
#
# @lc code=start
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
# 递归:
if head == None or head.next == None:
return head
curr = head.next
if curr.val == head.val:
while curr and curr.val == head.val:
curr = curr.next
head = curr
head = self.deleteDuplicates(curr)
else:
head.next = self.deleteDuplicates(curr)
return head
# 循环:
# if head == None or head.next == None:
# return head
# count = 1
# temp = head
# while temp.next:
# if temp.val == temp.next.val:
# temp = temp.next
# count += 1
# else:
# if count == 1:
# head = temp
# break
# if count > 1:
# count = 1
# temp = temp.next
# if temp.next == None and count >= 2:
# return None
# elif temp.next and count == 1:
# head = temp
# elif temp.next == None and count == 1:
# return temp
# elif temp.next and count >= 2:
# head = temp.next
# currPnt = head
# pnt = head.next
# while pnt.next:
# if pnt.val == pnt.next.val:
# pnt = pnt.next
# count += 1
# else:
# if count == 1:
# currPnt.next = pnt
# pnt = pnt.next
# currPnt = currPnt.next
# if count > 1:
# pnt = pnt.next
# count = 1
# if count == 1:
# currPnt.next = pnt
# else:
# currPnt.next = None
# return head
# @lc code=end
l1 = ListNode(2)
l2 = ListNode(2)
# l3 = ListNode(2)
# l4 = ListNode(3)
# l5 = ListNode(4)
# l6 = ListNode(4)
# l7 = ListNode(5)
l1.next = l2
# l2.next = l3
# l3.next = l4
s = Solution()
l = s.deleteDuplicates(l1)
while l:
print(l.val)
l = l.next
|
Python
|
UTF-8
| 313 | 3.078125 | 3 |
[] |
no_license
|
import matplotlib.pyplot as plt
import csv
x = []
y = []
with open('data.csv','r') as csvfile:
plots = csv.reader(csvfile)
for col in plots:
x.append((col[0]))
y.append((col[1]))
plt.plot(x, y, label='File')
plt.xlabel('X')
plt.ylabel('Y')
plt.title("Dataset")
plt.legend()
plt.show()
|
C#
|
UTF-8
| 2,790 | 2.59375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
using Dapper;
namespace OrleansSaga.Grains.Model
{
public class SqlEventStore : IEventStore
{
public const string SelectById = @"SELECT [GrainId], [EventType], [Data], [TaskStatus], [Created] FROM [dbo].[GrainEventStore] WHERE [GrainId] = @GrainId";
public const string Insert = @"INSERT INTO [dbo].[GrainEventStore] (GrainId, EventType, Data, TaskStatus, Created) VALUES (@GrainId, @EventType, @Data, @TaskStatus, @Created)";
string _connectionString;
public SqlEventStore()
{
_connectionString = ConfigurationManager.ConnectionStrings["GrainEventStore"].ConnectionString;
}
public async Task AddEvents(params GrainEvent[] events)
{
var r = await WithConnection(async c =>
{
foreach (var e in events)
{
var p = new DynamicParameters(e);
//p.Add("CorrelationId", correlationId, DbType.String);
var rows = await c.ExecuteAsync(
sql: Insert,
param: p,
commandType: CommandType.Text);
}
return Task.FromResult(0);
});
}
public async Task<IEnumerable<GrainEvent>> LoadEvents(long grainId)
{
return await WithConnection(async c =>
{
var p = new DynamicParameters();
p.Add("GrainId", grainId, DbType.Int64);
var events = await c.QueryAsync<GrainEvent>(
sql: SelectById,
param: p,
commandType: CommandType.Text);
return events;
});
}
protected async Task<T> WithConnection<T>(Func<SqlConnection, Task<T>> getData)
{
try
{
using (var connection = new SqlConnection(_connectionString))
{
await connection.OpenAsync(); // Asynchronously open a connection to the database
return await getData(connection); // Asynchronously execute getData, which has been passed in as a Func<IDBConnection, Task<T>>
}
}
catch (TimeoutException ex)
{
throw new Exception($"{GetType().FullName}.WithConnection() experienced a SQL timeout", ex);
}
catch (SqlException ex)
{
throw new Exception($"{GetType().FullName}.WithConnection() experienced a SQL exception (not a timeout)", ex);
}
}
}
}
|
Python
|
UTF-8
| 152 | 3.234375 | 3 |
[] |
no_license
|
n=int(input())
for i in range(0, 3):
X = 000
for j in range(0, 3):
X = (2*10)+1
for k in range(0, 3):
X = (3*100)+1
print(X)
|
PHP
|
UTF-8
| 3,957 | 3 | 3 |
[] |
no_license
|
<?php namespace UserAdministrator;
/**
* Class Controller
* @package UserAdministrator
*
* The Controller has not really a purpose,
* its job is to handle data that the user submits
*
*/
class Controller
{
/**
* @var object Processor|null
*/
private $processor = null;
/**
* @var object Input|null - User input
*/
public $input = null;
/**
* @var object Sanitizer|null - IM Sanitizer class instance
*/
private $sanitizer = null;
/**
* Controller constructor.
*
* @param $processor
*/
public function __construct($processor) {
$this->processor = $processor;
$this->input = new Input();
$this->sanitizer = $this->processor->imanager->sanitizer;
}
/**
* @param $name
*/
public function setSection($name) {
$this->processor->prepareSection($name, $this->input->whitelist);
}
/**
* Lets the unauthorized calls go to waste
* instead of causing a fatal error.
*
* @param $name
* @param $arguments
*/
public function __call($name, $arguments)
{
if(method_exists($this, $name)) {
$reflection = new \ReflectionMethod($this, $name);
if(!$reflection->isPublic()) return;
}
}
/**
* Login action
*
* Login form was sent
*/
public function login()
{
$this->input->whitelist->username = $this->sanitizer->text(
$this->input->post->username, array('maxLength' => 100)
);
$this->input->whitelist->password = $this->input->post->password;
$this->processor->actionLogin($this->input->whitelist);
}
/**
* Registration action
*
* Form is sent
*/
public function registration()
{
$this->input->whitelist->username = $this->sanitizer->pageName(
$this->input->post->username, array('maxLength' => 100)
);
$this->input->whitelist->email = $this->sanitizer->email(
$this->input->post->email
);
$this->input->whitelist->password = $this->input->post->password;
$this->input->whitelist->confirm = $this->input->post->confirm;
$this->processor->actionRegistration($this->input->whitelist);
}
/**
* Confirmation action
*
* Confirmation link clicked
*/
public function confirmation()
{
$this->input->whitelist->key = rawurldecode($this->input->get->key);
$this->input->whitelist->user = $this->sanitizer->pageName(
rawurldecode($this->input->get->user), array('maxLength' => 100)
);
$this->processor->actionConfirmation($this->input->whitelist);
}
}
class Input
{
public $post;
public $get;
public $whitelist;
public function __construct()
{
$this->post = new Post();
$this->get = new Get();
$this->whitelist = new Whitelist();
foreach($_POST as $key => $value) { $this->post->{$key} = $value; }
foreach($_GET as $key => $value) { $this->get->{$key} = $value; }
}
}
class Post
{
/**
*
* @param string $key
* @param mixed $value
* return $this
*
*/
public function __set($key, $value) { $this->{$key} = $value;}
public function __get($name) { return isset($this->{$name}) ? $this->{$name} : null;}
}
class Get
{
/**
*
* @param string $key
* @param mixed $value
* return $this
*
*/
public function __set($key, $value) { $this->{$key} = $value; }
public function __get($name) { return isset($this->{$name}) ? $this->{$name} : null; }
}
class Whitelist
{
/**
*
* @param string $key
* @param mixed $value
* return $this
*
*/
public function __set($key, $value) { $this->{$key} = $value; }
public function __get($name) { return isset($this->{$name}) ? $this->{$name} : null; }
}
|
TypeScript
|
UTF-8
| 275 | 2.65625 | 3 |
[] |
no_license
|
import {ThemeMode} from "./ThemeProvider";
export class IColor {
static quaternaryGray() {
return 'gray'
}
static orange(theme:ThemeMode) {
if (theme === ThemeMode.dark) {
return '#FFA500';
}
return '#aaA500';
}
}
|
Python
|
UTF-8
| 543 | 4.21875 | 4 |
[] |
no_license
|
# Liam O'Hainnin
#Looking at Variables.
X = 911
Y = 2
Z = X + Y
print (Z)
X = 914
Y = 3
Z = X + Y
print (Z)
fac = 7 * 6 * 5 * 4 * 3 * 2 * 1
print (fac)
b = True
c = False
print (c)
s = "sdvasvafsdasdasdvavf"
print (s[0:14:2])
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print (l[2:9:4])
s = "The quick brown fox jumps over the lazy dog."
print (s[1:55:2])
print (s[::-1])
print (s[::-2])
# reverse and display every second character of string input
g = input("Please enter a sentence: ")
print (g[::-2])
|
Java
|
UTF-8
| 2,167 | 2.140625 | 2 |
[] |
no_license
|
package com.company.modules.notary.service.impl;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.company.common.service.impl.BaseServiceImpl;
import com.company.modules.common.exception.ServiceException;
import com.company.common.context.Constant;
import com.company.common.dao.BaseDao;
import com.company.modules.notary.dao.NotaryManageDao;
import com.company.modules.notary.domain.HousNotarizationRegistration;
import com.company.modules.notary.service.NotaryManageService;
/**
* User: mcwang
* DateTime:2016-08-10 03:59:46
* details: 公证登记,Service实现层
* source: 代码生成器
*/
@SuppressWarnings("rawtypes")
@Service(value = "notaryManageServiceImpl")
public class NotaryManageServiceImpl extends BaseServiceImpl implements NotaryManageService {
/**
* 日志操作
*/
private static final Logger log = LoggerFactory.getLogger(NotaryManageServiceImpl.class);
/**
* 公证登记dao层
*/
@Autowired
private NotaryManageDao notaryManageDao;
/**
* 公证登记表,插入数据
* @param collateral 公证登记类
* @return 返回页面map
* @throws Exception
*/
@Override
public long insert(HousNotarizationRegistration housNotarizationRegistration) throws Exception {
try {
return notaryManageDao.insert(housNotarizationRegistration);
} catch (Exception e) {
log.error(e.getMessage(),e);
throw new ServiceException(e.getMessage(),e,Constant.FAIL_CODE_VALUE);
}
}
/**
* 公证登记表,根据流程id查询数据
* @param processInstanceId
* @return 返回页面map
* @throws Exception
*/
@Override
public Map<String,Object> getNotaryRegistDataByInstanceId(String processInstanceId) throws Exception {
try {
return notaryManageDao.getNotaryRegistDataByInstanceId(processInstanceId);
} catch (Exception e) {
log.error(e.getMessage(),e);
throw new ServiceException(e.getMessage(),e,Constant.FAIL_CODE_VALUE);
}
}
@Override
public BaseDao getMapper() {
return notaryManageDao;
}
}
|
C++
|
UTF-8
| 2,473 | 4.09375 | 4 |
[] |
no_license
|
/*
* Filename: constructor_and_destructor_timing_ex1.cpp
* Author: Wikus Jansen van Rensburg
* Date: October 11, 2020
* Description: This program is used to study when constructors and
* destructors are called.
*/
// ## You need to compile this program with the flag -std=c++11
#include <iostream>
// This class uses a constructor to initialize its member variables.
class Initializer_list{
int m_member1;
std::string m_member2;
std::string* m_member3;
public:
// Default constructor.
Initializer_list()
:m_member1{0}, m_member2{"default"}, m_member3{NULL}
{
std::cout << "Class Initializer_list constructor called." << std::endl;
}
// Destructor.
~Initializer_list(){
std::cout << "Class Initializer_list destructor called." << std::endl;
if(m_member3 != NULL){
delete[] m_member3;
}
}
// This creates an array to store strings.
void create_array(int size){
m_member3 = new std::string[size];
}
// Prints the members.
void print_members(){
std::cout << "m_member1: " << m_member1 << std::endl;
std::cout << "m_member2: " << m_member2 << std::endl;
}
};
// This class uses non-static member initialization.
class Non_static{
int m_member1{0};
std::string m_member2{"default"};
std::string* m_member3{NULL};
public:
Non_static()
// This will get precedencs over the non-static initialization.
//:m_member1{5}, m_member2{"set by constructor"}
{
std::cout << "Class Non_static constructor called." << std::endl;
}
// Destructor.
~Non_static(){
std::cout << "Class Non_static destructor called." << std::endl;
if(m_member3 != NULL){
delete[] m_member3;
}
}
// This creates an array to store strings.
void create_array(int size){
m_member3 = new std::string[size];
}
// Prints the members.
void print_members(){
std::cout << "m_member1: " << m_member1 << std::endl;
std::cout << "m_member2: " << m_member2 << std::endl;
}
};
int main(){
// Examples shocasting constructore and destructor timing.
{
// Example1
std::cout << "Example 1: Note that non1 is created after list1. Therefore is higher up on the stack"
<< " and will be destroyed first." << std::endl;
Initializer_list list1;
Non_static non1;
}
std::cout << std::endl << std::endl;
{
// Example2
std::cout << "Example 2: Now list2 is declared in an inner scope and will first be destroyed before"
<< " the object non2 is declared." << std::endl;
{
Initializer_list list2;
}
Non_static non2;
}
return 0;
}
|
Shell
|
UTF-8
| 664 | 3.359375 | 3 |
[] |
no_license
|
#!/bin/bash
#width="148mm" # a5
#height="210mm" # a5
width="149mm" # 6x4 photo
height="100mm" # 6x4 photo
# could use getopts here to alter the above settings
[ -z "$1" ] && echo Missing destination PNM file && exit 1
dest="$1"
# the default res is 75, opts found with `scanimage -A`
#echo "Warning: this is pretty low-res"
resolution=300 # 6x4 inch PNM is about 6MB
#resolution=1200 # 6x4 inch PNM is about 100MB
scanimage \
--progress \
--resolution $resolution \
--mode Color \
-x "$width" \
-y "$height" \
> "$dest"
# Missing \n after progress meter
echo
# could scan to /tmp/xxxx.pnm and then use `convert` to make $dest
|
TypeScript
|
UTF-8
| 695 | 3 | 3 |
[] |
no_license
|
import { Validator, Papers } from '../../types';
export abstract class ConsistencyValidator<T> implements Validator {
public validate (papers: Papers): boolean {
return this.getRelatedPapers(papers)
.filter(this.hasPaper)
.map(this.getFieldValue)
.every(this.isEveryValueSame);
}
protected abstract getRelatedPapers (papers: Papers): T[];
protected abstract getFieldValue (paper: T): string;
private hasPaper (paper: T): boolean {
return !!paper;
}
private isEveryValueSame(currentValue: string, index: number, array: string[]): boolean {
return index === 0 || currentValue === array[index - 1];
}
}
|
Python
|
UTF-8
| 1,682 | 2.625 | 3 |
[] |
no_license
|
from core import search_ep
from core import db_handler
import time
import re
strip = re.compile(r'[^(].*[^)]') # 去掉括号规则
bracket = re.compile(r'\([^()]+\)') # 获取values
employ_info = {
"starffId": None,
"name": None,
"age": None,
"phone": None,
"dept": None,
"enroll date": None
}
def process():
notice = """INSERT INTO Persons VALUES ('1', 'zhangtong', '29', '15999000001', 'soft')"""
print("请输入SQL 插入 语句比如: %s" % notice)
sql_insert = input();
if sql_insert.startswith("INSERT") and sql_insert.find("VALUES"):
key = sql_insert.split("VALUES")[0]
print(bracket.search(sql_insert).group())
input_employ_info = strip.search(bracket.search(sql_insert).group()).group()
tuple_employ_info = tuple(eval(input_employ_info)) # 转换成元组
id = int(tuple_employ_info[0])
name = tuple_employ_info[1]
age = int(tuple_employ_info[2])
phone = tuple_employ_info[3]
dept = tuple_employ_info[4]
employ_info["starffId"] = id
employ_info["name"] = name
employ_info["age"] = age
employ_info["phone"] = phone
employ_info["dept"] = dept
employ_info["enroll date"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 将本地时间戳 struct_time格式转成指定的字符串格式
if search_ep.process(1, employ_info) is True:
add_process(key, employ_info)
else:
print("已经有这个人了!")
else:
print("输入不正确!")
def add_process(key, args):
db_api = db_handler.db_handler()
db_api("%sVALUES = %s" %(key, args))
|
Swift
|
UTF-8
| 2,679 | 2.8125 | 3 |
[] |
no_license
|
//
// TapVC.swift
// gestureRecognizers
//
// Created by Luthfi Fathur Rahman on 6/19/17.
// Copyright © 2017 Luthfi Fathur Rahman. All rights reserved.
//
import UIKit
class TapVC: UIViewController {
@IBOutlet weak var cardContainerView: UIView!
@IBOutlet weak var backImageView: UIImageView!
@IBOutlet weak var frontImageView: UIImageView!
@IBOutlet weak var label_tapCount: UILabel!
var originView: UIImageView?
var destinationView: UIImageView?
private var backcardFlag = true
private var tapcounter = 0
override func viewDidLoad() {
super.viewDidLoad()
label_tapCount.text = String(describing: tapcounter)
label_tapCount.sizeToFit()
let singleTap = UITapGestureRecognizer(target: self, action: #selector(flipCard))
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
cardContainerView.addGestureRecognizer(singleTap)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func prepareForNextFlip() {
originView = nil
destinationView = nil
}
@objc func flipCard(_ sender: UITapGestureRecognizer){
tapcounter += 1
label_tapCount.text = String(describing: tapcounter)
label_tapCount.sizeToFit()
var transition = UIView.AnimationOptions.transitionFlipFromLeft
while originView == nil || destinationView == nil {
originView = backcardFlag ? backImageView : frontImageView
destinationView = backcardFlag ? frontImageView : backImageView
transition = backcardFlag ? UIView.AnimationOptions.transitionFlipFromLeft : UIView.AnimationOptions.transitionFlipFromRight
}
UIView.transition(from: originView!, to: destinationView!, duration: 1.0, options: [transition, .showHideTransitionViews], completion: { finised in
self.backcardFlag = !self.backcardFlag
self.prepareForNextFlip()
})
}
@IBAction func btn_resetTap(_ sender: UIButton) {
tapcounter = 0
label_tapCount.text = String(describing: tapcounter)
label_tapCount.sizeToFit()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.