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
|
---|---|---|---|---|---|---|---|
Shell
|
UTF-8
| 430 | 2.875 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/sh
sleep 30
echo "Start as daemon."
cd $TALEND_CONTAINER_HOME/bin/
./trun daemon &
echo "Done starting as deamon, wait a half of a minute for start to complete."
sleep 30
echo "Done starting, configure and stop."
echo "Configure ports."
sshpass -p tadmin ssh -o StrictHostKeyChecking=no tadmin@localhost -p 8101 "source scripts/$CONTAINER_PORTS_SCRIPT"
echo "Configured ports."
sleep 5
./trun stop
sleep 30
echo "Stopped."
|
C++
|
UHC
| 2,280 | 2.953125 | 3 |
[] |
no_license
|
//DFSMatrix.cpp
#include "DFSMatrix.h"
#include<stdio.h>
#include<Windows.h>
#include<iostream>
#include<fstream>
using namespace std;
#define col GetStdHandle(STD_OUTPUT_HANDLE) // ܼâ ڵ ƿɴϴ.
#define WHITE SetConsoleTextAttribute(col, 0x000f) //
DFSMatrix::DFSMatrix(){
q = 0;
m = 20;
n = 30;
dfs_map = new int* [m];
for(int i=0; i<m; i++){
dfs_map[i] = new int[n];
}
}
DFSMatrix::~DFSMatrix(){
for(int i=0; i<m; i++){
delete[]dfs_map[i];
}
delete[]dfs_map;
}
void DFSMatrix::setDFSMatrix(){
ifstream input;
input.open("dfsMaze.txt");//Ϸ Է
if(input.fail()){
cout<<"ϻ ٽý"<<endl;
return;
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(!input.eof())
input>>dfs_map[i][j];
else{
cout<<""<<endl;
return;
}
}
}
dfs(2, 0, 1);
input.close();
}
void DFSMatrix::dfs(int tr, int tc, int d){
int min = 600;
dfs_map[tr][tc] = 0; // 0 ǥ
if(tr == 13 && tc == 29){
if(min > d)
min=d;
stPath[q].a = tr;
stPath[q].b = tc;
q++;
return;
}
else if(dfs_map[tr][tc+1]!=0 && tc+1<30){//ϴ 3 0 ˻ մϴ.//ġ ƴϸ
stPath[q].a = tr;
stPath[q].b = tc;
q++;
dfs(tr, tc+1, d + 1);
}
else if(dfs_map[tr+1][tc]!=0 && tr+1<20){
stPath[q].a = tr;
stPath[q].b = tc;
q++;
dfs(tr+1, tc, d + 1);
}
else if(dfs_map[tr-1][tc]!=0 && tr-1>=0){
stPath[q].a = tr;
stPath[q].b = tc;
q++;
dfs(tr-1, tc, d + 1);
}
else if(dfs_map[tr][tc-1]!=0 && tc-1>=0){
stPath[q].a = tr;
stPath[q].b = tc;
q++;
dfs(tr, tc-1, d + 1);
}
dfs_map[tr][tc] = 1; // ǵưǷ 1 ǥ. κԴϴ.
}
|
Java
|
UTF-8
| 401 | 3.84375 | 4 |
[] |
no_license
|
package week1.day1;
public class Factorial {
/*
* Goal: Find the Factorial of a given number
*
* input: 5
* output: 5*4*3*2*1 = 120
*/
public static void main(String[] args) {
int input = 5;
int factorial = 1;
int i=1;
for(i=1; i<=input; i++) {
factorial = factorial*i;
}
System.out.println("The factorial of input: "+input +" is " +factorial);
}
}
|
PHP
|
UTF-8
| 898 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
<?php
declare(strict_types=1);
namespace Core\OAuth\OAuthBase\Yandex;
use Core\OAuth\Exception\OAuthException;
use Core\OAuth\OAuthBase\Common\CommonTokenCodeResponse;
use Core\OAuth\OAuthBase\OAuthBase;
use Core\OAuth\OAuthBase\IOAuthBase;
/**
* Управление OAuth авторизацией для сайта Yandex
*/
class OAuthYandex extends OAuthBase implements IOAuthBase
{
/**
* @param \stdClass $data Сырые данные из запроса
*
* @return CommonTokenCodeResponse
*
* @throws
*/
public function getTokenCodeResponse(\stdClass $data): CommonTokenCodeResponse
{
if (isset($data->error)) {
throw new OAuthException($data->error);
}
return new CommonTokenCodeResponse($data);
}
public function getTokenUrl(): string
{
return 'https://oauth.yandex.ru/token';
}
}
|
SQL
|
UTF-8
| 660 | 3.328125 | 3 |
[] |
no_license
|
/* SELECT */
/* FUNCAO PARA VER O HORARIO E DATA NO BANCO DE DADOS */
SELECT NOW();
/* SELECT PARA DIGITAR QUALQUER DADO */
SELECT 'Banco de Dados'
/* ALIAS(APELIDOS) DE COLUNAS */
SELECT 'Paula Fernandes' AS PROFESSORA;
/* SELECIONANDO APENAS ALGUNS ATRIBUTOS DA TABELA */
SELECT NOME,CPF,SEXO FROM CLIENTE;
/* FILTRO USANDO WHERE */
SELECT NOME,CPF,ENDERECO FROM CLIENTE
WHERE SEXO = 'M';
SELECT NOME,CPF,ENDERECO FROM CLIENTE
WHERE NOME = 'Valdomiro Santiago';
/* USANDO O LIKE */
SELECT NOME,CPF,ENDERECO FROM CLIENTE
WHERE ENDERECO LIKE '%SP';
/* CARACTER CORINGA % SIGNIFICA TUDO ANTES E TUDO DEPOIS*/
SELECT NOME,CPF,ENDERECO FROM CLIENTE
WHERE ENDERECO LIKE 'IJUI%';
|
C++
|
UTF-8
| 1,345 | 2.65625 | 3 |
[] |
no_license
|
#include<iostream>
#include<cstdio>
#include<map>
#include<vector>
#include<deque>
using namespace std;
int main(){
vector<bool>lookup(10000,true);
for(int i=2;i<10000;++i){
if(lookup[i]){
for(int j=2*i;j<10000;++j)if(j%i==0)lookup[j]=false;
}
}
map<int,int> indexOf;
int index=0;
printf("int primeList = { 2");
for(int i=3;i<10000;++i)if(lookup[i]) {
indexOf[i]=index++;
printf(" , %d",i);
}
printf("};");
vector<deque<int> > adjList(indexOf.size());
index=0;
int num,temp,l;
for(int i=2;i<10000;++i)if(lookup[i]){
num=i;l=1;
while(num>0){
temp=i-(num%10)*l;
for(int j=0;j<=9;++j){
if(i!=num%10 && indexOf.find(temp+j*l)!=indexOf.end()){
adjList[indexOf[i]].push_back(indexOf[temp+j*l]);
}
}
l*=10;
num=num/10;
}
++index;
}
/*for(int i=0;i<adjList.size();++i){
printf("%d : ",i);
for(int j=0;j<adjList[i].size();++j){
printf("%d ",adjList[i][j]);
}
printf("\n");
}*/
printf("\n\nint adjList = { { %d ",adjList[0][0]);
for(int i=1;i<adjList[0].size();++i){
printf(" , %d",adjList[0][i]);
}
printf(" } ");
for(int i=1;i<adjList.size();++i){
printf(" , { %d ",adjList[i][0]);
for(int j=1;j<adjList[i].size();++j){
printf(" , %d",adjList[i][j]);
}
printf(" } ");
}
printf(" } ;\n");
return 0;
}
|
Python
|
UTF-8
| 1,630 | 2.84375 | 3 |
[] |
no_license
|
import matplotlib.pyplot as plt
import os
import numpy as np
import matplotlib.pyplot as plt
class plot():
@staticmethod
def createBarChart(fileName, data):
barWidth = 0.15
ghsProgram = data['ghsProgram']
ghsAlgo = data['ghsAlgo']
br1 = np.arange(len(ghsProgram))
br2 = [x + barWidth for x in br1]
plt.bar(br1, ghsProgram, color ='maroon', width = barWidth,label ='Our Implementation')
plt.bar(br2, ghsAlgo, color ='blue', width = barWidth,label ='GHS Theory: 2E + 5NlogN')
plt.xlabel('Graph Nodes')
plt.ylabel('Message Count')
plt.xticks([r + barWidth for r in range(len(ghsAlgo))],data['Xlabel'])
plt.title('Comparission of Message Count- Edge Density '+ str(data['density']))
plt.legend()
filename = os.path.join(os.getcwd(),'fig', fileName + '.pdf')
# plt.savefig(filename, bbox_inches='tight')
plt.savefig(filename)
plt.clf()
@staticmethod
def createLineComparissionChart(fileName, data):
x = data['Xlabel']
y = data['ghsAlgo']
plt.plot(x, y, color='maroon', marker='o', label='GHS Theory: 2E + 5NlogN')
y1 = data['ghsProgram']
plt.plot(x, y1, color='blue', marker='*', label='Our Implementation')
plt.xlabel("Number of Nodes")
plt.ylabel("Message Count")
plt.title('Comparission of Message Count- Edge Density ' + str(data['density']))
filename = os.path.join(os.getcwd(),'fig', fileName + '.pdf')
plt.legend()
plt.savefig(filename)
plt.clf()
|
Python
|
UTF-8
| 540 | 4.5 | 4 |
[] |
no_license
|
#Написати функцію is_year_leap, приймає 1 аргумент - рік, і повертає True, якщо рік високосний, і False в іншому випадку.
def is_year_leap(year):
if year % 4 == 0:
return True
else:
return False
def main():
year = int(input("Введіть рік: "))
if is_year_leap(year) == True:
print("Рік високосний! ")
else:
print("Рік не є високосним! ")
if __name__ == "__main__":
main()
|
Markdown
|
UTF-8
| 2,755 | 2.53125 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: Vytvoření účtu úložiště pro Azure Data Lake Storage Gen2
description: Naučte se vytvořit účet úložiště pro použití s Azure Data Lake Storage Gen2.
author: normesta
ms.topic: how-to
ms.author: normesta
ms.date: 08/31/2020
ms.service: storage
ms.reviewer: stewu
ms.subservice: data-lake-storage-gen2
ms.openlocfilehash: 712f1dc0679ee49791831e782fb68c39a757870a
ms.sourcegitcommit: f28ebb95ae9aaaff3f87d8388a09b41e0b3445b5
ms.translationtype: MT
ms.contentlocale: cs-CZ
ms.lasthandoff: 03/29/2021
ms.locfileid: "98624333"
---
# <a name="create-a-storage-account-to-use-with-azure-data-lake-storage-gen2"></a>Vytvoření účtu úložiště pro použití s Azure Data Lake Storage Gen2
Pokud chcete používat funkce Data Lake Storage Gen2, vytvořte účet úložiště, který má hierarchický obor názvů.
## <a name="choose-a-storage-account-type"></a>Zvolit typ účtu úložiště
Funkce Data Lake Storage jsou podporované v následujících typech účtů úložiště:
- Účty pro obecné účely verze 2
- BlockBlobStorage
Informace o tom, jak si vybírat mezi nimi, najdete v tématu [Přehled účtu úložiště](../common/storage-account-overview.md).
## <a name="create-a-storage-account-with-a-hierarchical-namespace"></a>Vytvoření účtu úložiště s hierarchickým oborem názvů
Vytvořte účet pro [obecné účely v2](../common/storage-account-create.md) nebo účet [BlockBlobStorage](storage-blob-create-account-block-blob.md) s povoleným nastavením **hierarchického oboru názvů** .
Odemkněte možnosti Data Lake Storage při vytváření účtu povolením nastavení **hierarchického oboru názvů** na kartě **Upřesnit** na stránce **vytvořit účet úložiště** . Toto nastavení musíte povolit při vytváření účtu. Nemůžete ho později povolit.
Toto nastavení se zobrazuje na stránce **vytvořit účet úložiště** na následujícím obrázku.
> [!div class="mx-imgBorder"]
> 
Pokud máte existující účet úložiště, který chcete použít se službou Data Lake Storage a nastavení hierarchického oboru názvů je zakázané, musíte migrovat data na nový účet úložiště s povoleným nastavením.
> [!NOTE]
> **Data Protection** a **hierarchické obor názvů** nelze současně povolit.
## <a name="next-steps"></a>Další kroky
- [Přehled účtu úložiště](../common/storage-account-overview.md)
- [Použití Azure Data Lake Storage Gen2 pro požadavky na velké objemy dat](data-lake-storage-data-scenarios.md)
- [Řízení přístupu ve službě Azure Data Lake Storage Gen2](data-lake-storage-access-control.md)
|
SQL
|
ISO-8859-1
| 9,036 | 3.203125 | 3 |
[] |
no_license
|
-- Empresa : Supermercado So Roque Ltda.
-- Data :02/02/2013
-- Atualizado em : 24/04/2013
-- Desenvolvedor : Sandro Soares.
-- Solicitante : Solange Pinheiro
-- Descrio : Retorna as movimentaes de finalizadoras por dia e por loja.
-- Tambm incluido as devolucoes da agenda 21 por dia, enviar junto.
Select
r.cod as Loja
,r.finalizadora as finalizadora
,r.tab_conteudo as descricao
,nvl(sum(r.a),0)as "01",nvl(sum(r.b),0) as "02",nvl(sum(r.c),0) as "03",nvl(sum(r.d),0) as "04",nvl(sum(r.e),0) as "05",nvl(sum(r.f),0) as "06",nvl(sum(r.g),0) as "07",nvl(sum(r.h),0) as "08",nvl(sum(r.i),0) as "09",nvl(sum(r.j),0) as "10"
,nvl(sum(r.l),0) as "11",nvl(sum(r.m),0) as "12",nvl(sum(r.n),0) as "13",nvl(sum(r.p),0) as "14",nvl(sum(r.q),0) as "15",nvl(sum(r.r),0) as "16",nvl(sum(r.s),0) as "17",nvl(sum(r.t),0) as "18",nvl(sum(r.u),0) as "19",nvl(sum(r.v),0) as "20"
,nvl(sum(r.x),0) as "21",nvl(sum(r.z),0) as "22",nvl(sum(r.aa),0) as "23",nvl(sum(r.ab),0) as "24",nvl(sum(r.ac),0) as "25",nvl(sum(r.ad),0) as "26",nvl(sum(r.ae),0) as "27",nvl(sum(r.af),0) as "28",nvl(sum(r.ag),0) as "29",nvl(sum(r.ah),0) as "30"
,nvl(sum(r.ai),0) as "31"
from
(
select cod,
finalizadora,
tab_conteudo,
case when dta = '01' then to_number(sum(vlr)) end as A,
case when dta = '02' then to_number(sum(vlr)) end as B,
case when dta = '03' then to_number(sum(vlr)) end as C,
case when dta = '04' then to_number(sum(vlr)) end as D,
case when dta = '05' then to_number(sum(vlr)) end as E,
case when dta = '06' then to_number(sum(vlr)) end as F,
case when dta = '07' then to_number(sum(vlr)) end as G,
case when dta = '08' then to_number(sum(vlr)) end as H,
case when dta = '09' then to_number(sum(vlr)) end as I,
case when dta = '10' then to_number(sum(vlr)) end as J,
case when dta = '11' then to_number(sum(vlr)) end as L,
case when dta = '12' then to_number(sum(vlr)) end as M,
case when dta = '13' then to_number(sum(vlr)) end as N,
case when dta = '14' then to_number(sum(vlr)) end as P,
case when dta = '15' then to_number(sum(vlr)) end as Q,
case when dta = '16' then to_number(sum(vlr)) end as R,
case when dta = '17' then to_number(sum(vlr)) end as S,
case when dta = '18' then to_number(sum(vlr)) end as T,
case when dta = '19' then to_number(sum(vlr)) end as U,
case when dta = '20' then to_number(sum(vlr)) end as V,
case when dta = '21' then to_number(sum(vlr)) end as X,
case when dta = '22' then to_number(sum(vlr)) end as Z,
case when dta = '23' then to_number(sum(vlr)) end as AA,
case when dta = '24' then to_number(sum(vlr)) end as AB,
case when dta = '25' then to_number(sum(vlr)) end as AC,
case when dta = '26' then to_number(sum(vlr)) end as AD,
case when dta = '27' then to_number(sum(vlr)) end as AE,
case when dta = '28' then to_number(sum(vlr)) end as AF,
case when dta = '29' then to_number(sum(vlr)) end as AG,
case when dta = '30' then to_number(sum(vlr)) end as AH,
case when dta = '31' then to_number(sum(vlr)) end as AI
from vw_finalizadora,
(
select mcof_loja,
mcof_finaliza,
nvl(mcof_valor,0) vlr,
substr(mcof_data,6,7) as dta
from ag2vmcof
where mcof_agenda in
(122, 123, 124, 125, 126, 127, 128, 129, 130, 136, 140, 142, 143, 144)
and mcof_data between 1||to_char(to_date('&Dta_Inicial','dd/mm/yyyy'),'yymmdd') and 1||to_char(to_date('&Dta_Final','dd/mm/yyyy'),'yymmdd') ---between (1130301) and (1130331)
)A
where cod = mcof_loja (+)
and finalizadora = mcof_finaliza (+)
group by cod,dta,finalizadora,tab_conteudo
)r where r.cod not in (132,140,167,175,388)
group by r.cod ,r.finalizadora ,r.tab_conteudo
order by loja,finalizadora;
-----------------------------------------------------------------------------------------------------------------------------------
-- Retorna valores para conferencia das venda.
Select LJ as Loja
,dta
,sum(leitura_z) as leitura_z
,sum(ag_21) as ag_21
,sum(ag_53) as ag_53
,sum(gerencial) as gerencial
,trunc (sum(ag_53-gerencial-ag_21)) as Ag_53_X_Ger
,sum(cl) as Cliente
,sum(cup) as cupom
,round(sum(qt_vd)) as qtde_vda
from
(
--Leitura Z (Tesouraria)
Select rl_loja as LJ
,rms7to_date( rl_data) dta
,sum(rl_totmaq_1) as Leitura_Z
,to_number(0) as ag_21
,to_number(0) as ag_53
,to_number(0) as gerencial
,sum(rl_clientes_1) as cl
,to_number(0) as cup
,to_number(0) as qt_vd
from AG2VRLCX
where rl_data between 1||to_char(to_date('&Dta_Inicial','dd/mm/yyyy'),'yymmdd') and 1||to_char(to_date('&Dta_Final','dd/mm/yyyy'),'yymmdd')--(select 1||to_char((add_months(sysdate,-retro)-1),'yymmdd') as Dta_Inicio from dual) and (select 1||To_char(sysdate,'yymmdd') dta_final from dual)
group by rl_loja,rl_data
/*Select lz_loja as LJ
,rms7to_date( lz_data) dta
,sum(lz_valteclas_1 + lz_valteclas_2 ) as Leitura_Z
,to_number(0) as ag_21
,to_number(0) as ag_53
,to_number(0) as gerencial
,sum(lz_clientes) as cl
from AG2VLEIZ
where lz_data between 1||to_char(to_date('&Dta_Inicial','dd/mm/yyyy'),'yymmdd') and 1||to_char(to_date('&Dta_Final','dd/mm/yyyy'),'yymmdd') ---between (1130301) and (1130331)
group by lz_loja,lz_data */Union
--Cancelamento agenda 21
Select to_number(fis_loj_dst||fis_dig_dst) as LJ
,rms7to_date(fis_dta_agenda) as dta
,to_number(0) as Leitura_Z
,sum(fis_val_cont_ff_1 + fis_val_cont_ff_2 +fis_val_cont_ff_3 + fis_val_cont_ff_4 + fis_val_cont_ff_5) as Ag_21
,to_number(0) as ag_53
,to_number(0) as gerencial
,to_number(0) as cl
,to_number(0) as cup
,to_number(0) as qt_vd
from aa1cfisc
where fis_oper in (20,21,621) --fis_oper = 21 --fis_loj_dst = 1
and fis_dta_agenda between 1||to_char(to_date('&Dta_Inicial','dd/mm/yyyy'),'yymmdd') and 1||to_char(to_date('&Dta_Final','dd/mm/yyyy'),'yymmdd') ---between (1130301) and (1130331)
and fis_loj_dst not in (9,10,100,120)
and fis_situacao <> '9'
group by fis_loj_dst,fis_dig_dst,fis_dta_agenda
--order by 1,2
Union
-- Importao agenda 53
Select to_number(fis_loj_org||fis_dig_org) as LJ
,rms7to_date(fis_dta_agenda) as dta
,to_number(0) as Leitura_z
,to_number(0) as ag_21
,sum(fis_val_cont_ff_1 + fis_val_cont_ff_2 +fis_val_cont_ff_3 + fis_val_cont_ff_4 + fis_val_cont_ff_5) as Ag_53
,to_number(0) as gerencial
,to_number(0) as cl
,to_number(0) as cup
,to_number(0) as qt_vd
from aa1cfisc
where fis_oper = 53 ----fis_loj_org = 1
and fis_dta_agenda between 1||to_char(to_date('&Dta_Inicial','dd/mm/yyyy'),'yymmdd') and 1||to_char(to_date('&Dta_Final','dd/mm/yyyy'),'yymmdd') ---between (1130301) and (1130331)
group by fis_loj_org,fis_dig_org,fis_dta_agenda
Union
--Consulta Gerencial
select to_number(cd_fil||dac(cd_fil)) as LJ
,dim.dt_compl as Dta
,to_number(0) as Leitura_z
,to_number(0) as Ag_21
,to_number(0) as Ag_53
,round(sum (nvl(vl_vda,0)- nvl(vl_dvol_vda,0))) as Gerencial
,to_number(0) as cl
,to_number(0) as cup
,(agg.qtd_vda - nvl(agg.qtd_dvol_vda,0))as qt_vd
from agg_coml_fil agg ,(select id_dt,dt_compl from dim_per where dt_compl between to_date('&dta_inicial','dd/mm/yy') and to_date('&Dta_Final','dd/mm/yy'))dim
where cd_fil not in (9,10,50,51,52,52,53,100,103,120,13,14)
and agg.id_dt = dim.id_dt
group by cd_fil,dim.dt_compl,agg.qtd_vda,agg.qtd_dvol_vda
Union
-- Consulta cupons Visual Mix
select to_number(loja||dac(loja)) as LJ
,data as Dta
,to_number(0) as Leitura_z
,to_number(0) as Ag_21
,to_number(0) as Ag_53
,to_number(0) as Gerencial
,to_number(0) as cl
,sum(qtd_cuponsvenda)as cup
,to_number(0) as qt_vd
from vm_log.total_oper
where data between to_date('&dta_inicial', 'dd/mm/yyyy') and to_date('&Dta_Final', 'dd/mm/yyyy')
group by loja,data
)
group by LJ,DTA
order by 1,2
/* --Enviar junto com o moviemnto da tesourria as devolues da agenda 21
select to_number(fis_loj_org||fis_dig_org) as LJ
,rms7to_date(fis_dta_agenda)as dta
,fis_oper as agenda
,sum(fis_val_cont_ff_1+fis_val_cont_ff_2+fis_val_cont_ff_3+fis_val_cont_ff_4+fis_val_cont_ff_5)as vl
from aa1cfisc
where rms7to_date(FIS_DTA_AGENDA) between to_date('&Dta_Inicial','dd/mm/yyyy') and to_date('&Dta_Final','dd/mm/yyyy')
and fis_oper = 21
and fis_situacao <> '9'
and fis_loj_org not in (1007)
group by fis_loj_org,fis_dig_org,fis_dta_agenda,fis_oper
order by 1,2 */
|
C
|
UTF-8
| 2,117 | 2.96875 | 3 |
[] |
no_license
|
#ifdef sgi
/*
* Yellow pages utility routine to map client map names to names
* that are short enough to work with 14 character file names.
*/
/*
* Translation table for mapping dbnames.
*
* The mapped name must be short enough to remain unique
* after the addition of the suffixes ".t.dir" and ".t.pag".
* The 'makedbm' program adds ".t" and the dbm package
* adds the ".dir" and ".pag". With 14 character names,
* 10 characters is the limit.
*
* Let's not try to be cute for now, just an easy table
* lookup will do the trick.
*/
static char *yp_name_map[] = {
/* From To */
"passwd.byname", "pw.name",
"passwd.byuid", "pw.uid",
"group.byname", "grp.name",
"group.bygid", "grp.gid",
"hosts.byname", "hosts.name",
"hosts.byaddr", "hosts.addr",
"protocols.byname", "proto.name",
"protocols.bynumber", "proto.nbr",
"services.byname", "svc.name",
"networks.byname", "nets.name",
"networks.byaddr", "nets.addr",
"mail.aliases", "aliases",
"netgroup", "netgrp",
"netgroup.byuser", "netgrp.usr",
"netgroup.byhost", "netgrp.hst",
"ethers.byaddr", "ether.addr",
"ethers.byname", "ether.name",
"rpc.bynumber", "rpc.nbr",
0 /* end of list */
};
/*
* YP database name translation
*
* The map names as defined by SUN are too long to work as file
* names on systems that have traditional 14 character file names.
* Hide this limitation from YP clients by simply mapping the map
* names to shorter names.
*/
int
yp_make_dbname(name, newname, len)
register char *name; /* input name to be translated */
char *newname; /* buffer for returned name */
int len; /* length of 'newname' buffer */
{
register char **np;
/*
* Buzz the translation table looking at even numbered
* entries for a matching name.
*/
for (np = yp_name_map; *np; np += 2) {
/*
* If the name matches, the following odd numbered
* entry is the translation.
*/
if (strcmp(*np, name) == 0) {
np++;
break;
}
}
/*
* If no match, just use the original name
*/
if (*np == 0)
strncpy(newname, name, len);
else
strncpy(newname, *np, len);
}
#endif sgi
|
SQL
|
UTF-8
| 892 | 3.25 | 3 |
[
"MIT"
] |
permissive
|
create user pizarra_user password 'pizarra_3323948812bdz';
create database pizarra_db owner pizarra_user;
\c pizarra_db
drop schema if exists piz cascade;
create schema piz authorization pizarra_user;
grant all on schema piz to pizarra_user;
create table piz.users(
username text primary key,
md5pass text,
kind text,
rol text
);
alter table piz."users" owner to pizarra_user;
insert into piz.users
select 'test'||n, md5('clave'||n||'test'||n), 'direct', 'test'
from generate_series(1,10) n;
create table piz.pizarras(
pizarra text primary key,
username text references piz.users(username),
content text,
constraint "pizarra must be the username" check (pizarra=username)
);
alter table piz.pizarras owner to pizarra_user;
insert into piz.pizarras (pizarra, username, content) select username, username, '{"version": "0.0.1"}' from piz."users";
|
Java
|
UTF-8
| 978 | 2.46875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package io.github.ketao1989.jdk8;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author tao.ke Date: 2017/7/23 Time: 下午10:02
*/
public class ProcessTemplate {
private static final Logger logger = LoggerFactory.getLogger(ProcessTemplate.class);
public static <T> T execute(TemplateProcessor<T> processor){
T result = null;
long startTime = System.currentTimeMillis();
try {
{
processor.getBeforeProcess().process();
}
{
processor.getCheckParams().process();
}
{
result = (T) processor.getCoreProcessor().get();
}
// {
// action.succ(result, System.currentTimeMillis() - startTime);
// }
} catch (Exception e) {
} finally {
try {
{
processor.getAfterProcess().process();
}
} catch (Exception e) {
logger.error("finally中调用方法出现异常!", e);
}
}
return result;
}
}
|
C++
|
UTF-8
| 473 | 2.703125 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
ll phi( ll n ) {
ll res = n ;
for ( ll i = 2 ; i * i <= n ; i++){
if( n % i == 0 ){
while( n % i == 0 ) n = n / i ;
res = res - res / i ;
}
}
if(n > 1) res = res - res / n ;
return res ;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t ; cin >> t ;
while ( t-- ) {
ll n ; cin >> n ;
cout << phi(n) << "\n" ;
}
return 0;
}
|
C
|
UTF-8
| 516 | 3.5 | 4 |
[
"MIT"
] |
permissive
|
#include <stdio.h>
int main(void)
{
int a, b, c, t;
char str[4];
int i, izlaz[3];
scanf( "%d%d%d", &a, &b, &c );
if ( a > b ) { t = a; a = b; b = t; }
if ( a > c ) { t = a; a = c; c = t; }
if ( b > c ) { t = b; b = c; c = t; }
scanf( "%s", str );
for ( i=0; i<3; ++i ) {
if ( str[i] == 'A' ) izlaz[i] = a;
else if ( str[i] == 'B' ) izlaz[i] = b;
else if ( str[i] == 'C' ) izlaz[i] = c;
}
printf( "%d %d %d\n", izlaz[0], izlaz[1], izlaz[2] );
return 0;
}
|
PHP
|
ISO-8859-1
| 2,531 | 2.53125 | 3 |
[] |
no_license
|
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title></title>
</head>
<body >
</body>
<?php
$faire=1;
if (isset($_POST['seance_name']))
{
$seance_name=$_POST['seance_name'];
}
if (isset($_POST['sport_id']))
{
$sport_id=$_POST['sport_id'];
}
if (isset($_POST['date']))
{
$date=$_POST['date'];
}
if (isset($_POST['cal']))
{
$cal=$_POST['cal'];
}
if (isset($_POST['dist']))
{
$dist=$_POST['dist'];
}
if (isset($_POST['duration']))
{
$duration=$_POST['duration'];
}
if (isset($_POST['fat']))
{
$fat=$_POST['fat'];
}
if (isset($_POST['above']))
{
$above=$_POST['above'];
}
if (isset($_POST['below']))
{
$below=$_POST['below'];
}
if (isset($_POST['in_zone']))
{
$in_zone=$_POST['in_zone'];
}
if (isset($_POST['lower']))
{
$lower=$_POST['lower'];
}
if (isset($_POST['upper']))
{
$upper=$_POST['upper'];
}
if (isset($_POST['fmoy']))
{
$fmoy=$_POST['fmoy'];
}
if (isset($_POST['fmax']))
{
$fmax=$_POST['fmax'];
}
if (isset($_POST['vmoy']))
{
$vmoy=$_POST['vmoy'];
}
if (isset($_POST['vmax']))
{
$vmax=$_POST['vmax'];
}
define('PUN_ROOT', './');
require PUN_ROOT.'../config2.php';
require PUN_ROOT.'../include/fonctions.php';
echo "INSERT INTO seances (`name`, `sport_id`, `date`, `calories`, `distance`, `duration`, `fat_consumption`, `above`, `average`, `below`, `in_zone`, `lower`, `maximum`, `upper`, `Vaverage`, `Vmaximum`) values('$seance_name', '$sport_id', '$date' , '$cal' , '$dist' , '$duration' , '$fat' , '$above' , '$fmoy' , '$below' , '$in_zone', '$lower', '$fmax' , '$upper' , '$vmoy', '$vmax' )" ;
if ($fmoy && $fmax && $upper && $lower && $in_zone && $below && $above && $duration && $cal && $date && $sport_id && $seance_name)
{
/* Connecting, selecting database */
$link=connect_db($db_host, $db_username, $db_password, $db_name);
print 'Accs la base [<FONT COLOR=GREEN>OK</FONT>]<BR>';
//$date_parse= date_create_from_format('j-m-Y', $date);
//echo "date($date_parse[year],\"y\")/$date_parse[month]/$date_parse[day]";
mysql_query("INSERT INTO seances (`name`, `sport_id`, `date`, `calories`, `distance`, `duration`, `fat_consumption`, `above`, `average`, `below`, `in_zone`, `lower`, `maximum`, `upper`, `Vaverage`, `Vmaximum`) values('$seance_name', '$sport_id', '$date' , '$cal' , '$dist' , '$duration' , '$fat' , '$above' , '$fmoy' , '$below' , '$in_zone', '$lower', '$fmax' , '$upper' , '$vmoy', '$vmax' )");
}
else
{
print("<H2>Tous les champs (sauf peut tre Place) doivent tre non vide!!!</H2>");
}
?>
|
Markdown
|
UTF-8
| 748 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: "HTML"
comments: true
categories: HTML
---
### Box, Item
- BOX: header, footer, nav, aside, main, section, article: section 안에 들어가며, 재사용이 가능한, 혹은 반복되는 것을 묶어준 것, div: 다른 요소를 묶어서 스타일을 할때, span, form
- ITEM: a, button, input, label, img, video, audio, map, canvas, table
### Block, Inline
- block level: 한줄에 하나(추가시 아래에 삽입)
- lnline: 공간이 허용하는 한 같은 행에 삽입(추가시 공간이 허용하면 옆에 삽입)
### <span>, <div>
- div: block level
- span: inline level
### Grouping label and input
<pre>
<label for="input_name">Name: </label>
<input id="input_name" type = "text">
</pre>
|
Python
|
UTF-8
| 651 | 3.984375 | 4 |
[] |
no_license
|
# Find and Replace
words = "It's thanksgiving day. It's my birthday,too!"
print words
result = words.find('day')
print(result)
string = words.replace('day','month')
print string
#Min and Max
x = [2,54,-2,7,12,98]
print min(x)
print max(x)
#First and Last
x = ['hello',2,54,-2,7,12,98,'world']
print 'List: ', x
print 'Length of String is ', len(x)
print x[0]
print x[8]
print x[0], x[len(x) - 1]
#New Listpy
x = [19,2,54,-2,7,12,98,32,10,-3,6]
print x
x.sort()
print x
first_list = x[:len(x)/2]
second_list = x[len(x)/2:]
print "first list", first_list
print "second_list", second_list
second_list.insert(0,first_list)
print second_list
|
C++
|
UTF-8
| 571 | 2.984375 | 3 |
[] |
no_license
|
#include <iostream>
#include <string.h>
#include "CommonPair.h"
void CommonPair::copy(int key, double value)
{
Pair<int, double>::copy(key, value);
}
CommonPair::CommonPair()
{
}
CommonPair::CommonPair(int key, double value)
{
this->copy(key, value);
}
CommonPair::CommonPair(CommonPair const &other)
{
this->copy(other.getKey(), other.getValue());
}
CommonPair &CommonPair::operator=(CommonPair const &other)
{
if (this != &other)
{
this->copy(other.getKey(), other.getValue());
}
return *this;
}
CommonPair::~CommonPair()
{
}
|
Java
|
UTF-8
| 782 | 3.046875 | 3 |
[] |
no_license
|
package nl.utwente.plantcontroller.auth;
import java.security.SecureRandom;
import java.util.Random;
public class PasswordGenerator {
static final String allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public static String generatePass(){
Random rand = new Random();
String pass = "";
int lenght = Math.abs(rand.nextInt()) % 10 + 6; //minimaal 6 maximaal 16 chars genereren :)
for(int i = 0; i< lenght; i++){
pass += allowedChars.charAt(Math.abs(rand.nextInt()) % allowedChars.length());
}
return pass;
}
public static void main(String[] args){
for(int i = 0; i < 20; i++){
System.out.println(generatePass());
}
}
}
|
Python
|
UTF-8
| 216 | 3 | 3 |
[] |
no_license
|
from time import sleep
import sys
s = raw_input("Enter a recursive acronym: ")
for x in range(20000):
y = x**2
sleep(3)
sys.stderr.write("\nnot enough memory to perform this operation")
raw_input("")
sys.exit(1)
|
Markdown
|
UTF-8
| 3,471 | 2.75 | 3 |
[] |
no_license
|
# List pros / cons use docker-compose.yml on production
## "docker-compose.yml" vs "only docker"
See this examples:
* [Deploy Sentry only with Docker](examples/sentry-with-only-docker/)
* [Deploy Sentry with docker-compose](examples/sentry-with-docker-compose/)
Technically [docker-compose](https://docs.docker.com/compose/compose-file/) is a wrapper over [docker engine](https://docs.docker.com/engine/reference/commandline/cli/) then:
* if **docker engine** is stable then **docker-compose** is stable
**docker-compose.yml** pros:
* user can test easly `docker-compose.yml` locally
* only one syntax to understand for development and production `docker-compose.yml`
* This is simpler easier to read
```
sentry:
image: sentry:9
restart: unless-stopped
ports:
- 9000:9000
environment:
- SENTRY_SECRET_KEY="%**stxva=es(qsts1z1eu!1uks3r9q8z@w8dh8hm&akv3p9a*s"
- SENTRY_REDIS_HOST=sentry_redis
- SENTRY_POSTGRES_HOST=sentry_postgres
- SENTRY_DB_USER=sentry
- SENTRY_DB_PASSWORD=sentry
```
than
```
docker run -d --rm \
--network=sentry \
--name=sentry \
-e SENTRY_SECRET_KEY="%**stxva=es(qsts1z1eu!1uks3r9q8z@w8dh8hm&akv3p9a*s" \
-e SENTRY_REDIS_HOST=sentry_redis \
-e SENTRY_POSTGRES_HOST=sentry_postgres \
-e SENTRY_DB_USER=sentry \
-e SENTRY_DB_PASSWORD=sentry \
-p 9000:9000 \
sentry:9
```
* Admin-sys or DevOps can read easily what services running on server and how update it, `docker-compose.yml` is a contract
## Difference between development "docker-compose.yml" and production "docker-compose.yml"
### Development "docker-compose.yml" guidelines
* In development `docker-compose.yml` developer: use volumes to mount its source code to dynamically update it ([example](https://github.com/harobed/goworkspace/blob/master/docker-compose.yml#L10))
* In development `docker-compose.yml` developer: use `docker-compose build` to rebuild development Docker image
### Production "docker-compose.yml" guidelines
* Never build image on production ([La cuisson avec Docker](https://blog.garambrogne.net/la-cuisson-avec-docker.html) (french)):
* Never use [build options](https://docs.docker.com/compose/compose-file/#build) in docker-compose, example:
```
# docker-compose.yml
version: '3'
services:
webapp:
build: ./dir # Never use it in production
```
* `docker-compose build` is never executed on production server
* Always pull image from trusted public or private Docker registry
* Where building Docker image?
* Production Docker image building must be executed on developer computer or better in CI (GitLab-CI, Jenkins…)
* Usually production Dockerfile is different that development Dockerfile.
* Dockerfile has often some tooling useless in production Docker image. Example, in Golang project, I have [protoc](https://github.com/google/protobuf/releases/) or [go-bindata](https://github.com/jteeuwen/go-bindata/)... this tools are useless on production.
## When use Kubernetes or Swarm?
See [My opinionated microservice deployment guideline](https://github.com/harobed/opinionated-microservice-deployment-guideline)
## References
Pros:
* [Use Compose in production](https://docs.docker.com/compose/production/)
* [Docker Compose from development to production](https://medium.com/@basi/docker-compose-from-development-to-production-88000124a57c)
* In docker-compose GitHub issue: [Not recommended for production use. Why? #1264](https://github.com/docker/compose/issues/1264)
|
Java
|
UTF-8
| 2,248 | 2.390625 | 2 |
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.zxing.client.android.encode;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
// Referenced classes of package com.google.zxing.client.android.encode:
// Formatter
abstract class ContactEncoder
{
ContactEncoder()
{
}
static void doAppend(StringBuilder stringbuilder, StringBuilder stringbuilder1, String s, String s1, Formatter formatter, char c)
{
s1 = trim(s1);
if (s1 != null)
{
stringbuilder.append(s).append(':').append(formatter.format(s1)).append(c);
stringbuilder1.append(s1).append('\n');
}
}
static void doAppendUpToUnique(StringBuilder stringbuilder, StringBuilder stringbuilder1, String s, Iterable iterable, int i, Formatter formatter, Formatter formatter1, char c)
{
if (iterable != null) goto _L2; else goto _L1
_L1:
return;
_L2:
HashSet hashset;
Iterator iterator;
int j;
j = 0;
hashset = new HashSet(2);
iterator = iterable.iterator();
_L5:
if (!iterator.hasNext()) goto _L1; else goto _L3
_L3:
String s1 = trim((String)iterator.next());
if (s1 == null || s1.isEmpty() || hashset.contains(s1)) goto _L5; else goto _L4
_L4:
stringbuilder.append(s).append(':').append(formatter1.format(s1)).append(c);
if (formatter == null)
{
iterable = s1;
} else
{
iterable = formatter.format(s1);
}
stringbuilder1.append(iterable).append('\n');
j++;
if (j == i) goto _L1; else goto _L6
_L6:
hashset.add(s1);
goto _L5
}
static String trim(String s)
{
if (s == null)
{
return null;
}
String s1 = s.trim();
s = s1;
if (s1.isEmpty())
{
s = null;
}
return s;
}
abstract String[] encode(Iterable iterable, String s, Iterable iterable1, Iterable iterable2, Iterable iterable3, Iterable iterable4, String s1);
}
|
Java
|
WINDOWS-1250
| 2,807 | 2.53125 | 3 |
[] |
no_license
|
package br.com.fiap.resource;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import br.com.fiap.dao.ReservaDAO;
import br.com.fiap.dao.impl.ReservaDAOImpl;
import br.com.fiap.entity.Reserva;
import br.com.fiap.exception.ChaveInexistenteException;
import br.com.fiap.exception.CommitException;
import br.com.fiap.singleton.EntityManagerFactorySingleton;
//http://localhost:8080/12-WS-Restful/rest/reserva/1
@Path("/reserva")
public class ReservaResource {
private ReservaDAO dao;
public ReservaResource() {
EntityManagerFactory fabrica =
EntityManagerFactorySingleton.getInstance();
EntityManager em = fabrica.createEntityManager();
dao = new ReservaDAOImpl(em);
}
@DELETE
@Path("{id}")
public void remover(@PathParam("id") int codigo) {
try {
dao.remover(codigo);
dao.commit();
}catch(Exception e) {
e.printStackTrace();
throw new InternalServerErrorException(); //Erro 500
//return Response.serverError().build();
}
//return Response.noContent().build();
}
@PUT
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response atualizar(@PathParam("id") int codigo,
Reserva reserva) {
try {
reserva.setCodigo(codigo);
dao.atualizar(reserva);
dao.commit();
} catch (CommitException e) {
e.printStackTrace();
return Response.serverError().build(); //Erro 500
}
return Response.ok().build(); //200 OK
}
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Reserva buscar(@PathParam("id") int codigo) {
try {
return dao.consultar(codigo);
} catch (ChaveInexistenteException e) {
e.printStackTrace();
return null;
}
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response cadastrar(Reserva reserva, @Context UriInfo uri) {
try {
dao.cadastrar(reserva);
dao.commit();
} catch (CommitException e) {
e.printStackTrace();
return Response.serverError().build(); //Erro 500
}
//Construir a URL para acessar o recurso (reserva) cadastrada
UriBuilder builder = uri.getAbsolutePathBuilder();
//adicionar o cdigo da reserva na URL
builder.path(Integer.toString(reserva.getCodigo()));
return Response.created(builder.build()).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Reserva> buscar() {
return dao.listar();
}
}
|
Java
|
UTF-8
| 801 | 2.03125 | 2 |
[] |
no_license
|
package cn.geoportal.gmo.server.service;
import cn.geoportal.gmo.server.entity.SysMenu;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
*
*/
public interface SysMenuService extends IService<SysMenu> {
/**
* 1、根据用户id查询菜单列表
*
* @return
*/
List<SysMenu> getMenusByUserId();
/**
* 2、根据角色获取菜单列表
* @return
*/
List<SysMenu> getMenusWithRole();
/**
* 3、查询所有菜单
* @return
*/
List<SysMenu> getAllMenus();
/**
* 4、查询menu
* @param id
* @return
*/
SysMenu findMenuById(Integer id);
/**
* 5、更新menu
* @param sysMenu
* @return
*/
int UpdateMenuById(SysMenu sysMenu);
}
|
Markdown
|
UTF-8
| 750 | 2.609375 | 3 |
[] |
no_license
|
# 自定义Hook
State HOOK: useState
Effect HOOK: useEffect
自定义Hook:将一些常用的,跨越多个组件的HOOK功能,抽离出去形成一个函数,该函数就是自定义HOOK
由于其内部需要使用HOOK功能,所以它本身也需要按照HOOK规则实现:
1. 函数名必须以use开头
2. 调用自定义HOOK函数时,应该放到顶层
例如:
1. 很多组件都需要在第一次加载完成之后,获取所有学生的数据
2. 很多组件都需要在第一次加赞完成后,启动一个计时器,然后在组件销毁时卸载
> 使用hook的时候,如果没有按照hook的规则进行,eslint的一个插件会报出警告,eslint-plugin-react-hooks插件
npmjs网站搜eslint-plugin-react-hooks规则
|
Markdown
|
UTF-8
| 2,782 | 2.75 | 3 |
[] |
no_license
|
+++
title: "Tun Mustapha cannot be sworn in as Sabah Affairs Minister in early August unless unconstitutional pressure is applied to get the constitutional amendment to repeal Article 43(8) to become law"
date: "1993-06-18"
tags:
+++
_by Parliamentary Opposition Leader, DAP Secretary-General and MP for Tanjung, Lim Kit Siang, in Petaling Jaya on Friday, June 18, 1993:_
# Tun Mustapha cannot be sworn in as Sabah Affairs Minister in early August unless unconstitutional pressure is applied to get the constitutional amendment to repeal Article 43(8) to become law
Deputy Prime Minister, Ghafar Baba, said in Sabah yesterday that Tun Haji Mustapha Datuk Harun is expected to be sworn in as Sabah Affairs Minister in early August.</u>
Tun Mustapha cannot be sworn is as Sabah Affairs Minister in early August unless unconstitutional pressure is applied to get the constitutional amendment to repeal Article 43(8) to allow Tun Mustapha to keep his Usukan Sabah State Assembly seat to become law by early August.
The next Dewan Rakyat meeting is from July 19 to August 3 and the next Dewan Negara meeting from August 4 to 11. The bills passed by both Houses of Parliament will not become law until they are given the Royal Assent by the Yang di Pertuan Agong and published in the government gazette, which would normally take about one month after they had passed the Dewan Negara.
This means that according to normal practice, the constitution amendment bill to allow Tun Mustapha to become Federal Cabinet Minister without having to resign his State Assembly seat will not become law until early September.
Furthermore, under the constitution amendment in 1984, the Yang di Pertuan Agong can withhold his Royal Assent and remit the proposed new constitution amendment back to Parliament for reconsideration.
I am not saying that this will happen in the case of the new constitution amendment bill to allow Tun Mustapha to keep his Usukan Sabah State Assembly seat, although there is a stong and powerful case for the Yang di Pertuan Agong to withhold his Royal Assent on the fundamental issue as to whether it is proper and healthy that the Federal Constitution should be amended for the sake of one person.
In any event, no one, whether in Government or Opposition, should anticipate as to when Royal Assent would be given, or even if Royal Assent would be withheld, uncless unconstitutional pressure is applied.
It is therefore premature for Ghafar Baba to announce that Tun Mustapha would be sworn in as Sabah Affairs Minister in early August.
The government should give a clear-cut assurance that it would not apply unconstitutional pressure just to rush the new constitutional amendment bill through all atages so that Tun Mustapha could be sworn in as Sabah Affairs Minister in early August.
|
Go
|
UTF-8
| 2,050 | 3.25 | 3 |
[
"Apache-2.0"
] |
permissive
|
// Package canonical provides a simple normalization for device identifiers. These
// identifiers have the form {prefix}:{id}/{service}/{ignored}, where only {prefix}
// and {id} are required.
package canonical
import (
"errors"
"fmt"
"regexp"
"strings"
"unicode"
)
// Id represents a normalized identifer for a device.
type Id interface {
// Bytes returns a distinct byte slice representation
// of this canonicalized identifier.
Bytes() []byte
}
// id is the internal Id implementation
type id string
func (this id) Bytes() []byte {
return []byte(this)
}
var _ Id = id("")
const (
hexDigits = "0123456789abcdefABCDEF"
macDelimiters = ":-.,"
macPrefix = "mac"
macLength = 12
)
var (
// idPattern is the precompiled regular expression that all device identifiers must match.
// Matching is partial, as everything after the service is ignored.
idPattern = regexp.MustCompile(
`^(?P<prefix>(?i)mac|uuid|dns|serial):(?P<id>[^/]+)(?P<service>/[^/]+)?`,
)
)
// ParseId parses a raw string identifier into an Id
func ParseId(value string) (Id, error) {
match := idPattern.FindStringSubmatch(value)
if match == nil {
return nil, errors.New(fmt.Sprintf("Invalid device id: %s", value))
}
var (
prefix = strings.ToLower(match[1])
idPart = match[2]
service = match[3]
)
if prefix == macPrefix {
var invalidCharacter rune = -1
idPart = strings.Map(
func(r rune) rune {
switch {
case strings.ContainsRune(hexDigits, r):
return unicode.ToLower(r)
case strings.ContainsRune(macDelimiters, r):
return -1
default:
invalidCharacter = r
return -1
}
},
idPart,
)
if invalidCharacter != -1 {
return nil, errors.New(fmt.Sprintf("Invalid character in mac: %c", invalidCharacter))
} else if len(idPart) != macLength {
return nil, errors.New(fmt.Sprintf("Invalid length of mac: %s", idPart))
}
}
if len(service) > 0 {
return id(fmt.Sprintf("%s:%s%s/", prefix, idPart, service)), nil
}
return id(fmt.Sprintf("%s:%s", prefix, idPart)), nil
}
|
C#
|
UTF-8
| 2,230 | 3.328125 | 3 |
[] |
no_license
|
using DeepSearch_Labyrinth.Services;
using System;
namespace DeepSearch_Labyrinth
{
class Program
{
static void Main(string[] args)
{
SearchService service;
while (true)
{
int opt = MapChoice();
switch (opt)
{
case 1:
service = new SearchService("map_1");
break;
case 2:
service = new SearchService("map_2");
break;
default:
Console.WriteLine("Please, choose a valid map");
continue;
}
/*
//service.Widesolver();
service.Deepsolver();
service.printMatrix();
service.printSearch();
service.printPath();
Console.WriteLine("Custo de Busca: " + service.getSearchCost());
Console.WriteLine("Custo do Caminho: " + service.getPathCost());
*/
service.printMap();
service.Deepsolver();
service.printMapPath();
Console.WriteLine("Busca pesou: " + service.getSearchCost());
Console.WriteLine("Caminho Pesou: " + service.getPathCost());
Console.WriteLine("Total de Busca: " + service.getTotalCost());
Console.WriteLine("================================");
Console.WriteLine("Want to try again?\nY | Any other key, finishes app");
string choice = Console.ReadLine();
switch (choice)
{
case "Y":
continue;
case "y":
continue;
default:
return;
}
}
}
public static int MapChoice()
{
Console.WriteLine("Please, Choose your map: ");
Console.WriteLine("1 - Map 1");
Console.WriteLine("2 - Map 2");
return Convert.ToInt32(Console.ReadLine());
}
}
}
|
Java
|
UTF-8
| 3,016 | 2.171875 | 2 |
[] |
no_license
|
package com.google.api.services.sheets.v4.model;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
import java.util.List;
public final class CellData extends GenericJson {
@Key
private DataValidationRule dataValidation;
@Key
private CellFormat effectiveFormat;
@Key
private ExtendedValue effectiveValue;
@Key
private String formattedValue;
@Key
private String hyperlink;
@Key
private String note;
@Key
private PivotTable pivotTable;
@Key
private List<TextFormatRun> textFormatRuns;
@Key
private CellFormat userEnteredFormat;
@Key
private ExtendedValue userEnteredValue;
public DataValidationRule getDataValidation() {
return this.dataValidation;
}
public CellData setDataValidation(DataValidationRule dataValidationRule) {
this.dataValidation = dataValidationRule;
return this;
}
public CellFormat getEffectiveFormat() {
return this.effectiveFormat;
}
public CellData setEffectiveFormat(CellFormat cellFormat) {
this.effectiveFormat = cellFormat;
return this;
}
public ExtendedValue getEffectiveValue() {
return this.effectiveValue;
}
public CellData setEffectiveValue(ExtendedValue extendedValue) {
this.effectiveValue = extendedValue;
return this;
}
public String getFormattedValue() {
return this.formattedValue;
}
public CellData setFormattedValue(String str) {
this.formattedValue = str;
return this;
}
public String getHyperlink() {
return this.hyperlink;
}
public CellData setHyperlink(String str) {
this.hyperlink = str;
return this;
}
public String getNote() {
return this.note;
}
public CellData setNote(String str) {
this.note = str;
return this;
}
public PivotTable getPivotTable() {
return this.pivotTable;
}
public CellData setPivotTable(PivotTable pivotTable) {
this.pivotTable = pivotTable;
return this;
}
public List<TextFormatRun> getTextFormatRuns() {
return this.textFormatRuns;
}
public CellData setTextFormatRuns(List<TextFormatRun> list) {
this.textFormatRuns = list;
return this;
}
public CellFormat getUserEnteredFormat() {
return this.userEnteredFormat;
}
public CellData setUserEnteredFormat(CellFormat cellFormat) {
this.userEnteredFormat = cellFormat;
return this;
}
public ExtendedValue getUserEnteredValue() {
return this.userEnteredValue;
}
public CellData setUserEnteredValue(ExtendedValue extendedValue) {
this.userEnteredValue = extendedValue;
return this;
}
public CellData set(String str, Object obj) {
return (CellData) super.set(str, obj);
}
public CellData clone() {
return (CellData) super.clone();
}
}
|
Java
|
UTF-8
| 339 | 1.9375 | 2 |
[] |
no_license
|
package tomining.java.json.jackson.jodatime.model;
import org.joda.time.DateTime;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Data;
/**
* Created by naver on 2017. 5. 4..
*/
@Data
@Builder
public class User {
private String id;
private String password;
private DateTime registYmdt;
}
|
C
|
UTF-8
| 1,988 | 2.921875 | 3 |
[] |
no_license
|
#include <sys/types.h>
#include <unistd.h>
//#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "runservice.h"
ssize_t getline(char **buf, size_t *n, FILE *fp) {
char c;
int needed = 0;
int maxlen = *n;
char *buf_ptr = *buf;
if (buf_ptr == NULL || maxlen == 0) {
maxlen = 128;
if ((buf_ptr = malloc(maxlen)) == NULL)
return -1;
}
do {
c = fgetc(fp);
buf_ptr[needed++] = c;
if (needed >= maxlen) {
*buf = buf_ptr;
buf_ptr = realloc(buf_ptr, maxlen *= 2);
if (buf_ptr == NULL) {
(*buf)[needed - 1] = '\0';
return -1;
}
}
if (c == EOF || feof(fp))
return -1;
} while (c != '\n');
buf_ptr[needed] = '\0';
*buf = buf_ptr;
*n = maxlen;
return needed;
}
int chk_process(const char *process_name)
{
FILE *stream;
char *line = NULL;
size_t len = 0;
ssize_t read_len;
stream = popen( "ps", "r" );
if (stream == NULL)
return -1;
int exists = 0;
while ( (read_len = getline(&line, &len, stream)) != -1)
{
int len = strlen(line);
char *cmd = line + len;
while ( len >0 )
{
len--;
if ( *cmd == ' ')
{
cmd++;
break;
}
cmd--;
}
if( strncmp(cmd, process_name, strlen(process_name)) == 0 )
{
exists = 1;
break;
}
}
pclose( stream );
if ( line != NULL )
free(line);
return exists;
}
void run_service(const char *process_name, const char *package_name, const char *activity_name, int interval_sec)
{
while (1)
{
if ( chk_process(process_name) == 0)
{
char *pkg_activity_name = NULL;
asprintf(&pkg_activity_name, "/system/bin/am start --user 0 -n %s/%s", package_name, activity_name);
system(pkg_activity_name);
free(pkg_activity_name);
}
sleep(interval_sec);
}
return;
}
|
Java
|
UTF-8
| 373 | 2.875 | 3 |
[] |
no_license
|
package Lista1;
public class Questao11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] matriz = new int[10][10];
for (int i = 0; i < matriz.length; i++) {
for (int j = 0; j < matriz.length; j++) {
System.out.print((i+1) + "-" + (j+1) + " ");
if(j==9) {
System.out.println("\n");
}
}
}
}
}
|
Python
|
UTF-8
| 812 | 2.59375 | 3 |
[] |
no_license
|
"""
html转pdf
"""
import pdfkit
class Html2pdf(object):
__BASE_PATH = 'file/'
def __init__(self):
pass
@staticmethod
def handle():
options = {
'encoding': "UTF-8",
'no-outline': None,
'disable-smart-shrinking': None,
'no-pdf-compression': None
}
with open('file/中国轴承行业网_VIP才可见的文章_20170313.txt', 'r') as f:
for line in f.readlines():
line_split = line[:-1].split(': ')
try:
pdfkit.from_url(line_split[1], 'out/' + line_split[0] + '.pdf', options=options)
except IOError:
print('UnicodeDecodeError:', line_split)
if __name__ == '__main__':
handle = Html2pdf()
handle.handle()
|
Markdown
|
UTF-8
| 1,468 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
<p align="center">
<img src="https://yasinates.com/counter-up.gif" width="400">
</p>
<h2 align="center">React Counter Up</h2>
[](https://badge.fury.io/js/react)
This project is basic counter up app via [React](https://github.com/facebook/react/).
This project was developed for improve myself.
---
[**Demo URL**](http://yasinatesim.react-counter-up.surge.sh)
---
### Features
- [SCSS](https://sass-lang.com/guide) is used for coding css more effectively and easily
- [BEMCSS](http://getbem.com/introduction/) is used from CSS naming convention
Development with [Airbnb](https://github.com/airbnb/javascript), which is often a reasonable approach to JavaScript.
- Find and fix problems in your JavaScript code with [Eslint](https://eslint.org/).
- Beautify code with [Prettier](https://prettier.io/).
- Lint code and can prevent bad git with [Lint Staged](https://www.npmjs.com/package/lint-staged) and [Husky](https://www.npmjs.com/package/husky) tools.
## How to Use
1- Clone this repository
```bash
git clone https://github.com/yasinatesim/react-counter-up.git
```
2- Install the project dependencies
```bash
cd react-counter-up
npm install
```
### Development Version
```bash
npm start
```
### Production Version
```bash
npm run build
```
### Lint
```bash
npm run lint
```
## License
[](http://badges.mit-license.org)
|
JavaScript
|
UTF-8
| 5,032 | 2.515625 | 3 |
[] |
no_license
|
import React from 'react';
import { View, Button, TextInput, Text, TouchableOpacity, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useState } from 'react';
import { useEffect } from 'react';
export default function SetRecipe({ route, navigation }) {
const STORAGE_KEY = route.params.key;
const [title, setTitle] = useState("");
const [ingredients, setIngredients] = useState([]);
const [description, setDescription] = useState("");
const [steps, setSteps] = useState([]);
const [edit, setEdit] = useState(route.params.edit);
let data = { title: "", ingredients: [], description: "", steps: [] };
useEffect(() => {
async function getData() {
try {
const savedData = await AsyncStorage.getItem(STORAGE_KEY);
if (savedData != null) {
let newData = JSON.parse(savedData);
if (newData.title !== undefined) setTitle(newData.title);
if (newData.ingredients !== undefined) setIngredients(newData.ingredients);
if (newData.description !== undefined) setDescription(newData.description);
if (newData.steps !== undefined) setSteps(newData.steps);
navigation.setOptions({ title: title });
}
}
catch (e) {
console.error(e);
}
}
getData();
navigation.setOptions({
headerRight: () => (<TouchableOpacity onPress={() => setEdit(!edit)}><Text>Rediger</Text></TouchableOpacity>)
});
}, []);
useEffect(() => {
data.title = title;
data.ingredients = ingredients;
data.description = description;
data.steps = steps;
async function setData() {
try {
const jsonData = JSON.stringify(data);
await AsyncStorage.setItem(STORAGE_KEY, jsonData);
}
catch (e) {
console.error(e);
}
}
setData();
}, [title, description, ingredients, steps]);
function AddIngredient() {
setIngredients([...ingredients, ""]);
}
function EditIngredient(text, index) {
let s = ingredients;
s[index] = text;
setIngredients([...s]);
}
async function DeleteThis() {
await AsyncStorage.removeItem(STORAGE_KEY);
navigation.navigate('Home');
}
function EditView() {
return (
<View>
{console.log('render')}
<TextInput style={styles.title} placeholder='Tittel' onEndEditing={v => setTitle(v.nativeEvent.text)} defaultValue={title} />
<View style={styles.ingredients}>
<Text style={styles.input}>Ingredienser</Text>
{ingredients.map((o, i) => {
return (<TextInput
key={i}
style={styles.input}
placeholder="Tom ingrediens"
onEndEditing={(v) => EditIngredient(v.nativeEvent.text, i)}
defaultValue={o}
/>)
})}
<TouchableOpacity style={styles.button} onPress={AddIngredient}><Text>Legg til ingrediens</Text></TouchableOpacity>
</View>
<TextInput style={styles.input} placeholder='Beskrivelse' onEndEditing={v => setDescription(v.nativeEvent.text)} defaultValue={description} />
<Button title='Sett første steg' onPress={() => navigation.push('Set Step', { key: STORAGE_KEY, index: 1, edit: true })} />
<Button title='Slett oppskrift' onPress={DeleteThis} />
</View>)
}
function ShowView() {
return (
<View>
<Text style={styles.title}>{title}</Text>
<View style={styles.ingredients}>
<Text style={styles.input}>Ingredienser</Text>
{ingredients.map((o, i) => {
return (<Text key={i}>{o}</Text>);
})}
</View>
<Text style={styles.input}>{description}</Text>
<View>
{steps.map((o, i) => {
return (<Button key={i} title={"Steg " + (i + 1)} onPress={() => navigation.push('Set Step', { key: STORAGE_KEY, index: i + 1, edit: false })} />)
})}
</View>
</View>
)
}
return (
(edit) ? (<EditView />) : (<ShowView />)
);
}
const styles = StyleSheet.create({
button: {
fontSize: 16,
backgroundColor: 'lightgreen',
borderWidth: 1,
padding: 2
},
input: {
fontSize: 22
},
ingredients: {
backgroundColor: 'lightyellow',
margin: 5
},
title: {
fontSize: 30
}
})
|
C++
|
UTF-8
| 788 | 2.65625 | 3 |
[] |
no_license
|
#ifndef SIMULATION_FRAMEWORK_SIMULATIONINITIALIZER_H
#define SIMULATION_FRAMEWORK_SIMULATIONINITIALIZER_H
#include <SDL.h>
#include "enums/SubSystems.h"
namespace sf {
/** Initialize SDL at construction and shutdown at destruction. */
class Initializer {
public:
/** Initialize SDL's provided subsystems.
* @param subsystems The different subsystems OR'd together.
*/
explicit Initializer(const Uint32 subsystems = DEFAULT_SUBSYSTEMS);
~Initializer();
void initSubSystem(const Uint32 subsystem);
void quitSubSystem(const Uint32 subsystem);
private:
static const Uint32 DEFAULT_SUBSYSTEMS = SubSystems::EVENTS | SubSystems::VIDEO;
};
} // sf
#endif //SIMULATION_FRAMEWORK_SIMULATIONINITIALIZER_H
|
Shell
|
UTF-8
| 1,254 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
#!/bin/bash
INCLUDE_GLOB="include/*.sh"
source "$(dirname "$(readlink -f "$0")")"/../test.sh
start_test "Regression #31: double error reporting"
generate_test_fail_check 'assert_equals "$(false)" ""' <<EOF
[test.sh] pending_exception exception: Pending exception, probably a masked error in a command substitution
[test.sh] at check_pending_exceptions(test.sh:)
[test.sh] at assert_equals(test.sh:)
[test.sh] at main(the_test.sh:)
[test.sh] Pending exception:
[test.sh] implicit exception: Error in main(the_test.sh:): 'false' exited with status 1
EOF
generate_test_fail_check 'assert_equals "$(false)" "a"' <<EOF
[test.sh] pending_exception exception: Pending exception, probably a masked error in a command substitution
[test.sh] at check_pending_exceptions(test.sh:)
[test.sh] at assert_equals(test.sh:)
[test.sh] at main(the_test.sh:)
[test.sh] Pending exception:
[test.sh] implicit exception: Error in main(the_test.sh:): 'false' exited with status 1
EOF
generate_test_fail_check 'run_test_script ./__I_dont_exist' <<EOF
$TESTSH: line : $TEST_TMP/__I_dont_exist: No such file or directory
[test.sh] implicit exception: Error in run_test_script(test.sh:): '"\$test_script" "\$@"' exited with status 127
[test.sh] at main(the_test.sh:)
EOF
|
C#
|
UTF-8
| 1,997 | 3.109375 | 3 |
[] |
no_license
|
public static IEnumerable<T> MultisetIntersect(this IEnumerable<T> first,
IEnumerable<T> second, IEqualityComparer<T> comparer)
{
// Call the overload with the default comparer.
return first.MultisetIntersect(second, EqualityComparer<T>.Default);
}
public static IEnumerable<T> MultisetIntersect(this IEnumerable<T> first,
IEnumerable<T> second, IEqualityComparer<T> comparer)
{
// Validate parameters. Do this separately so check
// is performed immediately, and not when execution
// takes place.
if (first == null) throw new ArgumentNullException("first");
if (second == null) throw new ArgumentNullException("second");
if (comparer == null) throw new ArgumentNullException("comparer");
// Defer execution on the internal
// instance.
return first.MultisetIntersectImplementation(second, comparer);
}
private static IEnumerable<T> MultisetIntersectImplementation(
this IEnumerable<T> first, IEnumerable<T> second,
IEqualityComparer<T> comparer)
{
// Validate parameters.
Debug.Assert(first != null);
Debug.Assert(second != null);
Debug.Assert(comparer != null);
// Get the dictionary of the first.
IDictionary<T, long> counts = first.GroupBy(t => t, comparer).
ToDictionary(g => g.Key, g.LongCount(), comparer);
// Scan
foreach (T t in second)
{
// The count.
long count;
// If the item is found in a.
if (counts.TryGetValue(t, out count))
{
// This is positive.
Debug.Assert(count > 0);
// Yield the item.
yield return t;
// Decrement the count. If
// 0, remove.
if (--count == 0) counts.Remove(t);
}
}
}
|
JavaScript
|
UTF-8
| 1,441 | 4.4375 | 4 |
[
"MIT"
] |
permissive
|
// Implement the following operations of a queue using stacks.
//
// push(x) -- Push element x to the back of queue.
// pop() -- Removes the element from in front of queue.
// peek() -- Get the front element.
// empty() -- Return whether the queue is empty.
//
// Notes:
//
// You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
// Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
// You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
/**
* @constructor
*/
var Queue = function() {
this.data = [];
};
/**
* @param {number} x
* @returns {void}
*/
Queue.prototype.push = function(x) {
this.data.push(x);
};
/**
* @returns {void}
*/
Queue.prototype.pop = function() {
let temp = [];
for (let i = this.data.length - 2; i >= 0; i--) {
temp[i] = this.data.pop();
}
let wanted = this.data.pop();
for (let i = 0, n = temp.length; i < n; i++) {
this.data.push(temp[i]);
}
return wanted;
};
/**
* @returns {number}
*/
Queue.prototype.peek = function() {
return this.data[0];
};
/**
* @returns {boolean}
*/
Queue.prototype.empty = function() {
return this.data.length === 0;
};
|
Python
|
UTF-8
| 256 | 2.78125 | 3 |
[] |
no_license
|
def unpad(s):
if s[-1] == 0 or s[-s[-1]:] != bytes([s[-1]] * s[-1]):
return 'invalid'
return 'valid'
print(unpad(b'ICE ICE BABY\x04\x04\x04\x04'))
print(unpad(b'ICE ICE BABY\x05\x05\x05\x05'))
print(unpad(b'ICE ICE BABY\x01\x02\x03\x04'))
|
C++
|
UTF-8
| 394 | 3.015625 | 3 |
[] |
no_license
|
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
float x,y=10.5,average;
cin>>x;
while(x<0 || x>10.0){
cout<<"nota invalida"<<endl;
cin>>x;
}
cin>>y;
while(y<0 || y>10.0){
cout<<"nota invalida"<<endl;
cin>>y;
}
average = (x+y)/2.0;
cout<<fixed<<setprecision(2)<<"media = "<<average<<endl;
return 0;
}
|
C#
|
UTF-8
| 1,788 | 3.15625 | 3 |
[] |
no_license
|
using System;
namespace SuperVisitor.Potato
{
public static class Potato
{
public static void DoStuff()
{
var sqlServer = new SqlServerConfig
{
Server = "cda-dev-db02.devid.local",
Database = "CDA-DEV",
Port = 1512
};
var visitor = new GetConfigSummaryVisitor();
sqlServer.Accept(visitor);
Console.WriteLine(visitor.Result);
}
}
public interface IConfig
{
void Accept(IConfigVisitor visitor);
}
public interface IConfigVisitor
{
void Visit(SqlServerConfig sqlServerConfig);
void Visit(OracleConfig oracleConfig);
}
public class GetConfigSummaryVisitor : IConfigVisitor
{
public string Result { get; set; }
public void Visit(SqlServerConfig sqlServerConfig)
{
Result = $"Server=\"{sqlServerConfig.Server}\", Database=\"{sqlServerConfig.Server}\", Port={sqlServerConfig.Port}";
}
public void Visit(OracleConfig csvConfig)
{
Result = $"Filename=\"{csvConfig.Database}\", Seperator=\"{csvConfig.Server}\"";
}
}
public class SqlServerConfig : IConfig
{
public string Server { get; set; }
public string Database { get; set; }
public int Port { get; set; }
public void Accept(IConfigVisitor visitor)
{
visitor.Visit(this);
}
}
public class OracleConfig : IConfig
{
public string Server { get; set; }
public string Database { get; set; }
public int Port { get; set; }
public void Accept(IConfigVisitor visitor)
{
visitor.Visit(this);
}
}
}
|
Java
|
UTF-8
| 443 | 1.609375 | 2 |
[] |
no_license
|
package scripts;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;
import pom.EndocLoaded;
public class EnDocTest extends EnsuperTest {
@Test
public void doclodedTest()
{
Actions actions=new Actions(driver);
EndocLoaded d = new EndocLoaded(driver);
d.docperform(actions);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
d.docloaded();
}
}
|
C++
|
UTF-8
| 1,367 | 4.0625 | 4 |
[
"Unlicense"
] |
permissive
|
#include <iostream>
//
// Code by: Jeremy Pedersen
//
// Licensed under the BSD 2-clause license (FreeBSD license)
//
using namespace std;
class Student {
// Data
private:
string name;
int age;
float score;
// Methods (functions inside the class)
public:
void setData(string selfName, int selfAge, float selfScore) {
name = selfName;
age = selfAge;
score = selfScore;
}
void printData() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Score: " << score << endl;
}
};
int main() {
// Make a struct that can hold 3 students
Student students[3];
// Temporary variables
string name;
int age;
float score;
// Enter name, age, and score
for (int i = 0; i < 3; i++) {
cout << "Enter name, age, and score..." << endl;
cout << "Name: ";
cin >> name;
cout << "Age: ";
cin >> age;
cout << "Score: ";
cin >> score;
cout << endl;
// Put data into student array
students[i].setData(name, age, score);
}
cout << endl;
cout << "Printing array..." << endl;
cout << endl;
for (int i = 0; i < 3; i++) {
students[i].printData();
cout << endl;
}
return 0;
}
|
C
|
UTF-8
| 9,236 | 3.25 | 3 |
[] |
no_license
|
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sendfile.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/errno.h>
#define MAXLINE 4096
#define SA struct sockaddr
#define LISTENQ 1024
#define LENGTH_COMMAND 200
#define maxThreads 100
//Definition of boolean value
typedef int bool;
enum {
false,
true
};
//Error function
void error(char * msg) {
perror(msg);
exit(0);
}
bool checkMaincommand(const char* command){
if (strcmp(command,"quit")==0 || strcmp(command,"ls")==0 || strcmp(command,"get")==0)
return true;
if (strcmp(command,"put")==0)
return true;
return false;
}
void Send(int fd , char* message ,int messageLength){
if(send(fd , message , messageLength, 0)==-1){
printf("Error sending the following command: %s\n",messageLength);
exit(0);
}
}
//Functions that sends a request to the server (after already checking that the
//parameters are correct). It returns true if it was correct and false elsewhere
bool translateRequest(const char* param1, const char* param2, int controlfd){
FILE *desiredFile;
char aux[200];
if (strcmp(param1,"quit")==0){
Send(controlfd,"QUIT", LENGTH_COMMAND);
}
//checks if the file exists
else if (strcmp(param1,"put")==0){
desiredFile = fopen(param2, "r");
if (desiredFile==NULL){
printf("Unable to open %s\n",param2);
return false;
}
fclose(desiredFile);
strcpy(aux,"STOR ");
strcat(aux,param2);
Send(controlfd,aux, LENGTH_COMMAND);
}
else if (strcmp(param1,"ls")==0){
strcpy(aux,"LIST ");
strcat(aux,param2);
Send(controlfd,aux, LENGTH_COMMAND);
}
else{
strcpy(aux,"RETR ");
strcat(aux,param2);
Send(controlfd,aux, LENGTH_COMMAND);
}
return true;
}
//Functions that reads a charr array (input), returns true or false
//depending if the command structure is valid. It also writes the first
//parameter in param1 and the second in param2
bool sendRequest(const char* input,int controlfd){
char aux1[100],aux2[100],aux3[100];
bzero(aux1,100);
bzero(aux2,100);
bzero(aux3,100);
sscanf(input,"%s %s %s",aux1,aux2,aux3);
//printf("Param1: %s size:%i \nParam2: %s size:%i\nParam3: %s size:%i\n",aux1,strlen(aux1),aux2,strlen(aux2),aux3,strlen(aux3));
if (checkMaincommand(aux1)==false){
printf("Not a valid command\n");
return false;
}
if (strlen(aux3)!=0){
printf("Too many arguments for %s\n",aux1);
return false;
}
if (strlen(aux2)!=0 && strcmp(aux1,"quit")==0){
printf("Too many arguments for %s\n",aux1);
return false;
}
if (strlen(aux2)==0 && strcmp(aux1,"quit")!=0 && strcmp(aux1,"ls")!=0){
printf("Not enough arguments for %s\n",aux1);
return false;
}
return translateRequest(aux1,aux2,controlfd);
}
//Initialize the socket, bind it and make it a listener. It sends the address
//to the server and returns the id of the listener socket
int sendPortCommand(const struct sockaddr_in newAddress, int controlfd){
char ipAdress[INET_ADDRSTRLEN];
int port,portaux;
int datafd;
struct sockaddr_in auxaddress;
socklen_t auxlen = sizeof(auxaddress);
char * temp = NULL;
char message[200],aux[10];
strcpy(message,"PORT ");
datafd=socket(AF_INET, SOCK_STREAM, 0);
bind(datafd, (SA * ) & newAddress, sizeof(newAddress));
listen(datafd, LISTENQ);
////////inet_ntop(AF_INET, & (newAddress.sin_addr.s_addr), ipAdress, INET_ADDRSTRLEN);
//Getting the proxy addres for the logging
char serevraddres[INET_ADDRSTRLEN];
getsockname(datafd, (SA * ) & auxaddress, & auxlen);
inet_ntop(AF_INET, & (auxaddress), serevraddres, INET_ADDRSTRLEN);
///////port=ntohs(newAddress.sin_port);
portaux=ntohs(auxaddress.sin_port);
//printf("Client IP='%s', data PORT='%i'\n",serevraddres,portaux);
temp = strtok(serevraddres, ".");
while(temp){
strcat(message,temp);
strcat(message,",");
bzero(temp, strlen(temp));
temp = strtok(NULL, ".");
}
sprintf(aux,"%i",portaux/256);
strcat(message,aux);
strcat(message,",");
bzero(aux,10);
sprintf(aux,"%i",portaux%256);
strcat(message,aux);
//printf("Message: %s\n",message);
send(controlfd,message, LENGTH_COMMAND , 0);
return datafd;
}
//Function that waits for an incoming connection and handles the transfer of data to or from the server
bool transferingData(const char* param1, const char* param2,int listenfd,int controlfd){
char dataRespone[MAXLINE+1], server_response[LENGTH_COMMAND+1];
int datafd,n,sizeRecived=0;
struct sockaddr_in servaddrData;
int serverlen = sizeof(servaddrData);
FILE* desiredFile;
int fd;
struct stat file_stat;
//Accepting the server connection
datafd = accept(listenfd, (SA * ) &servaddrData, &serverlen);
bzero(server_response,LENGTH_COMMAND+1);
if(recv(controlfd,server_response, LENGTH_COMMAND, 0)<0){
printf("Error sending data port to server (no message back)\n");
close(datafd);
return false;
}
//We have to recieve a 201 port ok from the server
//printf("Answer after port command: %s\n",server_response,datafd);
if(strncmp(server_response,"201",3)!=0){
printf("Error sending data port to server (received error message)\n");
close(datafd);
return false;
}
bzero(dataRespone,MAXLINE+1);
//Receiving a file
if (strcmp(param1,"get")==0){
desiredFile = fopen(param2, "w");
while((n=recv(datafd,dataRespone, MAXLINE, 0))>0){
dataRespone[n]='\0';
sizeRecived+=n;
fwrite(dataRespone, sizeof(char), n, desiredFile);
}
printf("Received %i bytes\n",sizeRecived);
fclose(desiredFile);
}
//Recieveing a listing
else if(strcmp(param1,"ls")==0){
while((n=recv(datafd,dataRespone, MAXLINE, 0))>0){
dataRespone[n]='\0';
//printf("Received %i bytes\n",n);
printf("%s\n",dataRespone);
}
}
//Sending a file
else if(strcmp(param1,"put")==0){
fd = open(param2, O_RDONLY);
fstat(fd, &file_stat);
sendfile (datafd, fd, NULL, file_stat.st_size);
printf("Sent %i Bytes\n",file_stat.st_size);
close(fd);
}
close(datafd);
return true;
}
int main(int argc, char **argv){
int controlfd,listenfd;
struct sockaddr_in servaddr;
//Checks if the usage is correct
if (argc != 3){
printf("usage: ./ftpclient <Server-IP> <Listening-Port>");
exit(1);
}
//socket creates a TCP socket (returns socket identifier)
controlfd = socket(AF_INET, SOCK_STREAM, 0);
if (controlfd < 0)
error("Error initializing socket (socket())\n");
//Set struct to 0
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(atoi(argv[2])); /* daytime server */
// Htons converts to the binary port number
//inet_pton converts ASCII argument to the proper format ("presentation to numeric")
if(inet_pton(AF_INET, argv[1], &servaddr.sin_addr)!=1)
error("Error getting the address of the FTP server");
//conection between sockets, 3rd argument is the length of the socket adress
//SA is a generic sockaddr struct
if(connect(controlfd, (SA *) &servaddr, sizeof(servaddr))==-1)
error("Error connecting to the FTP server");
char client_command[LENGTH_COMMAND+1],server_response[LENGTH_COMMAND+1];
char param1[100],param2[100];
struct sockaddr_in dataAddress;
while(1){
bzero(client_command,LENGTH_COMMAND+1);
bzero(server_response,LENGTH_COMMAND+1);
bzero(param1,100);
bzero(param2,100);
//Getting the command from the user
printf("ftp>");
fgets(client_command,LENGTH_COMMAND,stdin);
//Taken the /n character off
client_command[strlen(client_command)-1]='\0';
sscanf(client_command,"%s %s",param1,param2);
//SendRequest checks if the command is correct before sending anything
if(sendRequest(client_command,controlfd)==false)
continue;
//if we don receive a response the server must have been disconnected
if(recv(controlfd,server_response, LENGTH_COMMAND, 0)<=0 || strcmp(client_command, "quit") == 0){
//printf("%s\n",server_response);
printf("Disconnected from the server\n");
break;
}
//printf("%s\n",server_response);
//The server response must have been a 200 command OK to continue
if(strncmp(server_response,"200",3)==0){
//Setting up the new data connection
bzero( & dataAddress, sizeof(dataAddress));
dataAddress.sin_family = AF_INET;
dataAddress.sin_addr.s_addr = htonl(INADDR_ANY);
dataAddress.sin_port = 0;
//Setting up the listenting port and sending the address to the server
listenfd=sendPortCommand(dataAddress,controlfd);
//Accepting the connection and sening the data
transferingData(param1,param2,listenfd,controlfd);
}
}
close(controlfd);
exit(0);
}
|
PHP
|
UTF-8
| 1,225 | 3.0625 | 3 |
[] |
no_license
|
<?php
class Usuario
{
private $_id;
private $_nombre;
private $_clave;
private $_ultimoLogueo;
private $_idEmpleado;
public function SetNombre($nombre)
{
$this->_nombre = $nombre;
}
public function SetClave($clave)
{
$this->_clave = sha1($clave);
}
public function SetUltimoLogueo($ultimoLogueo)
{
$this->_ultimoLogueo = $ultimoLogueo;
}
public function SetIdEmpleado($idEmpleado)
{
$this->_idEmpleado = $idEmpleado;
}
public function InsertarUsuarioParametros()
{
$objetoAccesoDato = AccesoDatos::dameUnObjetoAcceso();
$consulta =$objetoAccesoDato->RetornarConsulta("INSERT INTO usuarios (nombre,clave,ultimo_logueo,id_empleado)VALUES(:nombre,:clave,:ultimoLogueo,:idEmpleado)");
$consulta->bindValue(':nombre',$this->_nombre, PDO::PARAM_STR);
$consulta->bindValue(':clave', $this->_clave, PDO::PARAM_STR);
$consulta->bindValue(':ultimoLogueo', $this->_ultimoLogueo, PDO::PARAM_STR);
$consulta->bindValue(':idEmpleado', $this->_idEmpleado, PDO::PARAM_INT);
$consulta->execute();
return $objetoAccesoDato->RetornarUltimoIdInsertado();
}
}
?>
|
Python
|
UTF-8
| 1,008 | 4.28125 | 4 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
A Generator Expression
So, a generator expression produces a generator
A generator expression can be understood as a lazy version of a list comprehension:
it does not eagerly build a list, but returns a generator that will lazily produce the items on demand.
In other words, if a list comprehension is a factory of lists, a generator
expression is a factory of generators.
So, a generator expression produces a generator.
"""
import re
import reprlib
WORDS_PAT = re.compile(r'\w+')
class Sentence(object):
def __init__(self, text):
self.text = text
def __repr__(self):
return "Sentence(%s)" % reprlib.repr(self.text)
def __iter__(self):
return (match.group() for match in WORDS_PAT.finditer(self.text))
def test_whether_iterable():
s = Sentence("I am a good student. But i am stupid and simple.")
print(s)
for word in s:
print(word)
print(list(s))
if __name__ == '__main__':
test_whether_iterable()
|
Markdown
|
UTF-8
| 3,600 | 3.828125 | 4 |
[] |
no_license
|
#Types of Design Patterns
#Behavioral Patterns
Behavioral patterns are design patterns that are explain how the objects react. It describes how different objects and classes interact with each other by sending messages. They objects and classes talk to each other about how to do things and also how to divide a class amongst themselves. Behavioral patterns describe the flow. Behavioral patterns describe the pattern of communication between classes and objects. These patterns use inheritance to distribute communication between classes and objects. There are several kind of behavioral patterns. The template form and interpreter method are the most common type.
Template method is the most common kind of behavioral pattern. The template method makes use of abstract definition of the algorithm. It defines the algorithm step by step. Each step invokes either an abstract operation or a primitive operation. A subclass fleshes out the algorithm by defining the abstract operations. The other kind of pattern is the interpreter method which represents grammar as a class hierarchy and implements an interpreter as an operation on instances of these classes.
There are several other kinds of behavioral patterns like the chain of responsibity and the observer. The other methods of behavioral pattern make use of encapsulation where we encapsulate the algorithm and delegate requests to it.
#Creational Patterns
Creational design patterns abstract the instantiation process. They help make a system independent of how its objects are created, composed, and represented. A class creational pattern uses inheritance to vary the class that's instantiated, whereas an object creational pattern will delegate instantiation to another object. Creational patterns become important as systems evolve to depend more on object composition than class inheritance. As that happens, emphasis shifts away from hard-coding a fixed set of behaviors toward defining a smaller set of fundamental behaviors that can be composed into any number of more complex ones. Thus creating objects with particular behaviors requires more than simply instantiating a class.
#Structural Patterns
Structural patterns are concerned with how classes and objects are composed to form larger structures. Structural class patterns use inheritance to compose interfaces or implementations. As a simple example, consider how multiple inheritance mixes two or more classes into one. The result is a class that combines the properties of its parent classes. This pattern is particularly useful for making independently developed class libraries work together. Another example is the class form of the Adapter pattern. In general, an adapter makes one interface (the adaptee's) conform to another, thereby providing a uniform abstraction of different interfaces. A class adapter accomplishes this by inheriting privately from an adaptee class. The adapter then expresses its interface in terms of the adaptee's.
Rather than composing interfaces or implementations, structural object patterns describe ways to compose objects to realize new functionality. The added flexibility of object composition comes from the ability to change the composition at run-time, which is impossible with static class composition.
[Prev Page](https://github.com/Krithika-Balan2290/Concurrency-Design-Patterns/blob/master/Docs/Intro.md) | [Next Page](https://github.com/Krithika-Balan2290/Concurrency-Design-Patterns/blob/master/Docs/active.md)
[Back to contents](https://github.com/Krithika-Balan2290/Concurrency-Design-Patterns/blob/master/Index.md)
|
Python
|
UTF-8
| 1,552 | 3.171875 | 3 |
[] |
no_license
|
from hex_to_base64 import hex_to_base64
from subprocess import Popen, PIPE
#confirmed = "false"
confirmed = "true"
port_number_information = "input port number (1~223): "
hex_string_information = \
"input hex string\n" + \
" Example: 12345678ABCDEF\n"
command_format_string = \
'mosquitto_pub -h 127.0.0.1' + \
' -t "application/1/node/0000000000000000/tx"' + \
' -m "{{\\"confirmed\\": {0},\\"fPort\\":{1},' + \
'\\"data\\": \\"{2}\\"}}"'
def make_command_string(port, base64_string):
global confirmed
return command_format_string.format (confirmed, port, base64_string)
def input_port_number():
while True:
port = input (port_number_information)
try:
# if port is not number string, it rase ValueError
int_port = int(port)
# The range of port number is 1 to 223
if int_port <1 or int_port > 223:
raise ValueError
except ValueError:
print ("port must be number in 1 to 223")
continue
else:
break
return port
def input_hex_string_and_convert_to_base64():
while True:
hex_string = input (hex_string_information)
try:
base64_string = hex_to_base64 (hex_string)
#print ( "base64_string: " + base64_string )
except:
print ("check input string")
continue
else:
break
return base64_string
port = input_port_number ()
base64_string = input_hex_string_and_convert_to_base64 ()
#print ( "base64: " + base64_string )
command_string = make_command_string (port, base64_string)
#print ( "command_string: " + command_string )
Popen([command_string], shell=True, stdout=PIPE)
|
Java
|
UTF-8
| 8,739 | 3.8125 | 4 |
[] |
no_license
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Comparator;
/**
In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:
High Card: Highest value card.
One Pair: Two cards of the same value.
Two Pairs: Two different pairs.
Three of a Kind: Three cards of the same value.
Straight: All cards are consecutive values.
Flush: All cards of the same suit.
Full House: Three of a kind and a pair.
Four of a Kind: Four cards of the same value.
Straight Flush: All cards are consecutive values of same suit.
Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.
The cards are valued in the order:
2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.
If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on.
Consider the following five hands dealt to two players:
Hand Player 1 Player 2 Winner
1 5H 5C 6S 7S KD
Pair of Fives
2C 3S 8S 8D TD
Pair of Eights
Player 2
2 5D 8C 9S JS AC
Highest card Ace
2C 5C 7D 8S QH
Highest card Queen
Player 1
3 2D 9C AS AH AC
Three Aces
3D 6D 7D TD QD
Flush with Diamonds
Player 2
4 4D 6S 9H QH QC
Pair of Queens
Highest card Nine
3D 6D 7H QD QS
Pair of Queens
Highest card Seven
Player 1
5 2H 2D 4C 4D 4S
Full House
With Three Fours
3C 3D 3S 9S 9D
Full House
with Three Threes
Player 1
The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player's hand is in no specific order, and in each hand there is a clear winner.
How many hands does Player 1 win?
Answer: 376
@author Westy92
*/
public class Prob54 extends Euler
{
public static void main(String args[])
{
startTiming();
int p1 = 0, p2 = 0;
try
{
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Westy92\\Desktop\\Other\\Project Euler\\test\\Prob54.in"));
while ( in.ready() )
{
String hands = in.readLine();
Hand h1 = new Hand(hands.substring(0, 14));
Hand h2 = new Hand(hands.substring(15, hands.length()));
if ( h1.getHighestRank() == h2.getHighestRank() )
{
if ( h1.getHighestOfRank().compareTo(h2.getHighestOfRank()) == 0 )
{
int o;
for ( o = 0; o < 5 && h1.getHighestCard(o).compareTo(h2.getHighestCard(o)) == 0; ++o ){}
if ( h1.getHighestCard(o).compareTo(h2.getHighestCard(o)) > 0 )
++p1;
else
++p2;
}
else if ( h1.getHighestOfRank().compareTo(h2.getHighestOfRank()) > 0 )
++p1;
else
++p2;
}
else if ( h1.getHighestRank().compareTo(h2.getHighestRank()) > 0 )
++p1;
else
++p2;
}
} catch ( Exception e ) { }
System.out.println(p1);
stopTiming();
}
}
class Hand
{
public enum Rank { HIGHCARD, ONEPAIR, TWOPAIR, THREEKIND, STRAIGHT, FLUSH, FHOUSE, FOURKIND, SFLUSH, RFLUSH };
Card[] cards = new Card[5];
Card highestOfRank;
Hand (String in)
{
String[] inCards = in.split(" ");
for ( int i = 0; i < 5; ++i )
cards[i] = new Card(inCards[i]);
Arrays.sort(cards, new Card());
}
public Card getHighestCard(int offset)
{
return cards[4-offset];
}
public Card getHighestCard()
{
return getHighestCard(0);
}
public Card getHighestOfRank()
{
if ( highestOfRank == null )
getHighestRank();
return highestOfRank;
}
public Rank getHighestRank()
{
if ( cards[0].getSuit() == cards[1].getSuit() &&
cards[1].getSuit() == cards[2].getSuit() &&
cards[2].getSuit() == cards[3].getSuit() &&
cards[3].getSuit() == cards[4].getSuit() )
{ // some kind of flush
highestOfRank = cards[4];
if ( cards[0].getValue() == Card.Value.TEN &&
cards[4].getValue() == Card.Value.ACE )
return Rank.RFLUSH;
if ( cards[0].getValue().compareTo(Card.Value.TEN) < 0 &&
cards[0].getValue().ordinal() + 4 == cards[4].getValue().ordinal() )
return Rank.SFLUSH;
return Rank.FLUSH;
}
if ( cards[0].getValue() == cards[3].getValue() ||
cards[1].getValue() == cards[4].getValue() )
{
highestOfRank = cards[3];
return Rank.FOURKIND;
}
if ( ( cards[0].getValue() == cards[2].getValue() &&
cards[3].getValue() == cards[4].getValue() ) ||
( cards[0].getValue() == cards[1].getValue() &&
cards[2].getValue() == cards[4].getValue() ) )
{
highestOfRank = cards[2];
return Rank.FHOUSE;
}
if ( cards[0].getValue().ordinal() + 1 == cards[1].getValue().ordinal() &&
cards[1].getValue().ordinal() + 1 == cards[2].getValue().ordinal() &&
cards[2].getValue().ordinal() + 1 == cards[3].getValue().ordinal() &&
cards[3].getValue().ordinal() + 1 == cards[4].getValue().ordinal() )
{
highestOfRank = cards[4];
return Rank.STRAIGHT;
}
if ( cards[0].compareTo(cards[2]) == 0 ||
cards[1].compareTo(cards[3]) == 0 ||
cards[2].compareTo(cards[4]) == 0 )
{
highestOfRank = cards[2];
return Rank.THREEKIND;
}
if ( ( cards[0].compareTo(cards[1]) == 0 && cards[2].compareTo(cards[3]) == 0 ) ||
( cards[1].compareTo(cards[2]) == 0 && cards[3].compareTo(cards[4]) == 0 ) ||
( cards[0].compareTo(cards[1]) == 0 && cards[3].compareTo(cards[4]) == 0 ) )
{
highestOfRank = cards[3];
return Rank.TWOPAIR;
}
if ( cards[0].compareTo(cards[1]) == 0 || cards[1].compareTo(cards[2]) == 0 )
{
highestOfRank = cards[1];
return Rank.ONEPAIR;
}
if ( cards[2].compareTo(cards[3]) == 0 || cards[3].compareTo(cards[4]) == 0 )
{
highestOfRank = cards[3];
return Rank.ONEPAIR;
}
highestOfRank = cards[4];
return Rank.HIGHCARD;
}
}
class Card implements Comparable<Card>, Comparator<Card>
{
public enum Value { TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE };
public enum Suit { SPADE, HEART, DIAMOND, CLUB };
private Value v;
private Suit s;
Card()
{
v = Value.TWO;
s = Suit.CLUB;
}
Card(String in)
{
v = getVal(in.charAt(0));
s = getSuit(in.charAt(1));
}
public Suit getSuit()
{
return s;
}
public Value getValue()
{
return v;
}
public int compareTo(Card o)
{
if ( v == o.v )
return 0;
else if ( v.compareTo(o.v) < 0 )
return -1; // before
else
return 1; // after
}
public int compare(Card c1, Card c2)
{
return c1.compareTo(c2);
}
private Value getVal(char c)
{
switch(c)
{
case '2': return Value.TWO;
case '3': return Value.THREE;
case '4': return Value.FOUR;
case '5': return Value.FIVE;
case '6': return Value.SIX;
case '7': return Value.SEVEN;
case '8': return Value.EIGHT;
case '9': return Value.NINE;
case 'T': return Value.TEN;
case 'J': return Value.JACK;
case 'Q': return Value.QUEEN;
case 'K': return Value.KING;
case 'A': return Value.ACE;
}
return null;
}
private Suit getSuit(char c)
{
switch(c)
{
case 'H': return Suit.HEART;
case 'C': return Suit.CLUB;
case 'D': return Suit.DIAMOND;
case 'S': return Suit.SPADE;
}
return null;
}
public boolean sameSuit(Card c)
{
return s == c.s;
}
@Override
public boolean equals(Object obj)
{
if ( obj == this )
return true;
if ( obj == null || obj.getClass() != this.getClass() )
return false;
Card c = (Card) obj;
return c.s == s && c.v == v;
}
}
|
Java
|
UTF-8
| 1,537 | 2.703125 | 3 |
[] |
no_license
|
package com.example.android.clientintelligent.interpreter.tflite;
import com.example.android.clientintelligent.framework.pojo.Mission;
import java.io.IOException;
import java.nio.ByteBuffer;
public class FloatTFLiteClassifier extends TFLiteClassifier{
/** MobileNet requires additional normalization of the used input. */
private static final float IMAGE_MEAN = 127.5f;
private static final float IMAGE_STD = 127.5f;
private float[][] labelProbArray;
FloatTFLiteClassifier(Mission mission, String modelFilePath, float accuracy) throws IOException {
super(mission, modelFilePath, accuracy);
labelProbArray = new float[1][getNumLabels()];
}
protected float getProbability(int labelIndex) {
return labelProbArray[0][labelIndex];
}
protected void setProbability(int labelIndex, Number value) {
labelProbArray[0][labelIndex] = value.floatValue();
}
protected float getNormalizedProbability(int labelIndex) {
return labelProbArray[0][labelIndex];
}
protected void runInference() {
tflite.run(imgData, labelProbArray);
}
protected void runInference(ByteBuffer data){
tflite.run(data, labelProbArray);
}
@Override
protected void addPixelValue(int pixelValue) {
imgData.putFloat((((pixelValue >> 16) & 0xFF) - IMAGE_MEAN) / IMAGE_STD);
imgData.putFloat((((pixelValue >> 8) & 0xFF) - IMAGE_MEAN) / IMAGE_STD);
imgData.putFloat(((pixelValue & 0xFF) - IMAGE_MEAN) / IMAGE_STD);
}
}
|
Java
|
UTF-8
| 1,289 | 2.78125 | 3 |
[] |
no_license
|
import static org.junit.Assert.*;
import org.junit.Test;
public class SudokuVerifierTest {
// A correct Sudoku string: 417369825 632158947 958724316 825437169 791586432 346912758 289643571 573291684 164875293
// An incorrect Sudoku string: 123456789912345678891234567789123456678912345567891234456789123345678912234567891
@Test
public void testVerify_Correct_String() {
SudokuVerifier verifier = new SudokuVerifier();
int returnedValue = verifier.verify("417369825632158947958724316825437169791586432346912758289643571573291684164875293");
assertEquals("Correct string, should be 0.", 0, returnedValue);
}
@Test
public void testVerify_error_1_invalid_string_length_less() {
SudokuVerifier verifier = new SudokuVerifier();
assertEquals("should be -1.", -1, verifier.verify("000"));
}
@Test
public void testVerify_error_1_invalid_string_not_numbers() {
SudokuVerifier verifier = new SudokuVerifier();
assertEquals("should be -1.", -1, verifier.verify("000asfdadsfasf00"));
}
@Test
public void testVerify_error_2_invalid_sub_grids() {
SudokuVerifier verifier = new SudokuVerifier();
assertEquals("should be -2.", -2, verifier.verify("123456789912345678891234567789123456678912345567891234456789123345678912234567891"));
}
}
|
Python
|
UTF-8
| 1,749 | 2.78125 | 3 |
[] |
no_license
|
import unittest
import json
import errno
import os
from seprcph.json_loader import _objs_from_file
PATH = 'test.json'
class Foo(object):
def __init__(self, string, integer):
self.string = string
self.integer = integer
def obj_hook(kwargs):
return Foo(**kwargs)
class TestJsonFiles(unittest.TestCase):
def tearDown(self):
try:
os.remove(PATH)
except OSError as err:
if err.errno != errno.ENOENT:
raise
def test_no_file(self):
self.assertRaises(IOError, _objs_from_file, '', obj_hook)
def test_invalid_file(self):
self.assertRaises(IOError, _objs_from_file, '/foo/', obj_hook)
def test_empty_file(self):
with open(PATH, 'w') as f:
pass
self.assertRaises(ValueError, _objs_from_file,
PATH, obj_hook)
class TestJsonContents(unittest.TestCase):
def setUp(self):
json.dump([{'string': 'test', 'integer': 1}], open(PATH, 'w'))
def tearDown(self):
try:
os.remove(PATH)
except OSError as err:
if err.errno != errno.ENOENT:
raise
def test_load_object(self):
self.assertIsInstance(_objs_from_file(PATH, obj_hook)[0], Foo)
def test_load_object_int(self):
self.assertIsInstance(_objs_from_file(PATH, obj_hook)[0].integer, int)
def test_load_object_str(self):
self.assertIsInstance(_objs_from_file(PATH, obj_hook)[0].string, unicode)
def test_load_multpile_objs(self):
json.dump([{'string': 'test', 'integer': 1},
{'string': 'test2', 'integer': 2}], open(PATH, 'w'))
self.assertEquals(len(_objs_from_file(PATH, obj_hook)), 2)
|
Java
|
UTF-8
| 491 | 1.601563 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.qaplus.mapper;
import com.qaplus.entity.QaUser;
import com.qaplus.entity.QaUserExample;
import java.util.List;
public interface QaUserMapper {
int countByExample(QaUserExample example);
int deleteByExample(QaUserExample example);
int deleteByPrimaryKey(QaUser record);
int insertSelective(QaUser record);
List<QaUser> selectByExample(QaUserExample example);
QaUser selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(QaUser record);
}
|
Java
|
UTF-8
| 790 | 2.734375 | 3 |
[] |
no_license
|
package com.idp.studentmanagement.objects;
import androidx.annotation.NonNull;
public class UserType {
private int id;
private String type;
public UserType(int id, String type) {
this.id = id;
this.type = type;
}
public UserType(String type) {
this.type = type;
switch (type) {
case "ADMIN":
this.id = 1;
break;
case "SECRETARY":
this.id = 2;
break;
case "STUDENT":
this.id = 3;
break;
}
}
public int getId() {
return id;
}
public String getType() {
return type;
}
@NonNull
@Override
public String toString() {
return type;
}
}
|
Python
|
UTF-8
| 1,970 | 2.546875 | 3 |
[] |
no_license
|
import pandas as pd
base_path = 'G:/dataset/a3d6_chusai_a_train/dealt_data/'
trainset1_path = base_path + 'dataset_train_1/'
testset1_path = base_path + 'dataset_test_1/'
trainset2_path = base_path + 'dataset_train_2/'
testset2_path = base_path + 'dataset_test_2/'
trainset3_path = base_path + 'dataset_train_3/'
launch = pd.read_csv(base_path + 'app_launch_log.csv')
register = pd.read_csv(base_path + 'user_register_log.csv')
create = pd.read_csv(base_path + 'video_create_log.csv')
activity = pd.read_csv(base_path + 'user_activity_log.csv')
def cut_data_between(dataset_path, begin_day, end_day):
temp_register = register[(register['register_day'] >= begin_day) & (register['register_day'] <= end_day)]
temp_launch = launch[(launch['launch_day'] >= begin_day) & (launch['launch_day'] <= end_day)]
temp_create = create[(create['create_day'] >= begin_day) & (create['create_day'] <= end_day)]
temp_activity = activity[(activity['action_day'] >= begin_day) & (activity['action_day'] <= end_day)]
temp_register.to_csv(dataset_path + 'register.csv', index=False)
temp_launch.to_csv(dataset_path + 'launch.csv', index=False)
temp_create.to_csv(dataset_path + 'create.csv', index=False)
temp_activity.to_csv(dataset_path + 'activity.csv', index=False)
def generate_dataset():
print('开始划分数据集...')
begin_day = 1
end_day = 16
cut_data_between(trainset1_path, begin_day, end_day)
begin_day = 17
end_day = 23
cut_data_between(testset1_path, begin_day, end_day)
print('训练集1,测试集1划分完成')
begin_day = 8
end_day = 23
cut_data_between(trainset2_path, begin_day, end_day)
begin_day = 24
end_day = 30
cut_data_between(testset2_path, begin_day, end_day)
print('训练集2,测试集2划分完成')
begin_day = 15
end_day = 30
cut_data_between(trainset3_path, begin_day, end_day)
print('训练集3 划分完成')
generate_dataset()
|
Java
|
UTF-8
| 1,116 | 2.046875 | 2 |
[] |
no_license
|
package com.cebrail.app.domain;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.annotation.Generated;
import javax.persistence.metamodel.SetAttribute;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Book.class)
public abstract class Book_ {
public static volatile SingularAttribute<Book, BigDecimal> price;
public static volatile SingularAttribute<Book, String> description;
public static volatile SingularAttribute<Book, Long> id;
public static volatile SingularAttribute<Book, String> title;
public static volatile SingularAttribute<Book, LocalDate> publicationDate;
public static volatile SetAttribute<Book, Author> authors;
public static final String PRICE = "price";
public static final String DESCRIPTION = "description";
public static final String ID = "id";
public static final String TITLE = "title";
public static final String PUBLICATION_DATE = "publicationDate";
public static final String AUTHORS = "authors";
}
|
C#
|
UTF-8
| 4,857 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
using System;
using static System.Console;
using Packt.CS7;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Xml.Linq;
namespace LinqWithEFCore
{
class Program
{
static void Main(string[] args)
{
using (var db = new Northwind())
{
var query = db.Products
.ProcessSequence()
.Where(product => product.UnitPrice < 10M)
.OrderByDescending(product => product.UnitPrice)
.Select(product => new
{
product.ProductID,
product.ProductName,
product.UnitPrice
});
WriteLine("Products that cost less than $10:");
foreach (var item in query)
{
WriteLine($"{item.ProductID}: {item.ProductName} costs {item.UnitPrice:$#,##0.00}");
}
WriteLine();
// create two sequences that we want to join together
var categories = db.Categories.Select(
c => new { c.CategoryID, c.CategoryName }).ToArray();
var products = db.Products.Select(
p => new { p.ProductID, p.ProductName, p.CategoryID }).ToArray();
// join every product to its category to return 77 matches
var queryJoin = categories.Join(products,
category => category.CategoryID,
product => product.CategoryID,
(c, p) => new { c.CategoryName, p.ProductName, p.ProductID })
.OrderBy(cp => cp.ProductID); ;
foreach (var item in queryJoin)
{
WriteLine($"{item.ProductID}: {item.ProductName} is in {item.CategoryName}.");
}
// group all products by their category to return 8 matches
var queryGroup = categories.GroupJoin(products,
category => category.CategoryID,
product => product.CategoryID,
(c, Products) => new
{
c.CategoryName,
Products = Products.OrderBy(p => p.ProductName)
});
foreach (var item in queryGroup)
{
WriteLine(
$"{item.CategoryName} has {item.Products.Count()} products.");
foreach (var product in item.Products)
{
WriteLine($" {product.ProductName}");
}
}
WriteLine("Products");
WriteLine($" Count: {db.Products.Count()}");
WriteLine($" Sum of units in stock: {db.Products.Sum(p => p.UnitsInStock):N0}");
WriteLine($" Sum of units on order: {db.Products.Sum(p => p.UnitsOnOrder):N0}");
WriteLine($" Average unit price: {db.Products.Average(p => p.UnitPrice):$#,##0.00}");
WriteLine($" Value of units in stock: {db.Products.Sum(p => p.UnitPrice * p.UnitsInStock):$#,##0.00}");
WriteLine("Custom LINQ extension methods:");
WriteLine($" Mean units in stock: {db.Products.Average(p => p.UnitsInStock):N0}");
WriteLine($" Mean unit price: {db.Products.Average(p => p.UnitPrice):$#,##0.00}");
WriteLine($" Median units in stock: {db.Products.Median(p => p.UnitsInStock)}");
WriteLine($" Median unit price: {db.Products.Median(p => p.UnitPrice):$#,##0.00}");
WriteLine($" Mode units in stock: {db.Products.Mode(p => p.UnitsInStock)}");
WriteLine($" Mode unit price: {db.Products.Mode(p => p.UnitPrice):$#,##0.00}");
var productsForXml = db.Products.ToArray();
var xml = new XElement("products",
from p in productsForXml
select new XElement("product",
new XAttribute("id", p.ProductID),
new XAttribute("price", p.UnitPrice),
new XElement("name", p.ProductName)));
WriteLine(xml.ToString());
XDocument doc = XDocument.Load("settings.xml");
var appSettings = doc.Descendants(
"appSettings").Descendants("add")
.Select(node => new
{
Key = node.Attribute("key").Value,
Value = node.Attribute("value").Value
})
.ToArray();
foreach (var item in appSettings)
{
WriteLine($"{item.Key}: {item.Value}");
}
}
}
}
}
|
SQL
|
UTF-8
| 3,262 | 3.171875 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Feb 15, 2019 at 11:52 PM
-- Server version: 10.1.28-MariaDB
-- PHP Version: 7.1.11
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `quiz`
--
-- --------------------------------------------------------
--
-- Table structure for table `admin_athu`
--
CREATE TABLE `admin_athu` (
`adminid` int(11) NOT NULL,
`adminname` varchar(20) NOT NULL,
`adminpassword` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `admin_athu`
--
INSERT INTO `admin_athu` (`adminid`, `adminname`, `adminpassword`) VALUES
(3, 'aaa', '123');
-- --------------------------------------------------------
--
-- Table structure for table `exams`
--
CREATE TABLE `exams` (
`exam_id` int(11) NOT NULL,
`examname` varchar(25) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `exams`
--
INSERT INTO `exams` (`exam_id`, `examname`) VALUES
(1, 'java'),
(2, 'c#'),
(3, 'php'),
(4, 'android'),
(5, 'python');
-- --------------------------------------------------------
--
-- Table structure for table `questions`
--
CREATE TABLE `questions` (
`q_id` int(11) NOT NULL,
`q_title` varchar(255) NOT NULL,
`q_opa` varchar(255) NOT NULL,
`q_opb` varchar(255) NOT NULL,
`q_opc` varchar(255) NOT NULL,
`q_opd` varchar(255) NOT NULL,
`q_correct` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `students`
--
CREATE TABLE `students` (
`std_id` int(11) NOT NULL,
`std_name` varchar(25) NOT NULL,
`std_password` varchar(25) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `admin_athu`
--
ALTER TABLE `admin_athu`
ADD PRIMARY KEY (`adminid`),
ADD KEY `adminid` (`adminid`);
--
-- Indexes for table `exams`
--
ALTER TABLE `exams`
ADD PRIMARY KEY (`exam_id`);
--
-- Indexes for table `questions`
--
ALTER TABLE `questions`
ADD PRIMARY KEY (`q_id`);
--
-- Indexes for table `students`
--
ALTER TABLE `students`
ADD PRIMARY KEY (`std_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `admin_athu`
--
ALTER TABLE `admin_athu`
MODIFY `adminid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `exams`
--
ALTER TABLE `exams`
MODIFY `exam_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `questions`
--
ALTER TABLE `questions`
MODIFY `q_id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `students`
--
ALTER TABLE `students`
MODIFY `std_id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
JavaScript
|
UTF-8
| 5,184 | 2.953125 | 3 |
[] |
no_license
|
import React, { useState, useEffect } from "react";
import Head from "next/head";
import Pokedex from "../components/Pokedex";
import styles from "../styles/Home.module.css";
export default function Home() {
const [imageUrl, setImageUrl] = useState("");
const [pokemonName, setPokemonName] = useState("");
const [pokemonType, setPokemonType] = useState("");
const [pokemonHeight, setPokemonHeight] = useState("");
const [weight, setWeight] = useState("");
const [stats, setStats] = useState({});
const [searchTerm, setSearchTerm] = useState("");
const [loading, setLoading] = useState(false);
const [abilities, setAbilities] = useState([]);
const [id, setId] = useState(null);
const handleSearch = async () => {
setLoading(true);
console.log(searchTerm);
await fetch(`http://pokeapi.co/api/v2/pokemon/${searchTerm.toLowerCase()}`)
.then((response) => response.json())
.then((data) => {
console.log(data);
data.id && setId(data.id);
data.abilities && setAbilities(data.abilities);
data.name && setPokemonName(data.name);
data.types && setPokemonType(data.types[0].type.name);
data.height && setPokemonHeight(data.height);
data.weight && setWeight(data.weight);
data.stats && setStats(data.stats);
if (data.id) {
const strung = data.id.toString();
console.log(strung.length);
if (strung.length === 3) {
setImageUrl(data.id);
} else if (strung.length === 2) {
setImageUrl(`0${strung}`);
} else if (strung.length === 1) {
console.log(`00${strung}`);
setImageUrl(`00${strung}`);
} else {
return;
}
}
});
setLoading(false);
};
const increment = async () => {
setLoading(true);
id &&
(await fetch(`http://pokeapi.co/api/v2/pokemon/${id + 1}`)
.then((response) => response.json())
.then((data) => {
console.log(data);
data.id && setId(data.id);
data.abilities && setAbilities(data.abilities);
data.name && setPokemonName(data.name);
data.types && setPokemonType(data.types[0].type.name);
data.height && setPokemonHeight(data.height);
data.weight && setWeight(data.weight);
data.stats && setStats(data.stats);
if (data.id) {
const strung = data.id.toString();
console.log(strung.length);
if (strung.length === 3) {
setImageUrl(data.id);
} else if (strung.length === 2) {
setImageUrl(`0${strung}`);
} else if (strung.length === 1) {
console.log(`00${strung}`);
setImageUrl(`00${strung}`);
} else {
return;
}
}
}));
setLoading(false);
};
const decrement = async () => {
setLoading(true);
id !== 1 &&
(await fetch(`http://pokeapi.co/api/v2/pokemon/${id - 1}`)
.then((response) => response.json())
.then((data) => {
console.log(data);
data.id && setId(data.id);
data.abilities && setAbilities(data.abilities);
data.name && setPokemonName(data.name);
data.types && setPokemonType(data.types[0].type.name);
data.height && setPokemonHeight(data.height);
data.weight && setWeight(data.weight);
data.stats && setStats(data.stats);
if (data.id) {
const strung = data.id.toString();
console.log(strung.length);
if (strung.length === 3) {
setImageUrl(data.id);
} else if (strung.length === 2) {
setImageUrl(`0${strung}`);
} else if (strung.length === 1) {
console.log(`00${strung}`);
setImageUrl(`00${strung}`);
} else {
return;
}
}
}));
setLoading(false);
};
return (
<div className={styles.container}>
<Head>
<title>PokeDex</title>
<link
rel="icon"
href="https://image.pngaaa.com/241/259241-middle.png"
/>
</Head>
<img
className={styles.background}
src="https://free4kwallpapers.com/uploads/originals/2018/06/18/created-a-3d-render-of-a-pokemon-trophy-in-the-grass-wallpaper.jpg"
alt=""
/>
<Pokedex
width="100vw"
height="90vh"
imageUrl={
imageUrl
? `https://assets.pokemon.com/assets/cms2/img/pokedex/full/${imageUrl}.png`
: ""
}
setSearchTerm={(e) => setSearchTerm(e.target.value)}
searchTerm={searchTerm}
submit={() => handleSearch()}
name={pokemonName ? pokemonName : ""}
type={pokemonType ? pokemonType : ""}
stats={stats ? stats : ""}
pokemonHeight={pokemonHeight ? pokemonHeight : ""}
weight={weight ? weight : ""}
loading={loading}
id={id}
abilities={abilities}
increment={() => increment()}
decrement={() => decrement()}
/>
</div>
);
}
|
Python
|
UTF-8
| 5,009 | 3.859375 | 4 |
[] |
no_license
|
class Node:
def __init__(self, item):
self.val = item
self.left = None
self.right = None
class BTree:
def __init__(self):
self.head = Node(None)
self.in_order_list = []
self.pre_order_list = []
self.post_order_list = []
def add(self, item):
if self.head.val is None:
self.head = Node(item)
else:
self.__add_node(self.head, item)
def __add_node(self, cur, item):
if cur.val >= item:
if cur.left is None:
cur.left = Node(item)
else:
self.__add_node(cur.left, item)
else:
if cur.right is None:
cur.right = Node(item)
else:
self.__add_node(cur.right, item)
def search(self, item):
if self.head.val is None:
return False
else:
return self.__search_node(self.head, item)
def __search_node(self, cur, item):
if cur.val == item:
return True
elif cur.val >= item:
if cur.left is None:
print('search Fail!!!')
return False
else:
return self.__search_node(cur.left, item)
else:
if cur.right is None:
print('search Fail!!!')
return False
else:
return self.__search_node(cur.right, item)
def in_order_traverse(self):
if self.head is not None:
self.__in_order(self.head)
def __in_order(self, cur):
if cur.left is not None:
self.__in_order(cur.left)
self.in_order_list.append(cur.val)
print(cur.val)
if cur.right is not None:
self.__in_order(cur.right)
def pre_order_traverse(self):
if self.head.val is not None:
self.__pre_order(self.head)
def __pre_order(self, cur):
self.pre_order_list.append(cur.val)
print(cur.val)
if cur.left is not None:
self.__pre_order(cur.left)
if cur.right is not None:
self.__pre_order(cur.right)
def post_order_traverse(self):
if self.head is not None:
self.__post_order(self.head)
def __post_order(self, cur):
if cur.left is not None:
self.__post_order(cur.left)
if cur.right is not None:
self.__post_order(cur.right)
self.post_order_list.append(cur.val)
print(cur.val)
def remove(self, item):
if self.head.val is None:
print('there is no item')
return False
# head가 원하는 값일 때
if self.head.val == item:
pass
# head가 원하는 값이 아닐 때
else:
if self.head.val >= item:
self.__remove(self.head, self.head.left, item)
else:
self.__remove(self.head, self.head.right, item)
def __remove(self, parent, cur, item):
if cur is None:
print('there is no item')
return False
if cur.val == item:
# 자식이 없는 자식 일 때
if cur.left is None and cur.right is None:
if parent.left == cur:
parent.left = None
else:
parent.right = None
# 왼쪽 자식만 있을 때
elif cur.left is not None and cur.right is None:
if parent.left == cur:
parent.left = cur.left
else:
parent.right = cur.right
# 오른쪽 자식만 있을 때
elif cur.left is None and cur.right is not None:
if parent.left == cur:
parent.left = cur.right
else:
parent.right = cur.right
# 양 쪽 자식이 다 있는 경우
else:
cur.val = self.__most_left_val_from_right_node(cur.right).val
self.__remove_item(cur, cur.right, cur.val)
def __most_left_val_from_right_node(self, cur):
if cur.left is not None:
return self.__most_left_val_from_right_node(cur.left)
else:
return cur
def __remove_item(self, parent, cur, item):
if cur.val == item:
if parent.left == cur:
parent.left = None
else:
parent.right = None
else:
if cur.val > item:
self.__remove_item(cur, cur.left, item)
else:
self.__remove_item(cur, cur.right, item)
if __name__ == '__main__':
b_tree = BTree()
b_tree.add(5)
b_tree.add(3)
b_tree.add(7)
b_tree.add(1)
b_tree.add(4)
b_tree.in_order_traverse()
print('')
b_tree.pre_order_traverse()
print('')
b_tree.post_order_traverse()
print(b_tree.search(3))
b_tree.remove(3)
print(b_tree.search(3))
|
C
|
UTF-8
| 888 | 3.359375 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<time.h>
bool checkRepe(unsigned long int arr[],int n,int num){
for(int i = 0; i < n; i++)
{
if(arr[i] == num){
return false;
}
}
return true;
}
int main()
{
srand(time(NULL));
int seed=1000;
int step = 10;
int n=10;
printf("Enter the number of random numbers you want\n");
scanf("%d",&n);
unsigned long int ranNums[n];
int temp;
for(int i = 0; i < n; i++)
{
ranNums[0] =0;
}
int eachLeft = (seed-step)/n;
for (int i=0;i<n;i++){
temp=(rand()%step)+seed;
if(checkRepe(ranNums,n,temp)){
seed=seed-eachLeft;
step +=eachLeft+step;
ranNums[i] = temp;
}
else
{
i--;
}
}
for(int i=0;i<n-1;i++){
ranNums[i]=ranNums[i] << rand()%15 ^ ranNums[i+1] >> rand()%8;
printf("%lu\n",ranNums[i]);
}
return 0;
}
|
Java
|
UTF-8
| 662 | 2.28125 | 2 |
[] |
no_license
|
package com.e.taskapp_1;
import android.app.Application;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import com.e.taskapp_1.room.MyDataBase;
public class App extends Application {
private MyDataBase myDataBase;
public static App instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
myDataBase = Room.databaseBuilder(this,
MyDataBase.class, "mydatabase")
.allowMainThreadQueries().build();
}
public static App getInstance() {
return instance;
}
public MyDataBase getDataBase(){
return myDataBase;
}
}
|
Python
|
UTF-8
| 404 | 2.578125 | 3 |
[] |
no_license
|
from tornado.web import RequestHandler
class LoginHandler(RequestHandler):
def get(self):
self.render('login.html')
def post(self):
username = self.get_argument('username')
password = self.get_argument('password')
self.authentication(username,password)
def authentication(self,username,password):
if username != 'test':
return self.redirect('/login')
return self.redirect('/home')
|
JavaScript
|
UTF-8
| 1,997 | 2.734375 | 3 |
[] |
no_license
|
const express = require('express')
const app = express()
const cors = require('cors');
var floor_one = require('./floor_one');
var floor_two = require('./floor_two');
var port = process.env.PORT || 3000,
http = require('http'),
fs = require('fs'),
html = fs.readFileSync('index.html');
bodyParser = require('body-parser');
app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({extended: false});
var floors = {
1: floor_one,
2: floor_two
}
// app.get('/floors/:floorId/:roomId', (req, res) => {
// let floor = floors[req.params.floorId];
// let room = floor.filter(room => {
// return room.id == req.params.roomId;
// })[0];
// res.json(room);
// }
// );
app.get('/floors/:floorId', (req, res) => {
console.log('Get Request received for floor ${req.params.floorId} ')
const floorid = req.params.floorId;
res.json(floors[floorid]);
});
app.put('/event/:floorId/:roomName', urlencodedParser, (req, res) => {
console.log('Put Request received for floor ' + req.params.floorId + ' and room ' + req.params.roomName)
let floor = floors[req.params.floorId];
let room = floor.filter(room => {
return room.name == req.params.roomName;
})[0];
const index = floor.indexOf(room);
if (!room.busy) {
room.busy = true;
res.status(200);
res.send('Your room has been booked.');
} else {
room.busy = false;
res.status(400);
res.send('Sorry, this room is busy during that timeslot');
}
floors[req.params.floorId][index] = room;
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
// Put a friendly message on the terminal
console.log('Server running at http://127.0.0.1:' + port + '/');
|
Markdown
|
UTF-8
| 779 | 2.8125 | 3 |
[] |
no_license
|
---
title: "Confucius"
---
His doctrine of duty and public service had a great influence on subsequent Chinese thought and served as a code of conduct for government officials. Although his real name was Kongzi (551-479 B.C.E.).
Chinese philosopher (circa 551-478 BC)
(551-479 BCE) A Chinese philosopher known also as Kong Fuzi and created one of the most influential philosophies in Chinese history.
Western name for the Chinese philosopher Kongzi (551-479 B.C.E.). His doctrine of duty and public service had a great influence on subsequent Chinese thought and served as a code of conduct for government officials.(p. 62)
The founder of Confucianism (551-479 B.C.E.); an aristocrat of northern China who proved to be the greatest influence on Chinese culture in its history.
|
Java
|
UTF-8
| 171 | 2.703125 | 3 |
[] |
no_license
|
public class CreateTest1 {
public static void main(String[] args) {
for (int i = 0; i < 200_000; ++i) { System.out.println(200_000 + " " + 10_000); }
}
}
|
Java
|
UTF-8
| 944 | 2.140625 | 2 |
[] |
no_license
|
package utilities;
import java.util.Map;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Utilities {
WebDriver driver;
WebDriverWait webDriverWait;
public Utilities(WebDriver driver) {
this.driver = driver;
}
public void fillInTextInfo(By path, String SomeString) {
webDriverWait=new WebDriverWait(driver, 3,100);
webDriverWait.until(ExpectedConditions.presenceOfElementLocated(path)).sendKeys(SomeString);
}
public void click(By path) {
webDriverWait=new WebDriverWait(driver, 3,100);
webDriverWait.until(ExpectedConditions.presenceOfElementLocated(path)).click();
}
public void closeBrowser() {
webDriverWait=new WebDriverWait(driver, 3,100);
this.driver.quit();
}
public void LoginInfo(Map<String, String> map) {
// TODO Auto-generated method stub
}
}
|
Java
|
UTF-8
| 245 | 1.953125 | 2 |
[
"MIT"
] |
permissive
|
//,temp,sample_7343.java,2,9,temp,sample_7500.java,2,10
//,3
public class xxx {
private void doChangeDirectory(String path) {
if (path == null || ".".equals(path) || ObjectHelper.isEmpty(path)) {
return;
}
log.info("changing directory");
}
};
|
TypeScript
|
UTF-8
| 2,895 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
rpio.init({gpiomem: false}); /* Use /dev/mem for i²c/PWM/SPI */
rpio.init({mapping: 'gpio'}); /* Use the GPIOxx numbering */
/* Configure P11 as input with the internal pulldown resistor enabled */
rpio.open(11, rpio.INPUT, rpio.PULL_DOWN);
/* Configure P12 as output with the initiate state set high */
rpio.open(12, rpio.OUTPUT, rpio.HIGH);
/* Configure P13 as output, but leave it in its initial undefined state */
rpio.open(13, rpio.OUTPUT);
rpio.mode(12, rpio.INPUT); /* Switch P12 back to input mode */
console.log('Pin 12 = %d', rpio.read(12));
var buf = new Buffer(10000);
/* Read the value of Pin 12 10,000 times in a row, storing the values in buf */
rpio.readbuf(12, buf);
rpio.write(13, rpio.HIGH);
/* Write 1 0 1 0 1 0 1 0 to Pin 13 */
var buf = new Buffer(8).fill(rpio.LOW);
buf[0] = buf[2] = buf[4] = buf[6] = rpio.HIGH;
rpio.writebuf(13, buf);
var curpad = rpio.readpad(rpio.PAD_GROUP_0_27);
var slew = ((curpad & rpio.PAD_SLEW_UNLIMITED) == rpio.PAD_SLEW_UNLIMITED);
var hysteresis = ((curpad & rpio.PAD_HYSTERESIS) == rpio.PAD_HYSTERESIS);
var drive = (curpad & 0x7);
/* Disable input hysteresis but retain other current settings. */
var control = rpio.readpad(rpio.PAD_GROUP_0_27);
control &= ~rpio.PAD_HYSTERESIS;
rpio.writepad(rpio.PAD_GROUP_0_27, control);
rpio.pud(11, rpio.PULL_UP);
rpio.pud(12, rpio.PULL_DOWN);
function nuke_button(pin: number)
{
console.log('Nuke button on pin %d pressed', pin);
/* No need to nuke more than once. */
rpio.poll(pin, null);
}
function regular_button(pin: number)
{
/* Watch pin 11 forever. */
console.log('Button event on pin %d, is now %d', pin, rpio.read(pin));
}
/*
* Pin 11 watches for both high and low transitions. Pin 12 only watches for
* high transitions (e.g. the nuke button is pushed).
*/
rpio.poll(11, regular_button);
rpio.poll(12, nuke_button, rpio.POLL_HIGH);
rpio.close(11);
rpio.i2cBegin();
rpio.i2cSetSlaveAddress(0x20);
rpio.i2cSetBaudRate(100000); /* 100kHz */
rpio.i2cSetClockDivider(2500); /* 250MHz / 2500 = 100kHz */
var txbuf = new Buffer([0x0b, 0x0e, 0x0e, 0x0f]);
var rxbuf = new Buffer(32);
rpio.i2cWrite(txbuf); /* Sends 4 bytes */
rpio.i2cRead(rxbuf, 16); /* Reads 16 bytes */
rpio.i2cEnd();
rpio.open(12, rpio.PWM); /* Use pin 12 */
rpio.pwmSetClockDivider(64); /* Set PWM refresh rate to 300kHz */
rpio.pwmSetRange(12, 1024);
rpio.pwmSetData(12, 512);
rpio.spiBegin(); /* Switch GPIO7-GPIO11 to SPI mode */
rpio.spiSetCSPolarity(0, rpio.HIGH); /* Set CE0 high to activate */
rpio.spiSetClockDivider(128); /* Set SPI speed to 1.95MHz */
rpio.spiTransfer(txbuf, rxbuf, txbuf.length);
rpio.spiWrite(txbuf, txbuf.length);
rpio.spiEnd();
rpio.sleep(1); /* Sleep for n seconds */
rpio.msleep(1); /* Sleep for n milliseconds */
rpio.usleep(1); /* Sleep for n microseconds */
|
Java
|
UTF-8
| 2,104 | 2.65625 | 3 |
[] |
no_license
|
package Mailman;
import Interfaces.IOpazovalec;
import Models.Aktivnost;
import Models.Oseba;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.logging.Level;
import java.util.logging.Logger;
@Stateless
public class Email implements IOpazovalec
{
@Resource(lookup = "java:jboss/mail/gmail")
private Session session;
public void posodobi(Oseba os, Aktivnost a)
{
sendMail(os, a);
}
public void sendMail(Oseba os, Aktivnost a){
try
{
InitialContext ic = new InitialContext();
session = (Session) ic.lookup("java:jboss/mail/gmail");
Message message = new MimeMessage(session);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(os.getEmail()));
message.setSubject("Sprememba aktivnosti");
message.setText(a.getNaziv() + " se je spremenilo");
Transport.send(message);
} catch (MessagingException | NamingException e)
{
Logger.getLogger(Email.class.getName()).log(Level.WARNING, "Cannot posodobi mail", e);
}
}
public void sendMail(Oseba os, Aktivnost a, String messageString){
try
{
InitialContext ic = new InitialContext();
session = (Session) ic.lookup("java:jboss/mail/gmail");
Message message = new MimeMessage(session);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(os.getEmail()));
message.setSubject("Sprememba aktivnosti");
message.setText(messageString);
Transport.send(message);
} catch (MessagingException | NamingException e)
{
Logger.getLogger(Email.class.getName()).log(Level.WARNING, "Cannot posodobi mail", e);
}
}
}
|
C
|
UTF-8
| 238 | 3.203125 | 3 |
[] |
no_license
|
#include <stdio.h>
int main()
{
FILE *printer;
printer = popen("lp","w");
if( printer==NULL )
{
fprintf(stderr,"Unable to open `lp`\n");
return(1);
}
fprintf(printer,"Hello, Mr. Printer!\n");
pclose(printer);
return(0);
}
|
Shell
|
UTF-8
| 1,094 | 3.765625 | 4 |
[] |
no_license
|
#!/bin/sh
printf 'Enter username: '
read -r USERNAME
printf "Enter password: "
read -r PASSWORD
printf "Enter database name ${USERNAME}_[base]: "
read -r DB
if [ -z "$DB" ]; then
DB="base"
fi
DB="${USERNAME}_$DB"
echo ""
echo "Please confirm the following information:"
echo " Username: $USERNAME"
echo " Password: $PASSWORD"
echo " Database name: $DB"
echo ""
printf "Are these information correct? [y/n] : "
read -r CORRECT
echo ""
if [ "$CORRECT" != "y" ]; then
echo "CANCEL!"
exit
fi
SQLFILE="/tmp/dbcreate.$(date +'%s%N')"
echo "create database $DB CHARACTER SET utf8 COLLATE utf8_general_ci;\n" > $SQLFILE
echo "grant SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, EXECUTE, CREATE ROUTINE, ALTER ROUTINE, LOCK TABLES on $DB.* to '$USERNAME'@'localhost';\n" >> $SQLFILE
echo "set password for $USERNAME@'localhost' = password('$PASSWORD');\n" >> $SQLFILE
echo "flush privileges;\n" >> $SQLFILE
echo "Please enter the password of your MySQL root user:"
mysql -u root -p < $SQLFILE
rm $SQLFILE
echo ""
echo "Successful!"
|
C#
|
UTF-8
| 700 | 3.15625 | 3 |
[] |
no_license
|
using System.Collections.Generic;
namespace courseApp2.Models
{
public static class Repository //bu static sınıf uygulama içinde sadece 1 tane olucak ve new ile yeni obje üretilmicek veri tabanı rolünü üstlenicek sanal veritabanı oluşturduk bir nevi ramde geçici saklancak
{
public static List<Student> _student = new List<Student>();
public static List<Student> Students
{ //student getir
get
{
return _student;
}
}
public static void AddStudent(Student student)
{ //repository.AddStudent(student) student listeye ekle
_student.Add(student);
}
}
}
|
Markdown
|
UTF-8
| 938 | 2.640625 | 3 |
[] |
no_license
|
# registradores-de-uso-geral
Registradores de Uso Geral
Os 8 GPRs, ou Registradores de Uso Geral, são os seguintes (por ordem de introdução na pilha ao executar a instrução PUSHAD):
EAX - Acumulador. Usado em operações aritméticas.
ECX - Contador. Usado em loops.
EDX - Registrador de Dados. Usado em operações de entrada/saída e em multiplicações e divisões. É também uma extensão do Acumulador.
EBX - Base. Usado para apontar para dados no segmento DS.
ESP - Apontador da Pilha (Stack Pointer). Aponta para o topo da pilha (endereço mais baixo dos elementos da pilha).
EBP - Apontador da base do frame. Usado para acessar argumentos de procedimentos passados pela pilha.
ESI - Índice da fonte de dados a copiar (Source Index). Aponta para dados a copiar para DS:EDI.
EDI - Índice do destino de dados a copiar (Destination Index). Aponta para o destino dos dados a copiar de DS:ESI.
|
Java
|
UTF-8
| 2,142 | 2.5625 | 3 |
[] |
no_license
|
package voter;
import java.util.List;
/**
* Created by xaviersilva on 09/05/17.
*/
public class PersonalBackup {
protected int carbsInMeal;
protected int carbsRatio;
protected int bloodSugarLevel;
protected int targetBloodSugar;
protected int physicalAct;
protected List<Integer> physicalSamples;
protected List<Integer> bloodSamples;
public PersonalBackup(int carbsInMeal, int carbsRatio, int bloodSugarLevel, int targetBloodSugar, int physicalAct, List<Integer> physicalSamples, List<Integer> bloodSamples) {
this.carbsInMeal = carbsInMeal;
this.carbsRatio = carbsRatio;
this.bloodSugarLevel = bloodSugarLevel;
this.targetBloodSugar = targetBloodSugar;
this.physicalAct = physicalAct;
this.physicalSamples = physicalSamples;
this.bloodSamples = bloodSamples;
}
public int getCarbsInMeal() {
return carbsInMeal;
}
public void setCarbsInMeal(int carbsInMeal) {
this.carbsInMeal = carbsInMeal;
}
public int getCarbsRatio() {
return carbsRatio;
}
public void setCarbsRatio(int carbsRatio) {
this.carbsRatio = carbsRatio;
}
public int getBloodSugarLevel() {
return bloodSugarLevel;
}
public void setBloodSugarLevel(int bloodSugarLevel) {
this.bloodSugarLevel = bloodSugarLevel;
}
public int getTargetBloodSugar() {
return targetBloodSugar;
}
public void setTargetBloodSugar(int targetBloodSugar) {
this.targetBloodSugar = targetBloodSugar;
}
public int getPhysicalAct() {
return physicalAct;
}
public void setPhysicalAct(int physicalAct) {
this.physicalAct = physicalAct;
}
public List<Integer> getPhysicalSamples() {
return physicalSamples;
}
public void setPhysicalSamples(List<Integer> physicalSamples) {
this.physicalSamples = physicalSamples;
}
public List<Integer> getBloodSamples() {
return bloodSamples;
}
public void setBloodSamples(List<Integer> bloodSamples) {
this.bloodSamples = bloodSamples;
}
}
|
Java
|
UTF-8
| 1,197 | 2.109375 | 2 |
[] |
no_license
|
package com.xy.DayTenGoods.ui.goods;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import com.xy.DayTenGoods.util.DisplayUtil;
import com.xy.DayTenGoods.util.recyclerview.RecyclerViewHeader;
/**
* Created by xiaoyu on 2016/4/3.
*/
public class RecyclerViewSpaceHeaderView extends RecyclerViewHeader {
public RecyclerViewSpaceHeaderView(Context context) {
super(context);
init(context);
}
public RecyclerViewSpaceHeaderView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public RecyclerViewSpaceHeaderView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(context, 9));
View spaceView = new View(context);
spaceView.setBackgroundColor(Color.parseColor("#00000000"));
spaceView.setLayoutParams(params);
addView(spaceView);
}
}
|
C++
|
UTF-8
| 573 | 2.625 | 3 |
[] |
no_license
|
#pragma once
#include <map>
#include <vector>
#include <iostream>
class Statistics
{
public:
std::map<unsigned char, int> alpha;
unsigned char alphabet[256];
Statistics();
~Statistics();
void calculateStatistics(const std::vector<unsigned char>& text, std::map<unsigned char, int>& statistics);
double calculateIndexOfCoincidence(const std::vector<unsigned char>& text);
unsigned char getLetter(int number);
int getLetterNumber(unsigned char letter);
void ShowStatistics(const std::map<unsigned char, int>& map);
};
|
Shell
|
UTF-8
| 2,580 | 4.0625 | 4 |
[] |
no_license
|
#!/bin/bash
# Declare Colors
red=`tput setaf 1`
green=`tput setaf 2`
reset=`tput sgr0`
# check distro and see if we are on ubuntu
DISTRO="$(cat /etc/lsb-release | grep DISTRIB_ID | cut -d'=' -f2)"
# function that creates ~/.config/awesome if not there or cd if there
function copyAwesomeConfig {
# check ~/.config
if [ -d "~/.config" ]; then echo "config dir existed...";
else echo "creating ~/.config..."; mkdir "~/.config"; fi;
# check ~/.config/awesome
if [ -d "~/.config/awesome" ]; then echo "config dir existed...";
else echo "creating ~/.config..."; mkdir "~/.config/awesome"; fi;
# copy if can, otherwise error
{ sudo cp -avr ./awesome ~/.config/; } || { echo "${red}couldnt copy directory${reset}";}
}
# function to get node and npm
function getNodeNPM {
# install nodejs & npm
{ curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash;
sudo apt-get install nodejs;
echo "${green}Installed Node and NPM${reset}"; } ||
{ echo "${red}Ran into issue installing Node / NPM${reset}"; }
# sometimes need a symlink from nodejs to node
{ sudo ln -s /usr/bin/nodejs /usr/bin/node &&
echo "${green}added symlink${green}"; } ||
{ echo "didn't need symlink"; };
}
# function to get sublime
function getSublime {
# install sublime text 3
{ sudo add-apt-repository ppa:webupd8team/sublime-text-3 &&
sudo apt-get update &&
sudo apt-get install sublime-text-installer &&
echo "${green}Installed Sublime 3${reset}"; } ||
{ echo "${red}Ran into issue installing Sublime${reset}"; }
}
# function to get google chrome stable
function getChromeStable {
# install google chrome stable
{ wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -;
echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' | sudo tee /etc/apt/sources.list.d/google-chrome.list;
sudo apt-get update && sudo apt-get install google-chrome-stable;
echo "${green}Installed Google Chrome stable${reset}"; } ||
{ echo "${red}Ran into issue installing Google Chrome stable${reset}"; }
}
# install a bunch of crap, only if ubuntu
if [ $DISTRO != 'Ubuntu' ]; then echo "${red}! NOT UBUNTU : couldnt do shit${reset}";
else
# add ppa for the latest version of awesomewm
sudo add-apt-repository ppa:klaus-vormweg/awesome -y;
sudo apt update && sudo apt install awesome -y;
# install basic programs and such
sudo apt-get install curl vim build-essential htop git libssl-dev && sudo apt-get update;
# get and set various things...
getNodeNPM;
getSublime;
getChromeStable
copyAwesomeConfig
fi
|
Java
|
UTF-8
| 630 | 2.828125 | 3 |
[] |
no_license
|
package se.chalmers.krogkollen.vendor;
/**
* Created by Jonathan Nilsfors on 2014-08-25.
*/
public class Vendor implements IVendor {
private String name;
private double longitude;
private double latitude;
public Vendor(String name, double latitude, double longitude){
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
}
@Override
public String getName() {
return this.name;
}
@Override
public double getLatitude() {
return this.latitude;
}
@Override
public double getLongitude() {
return this.longitude;
}
}
|
Shell
|
UTF-8
| 2,149 | 3.984375 | 4 |
[] |
no_license
|
#!/usr/bin/env bash
# bin/compile <build-dir> <cache-dir> <env-dir>
# Configure environment
set -e # fail fast
set -o pipefail # don't ignore exit codes when piping output
# set -x # enable debugging
# Functions
function indent() {
c='s/^/ /'
case $(uname) in
Darwin) sed -l "$c";;
*) sed -u "$c";;
esac
}
function package_download() {
engine="$1"
version="$2"
location="$3"
stack="$4"
mkdir -p $location
package="https://artifactory.gameofloans.com/artifactory/blob-store/org.stunnel/${engine}/${engine}-${version}.tar.gz"
curl_opts=""
if [[ -n "$ARTIFACTORY_USERNAME" ]] && [[ -n "$ARTIFACTORY_PASSWORD" ]] ; then
curl_opts="-u ${ARTIFACTORY_USERNAME}:${ARTIFACTORY_PASSWORD}"
fi
echo "fetching $package to $location. username: '$ARTIFACTORY_USERNAME'"
curl $curl_opts $package -s -o - | tar xzf - -C $location
}
# Clean up leaking environment
unset GIT_DIR
# Version
if [ "$STACK" == "cedar-14" ]; then
STUNNEL_VERSION="5.17"
else
STUNNEL_VERSION="5.02"
fi
# Directories
BUILD_DIR=$1
CACHE_DIR=$2
ENV_DIR=$3
BUILDPACK_DIR="$(dirname $(dirname $0))"
VENDORED_STUNNEL="vendor/stunnel"
echo "Using stunnel version: ${STUNNEL_VERSION}" | indent
echo "Using stack version: ${STACK}" | indent
[ -f "$ENV_DIR/ARTIFACTORY_USERNAME" ] && export ARTIFACTORY_USERNAME=$(cat "$ENV_DIR/ARTIFACTORY_USERNAME")
[ -f "$ENV_DIR/ARTIFACTORY_PASSWORD" ] && export ARTIFACTORY_PASSWORD=$(cat "$ENV_DIR/ARTIFACTORY_PASSWORD")
# Vendor stunnel into the slug
PATH="$BUILD_DIR/$VENDORED_STUNNEL/bin:$PATH"
echo "-----> Fetching and vendoring stunnel"
mkdir -p "$BUILD_DIR/$VENDORED_STUNNEL"
package_download "stunnel" "${STUNNEL_VERSION}" "${BUILD_DIR}/${VENDORED_STUNNEL}" "${STACK}"
echo "-----> Moving the configuration generation script into app/bin"
mkdir -p $BUILD_DIR/bin
cp "$BUILDPACK_DIR/bin/stunnel-conf.sh" $BUILD_DIR/bin
chmod +x $BUILD_DIR/bin/stunnel-conf.sh
echo "-----> Moving the start-stunnel script into app/bin"
mkdir -p $BUILD_DIR/bin
cp "$BUILDPACK_DIR/bin/start-stunnel" $BUILD_DIR/bin/
chmod +x $BUILD_DIR/bin/start-stunnel
echo "-----> stunnel done"
|
Java
|
UTF-8
| 3,583 | 2.09375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.store.web.front.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.company.core.util.MessageUtil;
import com.company.core.util.SessionUtil;
import com.store.web.front.dto.FileUpload;
import com.store.web.front.service.FileService;
import com.store.web.front.view.FileDownloadView;
@Controller
public class FileController {
@Autowired
FileService fileService;
@Resource(name="storage")
File storage;
@Autowired
protected Validator validator;
long fileSeq = System.currentTimeMillis();
Logger logger = Logger.getLogger(this.getClass());
@RequestMapping(value="/file/upload.html", method=RequestMethod.GET)
public ModelAndView uploadForm(@ModelAttribute("attach") FileUpload attach, HttpServletRequest request){
return new ModelAndView("file.upload.form");
}
@RequestMapping(value="/file/upload.html", method=RequestMethod.POST)
public ModelAndView uploadSubmit(@ModelAttribute("fileAttach") FileUpload attach, BindingResult result, HttpServletRequest request, HttpServletResponse response){
validator.validate(attach, result);
if (result.hasErrors()){
ModelAndView mav = new ModelAndView("file.upload.form");
return mav;
}
attach.setPhysicalName(Long.toString(fileSeq++));
try{
attach.getFile().transferTo(new File(storage, attach.getPhysicalName()));
UserDetails user = SessionUtil.getUserDetails(request);
attach.setUsrId(user.getUsername());
fileService.addAttachment(attach);
}catch(IOException ioe){
logger.error(ioe);
}catch(IllegalStateException ise){
logger.error(ise);
}
return list(request, response);
}
@RequestMapping(value="/file/download.html")
public ModelAndView download(HttpServletRequest request, HttpServletResponse response) {
String fileId = request.getParameter("fid");
if((fileId == null) || "".equals(fileId))
return list(request, response);
FileUpload fileUpload = fileService.getFileByPhysicalName(fileId);
if(fileUpload == null)
return list(request, response);
File file = new File(storage, fileUpload.getPhysicalName());
if(!file.exists()){
MessageUtil.saveMessage(request, "fileNotFound", fileUpload.getLogicalName());
return list(request, response);
}
return new ModelAndView("fileDownloadView", FileDownloadView.FILE_MODEL_KEY, fileUpload);
}
@RequestMapping(value="/file/list.html")
public ModelAndView list(HttpServletRequest request, HttpServletResponse response) {
List<FileUpload> fileList = fileService.getEntireFileList();
return new ModelAndView("file.download.list", "fileList", fileList);
}
}
|
C++
|
UTF-8
| 468 | 2.515625 | 3 |
[] |
no_license
|
#include "streamBuffer.h"
size_t bufferedStream::fread(void *dst, int siz, int C)
{
// TODO implement this method
// for now stubbed so that compilation is possible
return 0;
}
bufferedStream::~bufferedStream()
{
if(buffer != nullptr)
delete[] buffer;
}
int bufferedStream::appendDataToBuffer( char * buffer, std::size_t bufSize)
{
return -1;
}
char * bufferedStream::getNextDataPointer( std::size_t requiredSize)
{
return buffer;
}
|
C#
|
UTF-8
| 1,995 | 3.875 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _05.ClosestTwoPoints
{
class Program
{
static void Main(string[] args)
{
int numberOfPoints = int.Parse(Console.ReadLine());
Point[] points = new Point[numberOfPoints];
for (int p = 0; p < numberOfPoints; p++)
{
points[p] = GetPointCoordinates(points);
}
double minDistance = double.MaxValue;
Point minFirst = new Point();
Point minSecond = new Point();
for (int firstPoint = 0; firstPoint < points.Length; firstPoint++)
{
for (int secondPoint = firstPoint + 1; secondPoint < points.Length; secondPoint++)
{
double distance = CalculateDistanceBetweenTwoPoints(points[firstPoint], points[secondPoint]);
if (distance < minDistance)
{
minDistance = distance;
minFirst = points[firstPoint];
minSecond = points[secondPoint];
}
}
}
Console.WriteLine($"{minDistance:f3}\n({minFirst.X}, {minFirst.Y})\n({minSecond.X}, {minSecond.Y})");
}
private static Point GetPointCoordinates(Point[] points)
{
double[] pointArgs = Console.ReadLine().Split().Select(double.Parse).ToArray();
Point point = new Point
{
X = pointArgs[0],
Y = pointArgs[1]
};
return point;
}
private static double CalculateDistanceBetweenTwoPoints(Point firstPoint, Point secondPoint)
{
double a = firstPoint.X - secondPoint.X;
double b = firstPoint.Y - secondPoint.Y;
return Math.Sqrt(Math.Pow(a, 2) + Math.Pow(b, 2));
}
}
}
|
Java
|
UTF-8
| 9,006 | 2 | 2 |
[] |
no_license
|
package com.gratus.userapp.Fragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.gratus.userapp.R;
import com.gratus.userapp.activity.Intro.SplashScreenActivity;
import com.gratus.userapp.activity.Profile.Customer_Profile_Edit_Activity;
import com.gratus.userapp.adapter.CustomerProfileAdapter;
import com.gratus.userapp.model.CustomerAddress;
import com.gratus.userapp.model.CustomerRegAdapterModel;
import com.gratus.userapp.model.CustomerRegModel;
import com.gratus.userapp.model.FavoriteRestaurant;
import java.util.ArrayList;
import static com.gratus.userapp.activity.Intro.SplashScreenActivity.MyPREFERENCES;
public class Customer_Profile_Fragment extends Fragment {
private RelativeLayout exceptionRl;
private RecyclerView custRecyclerView;
private TextView signUp;
private CustomerProfileAdapter mAdapter;
private SharedPreferences tokenpref;
private FirebaseAuth firebaseAuth;
private DatabaseReference dbReference;
private FirebaseUser firebaseUser;
private RecyclerView.LayoutManager mLayoutManager;
private CustomerRegModel customerRegModel = new CustomerRegModel();
String email, password, cid;
private static Context context_main;
private int PROFILE = 1;
private int ADDRESS = 2;
private int LISTITEM = 3;
private int LOGOUT = 4;
private int HEADER = 5;
private int ITEMSEPARATOR = 6;
private int SEPARATORLINE = 7;
public Customer_Profile_Fragment() {
}
public static Customer_Profile_Fragment newInstance(Context context) {
Customer_Profile_Fragment fragment = new Customer_Profile_Fragment();
Bundle args = new Bundle();
fragment.setArguments(args);
context_main = context;
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_customer_profile_no_edit, container, false);
exceptionRl = view.findViewById(R.id.exceptionRl);
custRecyclerView = view.findViewById(R.id.custRecyclerView);
signUp = view.findViewById(R.id.signUpTv);
tokenpref = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
email = tokenpref.getString(getString(R.string.email_id_pref), null);
password = tokenpref.getString(getString(R.string.password_id_pref), null);
cid = tokenpref.getString(getString(R.string.cid_id_pref), null);
signUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
customerRegModel.setCID(cid);
customerRegModel.setEmail(email);
Intent i = new Intent(context_main, Customer_Profile_Edit_Activity.class);
i.putExtra(getString(R.string.cust_profile_data), customerRegModel);
startActivity(i);
((Activity)context_main).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
getCustomerProfile();
return view;
}
private void getCustomerProfile() {
customerRegModel = new CustomerRegModel();
dbReference = FirebaseDatabase.getInstance().getReference(getString(R.string.customer_details)).child(cid);
dbReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child("Name").getValue()!=null) {
customerRegModel.setName(dataSnapshot.child("Name").getValue().toString());
}
if(dataSnapshot.child("Phone").getValue()!=null) {
customerRegModel.setPhone_number(dataSnapshot.child("Phone").getValue().toString());
}
if(dataSnapshot.child("eMail").getValue()!=null) {
customerRegModel.setEmail(dataSnapshot.child("eMail").getValue().toString());
}
if(dataSnapshot.child("profileImageAddress").getValue()!=null) {
customerRegModel.setProfile_photo(dataSnapshot.child("profileImageAddress").getValue().toString());
}
if(dataSnapshot.child("CID").getValue()!=null) {
customerRegModel.setCID(dataSnapshot.child("CID").getValue().toString());
}
if(dataSnapshot.child("cust_completed").getValue()!=null) {
customerRegModel.setCust_completed((Boolean) dataSnapshot.child("cust_completed").getValue());
}
if(dataSnapshot.child("favorite_restaurant").getValue()!=null) {
customerRegModel.setFavorite_restaurant((ArrayList<FavoriteRestaurant>) dataSnapshot.child("favorite_restaurant").getValue());
}
if(dataSnapshot.child("customerAddresses").getValue()!=null) {
customerRegModel.setCustomerAddresses((ArrayList<CustomerAddress>) dataSnapshot.child("customerAddresses").getValue());
}
if(customerRegModel==null){
exceptionRl.setVisibility(View.VISIBLE);
custRecyclerView.setVisibility(View.GONE);
}
else{
setAdapterList();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(context_main, getString(R.string.internal_error), Toast.LENGTH_LONG).show();
getCustomerProfile();
}
});
}
private void setAdapterList() {
exceptionRl.setVisibility(View.GONE);
custRecyclerView.setVisibility(View.VISIBLE);
ArrayList<CustomerRegAdapterModel> customerRegAdapterModels = new ArrayList<>();
if(customerRegModel!=null){
customerRegAdapterModels.add(new CustomerRegAdapterModel(PROFILE,
customerRegModel.getName(),customerRegModel.getPhone_number(),
customerRegModel.getEmail(),customerRegModel.getProfile_photo()));
if(customerRegModel.getCustomerAddresses()!=null && customerRegModel.getCustomerAddresses().size()>0) {
customerRegAdapterModels.add(new CustomerRegAdapterModel(ITEMSEPARATOR));
customerRegAdapterModels.add(new CustomerRegAdapterModel(HEADER, "Address",
customerRegModel.getCustomerAddresses().size()));
for(int i=0 ;i<customerRegAdapterModels.size();i++) {
customerRegAdapterModels.add(new CustomerRegAdapterModel(ADDRESS,
customerRegModel.getCustomerAddresses().get(i).getAddress_type(),
customerRegModel.getCustomerAddresses().get(i)));
customerRegAdapterModels.add(new CustomerRegAdapterModel(SEPARATORLINE));
}
}
if(customerRegModel.getCustomerAddresses()!=null && customerRegModel.getFavorite_restaurant().size()>0) {
customerRegAdapterModels.add(new CustomerRegAdapterModel(ITEMSEPARATOR));
customerRegAdapterModels.add(new CustomerRegAdapterModel(LISTITEM, "Favorite",
customerRegModel.getFavorite_restaurant()));
}
customerRegAdapterModels.add(new CustomerRegAdapterModel(ITEMSEPARATOR));
customerRegAdapterModels.add(new CustomerRegAdapterModel(LOGOUT));
}
mLayoutManager = new LinearLayoutManager(getActivity());
mAdapter = new CustomerProfileAdapter(customerRegAdapterModels,context_main);
custRecyclerView.setLayoutManager(mLayoutManager);
custRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
@Override
public void onResume() {
super.onResume();
getCustomerProfile();
}
}
|
Python
|
UTF-8
| 814 | 3.78125 | 4 |
[] |
no_license
|
'''
Created on Apr 23, 2021
@author: Karthik
'''
def make_amount(rupees_to_make,no_of_five,no_of_one):
five_needed=0
one_needed=0
#Start writing your code here
#Populate the variables: five_needed and one_needed
five_needed = rupees_to_make // 5
if(five_needed>no_of_five):
five_needed = no_of_five
one_needed = rupees_to_make - (five_needed*5)
if(rupees_to_make > ((5*no_of_five) + (no_of_one)) or (one_needed>no_of_one)) :
print(-1)
else :
print("No. of Five needed :", five_needed)
print("No. of One needed :", one_needed)
#Provide different values for rupees_to_make,no_of_five,no_of_one and test your program
rupees_to_make=93
no_of_five=19
no_of_one=2
make_amount(rupees_to_make,no_of_five,no_of_one)
|
PHP
|
UTF-8
| 6,166 | 2.609375 | 3 |
[] |
no_license
|
<?php
include_once "conexion.php";
$op = $_POST["caso"];
switch($op)
{
case "agregar" :
AgregarPerro_bd();
break;
case "verificar":
VerificarPerro();
break;
case "traerBD":
TraerBD();
break;
case "eliminarPerro":
EliminarPerro();
break;
case "filtrar":
ObtenerPerrosPorTamaño();
break;
case "cantidad":
CantidadTamaño();
break;
default :
echo "=(";
break;
}
function AgregarPerro_bd()
{
$obJson = json_decode($_POST["obJson"]);
$obJson->precio = $obJson->precio;
$obJson->pathFoto = "fotos/" . $obJson->nombre . "." . date("Ymd_His") . "." . pathinfo($_FILES["foto"]["name"],PATHINFO_EXTENSION);
$retorno = new StdClass();
$retorno->TodoOk = false;
$con = new Conexion();
$consulta = $con->objPDO()->prepare("INSERT INTO perros (tamanio,edad,precio,nombre,raza,path_foto) VALUES (:tamanio,:edad,:precio,:nombre,:raza,:path_foto)");
//,edad,precio,nombre,raza,path_foto ,:edad,:nombre,:precio,:nombre,:raza,:path_foto
//$consulta->bindParam(':id', $id, PDO::PARAM_INT);
$consulta->bindValue(':tamanio', $obJson->tamanio, PDO::PARAM_STR);
$consulta->bindValue(':edad', $obJson->edad, PDO::PARAM_INT);
$consulta->bindValue(':precio', $obJson->precio, PDO::PARAM_STR);
$consulta->bindValue(':nombre', $obJson->nombre, PDO::PARAM_STR);
$consulta->bindValue(':raza',$obJson->raza,PDO::PARAM_STR);
$consulta->bindValue(':path_foto',$obJson->pathFoto,PDO::PARAM_STR);
if($consulta->execute())
{
if(move_uploaded_file($_FILES["foto"]["tmp_name"], "./" . $obJson->pathFoto))
{
$retorno->TodoOk = true;
}
}
echo json_encode($retorno);
EliminarTmp();
}
function VerificarPerro()
{
$obJson = json_decode($_POST["obJson"]);
$retorno = new StdClass();
$retorno->Existe = false;
$con = new Conexion();
$consulta = $con->objPDO()->prepare("SELECT * FROM perros WHERE edad = {$obJson->edad} AND raza = '{$obJson->raza}'");
$consulta->execute();
$ele = $consulta->fetchObject("StdClass");
if($ele != null)
{
$retorno->Existe = true;
}
echo json_encode($retorno);
}
function TraerBD()
{
$perros = array();
$con = new Conexion();
$consulta = $con->objPDO()->prepare("SELECT * FROM perros");
$consulta->execute();
while($fila = $consulta->fetch(PDO::FETCH_OBJ))
{
array_push($perros,$fila);
}
echo json_encode($perros);
}
function EliminarPerro()
{
$obJson = json_decode($_POST["obJson"]);
$retorno = new StdClass();
$retorno->Exito = false;
$con = new Conexion();
$consulta = $con->objPDO()->prepare("DELETE FROM perros WHERE nombre = '{$obJson->nombre}' AND raza = '{$obJson->raza}'");
if($consulta->execute())
{
$retorno->Exito = true;
}
echo json_encode($retorno);
}
function ObtenerPerrosPorTamaño()
{
$tam = $_POST["tamanio"];
$perros = array();
$con = new Conexion();
$consulta = $con->objPDO()->prepare("SELECT * FROM perros WHERE tamanio = '{$tam}'");
$consulta->execute();
while($fila = $consulta->fetch(PDO::FETCH_OBJ))
{
array_push($perros,$fila);
}
echo json_encode($perros);
}
function CantidadTamaño()
{
$retorno = new StdClass();
$retorno->cant = 0;
$retorno->tam = "No disponible";
$tam1 = 0;
$tam2 = 0;
$tam3 = 0;
$perros = array();
$con = new Conexion();
$consulta = $con->objPDO()->prepare("SELECT * FROM perros");
$consulta->execute();
while($fila = $consulta->fetch(PDO::FETCH_OBJ))
{
array_push($perros,$fila);
}
var_dump($perros);
foreach($perros as $element)
{
if(strtolower($element->tamanio) == "chico")
{
$tam1++;
}
else if(strtolower($element->tamanio) == "mediano")
{
$tam2++;
}
else if(strtolower($element->tamanio) == "grande")
{
$tam3++;
}
}
echo "TAMAÑOS DE PERROS CON MAYOR CANTIDAD:\n";
if($tam1 >= $tam2 && $tam1 >= $tam3)
{
echo "Tamaño: Chico Cantidad: {$tam1}\n";
}
if($tam2 >= $tam1 && $tam2 >= $tam3)
{
echo "Tamaño: Mediano Cantidad: {$tam2}\n";
}
if($tam3 >= $tam1 && $tam3 >= $tam2)
{
echo "Tamaño: Grande Cantidad: {$tam3}\n";
}
echo "TAMAÑOS DE PERROS CON MENOR CANTIDAD:\n";
if($tam1 != 0 && $tam2 != 0 && $tam3 !=0)
{
if($tam1 <= $tam2 && $tam1 <= $tam3)
{
echo "Tamaño: Chico Cantidad: {$tam1}\n";
}
if($tam2 <= $tam1 && $tam2 <= $tam3)
{
echo "Tamaño: Mediano Cantidad: {$tam2}\n";
}
if($tam3 <= $tam1 && $tam3 <= $tam2)
{
echo "Tamaño: Grande Cantidad: {$tam3}\n";
}
}
else if($tam1 != 0 && $tam2 != 0 && $tam3 ==0)
{
if($tam1 <= $tam2)
{
echo "Tamaño: Chico Cantidad: {$tam1}\n";
}
if($tam2 <= $tam1)
{
echo "Tamaño: Mediano Cantidad: {$tam2}\n";
}
}
else if($tam1 != 0 && $tam2 == 0 && $tam3 != 0)
{
if($tam1 <= $tam3)
{
echo "Tamaño: Chico Cantidad: {$tam1}\n";
}
if($tam3 <= $tam1)
{
echo "Tamaño: Grande Cantidad: {$tam2}\n";
}
}
else if($tam1 == 0 && $tam2 != 0 && $tam3 != 0)
{
if($tam2 <= $tam3)
{
echo "Tamaño: Mediano Cantidad: {$tam1}\n";
}
if($tam3 <= $tam2)
{
echo "Tamaño: Grande Cantidad: {$tam2}\n";
}
}
}
function EliminarTmp()
{
$files = glob('./fotos_tmp/*'); //obtenemos todos los nombres de los ficheros
foreach($files as $file)
{
if(is_file($file))
{
unlink($file); //elimino el fichero
}
}
}
|
JavaScript
|
UTF-8
| 727 | 3.875 | 4 |
[] |
no_license
|
function even(arr) {
for (var i = 0; i < arr.length; i++)
{
if (Array.isArray(arr[i]))//判断是不是数组,是数组则递归
{
even(arr[i]);
}
else{
arrf.push(arr[i]);
}
}
return arrf;
}
var arrf = [];
let arr = [1, [2, [3, 4]]];
even(arr);
console.log(arrf);
/* 非递归,toString数组扁平化
arrn = [];
arr = arr.toString();
for (const key in arr) {
if (Object.hasOwnProperty.call(arr, key)) {
const element = arr[key];
if(arr[key] == ',');
else{
arrn.push(+arr[key]);//‘+’转化数据成Number类型
}
}
}
console.log(arrn);
*/
|
Go
|
UTF-8
| 513 | 2.90625 | 3 |
[] |
no_license
|
package objects
import "testing"
func TestMakeDoc(t *testing.T) {
text := "The quick brown fox"
doc := MakeDoc(text)
if doc.Text != text {
t.Error("Given text and DocText not equal")
}
if len(doc.Tokens) != 4 {
t.Error("4 tokens expected for", text, "got", len(doc.Tokens))
}
}
func TestCountTokens(t *testing.T) {
test := "aa bb cc bb"
doc := MakeDoc(test)
counts := doc.CountTokens()
if counts["bb"] != 2 {
t.Error("There are 2 `bb` tokens in string `", test, "`, got", counts["bb"])
}
}
|
Java
|
UTF-8
| 1,902 | 2.125 | 2 |
[
"MIT"
] |
permissive
|
package ru.test.struts2.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import ru.test.struts2.entity.LoginBean;
/**
* @author Artem Pronchakov | email/xmpp: artem.pronchakov@calisto.email
*/
@Namespace("/")
@ResultPath("/")
public class LoginAction extends ActionSupport {
private LoginBean loginBean;
@Override
@Action(value = "login-action", results = {
@Result(name = "input", location = "login.jsp"),
@Result(name = "success", location = "success.jsp"),
@Result(name = "failure", location = "failure.jsp")
})
@Validations(requiredStrings = {
@RequiredStringValidator(fieldName = "loginBean.username", type = ValidatorType.FIELD, key = "username_required"),
@RequiredStringValidator(fieldName = "loginBean.password", type = ValidatorType.FIELD, key = "password_required")
})
public String execute() throws Exception {
if ("gemini".equals(loginBean.getUsername()) && "systems".equals(loginBean.getPassword())) {
return "success";
} else {
return "failure";
}
}
@Override
@Action(value = "login-screen", results = {
@Result(name = "input", location = "login.jsp")
})
public String input() throws Exception {
return "input";
}
public LoginBean getLoginBean() {
return loginBean;
}
public void setLoginBean(LoginBean loginBean) {
this.loginBean = loginBean;
}
}
|
Java
|
UTF-8
| 1,401 | 2.578125 | 3 |
[] |
no_license
|
package com.threerings.fisy.tools;
import java.util.Collections;
import java.util.List;
import java.io.IOException;
import com.bungleton.yarrgs.Positional;
import com.bungleton.yarrgs.Unmatched;
import com.bungleton.yarrgs.Usage;
import com.bungleton.yarrgs.Yarrgs;
import com.samskivert.io.StreamUtil;
import com.threerings.fisy.Directory;
import com.threerings.fisy.Record;
import com.threerings.fisy.Path;
import com.threerings.fisy.Paths;
public class fisycat
{
@Positional(0) @Usage("The uri to read and print to stdout")
public String file;
@Unmatched @Usage("Additional uris to read and print to stdout")
public List<String> files = Collections.emptyList();
public static void main (String[] args)
throws IOException
{
fisycat parsed = Yarrgs.parseInMain(fisycat.class, args);
dump(Paths.from(parsed.file));
for (String file : parsed.files) {
dump(Paths.from(file));
}
}
protected static void dump (Path file)
throws IOException
{
if (!file.exists()) {
if (file instanceof Directory) {
System.err.println("'" + file + "' is a directory, not a file");
} else {
System.err.println("'" + file + "' doesn't exist");
}
} else {
StreamUtil.copy(((Record)file).read(), System.out);
}
}
}
|
JavaScript
|
UTF-8
| 7,331 | 2.6875 | 3 |
[] |
no_license
|
import React from 'react';
class App extends React.Component{
constructor(props){
super(props);
this.state = {
index:0,
subIndex:0,
checked1:true,
checked2:true
};
this.changeState = this.changeState.bind(this);
this.subList= [];
console.log("constructor");
}
changeState(){
const nowIndex = this.state.index + 1;
this.setState({index:nowIndex});
console.log(`=======start update ${nowIndex}======`);
}
changeSubProps =()=>{
const nowIndex = this.state.subIndex + 1;
this.createSub(nowIndex);
this.setState({subIndex:nowIndex});
console.log(`=======start update subIndex${nowIndex}======`);
}
createSub = (nowIndex)=>{
this.subList = [];
for(let i = 0 ; i < 2; i ++){
this.subList.push(<AppSub key={`subkey-${i}`} pIndex={nowIndex} num={i}/>);
}
}
stopGetDerivedStateFromProps = (e) =>{
console.log(e.target);
let checked = true;
const tarVal = parseInt(e.target.value);
if(tarVal === 0){
checked = true;
}else if(tarVal === 1){
checked = false;
}
this.setState({checked1:checked});
}
stopShouldComponentUpdate = (e) =>{
console.log(e.target);
let checked = true;
const tarVal = parseInt(e.target.value);
if(tarVal === 0){
checked = true;
}else if(tarVal === 1){
checked = false;
}
this.setState({checked2:checked});
}
//mounting
/* componentWillMount(){
console.log("componentWillMount");
} */
//mounting & updating
static getDerivedStateFromProps(nextProps,preState){
console.log("getDerivedStateFromProps");
console.log("nextProps",nextProps);
console.log("preState",preState);
if(!preState.checked1)
return null;
return preState;
}
//mounting & updating
render(){
console.log("render");
return(
<div key="main">
<div className="Border">
Main render Count!- {this.state.index}
<div>
<button onClick={this.changeState}>change state</button>
<button onClick={this.changeSubProps}>change sub props</button>
</div>
<hr></hr>
<div onChange={this.stopGetDerivedStateFromProps}>
<div>
stop getDerivedStateFromProps
</div>
<label htmlFor="gOpen">open</label>
<input type="radio" name="getDerivedStateFromProps" id="gOpen" value="0" checked={this.state.checked1}/>
<label htmlFor="gClose">close</label>
<input type="radio" name="getDerivedStateFromProps" id="gClose" value="1" checked={!this.state.checked1}/>
</div>
<hr></hr>
<div onChange={this.stopShouldComponentUpdate}>
<div>
stop shouldComponentUpdate
</div>
<label htmlFor="sOpen">open</label>
<input type="radio" name="shouldComponentUpdate" id="sOpen" value="0" checked={this.state.checked2}/>
<label htmlFor="sClose">close</label>
<input type="radio" name="shouldComponentUpdate" id="sClose" value="1" checked={!this.state.checked2}/>
</div>
</div>
{this.subList}
</div>
);
}
//mounting
componentDidMount(){
console.log("componentDidMount");
}
/*//updating
componentWillReceiveProps(nextProps){
console.log("componentWillReceiveProps");
} */
shouldComponentUpdate(nextProps,nextState){
console.log("shouldComponentUpdate");
if(!this.state.checked2)
return false;
return true;
}
/* componentWillUpdate(nextProps,nextState){
console.log("componentWillUpdate");
} */
getSnapshotBeforeUpdate(preProps,preState){
console.log("getSnapshotBeforeUpdate");
console.log("preProps",preProps);
console.log("preState",preState);
console.log("=======================");
return "testSnapShot";
}
componentDidUpdate(preProps, preState , snapshot){
console.log("componentDidUpdate");
console.log("preProps",preProps);
console.log("preState",preState);
console.log("snapshot",snapshot);
console.log("=======================");
}
//Unmounting
componentWillUnmount(){
console.log("componentWillUnmount");
}
}
class AppSub extends React.Component{
constructor(props){
super(props);
this.name = `sub - ${this.props.num}`;
this.state = {index:0};
this.changeState = this.changeState.bind(this);
console.log(this.name ,"constructor");
}
changeState(){
const nowIndex = this.state.index + 1;
this.setState({index:nowIndex});
console.log(this.name ,`=======start update ${nowIndex}======`);
}
//mounting
/* componentWillMount(){
console.log("componentWillMount");
} */
//mounting & updating
static getDerivedStateFromProps(nextProps,preState){
console.log(`sub - ${nextProps.num}`,"getDerivedStateFromProps");
console.log("nextProps",nextProps);
console.log("preState",preState);
return preState;
}
//mounting & updating
render(){
console.log(this.name ,"render");
return(
<div className="subBorder">
{this.name}
<div>props render count - {this.props.pIndex}</div>
<div>state render count - {this.state.index}</div>
<div>
<button onClick={this.changeState}>change state</button>
</div>
</div>
);
}
//mounting
componentDidMount(){
console.log(this.name ,"componentDidMount");
}
/* //updating
componentWillReceiveProps(nextProps){
console.log("componentWillReceiveProps");
} */
shouldComponentUpdate(nextProps,nextState){
if(nextProps.pIndex > this.props.pIndex ){
console.log(this.name ,"============Props Update===============");
}
if(nextState.index > this.state.index){
console.log(this.name ,"============State Update===============");
}
console.log(this.name ,"shouldComponentUpdate");
return true;
}
/* componentWillUpdate(nextProps,nextState){
console.log("componentWillUpdate");
} */
getSnapshotBeforeUpdate(preProps,preState){
console.log(this.name ,"getSnapshotBeforeUpdate");
console.log("preProps",preProps);
console.log("preState",preState);
console.log("=======================");
return `${this.name}-testSnapShot`;
}
componentDidUpdate(preProps, preState , snapshot){
console.log(this.name ,"componentDidUpdate");
console.log("preProps",preProps);
console.log("preState",preState);
console.log("snapshot",snapshot);
console.log("=======================");
}
//Unmounting
componentWillUnmount(){
console.log(this.name ,"componentWillUnmount");
}
}
export default App;
|
C++
|
UTF-8
| 1,337 | 3.96875 | 4 |
[] |
no_license
|
//Lab9-1.cpp - circle calculations
//Created/revised by <your name> on <current date>
#include <iostream>
#include <cmath>
using namespace std;
//function prototypes
double getArea(double rad);
double getDiameter(double rad);
double getCircumference(double rad);
int main()
{
int choice = 0;
double radius = 0.0;
cout << "1 Circle area" << endl;
cout << "2 Circle diameter" << endl;
cout << "3 Circle circumference" << endl;
cout << "Enter your choice (1, 2, or 3): ";
cin >> choice;
if (choice < 1 || choice > 3)
cout << "Invalid choice" << endl;
else
{
cout << "Radius: ";
cin >> radius;
if (choice == 1)
cout << "Area: " << getArea(radius);
else if (choice == 2)
cout << "Diameter: " << getDiameter(radius);
else
cout << "Circumference: " << getCircumference(radius);
//end if
cout << endl;
} //end if
return 0;
} //end of main function
//*****function definitions*****
double getArea(double rad)
{
const double PI = 3.141593;
double area = 0.0;
area = PI * pow(rad, 2);
return area;
} //end getArea function
double getDiameter(double rad)
{
return 2 * rad;
} //end getDiameter function
double getCircumference(double rad)
{
const double PI = 3.141593;
double circumference = 0.0;
circumference = 2 * PI * rad;
return circumference;
} //end getCircumference function
|
Java
|
UTF-8
| 275 | 1.804688 | 2 |
[] |
no_license
|
package ui.tests;
import org.junit.Ignore;
import org.junit.Test;
public class RegistrationTest extends BaseUITestCase {
@Ignore
@Test
public void successfulRegistrationTest() {
homeSteps
.registerNewUser()
.verifyCorrectUserIsLoggedIn();
}
}
|
Python
|
UTF-8
| 10,129 | 2.53125 | 3 |
[] |
no_license
|
#!/usr/local/bin/python
import string,math,os,sys
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def GetRequestedEvents(run_card_name):
name = ""
val = 0
nevt = 1000;
run_card=open(run_card_name,"r")
lines = run_card.readlines()
for line in lines:
x = line.split()
if (len(x)==0):
continue;
elif (is_number(x[0])and(len(x)>=2)): #This line reads a number
val = x[0];
name = x[2];
if (name=="nevents"):
nevt = int(val)
break
return nevt
def GetTargetMass(run_card_name,verbose=False):
name = ""
run_card=open(run_card_name,"r")
lines = run_card.readlines()
for line in lines:
x = line.split()
if (len(x)==0):
continue;
if (is_number(x[0])and(len(x)>=2)): #This line reads a number
val = x[0];
name = x[2];
if (name=="mbeam2"):
M = float(val);
return M
if (verbose):
print "Error in GetTargetMass"
return 0.
def GetChiMass(param_card_name,verbose=False):
name = ""
param_card=open(param_card_name,"r")
lines = param_card.readlines();
for line in lines:
x = line.split()
if (len(x)==0):
continue;
if ((is_number(x[0])==True) and (is_number(x[1])==True) and (x[2]=="#")):
parName=x[3]
if (parName=="FMASS"):
M=float(x[1])
return M
if (verbose):
print "Error in getChiMass"
return 0.
def GetAprimeMass(param_card_name,verbose=False):
name = ""
param_card=open(param_card_name,"r")
lines = param_card.readlines();
for line in lines:
x = line.split()
if (len(x)==0):
continue;
if ((is_number(x[0])==True) and (is_number(x[1])==True) and (x[2]=="#")):
parName=x[3]
if (parName=="APMASS"):
M=float(x[1])
return M
if (verbose):
print "Error in getAprimeMass"
return 0.
def GetAlphaDark(param_card_name,verbose=False):
name = ""
param_card=open(param_card_name,"r")
lines = param_card.readlines();
for line in lines:
x = line.split()
if (len(x)==0):
continue;
if ((is_number(x[0])==True) and (is_number(x[1])==True) and (x[2]=="#")):
parName=x[3]
if (parName=="alphaD"):
alphaD=float(x[1])
return alphaD
if (verbose):
print "Error in GetAlphaDark"
return 0.
def GetEpsilon(param_card_name,verbose=False):
name = ""
param_card=open(param_card_name,"r")
lines = param_card.readlines();
for line in lines:
x = line.split()
if (len(x)==0):
continue;
if ((is_number(x[0])==True) and (is_number(x[1])==True) and (x[2]=="#")):
parName=x[3]
if (parName=="epsilon"):
eps=float(x[1])
return eps
if (verbose):
print "Error in GetEpsilon"
return 0.
#This function reads the provided run_card, and checks if the electron showering option was asked for - or not.
#The relevant informations are in the "<BDX>" section
#This will return:
# useShowering: bool, use or not the showering
# Emin : double, minimum electron energy
# Emax : double, maximum electron energy
# n : number of bins in the (Emin,Emax) interval
def CheckElectronShowering(run_card_name,verbose=False):
isBDX = False;
name = ""
val = 0
useShowering = False;
Emax=11;
Emin=1;
n = 10;
run_card=open(run_card_name,"r")
lines = run_card.readlines()
for line in lines:
x = line.split()
if (len(x)==0):
continue;
elif (line.find("<BDX>") != -1): #This line starts the BDX part
isBDX=True
elif (line.find("</BDX>") != -1): #This line ends the BDX part
isBDX=False
elif (is_number(x[0])and(len(x)>=2)): #This line reads a number
val = x[0];
name = x[2];
#Now check values
#E0
if (name=="ebeam1"):
Emax = float(val);
elif ((isBDX==True)and(name=="USESHOWERING")):
if (int(val)>=1):
useShowering = True;
else:
useShowering = False;
elif ((isBDX==True)and(name=="EMINSHOWERING")):
Emin = float(val);
elif ((isBDX==True)and(name=="NBINSSHOWERING")):
n = int(val);
run_card.close();
if (verbose==True):
print "CheckElectronShowering:"
print "useShowering: ",useShowering
print "Ebeam: ",Emax
return useShowering,Emax,n
#This function reads the provided run_card, and checks if the electron showering option was asked for - or not.
#The relevant informations are in the "<BDX>" section
#This will return:
# useShowering: bool, use or not the showering
# Ebeam : double, beam energy
def CheckElectronShoweringNew(run_card_name,verbose=False):
isBDX = False;
name = ""
val = 0
useShowering = False;
Ebeam=11;
run_card=open(run_card_name,"r")
lines = run_card.readlines()
for line in lines:
x = line.split()
if (len(x)==0):
continue;
elif (line.find("<BDX>") != -1): #This line starts the BDX part
isBDX=True
elif (line.find("</BDX>") != -1): #This line ends the BDX part
isBDX=False
elif (is_number(x[0])and(len(x)>=2)): #This line reads a number
val = x[0];
name = x[2];
#Now check values
#E0
if (name=="ebeam1"):
Ebeam = float(val);
elif ((isBDX==True)and(name=="USESHOWERING")):
if (int(val)>=1):
useShowering = True;
else:
useShowering = False;
run_card.close();
if (verbose==True):
print "CheckElectronShowering:"
print "useShowering set to: ",useShowering
print "Ebeam: ",Ebeam
return useShowering,Ebeam
def CreateRunCardDifferentEnergy(Ei,src_run_card_name,dest_run_card_name):
src_run_card=open(src_run_card_name,"r")
dest_run_card=open(dest_run_card_name,"w")
lines = src_run_card.readlines()
name = ""
for line in lines:
x = line.split()
if (len(x)==0):
continue;
elif ((is_number(x[0])and(len(x)>=2))): #This line reads a number
val = x[0];
name = x[2];
if (name == "ebeam1"):
newline = " "+str(Ei)+" = ebeam1 ! beam 1 energy in GeV\n"
dest_run_card.write(newline)
else:
dest_run_card.write(line)
src_run_card.close()
dest_run_card.close()
def createParamCard(aMass,chiMass,epsilon,alphaD):
print "CREATE PARAM CARD"
paramcardIN = open("Cards/param_card.dat", "r")
paramcardOUT = open("run/param_card.dat","w")
lines = paramcardIN.readlines()
iii = 0
for line in lines:
x = line.split()
if (len(x)>0):
if (x[0][0]=="#"):
paramcardOUT.write(line)
elif (is_number(x[0])==False):
paramcardOUT.write(line)
elif ((is_number(x[0])==True) and (is_number(x[1])==True) and (x[2]=="#")):
parName=x[3]
if (parName=="FMASS"):
x[1]=str(chiMass)
elif (parName=="APMASS"):
x[1]=str(aMass)
elif (parName=="epsilon"):
x[1]=str(epsilon)
elif (parName=="alphaD"):
x[1]=str(alphaD)
paramcardOUT.write(" ")
for word in x:
paramcardOUT.write(word+" ")
paramcardOUT.write("\n")
else:
paramcardOUT.write(line)
paramcardIN.close()
paramcardOUT.close()
def createRunCard(nevents,eBeam,ldet,fiduciallx,fiducially,fiduciallz,procid):
print "CREATE RUN CARD"
runcardIN = open("Cards/run_card.dat", "r")
runcardOUT = open("run/run_card.dat","w")
lines = runcardIN.readlines()
iii = 0
for line in lines:
x = line.split()
if (len(x)>0):
if (x[0][0]=="#"):
runcardOUT.write(line)
elif (is_number(x[0])==False):
runcardOUT.write(line)
elif ((is_number(x[0])==True) and (x[1]=="=")):
parName=x[2]
if (parName=="nevents"):
x[0]=str(nevents)
elif (parName=="ebeam1"):
x[0]=str(eBeam)
elif (parName=="ldet"):
x[0]=str(ldet)
elif (parName=="fiduciallx"):
x[0]=str(fiduciallx)
elif (parName=="fiducially"):
x[0]=str(fiducially)
elif (parName=="fiduciallz"):
x[0]=str(fiduciallz)
elif (parName=="procid"):
x[0]=str(procid)
runcardOUT.write(" ")
for word in x:
runcardOUT.write(word+" ")
runcardOUT.write("\n")
else:
paramcardOUT.write(line)
runcardIN.close()
runcardOUT.close()
def createCards(fname):
print "CREATE CARDS"
print fname
if (os.path.isfile(fname)==False):
print "file does not exist"
sys.exit(1)
else:
cardIN = open(fname, "r")
lines = cardIN.readlines()
if (len(lines)!=1):
sys.exit(2)
line=lines[0]
x = line.split()
createRunCard(x[5],x[6],x[7],x[8],x[9],x[10],x[11])
createParamCard(x[1],x[2],x[3],x[4])
sys.exit(0)
|
Python
|
UTF-8
| 1,322 | 3.921875 | 4 |
[] |
no_license
|
import time
#From 100 million data, find target
data = list(range(1,100000000))
target = 1000
#Time check function
def time_take_chk(fname):
t1=time.clock()
if fname(data,target) == True:
t2=time.clock()
print((fname.__name__) + "method took ",(t2-t1)," seconds")
else:
print((fname.__name__),"Return false")
#Linear search
def l_search(data,target):
for i in range(len(data)):
if data[i] == target:
return True
return False
time_take_chk(l_search)
#Binary search
def b_search(data,target):
low = 0
high = len(data)
while low <= high:
mid = (low+high)//2
if target == data[mid]:
return True
elif target < data[mid]:
high = mid - 1
else:
low = mid + 1
return False
time_take_chk(b_search)
def b_search_recur(data,target,low,high):
if low > high:
return False
else:
mid = (low+high)//2
if target == data[mid]:
return True
elif target < data[mid]:
return b_search_recur(data,target,low,mid-1)
else:
return b_search_recur(data,target,mid+1,high)
t1=time.time()
print(b_search_recur(data,target,0,len(data)-1))
t2=time.time()
print("recursive binary search took ",(t2-t1)," seconds")
|
C++
|
UTF-8
| 5,146 | 2.609375 | 3 |
[] |
no_license
|
#include "ObjReader.h"
#include <cstdlib>
#include <cstdio>
#include <stdio.h>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
// #include <regex>
ObjReader::ObjReader(){
is_transformed = false;
}
ObjReader::~ObjReader(){
}
//Sources viewed/used: http://www.opengl-tutorial.org/beginners-tutorials/tutorial-7-model-loading/
//This reader doesn't use textures
void ObjReader::parse(const char* file_loc, int f_type){
//read obj file first
std::ifstream file;
file.open(file_loc);
std::string line;
glm::vec3 ka;
glm::vec3 kd;
glm::vec3 ks;
int sp = 1;
glm::vec3 kr;
Transform* trans = new Transform();
bool is_transformed = false;
while(std::getline(file, line)){
std::stringstream l(line);
char type[10];
std::string vals;
l >> type;
std::getline(l, vals);
if(strcmp(type, "v") == 0){
glm::vec3 vert;
sscanf(vals.c_str(), "%f %f %f\n", &vert.x, &vert.y, &vert.z);
v.push_back(vert);
} else if(strcmp(type, "vn") == 0){
glm::vec3 norm;
sscanf(vals.c_str(), "%f %f %f\n", &norm.x, &norm.y, &norm.z);
vn.push_back(norm);
} else if(strcmp(type, "vt") == 0){
glm::vec2 tex;
sscanf(vals.c_str(), "%f %f\n", &tex.x, &tex.y);
} else if(strcmp(type, "f") == 0){
unsigned int vert_ind[3], normal_ind[3];
// printf("%d\n", f_type);
if(f_type == 0){
sscanf(vals.c_str(), "%d %d %d\n", &vert_ind[0], &vert_ind[1], &vert_ind[2]);
v_index.push_back(vert_ind[0]);
v_index.push_back(vert_ind[1]);
v_index.push_back(vert_ind[2]);
} else if(f_type == 1){
sscanf(vals.c_str(), "%d//%d %d//%d %d//%d\n", &vert_ind[0], &normal_ind[0], &vert_ind[1], &normal_ind[1], &vert_ind[2], &normal_ind[2]);
v_index.push_back(vert_ind[0]);
v_index.push_back(vert_ind[1]);
v_index.push_back(vert_ind[2]);
vn_index.push_back(normal_ind[0]);
vn_index.push_back(normal_ind[1]);
vn_index.push_back(normal_ind[2]);
}
} else {
printf("Unknown prefix '%s' in line: %s\n", type, line.c_str());
}
}
file.close();
// FILE* file = fopen(file_loc, "r");
// if(file == NULL){
// printf("Obj file at %s not found.\n", file_loc);
// }
// while(true){
// char type[128];
// int response = fscanf(file, "%s", type);
// if(response == EOF){
// // printf("%s\n", "EOF");
// break;
// }
// if(strcmp(type, "v") == 0){
// glm::vec3 vert;
// fscanf(file, "%f %f %f\n", &vert.x, &vert.y, &vert.z);
// v.push_back(vert);
// } else if(strcmp(type, "vn") == 0){
// glm::vec3 norm;
// fscanf(file, "%f %f %f\n", &norm.x, &norm.y, &norm.z);
// vn.push_back(norm);
// } else if(strcmp(type, "vt") == 0){
// glm::vec2 tex;
// fscanf(file, "%f %f\n", &tex.x, &tex.y);
// } else if(strcmp(type, "f") == 0){
// unsigned int vert_ind[3], normal_ind[3];
// // printf("%d\n", f_type);
// if(f_type == 0){
// fscanf(file, "%d %d %d\n", &vert_ind[0], &vert_ind[1], &vert_ind[2]);
// v_index.push_back(vert_ind[0]);
// v_index.push_back(vert_ind[1]);
// v_index.push_back(vert_ind[2]);
// } else if(f_type == 1){
// fscanf(file, "%d//%d %d//%d %d//%d\n", &vert_ind[0], &normal_ind[0], &vert_ind[1], &normal_ind[1], &vert_ind[2], &normal_ind[2]);
// v_index.push_back(vert_ind[0]);
// v_index.push_back(vert_ind[1]);
// v_index.push_back(vert_ind[2]);
// vn_index.push_back(normal_ind[0]);
// vn_index.push_back(normal_ind[1]);
// vn_index.push_back(normal_ind[2]);
// }
// }
// }
}
void ObjReader::createObj(Scene& scene, glm::vec3 ka, glm::vec3 kd, glm::vec3 ks, int sp, glm::vec3 kr){
//handle adding triangles to scene
// printf("%lu\n", v_index.size());
if(v_index.size() == vn_index.size()){
//do barycentric interpolation
for(int i = 0; i < v_index.size(); i+=3){
unsigned int i1 = v_index[i];
unsigned int i2 = v_index[i+1];
unsigned int i3 = v_index[i+2];
// printf("%d %d %d\n", i1, i2, i3);
glm::vec3 v1 = v[i1 - 1];
glm::vec3 v2 = v[i2 - 1];
glm::vec3 v3 = v[i3 - 1];
Triangle* tri = new Triangle(v1, v2, v3);
tri->setAmbient(ka);
tri->setDiffuse(kd);
tri->setSpecular(ks);
tri->setSpecularPow(sp);
tri->setReflect(kr);
if(is_transformed){
tri->setTransform(trans);
}
scene.insertTriangle(tri);
}
} else if (v_index.size() != 0 && vn_index.size() == 0){
//do flat shading
for(int i = 0; i < v_index.size(); i+=3){
unsigned int i1 = v_index[i];
unsigned int i2 = v_index[i+1];
unsigned int i3 = v_index[i+2];
// printf("%d %d %d\n", i1, i2, i3);
glm::vec3 v1 = v[i1 - 1];
glm::vec3 v2 = v[i2 - 1];
glm::vec3 v3 = v[i3 - 1];
Triangle* tri = new Triangle(v1, v2, v3);
tri->setAmbient(ka);
tri->setDiffuse(kd);
tri->setSpecular(ks);
tri->setSpecularPow(sp);
tri->setReflect(kr);
if(is_transformed){
tri->setTransform(trans);
}
scene.insertTriangle(tri);
}
}
}
void ObjReader::setTransform(glm::mat4 mat){
trans = mat;
is_transformed = true;
}
void ObjReader::reset(){
v.clear();
vn.clear();
v_index.clear();
vn_index.clear();
trans = glm::mat4(1.0f);
is_transformed = false;
}
|
C#
|
UTF-8
| 1,874 | 2.65625 | 3 |
[] |
no_license
|
using Microsoft.EntityFrameworkCore;
using SnookerTrainingCore.Domain.Entidades;
using SnookerTrainingCore.Domain.Repositorios.Interfaces;
using SnookerTrainingCore.Infra.Contexto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace SnookerTrainingCore.Infra.Repositorios
{
public class PontuacaoRepositorio : IPontuacaoRepositorio
{
private readonly SnookerContexto _contexto;
public PontuacaoRepositorio(SnookerContexto contexto)
{
_contexto = contexto;
}
public void Adicionar(Pontuacao pontuacao)
{
_contexto.Pontuacoes.Add(pontuacao);
Salvar();
}
public void AdicionarTodos(IEnumerable<Pontuacao> pontuacao)
{
foreach (var entity in pontuacao)
Adicionar(entity);
}
public void Atualizar(Pontuacao pontuacao)
{
_contexto.Entry(pontuacao).State = EntityState.Modified;
Salvar();
}
public IEnumerable<Pontuacao> Buscar(Expression<Func<Pontuacao, bool>> predicate)
{
return _contexto.Pontuacoes.Where(predicate).AsNoTracking();
}
public void Dispose()
{
//throw new NotImplementedException();
}
public Pontuacao ObterPorId(int id)
{
return _contexto.Pontuacoes.Where(x => x.IdPontuacao == id).FirstOrDefault();
}
public IEnumerable<Pontuacao> ObterTodos()
{
return _contexto.Pontuacoes.AsNoTracking();
}
public void Remover(Pontuacao pontuacao)
{
_contexto.Pontuacoes.Remove(pontuacao);
Salvar();
}
public void Salvar()
{
_contexto.SaveChanges();
}
}
}
|
Python
|
UTF-8
| 272 | 4.125 | 4 |
[] |
no_license
|
for numero in range(0,61):
print(f"el cuadrado de {numero} es: {numero*numero}")
print("\n ############ CON METODO WHILE ##############")
numero = 0
while numero <=60:
cuadrado = numero*numero
print(f"el cuadrado de {numero} es: {cuadrado}")
numero+=1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.