language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
C++
|
UTF-8
| 1,635
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct figure
{
char ch;
double rx1,rx2,ry1,ry2;
double cx1,cy1,cr1;
};
main()
{
ios::sync_with_stdio(0);
char ch;
double a,b,c,d,x,y;
figure fff[10];
int idx1=0,point=1;
while(cin>>ch&&ch!='*')
{
if(ch=='r')
{
cin>>a>>b>>c>>d;
fff[idx1].ch=ch;
fff[idx1].rx1=a;
fff[idx1].ry1=b;
fff[idx1].rx2=c;
fff[idx1].ry2=d;
idx1++;
}
else
{
cin>>a>>b>>c;
fff[idx1].ch=ch;
fff[idx1].cx1=a;
fff[idx1].cy1=b;
fff[idx1].cr1=c;
idx1++;
}
}
while(cin>>x>>y&&x!=9999.9&&y!=9999.9)
{
bool chk=true;
for(int i=0;i<idx1;++i)
{
if(fff[i].ch=='r')
{
if(x>fff[i].rx1&&x<fff[i].rx2&&y>fff[i].ry2&&y<fff[i].ry1){
cout<<"Point "<<point<<" is contained in figure "<<i+1<<endl;
chk=false;
}
}
else
{
if((x-fff[i].cx1)*(x-fff[i].cx1)+(y-fff[i].cy1)*(y-fff[i].cy1)<fff[i].cr1*fff[i].cr1)
{
cout<<"Point "<<point<<" is contained in figure "<<i+1<<endl;
chk=false;
}
}
}
if(chk)
cout<<"Point "<<point<<" is not contained in any figure"<<endl;
point++;
}
}
|
Python
|
UTF-8
| 289
| 2.53125
| 3
|
[] |
no_license
|
import multiprocessing as mpi
def run(a):
print(a.get())
if __name__ == '__main__':
queue=mpi.Queue()
for i in range(10):
queue.put(i)
for i in range(5):
p = mpi.Process(target=run, args=(queue,))
p.start()
p.join()
print(queue.get())
|
Java
|
UTF-8
| 4,734
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
package com.daxton.fancychat.api;
import com.daxton.fancychat.FancyChat;
import com.daxton.fancychat.config.PlayerData;
import com.daxton.fancycore.api.character.conversion.ColorConversion;
import com.daxton.fancycore.nms.ItemBaseComponent;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ChatConversion {
//聊天訊息處理
public static TextComponent valueOf(Player player, String inputString){
//顏色代碼轉換
//inputString = ConversionMessage.valueOf(inputString);
inputString = PlayerData.getColorString(player) + inputString;
if(inputString.contains("[item]")){
inputString = inputString.replace("[item]", "`[item]`");
TextComponent allChat = new TextComponent("");
String[] outputStringArray = inputString.split("`");
Arrays.stream(outputStringArray).forEach(s -> {
FancyChat.fancyChat.getLogger().info(s);
if(s.equals("[item]")){
allChat.addExtra(toItem(player));
}else {
allChat.addExtra(toColor(s));
}
});
return allChat;
}else {
return toColor(inputString);
}
//return new TextComponent(inputString);
}
//物品顯示設定
public static TextComponent toItem(Player player){
TextComponent textComponent = new TextComponent();
textComponent.setText("[item]");
textComponent.setColor(ChatColor.BLUE);
if(player.getInventory().getItemInMainHand().getType() != Material.AIR){
ItemStack itemStack = player.getInventory().getItemInMainHand();
textComponent.setHoverEvent( new HoverEvent(HoverEvent.Action.SHOW_ITEM, ItemBaseComponent.to(itemStack)));
}
return textComponent;
}
//聊天字串加上顏色
public static TextComponent toColor(String input){
TextComponent textComponent = new TextComponent();
input = translateHexColorCodes("\\{#" ,"\\}", input);
input = translateColorCodes("\\{#" ,"\\}", input);
if(input.contains("`")){
String[] xArray = input.split("`");
for(String s : xArray){
String[] sArray = s.split("\\|");
if(sArray.length == 2){
TextComponent textAdd = new TextComponent(sArray[1]);
if(sArray[0].length() == 6){
textAdd.setColor(ChatColor.of("#"+sArray[0]));
}
if(sArray[0].length() == 1){
textAdd.setColor(ColorConversion.hexToColor(sArray[0]));
}
textComponent.addExtra(textAdd);
}else {
Pattern pattern = Pattern.compile("([A-Fa-f0-9]{6})"+"\\|");
Matcher matcher = pattern.matcher(s);
if(matcher.find()){
FancyChat.fancyChat.getLogger().info(s);
}else {
textComponent.addExtra(new TextComponent(s));
}
}
}
}else {
textComponent.addExtra(input);
}
return textComponent;
}
//顏色轉換§
public static String translateColorCodes(String startTag, String endTag, String message) {
final Pattern hexPattern = Pattern.compile(startTag + "([A-Fa-f0-9]{1})" + endTag);
Matcher matcher = hexPattern.matcher(message);
StringBuffer buffer = new StringBuffer(message.length() + 4 * 8);
while (matcher.find()) {
String group = matcher.group(1);
//System.out.println(group);
matcher.appendReplacement(buffer, "`"+group+"|");
}
return matcher.appendTail(buffer).toString();
}
//16進制顏色轉換§
public static String translateHexColorCodes(String startTag, String endTag, String message) {
final Pattern hexPattern = Pattern.compile(startTag + "([A-Fa-f0-9]{6})" + endTag);
Matcher matcher = hexPattern.matcher(message);
StringBuffer buffer = new StringBuffer(message.length() + 4 * 8);
while (matcher.find()) {
String group = matcher.group(1);
//System.out.println(group);
matcher.appendReplacement(buffer, "`"+group+"|");
}
return matcher.appendTail(buffer).toString();
}
}
|
Markdown
|
UTF-8
| 3,763
| 3.125
| 3
|
[] |
no_license
|
# Image
## Image
포토문자\(MMS\)에 사용 될 이미지 관리 관련 예제 입니다.
### 서버에 이미지 파일 등록
- 이미지 파일을 쿨에스엠에스 미디어 서버에 저장합니다.
```text
import sys
from sdk.api.image import Image
from sdk.exceptions import CoolsmsException
## @brief This sample code demonstrate how to upload image through CoolSMS Rest API
if __name__ == "__main__":
# set api key, api secret
api_key = "#ENTER_YOUR_OWN#"
api_secret = "#ENTER_YOUR_OWN#"
# image is must be entered
image = "test.jpg" # image file
cool = Image(api_key, api_secret)
try:
response = cool.upload_image(image)
print("Image ID : %s" % response['image_id'])
except CoolsmsException as e:
print("Error Code : %s" % e.code)
print("Error Message : %s" % e.msg)
sys.exit()
```
### 이미지 리스트 보기
- 등록된 이미지를 확인 할 수 있습니다.
```text
import sys
from sdk.api.image import Image
from sdk.exceptions import CoolsmsException
## @brief This sample code demonstrate how to check image list through CoolSMS Rest API
if __name__ == "__main__":
# set api key, api secret
api_key = "#ENTER_YOUR_OWN#"
api_secret = "#ENTER_YOUR_OWN#"
# Optional parameters for your own needs
params = dict()
# params["offset"] = "0" # default 0
# params["limit"] = "20" # default 20
cool = Image(api_key, api_secret)
try:
response = cool.get_image_list(params)
print("Total Count : %s" % response['total_count'])
print("Limit : %s" % response['limit'])
print("Offset : %s" % response['offset'])
print("List : %s" % response['list'])
except CoolsmsException as e:
print("Error Code : %s" % e.code)
print("Error Message : %s" % e.msg)
sys.exit()
```
### 이미지 정보 보기
- 해당 이미지 파일의 정보를 확인 할 수 있습니다.
```text
import sys
from sdk.api.image import Image
from sdk.exceptions import CoolsmsException
## @brief This sample code demonstrate how to check image info through CoolSMS Rest API
if __name__ == "__main__":
# set api key, api secret
api_key = "#ENTER_YOUR_OWN#"
api_secret = "#ENTER_YOUR_OWN#"
image_id = "IMG57A42896DF7B0"
cool = Image(api_key, api_secret)
try:
response = cool.get_image_info(image_id)
print("Image_id : %s" % response['image_id'])
print("File_name : %s" % response['file_name'])
print("Original_name : %s" % response['original_name'])
print("File_size : %s" % response['file_size'])
print("Width : %s" % response['width'])
print("Height : %s" % response['height'])
except CoolsmsException as e:
print("Error Code : %s" % e.code)
print("Error Message : %s" % e.msg)
sys.exit()
```
### 이미지 삭제
- 해당 이미지를 서버에서 삭제합니다.
```text
import sys
from sdk.api.image import Image
from sdk.exceptions import CoolsmsException
## @brief This sample code demonstrate how to delete images through CoolSMS Rest API
if __name__ == "__main__":
# set api key, api secret
api_key = "#ENTER_YOUR_OWN#"
api_secret = "#ENTER_YOUR_OWN#"
# image_id is must be entered
image_id = "IMG57A44C8F5DC06"
cool = Image(api_key, api_secret)
try:
response = cool.delete_images(image_id)
print("Success Count : %s" % response['success_count'])
print("Error Count : %s" % response['error_count'])
print("Error List : %s" % response['error_list'])
except CoolsmsException as e:
print("Error Code : %s" % e.code)
print("Error Message : %s" % e.msg)
sys.exit()
```
|
SQL
|
UTF-8
| 2,945
| 3.828125
| 4
|
[] |
no_license
|
-- comentários
-- a linha abaixo cria um banco de dados
create database dbinfox;
-- a linha abaixo escolhe o banco de dados a ser utilizado
use dbinfox;
-- o bloco de instruções abaixo cria uma tabela
create table tbusuarios(
iduser int primary key,
usuario varchar(50) not null,
fone varchar(15),
login varchar(15) not null unique,
senha varchar(15) not null
);
-- o comando abaixo descreve a tabela
describe tbusuarios;
-- a linha abaixo insere dados na tabela (CRUD) create, read, update e delete
-- create -> insert
insert into tbusuarios(iduser,usuario,fone,login,senha)
values(1,'Marcos alves','999999999','marcosalves','123456');
insert into tbusuarios(iduser,usuario,fone,login,senha)
values(2,'administrador','999999999','admin','admin');
insert into tbusuarios(iduser,usuario,fone,login,senha)
values(3,'bill gates','999999999','bill','123456');
-- a linha abaixo exibe os dados da tabela (crud)
-- read -> select
select * from tbusuarios;
-- a linha abaixo modifica dados da tabela (crud)
-- update -> update
update tbusuarios set fone='888888888' where iduser=2;
-- a linha abaixo apaga um registro da tabela (crud)
-- delete -> delete
-- delete from tbusuarios where iduser=3;
-- -------------------------- Passo 2 - Criação da tabela de Clientes -------------------------
create table tbclientes(
idcli int primary key auto_increment,
nomecli varchar (50) not null,
endcli varchar(100),
cidadecli varchar (50) not null,
estadocli varchar (50) not null,
cepcli varchar (50) not null,
fonecli varchar(50) not null,
emailcli varchar (50)
);
describe tbclientes;
insert into tbcliente(nomecli,endcli,cidadecli,estadocli,cepcli,fonecli,emailcli)
values('marcos alves','Rua do pinguim','São Paulo','São Paulo','02000000','11-999999999','marco@gmail.com');
insert into tbcliente(nomecli,endcli,cidadecli,estadocli,cepcli,fonecli,emailcli)
values('administrador','Rua da empresa','Guarulhos','São Paulo','02000000','11-888888888','marco@gmail.com');
insert into tbcliente(nomecli,endcli,cidadecli,estadocli,cepcli,fonecli,emailcli)
values('bill gates','Rua da Janela','São Paulo','São Paulo','05000000','11-666666666','marco@gmail.com');
select * from tbclientes;
-- --------------------------- Passo 3 - Criação da tabela ordem de serviço -----------------------
use dbinfox;
create table tbos(
os int primary key auto_increment,
data_os timestamp default current_timestamp,
equipamento varchar(150) not null,
defeito varchar (150) not null,
servico varchar (150),
tecnico varchar (150),
valor decimal (10,2),
idcli int not null,
foreign key(idcli) references tbclientes(idcli)
);
describe tbos;
insert into tbos (equipamento,defeito,servico,tecnico,valor,idcli)
values ('Notebook','Não Liga','Troca da fonte','Zé',87.50,1);
select * from tbos;
-- código abaixo traz informações de duas tabelas
select
O.os,equipamento,defeito,servico,valor,
C.nomecli,fonecli
from tbos as O
inner join tbclientes as C
on (O.idcli = C.idcli);
|
C#
|
UTF-8
| 2,840
| 2.875
| 3
|
[
"Unlicense"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Windows.Forms;
namespace GetUnusedSkills
{
public partial class Form1 : Form
{
public Form1 ( )
{
InitializeComponent( );
}
public static string Reverse ( string s )
{
char [ ] charArray = s.ToCharArray( );
Array.Reverse( charArray );
return new string( charArray );
}
private void button1_Click ( object sender , EventArgs e )
{
List<string> AllStringData = new List<string>( );
List<string> AllStringData2 = new List<string>( );
string Regex1 = @"\[(\w\w\w\w)\]";
string Regex2 = @"\[(\w\w\w\w)\]";
foreach ( string file in Directory.GetFiles( textBox1.Text , "*.xxx" , SearchOption.AllDirectories ) )
{
AllStringData.AddRange( File.ReadAllLines( file ) );
}
foreach ( string file in Directory.GetFiles( textBox1.Text , "*.txt" , SearchOption.AllDirectories ) )
{
AllStringData2.AddRange( File.ReadAllLines( file ) );
}
MessageBox.Show( "Ab:" + AllStringData.Count.ToString( ) );
List<string> AbilCodes = new List<string>( );
foreach ( string str in AllStringData )
{
Match RegexMatch = Regex.Match( str , Regex2 );
if ( RegexMatch.Success )
{
AbilCodes.Add( RegexMatch.Groups [ 1 ].Value );
}
}
MessageBox.Show( "Abils:" + AbilCodes.Count.ToString( ) );
foreach ( string str in AllStringData2 )
{
Match RegexMatch = Regex.Match( str , Regex1 );
if ( RegexMatch.Success )
{
for ( int i = 0 ; i < AbilCodes.Count ; i++ )
{
string value = RegexMatch.Groups [ 1 ].Value;
if ( AbilCodes [ i ] == value )
{
AbilCodes.RemoveAt( i );
i--;
}
value = Reverse( value );
if ( AbilCodes [ i ] == value )
{
AbilCodes.RemoveAt( i );
i--;
}
}
}
}
MessageBox.Show( "Abils:" + AbilCodes.Count.ToString( ) );
File.WriteAllLines( "outdata.txt" , AbilCodes.ToArray( ) );
}
}
}
|
PHP
|
UTF-8
| 1,724
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
<?php
require_once __DIR__ .'/../vendor/autoload.php';
use Kristuff\Mishell\Console;
Console::log(' '. Console::text('Overview:', 'underlined', 'bold'));
Console::log(" - Use " . Console::text("int|bool ", 'blue') . Console::text("Console::askInt()", 'lightblue', 'underlined') . " to ask user to enter a number in the console.");
Console::log();
Console::log(' '. Console::text('Tips:', 'underlined', 'bold'));
Console::log(" - The method returns " . Console::text("int", 'blue') . " value or " . Console::text("false", 'blue'). " if the entered value is not a valid int number.");
Console::log(" - You can customize colors (foreground and background) and some styles in same way than ");
Console::log(' with ' . Console::text("Console::text()", 'lightblue', 'underlined') .
' and ' . Console::text("Console::log()", 'lightblue', 'underlined'). ' methods.');
Console::log();
Console::log(' '. Console::text('Usage:', 'underlined', 'bold'));
Console::log(' ' . Console::text("\$value = Console::askInt('Please enter a number > ');", 'lightmagenta'));
Console::log(' ' . Console::text("if (\$value !== false) {", 'lightmagenta'));
Console::log(' ' . Console::text("// Do something with \$value", 'green'));
Console::log();
Console::log(' '. Console::text('Sample:', 'underlined', 'bold'));
// -----------------
// sample start here
// -----------------
$value = Console::askInt(' Please enter a number > ');
if ($value !== false){
Console::log(' => The value you entered is [' . Console::text($value, 'yellow') . ']');
} else {
Console::log(Console::text(' Error:', 'red'));
Console::log(Console::text(' => the value you entered is not a valid number.', 'red'));
}
?>
|
Java
|
UTF-8
| 294
| 1.90625
| 2
|
[] |
no_license
|
package com.matey.bootwebservice.web.dto;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
@Getter
@RequiredArgsConstructor
@ToString(of = { "name", "amount" })
public class HelloResponseDTO {
private final String name;
private final int amount;
}
|
Java
|
UTF-8
| 1,617
| 2.484375
| 2
|
[] |
no_license
|
package Object;
import AccesData.DatabaseConnection;
import DAO.DAOEtat;
import DAO.DAOPersonne;
import java.util.ArrayList;
import java.util.Date;
public class Commande {
private int id;
private float prix;
private Date date;
private Personne personne;
private ArrayList<Pain> pains;
private Etat etat;
public Commande(){}
public Commande(int id, float prix, Date date, int personne, ArrayList<Pain> pains, int etat){
this.id = id;
this.prix = prix;
this.date = date;
DAOPersonne daoPersonne = new DAOPersonne(DatabaseConnection.createData());
this.personne = daoPersonne.find(personne);
this.pains = pains;
DAOEtat daoEtat = new DAOEtat(DatabaseConnection.createData());
this.etat = daoEtat.find(etat);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public float getPrix() {
return prix;
}
public void setPrix(float prix) {
this.prix = prix;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Personne getPersonne() {
return personne;
}
public void setPersonne(Personne personne) {
this.personne = personne;
}
public ArrayList<Pain> getPains() {
return pains;
}
public void setPains(ArrayList<Pain> pains) {
this.pains = pains;
}
public Etat getEtat() {
return etat;
}
public void setEtat(Etat etat) {
this.etat = etat;
}
}
|
JavaScript
|
UTF-8
| 4,243
| 2.96875
| 3
|
[] |
no_license
|
/*
* decaffeinate suggestions:
* DS103: Rewrite code to no longer use __guard__
* DS104: Avoid inline assignments
* DS201: Simplify complex destructure assignments
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
class Token {
constructor(params) {
this.type = params.type != null ? params.type : 'plain';
this.text = params.text != null ? params.text : '';
if (this.type !== 'plain') {
this.original = params.original != null ? params.original : null;
if (params.length != null) {
this.length = params.length;
}
}
this.parent = params.parent != null ? params.parent : null;
this.prev = params.prev != null ? params.prev : null;
this.next = params.next != null ? params.next : null;
}
// TODO: Support surrogates
prevChar() {
let prevChar = null;
let prevToken = this.prev;
while (prevChar === null && prevToken !== null) {
if (prevToken !== null && prevToken.text.length !== 0) {
prevChar = prevToken.text[prevToken.text.length - 1];
}
prevToken = prevToken.prev;
}
if (prevChar === null) {
return '';
}
return prevChar;
}
// TODO: Support surrogates
nextChar() {
let nextChar = null;
let nextToken = this.next;
while (nextChar === null && nextToken !== null) {
if (nextToken !== null && nextToken.text.length !== 0) {
nextChar = nextToken.text[0];
}
nextToken = nextToken.next;
}
if (nextChar === null) {
return '';
}
return nextChar;
}
remove() {
if (this.prev != null) {
this.prev.next = this.next;
}
if (this.next != null) {
this.next.prev = this.prev;
}
const index = this.parent.tokens.indexOf(this);
this.parent.tokens.splice(index, index - index + 1, ...[].concat([]));
return this;
}
joinNext() {
if (this.next != null) {
this.text += this.next.text;
this.next.remove();
}
return this;
}
// Override to add possibility to return null
substr(start, length) {
const params = {text: this.text.substr(start, length)};
if (this.type != null) {
params.type = this.type;
}
// TODO: Consider
if (this.original != null) {
params.original = this.original;
}
if (this.prev != null) {
params.prev = this.prev;
}
if (this.next != null) {
params.next = this.next;
}
if (this.length != null) {
params.length = this.length;
}
if (this.type === 'upright' && length === 0) {
params.type = 'plain';
delete params.original;
}
return new Token(params);
}
before(token) {
token.parent = this.parent;
if (this.prev != null) {
this.prev.next = token;
}
token.prev = this.prev;
this.prev = token;
token.next = this;
const index = this.parent.tokens.indexOf(this);
this.parent.tokens.splice(index, index - 1 - index + 1, ...[].concat([token]));
return this;
}
after(token) {
let ref;
token.parent = this.parent;
if (this.next != null) {
this.next.prev = token;
}
token.next = this.next;
this.next = token;
token.prev = this;
const index = this.parent.tokens.indexOf(this);
this.parent.tokens.splice((ref = index + 1), index - ref + 1, ...[].concat([token]));
return this;
}
replaceWith(tokens) {
// Glue tokens
let index;
for (index = 0; index < tokens.length; index++) {
const token = tokens[index];
token.parent = this.parent;
if (tokens[index + 1] != null) {
token.next = tokens[index + 1];
}
if (tokens[index - 1] != null) {
token.prev = tokens[index - 1];
}
}
if (this.prev != null) {
this.prev.next = tokens[0] != null ? tokens[0] : null;
}
if (tokens[0] != null) {
tokens[0].prev = this.prev;
}
if (this.next != null) {
let left;
this.next.prev = (left = tokens[tokens.length - 1]) != null ? left : null;
}
__guard__(tokens[tokens.length - 1], (x) => (x.next = this.next));
index = this.parent.tokens.indexOf(this);
this.parent.tokens.splice(index, index - index + 1, ...[].concat(tokens));
this.prev = null;
this.next = null;
this.parent = null;
return this;
}
}
module.exports = Token;
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null ? transform(value) : undefined;
}
|
JavaScript
|
UTF-8
| 2,699
| 2.875
| 3
|
[] |
no_license
|
import React, {useState} from 'react';
import './ExpenseForm.css';
import './NewExpense.css';
const ExpenseForm = (props) => {
//const [enterdTitle, setEnteredTitle] = useState('');
//const [enteredAmount, setEnteredAmount] = useState('');
//const [enteredDate, setEnteredDate] = useState('');
const [userInput, setUserInput] = useState({
enteredTitle: '',
enteredAmount: '',
enteredDate: ''
});
const titleChangedHandler = (event) => {
// If you use this approach, React will guarantee
// that the state snapshot it gives you here
// in this inner function,
// will always be the latest state snapshot,
// keeping all scheduled state updates in mind.
setUserInput((prevState) => {
return {...prevState, enteredTitle: event.target.value};
});
};
const amountChangeHandler = event => {
//setEnteredAmount(event.target.value);
setUserInput((prevState) => {
return {...prevState, enteredAmount: event.target.value};
});
};
const dateChangeHandler = event => {
//setEnteredDate(event.target.value);
setUserInput((prevState) => {
return {...prevState, enteredDate: event.target.value};
});
};
const submitHandler = (event) => {
// to prevent default page reload
event.preventDefault();
const expenseData = {
title: userInput.enteredTitle,
amount: userInput.enteredAmount,
date: new Date(userInput.enteredDate)
};
setUserInput((prevState) => {
return {...prevState, enteredTitle: 'Foo'};
});
props.onSaveExpenseData(expenseData);
}
return <form onSubmit={submitHandler}>
<div className="new-expense__controls">
<div className="new-expense__control">
<label>Title</label>
<input type="text" value={userInput.enteredTitle} onChange={titleChangedHandler}/>
</div>
<div className="new-expense__control">
<label>Amount</label>
<input type="number" value={userInput.enteredAmount} min="0.01" step="0.01" onChange={amountChangeHandler}/>
</div>
<div className="new-expense__control">
<label>Date</label>
<input type="date" value={userInput.enteredDate} min="2019-01-01" max="2022-12-31" onChange={dateChangeHandler}/>
</div>
</div>
<div className="new-expense__actions">
<button type="submit">Add expense</button>
</div>
</form>
}
export default ExpenseForm;
|
Python
|
UTF-8
| 7,297
| 3.09375
| 3
|
[
"Apache-2.0"
] |
permissive
|
# ========================================================================
# Copyright (C) 2019 The MITRE Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========================================================================
import vs_test_path_fixup
import unittest
import cirq
class SuperdenseCodingTests(unittest.TestCase):
"""
This class contains a simple implementation of the superdense coding protocol.
Note that unlike the other fundamental algorithms, this class uses a "circuit"
instance variable to represent the quantum circuit that holds the superdense coding
protocol. This is another example of Cirq's flexibility with respect to circuits
and registers.
"""
def setUp(self):
"""
Iniitalizes the unit test class.
"""
self.circuit = cirq.Circuit()
# ==============================
# == Algorithm Implementation ==
# ==============================
def encode_message(self, buffer, pair_a):
"""
Encodes two bits of information into an entangled qubit.
Parameters:
buffer (list[bool]): The two bits to encode into the qubit.
pair_a (Qid): The qubit to encode the information into. This
qubit must have already been entangled with another one.
"""
# Superposition takes advantage of the fact that if you start with |00> + |11>,
# you can modify it with X and Z on one qubit in a way that will affect both
# qubits.
# Nothing, X, Z, and XZ will all produce discrete, measureable states when
# both qubits are disentangled.
# We're going to use this lookup table to encode the given bits into the qubit
# pair:
# 00 = |00> + |11> (nothing happens)
# 01 = |01> + |10> (X, the parity is flipped)
# 10 = |00> - |11> (Z, the phase is flipped)
# 11 = |01> - |10> (XZ, parity and phase are flipped)
if(buffer[1]):
self.circuit.append(cirq.X(pair_a)) # X if the low bit is 1
if(buffer[0]):
self.circuit.append(cirq.Z(pair_a)) # Z if the high bit is 1
def decode_message(self, pair_a, pair_b):
"""
Decodes two bits of information from an entangled pair of qubits.
Parameters:
pair_a (Qid): The "remote" qubit that was modified by the encoding
process.
pair_b (Qid): The "local" qubit that we received, which wasn't
directly modified.
Returns:
a_measurement_key (str): The key of the measurement of the "remote" qubit.
b_measurement_key (str): The key of the measurement of the "local" qubit.
"""
a_measurement_key = "a_measurement"
b_measurement_key = "b_measurement"
self.circuit.append([
cirq.CNOT(pair_a, pair_b),
cirq.H(pair_a)
])
# Here's the decoding table based on the states after running
# them through CNOT(A, B) and H(A):
# |00> + |11> => |00> + |10> => |00>, so 00 means nothing happened
# |01> + |10> => |01> + |11> => |01>, so 01 means X happened
# |00> - |11> => |00> - |10> => |10>, so 10 means Z happened
# |01> - |10> => |01> - |11> => |11>, so 11 means XZ happened
# Notice how all 4 options align with the bit string used by the encoding
# table, so measuring these qubits gives us the original bits where
# pair_b corresponds to whether or not X was used, and pair_a corresponds
# to Z.
self.circuit.append([
cirq.measure(pair_a, key=a_measurement_key),
cirq.measure(pair_b, key=b_measurement_key),
])
return (a_measurement_key, b_measurement_key)
# ====================
# == Test Case Code ==
# ====================
def run_test(self, description, iterations, buffer):
"""
Runs the superdense coding algorithm on the given classical buffer.
Parameters:
description (str): A description of the test, for logging.
iterations (int): The number of times to run the circuit.
buffer (list[Bool]): The buffer containing the two bits to send.
"""
# Construct the registers and circuit.
print(f"Running test: {description}")
pair_a = cirq.NamedQubit(name="pair_a")
pair_b = cirq.NamedQubit(name="pair_b")
# Entangle the qubits together
self.circuit.append([
cirq.H(pair_a),
cirq.CNOT(pair_a, pair_b)
])
# Encode the buffer into the qubits, then decode them into classical measurements
self.encode_message(buffer, pair_a)
(a_measurement_key, b_measurement_key) = self.decode_message(pair_a, pair_b)
# Run the circuit N times.
simulator = cirq.Simulator()
result = simulator.run(self.circuit, repetitions=iterations)
# Check the first qubit to make sure it was always the expected value
desired_a_state = int(buffer[0])
a_result = result.histogram(key=a_measurement_key)
correct_a_counts = a_result[desired_a_state]
if correct_a_counts != iterations:
self.fail(f"Test {description} failed. The first bit should have been {desired_a_state} all " +
f"{iterations} times but it was only in this state {correct_a_counts} times.")
else:
print(f"The first qubit was {desired_a_state} all {iterations} times.")
# Check the second qubit to make sure it was always the expected value
desired_b_state = int(buffer[1])
b_result = result.histogram(key=b_measurement_key)
correct_b_counts = b_result[desired_b_state]
if correct_b_counts != iterations:
self.fail(f"Test {description} failed. The second bit should have been {desired_b_state} all " +
f"{iterations} times but it was only in this state {correct_b_counts} times.")
else:
print(f"The second qubit was {desired_b_state} all {iterations} times.")
print("Passed!")
print()
def test_00(self):
"""
Runs the superdense coding test on [00].
"""
self.run_test("Superdense [00]", 100, [False, False])
def test_01(self):
"""
Runs the superdense coding test on [01].
"""
self.run_test("Superdense [01]", 100, [False, True])
def test_10(self):
"""
Runs the superdense coding test on [10].
"""
self.run_test("Superdense [10]", 100, [True, False])
def test_11(self):
"""
Runs the superdense coding test on [11].
"""
self.run_test("Superdense [11]", 100, [True, True])
if __name__ == '__main__':
unittest.main()
|
Python
|
UTF-8
| 547
| 2.75
| 3
|
[] |
no_license
|
#!/usr/bin/env python3
import json
import subprocess
import sys
def run(input_file):
with open(input_file, encoding='utf-8') as data_file:
data = json.load(data_file)
for item in data['data']:
output = subprocess.check_output([
'mongo',
'report',
'--eval',
'db.errors.insert({});'.format(item)
])
print(output)
if __name__ == '__main__':
if len(sys.argv) > 1:
sys.exit(run(sys.argv[1]))
else:
print("Usage: classify.py json_file")
|
C++
|
UTF-8
| 871
| 3.203125
| 3
|
[] |
no_license
|
// ===-- chapter-4/chapter-4.cpp -------------------------- -*- C++ -*- --=== //
/**
* @file
* @brief Chapter 4: Integral Type Wappers and Operators
*
* C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost
* and Beyond.
*
* @author Matt Bisson - 2/28/2014
*/
#include "exercise-4-0.hpp"
#include "exercise-4-1.hpp"
#include "exercise-4-2.hpp"
#include "exercise-4-3.hpp"
#include "exercise-4-4.hpp"
#include "exercise-4-5.hpp"
#include <vector>
int main()
{
#ifdef EXERCISE_4_5
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
std::vector<int>::iterator it = container_find(v, 2);
std::vector<int> const& v_ref = v;
std::vector<int>::const_iterator it_const = container_find(v_ref, 2);
printf("it %s it_const\n", (*it == *it_const) ? "==" : "!=");
#endif
return 0;
}
|
C#
|
UTF-8
| 741
| 2.8125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Passenger.Core.Domain;
using Passenger.Core.Repositories;
namespace Passenger.Infrastructure.Repositories
{
public class InMemoryDriverRespository : IDriverRepository
{
private static ISet<Driver> _drivers = new HashSet<Driver>();
public async Task AddAsync(Driver driver)
{
_drivers.Add(driver);
}
public async Task<IEnumerable<Driver>> GetAllAsync()=>_drivers;
public async Task<Driver> GetAsync(Guid id)=> _drivers.Single(x=> x.DriverId == id);
public async Task UpdateAsync(Driver driver)
{
await Task.CompletedTask;
}
}
}
|
Java
|
UTF-8
| 15,669
| 1.742188
| 2
|
[
"MIT"
] |
permissive
|
/*
* ***** BEGIN LICENSE BLOCK *****
*
* Zimbra Collaboration Suite Server
* Copyright (C) 2011, 2012 VMware, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
*
* ***** END LICENSE BLOCK *****
*/
/**
*
*/
package org.zmail.qa.selenium.projects.desktop.ui.briefcase;
import java.util.*;
import org.zmail.qa.selenium.framework.items.*;
import org.zmail.qa.selenium.framework.ui.*;
import org.zmail.qa.selenium.framework.util.*;
import org.zmail.qa.selenium.framework.util.ZmailSeleniumProperties.AppType;
import org.zmail.qa.selenium.projects.desktop.ui.DialogWarning;
import org.zmail.qa.selenium.projects.desktop.ui.AppAjaxClient;
import org.zmail.qa.selenium.projects.desktop.ui.briefcase.DialogCreateBriefcaseFolder;
import org.zmail.qa.selenium.projects.desktop.ui.*;
/**
* @author zmail
*
*/
public class TreeBriefcase extends AbsTree {
public final static String stringToReplace = "<TREE_ITEM>";
public static class Locators {
public final static String zTreeItems = new StringBuffer("css=div[id='zovc__main_Briefcase'] td:contains('").
append(stringToReplace).append("')").toString();
public static final String briefcaseListView = "css=[id='zl__BDLV__rows']";
public static final String briefcaseTreeView = "css=[id*=zti__main_Briefcase__";
public static final String briefcaseTreeView_Desktop = "css=td[id*='main_Briefcase']";
public static final String zNewTagTreeMenuItem = "css=td[id$=_left_icon]>[class=ImgNewTag]";
public static final String zNewFolderTreeMenuItem = "css=tr[id=POPUP_NEW_BRIEFCASE]:contains('New Folder')";
public static final String zNewBriefcaseTreeMenuItem = "css=tr[id=POPUP_NEW_BRIEFCASE]:contains('New Briefcase')";
public static final String zRenameTagTreeMenuItem = "css=td[id$=_left_icon]>[class=ImgRename]";
public static final String zDeleteTreeMenuItem = "css=td[id$=_left_icon]>[class=ImgDelete]";
//public static final String zDeleteTreeMenuItem = "css=div[id='DELETE_WITHOUT_SHORTCUT'] tr[id^='POPUP_DELETE']:contains(Delete)";
public static final String treeExpandCollapseButton = "css=div[id='zovc__main_Briefcase'] div[id^='DWT'][class='DwtTreeItem'] [class^='ImgNode']";
public static final String multipleTrees = "css=div[id='zovc__main_Briefcase'] div[id^='zovc__main_Briefcase'][id$='__SECTION'][class^='DwtComposite ZmOverview']:nth-of-type(<NUM>)";
public static final String multipleTreesExpandCollapseButton = multipleTrees + " div[id^='DWT'] [class^='ImgNode']";
public static final String multipleLocalFolderTreesExpandCollapseButton = multipleTrees + " div[class='DwtTreeItemLevel1ChildDiv'] [class^='ImgNode']";
}
public TreeBriefcase(AbsApplication application) {
super(application);
logger.info("new " + TreeBriefcase.class.getCanonicalName());
}
@Override
public AbsPage zTreeItem(Action action, Button option, IItem item)
throws HarnessException {
logger.info(myPageName() + " zTreeItem(" + action + ", " + option
+ ", " + item.getName() + ")");
tracer.trace("Click " + action + " then " + option + " on item "
+ item.getName());
// Validate the arguments
if ((action == null) || (option == null) || (item == null)) {
throw new HarnessException(
"Must define an action, option, and item");
}
AbsPage page = null;
String actionLocator = null;
String optionLocator = null;
if (item instanceof TagItem) {
actionLocator = Locators.briefcaseTreeView_Desktop + "[id*='"
+ MyApplication.zGetActiveAccount().EmailAddress + "']"
+ ":contains('" + item.getName() + "')";
}else if (item instanceof FolderItem) {
FolderItem folder = (FolderItem) item;
String emailAddress = folder.isDesktopClientLocalFolder() ?
ZmailAccount.clientAccountName :
MyApplication.zGetActiveAccount().EmailAddress;
if (folder.getName().equals("USER_ROOT")) {
//TODO: Bug 65039
actionLocator = Locators.zTreeItems.replace(TreeBriefcase.stringToReplace,
"Local Folders");
} else {
actionLocator = Locators.briefcaseTreeView_Desktop + "[id*='"
+ emailAddress + "']"
+ "[id$='" + ((FolderItem) item).getId()
+ "_imageCell']";
}
} else {
throw new HarnessException("Must use IItem as argument, but was "
+ item.getClass());
}
if (action == Action.A_RIGHTCLICK) {
this.zRightClickAt(actionLocator, "0,0");
} else {
throw new HarnessException("implement me! " + action
+ ": not implemented");
}
if (option == Button.B_TREE_NEWTAG) {
optionLocator = Locators.zNewTagTreeMenuItem;
page = new DialogTag(MyApplication,
((AppAjaxClient) MyApplication).zPageBriefcase);
} else if (option == Button.B_TREE_RENAMETAG) {
optionLocator = Locators.zRenameTagTreeMenuItem;
page = new DialogRenameTag(MyApplication,
((AppAjaxClient) MyApplication).zPageBriefcase);
} else if (option == Button.B_TREE_DELETE) {
optionLocator = Locators.zDeleteTreeMenuItem;
if (item instanceof TagItem) {
page = new DialogWarning(
DialogWarning.DialogWarningID.DeleteTagWarningMessage,
MyApplication,
((AppAjaxClient) MyApplication).zPageBriefcase);
}
}else if (option == Button.B_TREE_NEWFOLDER) {
FolderItem folder = (FolderItem) item;
if (folder.getName().equals("USER_ROOT")) {
optionLocator = Locators.zNewBriefcaseTreeMenuItem;
} else {
optionLocator = Locators.zNewFolderTreeMenuItem;
}
page = new DialogCreateBriefcaseFolder(MyApplication,
((AppAjaxClient) MyApplication).zPageBriefcase);
} else {
throw new HarnessException("button " + option
+ " not yet implemented");
}
if (actionLocator == null)
throw new HarnessException("locator is null for action " + action);
if (optionLocator == null)
throw new HarnessException("locator is null for option " + option);
// Default behavior. Click the locator
zClick(optionLocator);
// If there is a busy overlay, wait for that to finish
this.zWaitForBusyOverlay();
if (page != null) {
// Wait for the page to become active, if it was specified
//page.zWaitForActive();
}
return (page);
}
public AbsPage zTreeItem(Action action, IItem item, boolean isRowAdded)
throws HarnessException {
tracer.trace("Click " + action + " on folder " + item.getName());
String treeItemLocator = null;
if (ZmailSeleniumProperties.getAppType() == AppType.DESKTOP) {
treeItemLocator = Locators.briefcaseTreeView_Desktop
+ "[class='DwtTreeItem-Text']";
} else {
treeItemLocator = Locators.briefcaseTreeView
+ "][class='DwtTreeItem-selected']";
}
AbsPage page = zTreeItem(action, item);
zWaitForElementPresent(treeItemLocator);
String listItemLocator = "css=[id='zl__BDLV__rows']";
if (isRowAdded)
listItemLocator += " div[class^='Row']";
zWaitForElementPresent(listItemLocator);
return page;
}
@Override
public AbsPage zTreeItem(Action action, IItem item) throws HarnessException {
logger.info(myPageName() + " zTreeItem(" + action + ", "
+ item.getName() + ")");
tracer.trace("Click " + action + " on item " + item.getName());
// Validate the arguments
if ((action == null) || (item == null)) {
throw new HarnessException("Must define an action, and item");
}
AbsPage page = null;
String locator = null;
if (item instanceof TagItem) {
locator = Locators.briefcaseTreeView_Desktop + "[id*='"
+ MyApplication.zGetActiveAccount().EmailAddress + "']"
+ ":contains('" + item.getName() + "')";
} else if (item instanceof FolderItem) {
FolderItem folder = (FolderItem) item;
String emailAddress = folder.isDesktopClientLocalFolder() ?
ZmailAccount.clientAccountName :
MyApplication.zGetActiveAccount().EmailAddress;
locator = Locators.briefcaseTreeView_Desktop + "[id*='"
+ emailAddress + "']"
+ "[id$='" + ((FolderItem) item).getId()
+ "_imageCell']";
} else {
throw new HarnessException("Must use IItem as argument, but was "
+ item.getClass());
}
if (action == Action.A_LEFTCLICK) {
zWaitForBusyOverlay();
// FALL THROUGH
} else if (action == Action.A_RIGHTCLICK) {
if (!this.sIsElementPresent(locator))
throw new HarnessException(
"Unable to locate folder in the tree " + locator);
// Select the folder
this.zRightClick(locator);
// return a context menu
return (new ContextMenu(MyApplication));
} else {
throw new HarnessException("Action " + action
+ " not yet implemented");
}
if (!this.sIsElementPresent(locator))
throw new HarnessException("Unable to locate folder in the tree "
+ locator);
// Default behavior. Click the locator
zClick(locator);
// If there is a busy overlay, wait for that to finish
zWaitForBusyOverlay();
if (page != null) {
// Wait for the page to become active, if it was specified
page.zWaitForActive();
}
return (page);
}
/*
* (non-Javadoc)
*
* @see
* org.zmail.qa.selenium.framework.ui.AbsTree#zPressButton(org.zmail.qa
* .selenium.framework.ui.Button)
*/
@Override
public AbsPage zPressButton(Button button) throws HarnessException {
tracer.trace("Click " + button);
if (button == null)
throw new HarnessException("Button cannot be null");
AbsPage page = null;
String locator = null;
if (button == Button.B_TREE_NEWBRIEFCASE) {
locator = "id=overviewHeader-Text FakeAnchor";
page = new DialogCreateBriefcaseFolder(MyApplication,
((AppAjaxClient) MyApplication).zPageBriefcase);
if (!this.sIsElementPresent(locator)) {
throw new HarnessException(
"Unable to locate folder in the tree " + locator);
}
this.zClick(locator);
zWaitForBusyOverlay();
return page;
// FALL THROUGH
} else if (button == Button.B_TREE_NEWTAG) {
locator = "css=div[class^=ImgNewTag ZWidget]";
if (!this.sIsElementPresent(locator)) {
throw new HarnessException("Unable to locate folder in tree "
+ locator);
}
page = new DialogTag(MyApplication,
((AppAjaxClient) MyApplication).zPageBriefcase);
} else if (button == Button.B_TREE_BRIEFCASE_EXPANDCOLLAPSE) {
locator = null;
page = null;
// TODO: implement me
// FALL THROUGH
} else if(button== Button.O_NEW_BRIEFCASE){
locator ="css=div[id='ztb__BDLV'] div[id='zb__BDLV__NEW_MENU'] td[id='zb__BDLV__NEW_MENU_dropdown'] >div";
if (!this.sIsElementPresent(locator)) {
throw new HarnessException("Unable to locate folder in tree "
+ locator);
}
sMouseDown(locator);
}else {
throw new HarnessException("no logic defined for button " + button);
}
if (locator == null) {
throw new HarnessException("locator was null for button " + button);
}
// Default behavior, process the locator by clicking on it
//
// Click it
this.zClick(locator);
// If the app is busy, wait for that to finish
zWaitForBusyOverlay();
// If page was specified, make sure it is active
if (page != null) {
// This function (default) throws an exception if never active
page.zWaitForActive();
}
return (page);
}
public List<TagItem> zListGetTags() throws HarnessException {
List<TagItem> items = new ArrayList<TagItem>();
// TODO: implement me!
// Return the list of items
return (items);
}
/**
* Expand all the folders tree
* @return
* @throws HarnessException
*/
public void zExpandAll() throws HarnessException {
// Browse all inventory in case of multiple accounts situation
int i = 1;
String locator = null;
String expandCollapseLocator = null;
String expandCollapseLocalFoldersLocator = null;
for (i = 1; i < 100; i++) {
locator = Locators.multipleTrees.replace("<NUM>",
Integer.toString(i));
if (!sIsElementPresent(locator)) {
break;
} else {
expandCollapseLocator = Locators.multipleTreesExpandCollapseButton.replace("<NUM>",
Integer.toString(i));
expandCollapseLocator = expandCollapseLocator.replace(
"ImgNode", "ImgNodeCollapsed");
expandCollapseLocalFoldersLocator = Locators.multipleLocalFolderTreesExpandCollapseButton.replace("<NUM>",
Integer.toString(i));
expandCollapseLocalFoldersLocator = expandCollapseLocalFoldersLocator.replace(
"ImgNode", "ImgNodeCollapsed");
while (sIsElementPresent(expandCollapseLocator)) {
sMouseDownAt(expandCollapseLocator, "0,0");
}
while (sIsElementPresent(expandCollapseLocalFoldersLocator)) {
sMouseDownAt(expandCollapseLocalFoldersLocator, "0,0");
}
}
}
}
/**
* Collapse all the folders tree
* @return
* @throws HarnessException
*/
public void zCollapseAll() throws HarnessException {
// Browse all inventory in case of multiple accounts situation
int i = 1;
String locator = null;
String expandCollapseLocator = null;
String expandCollapseLocalFoldersLocator = null;
for (i = 1; i < 100; i++) {
locator = Locators.multipleTrees.replace("<NUM>",
Integer.toString(i));
if (!sIsElementPresent(locator)) {
break;
} else {
expandCollapseLocator = Locators.multipleTreesExpandCollapseButton.replace("<NUM>",
Integer.toString(i));
expandCollapseLocator = expandCollapseLocator.replace(
"ImgNode", "ImgNodeExpanded");
expandCollapseLocalFoldersLocator = Locators.multipleLocalFolderTreesExpandCollapseButton.replace("<NUM>",
Integer.toString(i));
expandCollapseLocalFoldersLocator = expandCollapseLocalFoldersLocator.replace(
"ImgNode", "ImgNodeExpanded");
while (sIsElementPresent(expandCollapseLocator)) {
sMouseDownAt(expandCollapseLocator, "0,0");
}
while (sIsElementPresent(expandCollapseLocalFoldersLocator)) {
sMouseDownAt(expandCollapseLocalFoldersLocator, "0,0");
}
}
}
}
public void zExpandFolders() throws HarnessException {
throw new HarnessException("implement me!");
}
public boolean zIsFoldersExpanded() throws HarnessException {
throw new HarnessException("implement me!");
}
public void zExpandTags() throws HarnessException {
throw new HarnessException("implement me!");
}
public boolean zIsTagsExpanded() throws HarnessException {
throw new HarnessException("implement me!");
}
/*
* (non-Javadoc)
*
* @see framework.ui.AbsTree#myPageName()
*/
@Override
public String myPageName() {
return (this.getClass().getName());
}
@Override
public boolean zIsActive() throws HarnessException {
// Make sure the briefcase page is active
if (!((AppAjaxClient) MyApplication).zPageBriefcase.zIsActive()) {
((AppAjaxClient) MyApplication).zPageBriefcase.zNavigateTo();
}
boolean loaded = this.sIsElementPresent(Locators.briefcaseListView);
if (!loaded)
return (false);
return (loaded);
}
}
|
Java
|
UTF-8
| 1,546
| 2.9375
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lab4.net.suetholz.pos.lineitem;
import lab4.net.suetholz.pos.Product;
import lab4.net.suetholz.pos.api.LineItemStrategy;
/**
*
* @author wsuetholz
*/
public class BasicLineItem implements LineItemStrategy {
private Product product;
private int quantity;
public BasicLineItem (Product product, int quantity) {
setProduct(product);
setQuantity(quantity);
}
public final void setProduct(Product product) {
if (product == null) {
throw new IllegalArgumentException();
}
this.product = product;
}
@Override
public final Product getProduct() {
return product;
}
@Override
public final String getProductId() {
return product.getId();
}
@Override
public final String getProductDesc() {
return product.getDescription();
}
public final void setQuantity(int quantity) {
if (quantity < 0) {
throw new IllegalArgumentException();
}
this.quantity = quantity;
}
@Override
public int getQuantity() {
return quantity;
}
@Override
public final double getUnitCost() {
return product.getUnitPrice();
}
@Override
public final double getDiscountAmount() {
return product.getDiscountAmount(quantity);
}
@Override
public final double getExtendedAmount() {
return (product.getUnitPrice()*quantity);
}
}
|
Markdown
|
UTF-8
| 1,278
| 2.640625
| 3
|
[] |
no_license
|
---
layout: post
title: "chemistry ពិសោធន៍កម្រិតរលាយរបស់សមាសធាតុអុីយ៉ុងនិងសមាសធាតុកូវ៉ាឡង់"
date: 2021-04-28
category: Chemistry
published: True
list tittle: "videos"
---
<html>
<head>
<style>
body {
background-color: #BE77EC;
}
</style>
</head>
<body>
<p>
The video and poster below is an experiment on the solubility of ions and covalent compounds made by student Yun KhunLeangHeng from Grade 10.5 of E2stem School.
វីដេអូនិងposterខាងក្រោមនេះគឺជាការធ្វើពិសោធន៍កម្រិតរលាយរបស់សមាសធាតុអុីយ៉ុងនិងសមាសធាតុកូវ៉ាឡង់ដែលធ្វើដោយសិស្សឈ្មោះ យុន ឃុនលាងហេង មកពីថ្នាក់ 10.5 នៃសាលាE2stem។
<iframe width="800" height="450" src="https://www.youtube.com/embed/pv1sluyy5yw" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
---
<img src="https://i.ibb.co/BPnZqQX/c1.jpg" style="565" height="900">
|
C++
|
UTF-8
| 501
| 3.671875
| 4
|
[] |
no_license
|
#include"time.h"
time::time()
{
cout<<"\n\n default constuctor called\n";
hh=mm=sec=0;
}
time::time(int h,int m,int s)
{
cout<<"\n\n paramaterized constructor \n\n";
hh=h;
mm=m;
sec=s;
}
time::time(time &t)
{
cout<<"\n\n copy constuctor called \n\n";
this->hh=t.hh;
this->mm=t.mm;
this->sec=t.sec;
}
void time::display()
{
cout<<"\n\n---------------\n"<<hh<<":"<<mm<<":"<<sec<<"\n--------------------\n\n";
}
void time::accept()
{
cout<<"enter the time: ";
cin>>hh>>mm>>sec;
}
|
JavaScript
|
UTF-8
| 2,485
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
/**
Copyright 2016 Split Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
import Redis from 'ioredis';
import tape from 'tape-catch';
import KeyBuilder from '../../../Keys';
import LatencyCacheInRedis from '../../../LatencyCache/InRedis';
import SettingsFactory from '../../../../utils/settings';
const settings = SettingsFactory({
storage: {
type: 'REDIS'
}
});
tape('METRICS CACHE IN REDIS / should count based on ranges', async function (assert) {
const connection = new Redis(settings.storage.options);
const keys = new KeyBuilder(settings);
const cache = new LatencyCacheInRedis(keys, connection);
const metricName = 'testing';
let state;
await cache.clear();
await cache.track(metricName, 1);
await cache.track(metricName, 1.2);
await cache.track(metricName, 1.4);
state = await cache.state();
assert.true(state[metricName][0] === 3, 'the bucket #0 should have 3');
await cache.track(metricName, 1.5);
state = await cache.state();
assert.true(state[metricName][1] === 1, 'the bucket #1 should have 1');
await cache.track(metricName, 2.25);
await cache.track(metricName, 2.26);
await cache.track(metricName, 2.265);
state = await cache.state();
assert.true(state[metricName][2] === 3, 'the bucket #3 should have 1');
await cache.track(metricName, 985251);
state = await cache.state();
assert.true(state[metricName][22] === 1, 'the bucket #22 should have 1');
connection.quit();
assert.end();
});
tape('METRICS CACHE IN REDIS / clear', async function (assert) {
const connection = new Redis(settings.storage.options);
const keys = new KeyBuilder(settings);
const cache = new LatencyCacheInRedis(keys, connection);
const metricName = 'testing';
await Promise.all([
cache.track(metricName, 1),
cache.track(metricName, 1000)
]);
await cache.clear();
let isEmpty = await cache.isEmpty();
assert.true(isEmpty, 'after call clear, the cache should be empty');
connection.quit();
assert.end();
});
|
PHP
|
UTF-8
| 942
| 2.546875
| 3
|
[] |
no_license
|
<?php
header("Content-Type: text/html; charset=utf-8");
if(isset($_POST['name'])) {
$email = "sergas5555@yandex.ru"; #Email, на него придут письма
$title = "Заказ с сайта "; #Заголовок письма
$text = "
Информация о покупателе:
Имя: ".$_POST['name']."
Телефон: ".$_POST['phone']."
Модель: ".$_POST['comment']."
Заявка пришла с сайта:" . $_SERVER['HTTP_REFERER'] ."
Время заказа: ".date("Y-m-d H:i:s")."
IP адрес клиента: ". $_SERVER['REMOTE_ADDR'];
if(mail($email, $title, $text)) {
header('Location: thanks.html');
} else {
echo "Ошибка. Возможно функция mail отключена. Обратитесь к хостинг-провайдеру или возьмите консультацию на сайте, где купили шаблон";
}
} else {
echo "Ошибка";
}
?>
|
C
|
UTF-8
| 368
| 2.8125
| 3
|
[] |
no_license
|
#include <sys/utsname.h>
#include <unistd.h>
void main()
{
struct utsname name;
struct utsname *pname;
pname=&name;
if(uname(pname)<0){
printf("Error!\n");
exit(1);
}
printf("%s\n",pname->sysname);
printf("%s\n",pname->nodename);
printf("%s\n",pname->release);
printf("%s\n",pname->version);
printf("%s\n",pname->machine);
}
|
Java
|
UTF-8
| 415
| 2.234375
| 2
|
[] |
no_license
|
package db.model;
/**
* Created by eason on 2017/8/23.
*/
public class TableModel {
private String name;
private String Comment;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return Comment;
}
public void setComment(String comment) {
Comment = comment;
}
}
|
Python
|
UTF-8
| 3,539
| 3.40625
| 3
|
[] |
no_license
|
def transliterate(logoi):
#
# Purpose: replaces greek characters with latin
# Input Parameter(s): logoi: greek characters and punctuation(string)
# Return Value(s): a transliterated word, name, phrase or sentence(string)
#
# first, we find where all of the capitalized words and names are,
# so that we don't need to account for twice as many characters
logoi_list = logoi.split()
capitalized_logoi_indices = []
for index, logos in enumerate(logoi_list):
if logos[0].isupper():
capitalized_logoi_indices += [index]
logoi = logoi.lower()
# this first part is necessary because of the complicated nature of diphthongs with rough breathings.
rough_diphthong_pairs = [
[['αἱ', 'αἳ', 'αἵ', 'αἷ'], 'hai'],
[['αὑ', 'αὓ', 'αὕ', 'αὗ'], 'hau'],
[['εἱ', 'εἳ', 'εἵ', 'εἷ'], 'hei'],
[['εὑ', 'εὓ', 'εὓ', 'εὗ'], 'heu'],
[['οἱ', 'οἳ', 'οἵ', 'οἷ'], 'hoi'],
[['οὑ', 'οὓ', 'οὕ', 'οὗ'], 'hou'],
[['εὑ', 'εὓ', 'εὕ', 'εὗ'], 'heu'],
[['ηὑ', 'ηὓ', 'ηὕ', 'ηὗ'], 'hēu'],
[['υἱ', 'υἳ', 'υἵ', 'υἷ'], 'hui']
]
for pair in rough_diphthong_pairs:
for diphthong in pair[0]:
if diphthong in logoi:
logoi = logoi.replace(diphthong, pair[1])
# the next four lines address nasals like in the word for 'angel'
logoi = logoi.replace("γγ", "ng")
logoi = logoi.replace("γκ", "nk")
logoi = logoi.replace("γξ", "nx")
logoi = logoi.replace("γχ", "nχ")
# now we create an empty string to fill as we go along
transliteration = ""
ch_list = [['αάάἀἂἄἆὰᾶᾳᾀᾂᾄᾆᾲᾷᾴ', 'a'], ['ἁἃἅἇᾁᾃᾅᾇ', 'ha'], ['β', 'b'], ['γ', 'g'], ['δ', 'd'], ['εέέἐἒἔὲ', 'e'],
['ἑἓἕ', 'he'], ['ζ', 'z'], ['ηήἠἢἤἦὴῆῃᾐᾒᾔᾖῂῇῄ', 'ē'], ['ἡἣἥἧᾑᾓᾕᾗ', 'hē'], ['θ', 'th'],
['ιίίἰἲἴἶὶῖῗΐϊ', 'i'], ['ἱἳἵἷ', 'hi'], ['κ', 'k'], ['λ', 'l'], ['μ', 'm'], ['ν', 'n'], ['ξ', 'x'],
['οόόὀὂὄὸ', 'o'], ['ὁὃὅ', 'ho'], ['π', 'p'], ['ρῤ', 'r'], ['ῥ', 'rh'], ['σς', 's'], ['τ', 't'],
['υύύὐὒὔὖὺῦῧῢΰϋ', 'u'], ['ὑὓὕὗ', 'hu'], ['φ', 'ph'], ['χ', 'ch'], ['ψ', 'ps'],
['ωώώὠὢὤὦὼῶῳᾠᾢᾤᾦῲῷῴ', 'ō'], ['ὡὣὥὧᾡᾣᾥᾧ', 'hō'], ['·', ':'], [';', '?']]
for ch in logoi:
greeklet = False
for pair in ch_list:
if ch in pair[0]:
greeklet = True
transliteration += pair[1]
if not greeklet:
transliteration += ch
# and now we re-introduce capitalization
transliteration_list = transliteration.split()
for index, word in enumerate(transliteration_list):
if index in capitalized_logoi_indices:
transliteration_list[index] = word[0].upper() + word[1:]
transliteration = ' '.join(transliteration_list)
return transliteration
if __name__ == "__main__":
print(transliterate(input("Paste greek here: ")))
|
Java
|
UTF-8
| 699
| 3.40625
| 3
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.List;
public class prgrmd28_practice_arraylist {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String>a1=new ArrayList<String>();
a1.add("item1");
a1.add("item2");
a1.add("item3");
a1.add("item4");
a1.add("item5");
System.out.println("Total items" + a1.size());
System.out.println("Testing item4 exists " +a1.contains("item4"));
System.out.println("Printing all the items" +a1);
System.out.println("Removing item3");
a1.remove("item3");
System.out.println("printing all items after removing" +a1);
System.out.println("Total items after removing "+a1.size());
}
}
|
Ruby
|
UTF-8
| 1,486
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
require_relative 'kb8_utils'
require_relative 'kb8_run'
class Kb8Context
attr_accessor :cluster,
:name,
:namespace,
:user
CMD_CONFIG_VIEW = "#{Kb8Run::CMD_KUBECTL} config view -o yaml"
def initialize(context)
context_setting = nil
case context.class.to_s
when 'Hash'
context_setting = context
when 'String'
@name = context
all_config = Kb8Run.get_yaml_data(CMD_CONFIG_VIEW)
all_config['contexts'].each do |a_context|
if a_context['name'] == context
context_setting = a_context['context']
break
end
end
unless context_setting
raise "Context '#{@name}' not found"
end
when 'Kb8Context'
context_setting = context
else
raise 'Invalid context, expecting Hash'
end
unless context_setting['cluster'] && context_setting['namespace']
raise 'Invalid context, expecting at least a cluster and namespace.'
end
@cluster = context_setting['cluster']
@namespace = context_setting['namespace']
if context_setting['name']
@name = context_setting['name']
else
@name = @namespace
end
@user = context_setting['user']
end
def [](key)
case key
when 'name'
@name
when 'namespace'
@namespace
when 'cluster'
@cluster
when 'user'
@user
else
nil
end
end
end
|
PHP
|
UTF-8
| 577
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Requests\PhoneNumber;
use Illuminate\Foundation\Http\FormRequest;
use App\Rules\PhoneNumber\IsMatchesToken;
class TokenRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'digits' => ['required', new IsMatchesToken]
];
}
public function messages()
{
return [
'digits.required' => 'Magic numbers cannot be empty!',
'digits' => 'The given magic number must be a number!'
];
}
}
|
Java
|
UTF-8
| 1,008
| 3.28125
| 3
|
[] |
no_license
|
package lab6;
class Counter extends Thread {
private final int number;
private final long n;
private final long N;
private final int countOfThreads;
private long result = 0;
private long date1;
private long date2;
Counter(int number, long n, long N, int countOfThreads) {
this.number = number;
this.n = n;
this.N = N;
this.countOfThreads = countOfThreads;
this.start();
}
@Override
public void run() {
long countOfSteps = N / countOfThreads;
int steps = 0;
date1 = System.nanoTime();
for (long i = (number - 1) * countOfSteps * n; steps < countOfSteps; steps++) {
i += n;
result += i;
}
date2 = System.nanoTime();
}
public long getResult() {
return result;
}
public long getDate1() {
return date1;
}
public long getDate2() {
return date2;
}
}
|
PHP
|
UTF-8
| 1,096
| 3.015625
| 3
|
[] |
no_license
|
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
table{
margin:auto;
}
th,td:nth-child(n){
text-align: left;
padding: 0.2em 0.5em 0.2em 0.5em;
border-bottom: 1px solid;
}
tr:last-child td{
border-bottom: 0px;
}
</style>
</head>
<body>
<?php
$data=array(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
?>
<table>
<tr>
<th>Name</th>
<th>Stock</th>
<th>Sold</th>
</tr>
<tr>
<?php
for($i=0;$i<count($data);$i++)
{
echo
'<tr>';
for($j=0;$j<count($data[$i]);$j++)
{
echo
'<td>'.$data[$i][$j].'</td>';
}
echo
'</tr>' ;
}
?>
</tr>
</table>
<table>
<th>Name</th>
<th>Stock</th>
<th>Sold</th>
<?php
foreach ($data as list($a, $b,$c)) {
echo "<tr><td> $a</td><td> $b</td><td> $c</td></tr>";
}
?>
</table>
<table>
<th>Name</th>
<th>Stock</th>
<th>Sold</th>
<?php
function scroegg($x){
$tr='<tr>';
$join=join("</td><td>",$x);
$tr.="<td>".$join."</td>";
$tr.="</tr>";
return $tr;
}
echo join("",array_map("scroegg",$data));
?>
</table>
</body>
</html>
|
JavaScript
|
UTF-8
| 758
| 2.75
| 3
|
[] |
no_license
|
const { chromium } = require('playwright');
(async() => {
// function code
// launching browser
const browser = await chromium.launch({ headless:false , slowMo:100 });
// creating a page inside browser
const page = await browser.newPage();
// navigating to site
await page.goto('https://the-internet.herokuapp.com/key_presses');
await page.click('input')
await page.keyboard.type('one does not simply exit vim')
await page.keyboard.down('Shift')
for (let i = 0; i < ' exit vim'.length; i++) {
await page.keyboard.press('ArrowLeft')
}
await page.keyboard.up('Shift')
await page.keyboard.press('Backspace')
await page.keyboard.type(' walk into mordor')
// closing browser
await browser.close();
})();
|
C++
|
UTF-8
| 679
| 2.78125
| 3
|
[] |
no_license
|
class Solution {
public:
double minmaxGasDist(vector<int>& stations, int K) {
int n = stations.size();
double begin = 0, end = stations[n-1] - stations[0];
while(end - begin > 0.000001) {
double mid = (begin+end)/2;
//calculate k_mid
int k_mid = 0;
for(int i = 0; i < n-1; ++i) {
double dis = stations[i+1] - stations[i];
k_mid += ceil(dis/mid) - 1;
}
if(k_mid > K) {
begin = mid;
}
else {
end = mid;
}
}
return begin;
}
};
|
Java
|
UTF-8
| 1,943
| 3.140625
| 3
|
[] |
no_license
|
package task_2.task_2_1.view;
import task_2.task_2_1.model.Options;
import java.util.Scanner;
public class UserInput {
private Scanner scn;
public UserInput(){}
public int enterIntValue(BooksView view){
scn = new Scanner(System.in);
int val = 0;
while(true){
if(scn.hasNextInt()){
val = scn.nextInt();
if(val>0)
return val;
else {
view.printMessage(view.ERROR_VAL);
scn = new Scanner(System.in);
}
}else{
view.printMessage(view.ERROR_VAL);
scn = new Scanner(System.in);
}
}
}
public String enterStringValue(BooksView view){
scn = new Scanner(System.in);
String val = "";
while(true){
if(scn.hasNextLine()){
val = scn.nextLine();
if(!val.equals("") || !val.equals(" "))
return val;
else {
view.printMessage(view.ERROR_VAL);
scn = new Scanner(System.in);
}
}else{
view.printMessage(view.ERROR_VAL);
scn = new Scanner(System.in);
}
}
}
public Options enterOptionValue(BooksView view){
scn = new Scanner(System.in);
int val = 0;
Options[] options = Options.values();
while(true){
if(scn.hasNextInt()){
val = scn.nextInt();
if(val>0 && val<6)
return options[val-1];
else {
view.printMessage(view.ERROR_VAL);
scn = new Scanner(System.in);
}
}else{
view.printMessage(view.ERROR_VAL);
scn = new Scanner(System.in);
}
}
}
}
|
Python
|
UTF-8
| 556
| 2.53125
| 3
|
[] |
no_license
|
import os, sys
# files for which trees 2b created
indir='trees/'
alle=os.listdir(indir)
#
for a in alle[:]:
info=open(indir+a).read()
vals=[]
for k in info.split(':')[1:]:
number=k.split(')')[0].split(',')[0]
vals.append([float(number),number])
vals.sort()
# mark top branch
for v in vals[:-3]:
info=info.replace(':'+v[1],'')
info=info.replace(':'+vals[-3][1],'')
info=info.replace(':'+vals[-2][1],' #1')
info=info.replace(':'+vals[-1][1],'')
outwrite=open('top2tree/'+a,'w')
outwrite.write(info)
outwrite.close()
|
JavaScript
|
UTF-8
| 933
| 2.703125
| 3
|
[] |
no_license
|
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("scrollChart",{
height: 230,
title :{
text: "Scrolling chart"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 100;
var dataLength = 100; // number of dataPoints visible at any point
//var updateChart = function () {
$.getJSON('/chart/chart.php',
{value:' Lux'},
function(data){
$.each(data, function(key, value){
dps.push({
x: key,
y: value
});
});
alert(dps);
});
//if (dps.length > dataLength)
//{
// dps.shift();
//}
chart.render();
//};
// generates first set of dataPoints
//updateChart();
// update chart after specified time.
//setInterval(function(){updateChart()}, updateInterval);
}
|
C++
|
UTF-8
| 1,013
| 2.609375
| 3
|
[] |
no_license
|
/*
* main.cpp
* Math. Code Reference: Marching Cubes C-Algorithmus by Paul Bourke
* Last Changes: 06.05.2018
* Author: manitoo , C++/Qt Subclassing QOpenGLWidget , QOpenGLFunctions , GLSL Shading
*/
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setFont(QFont("Palatino", 12, QFont::Bold));
// --- An OpenGL Rendering Context is a set of OpenGL State Variables ---
QSurfaceFormat format;
format.setDepthBufferSize(24);
format.setVersion(3, 1);
format.setProfile(QSurfaceFormat::CoreProfile);
//format.setProfile(QSurfaceFormat::CompatibilityProfile);
QSurfaceFormat::setDefaultFormat(format);
MainWindow mainwindow(nullptr,/* Resolution <= 101 */51);
mainwindow.setWindowTitle("[ Marching Cubes | Cube/Tetrahedron - Algorithm | Math-Level-Sets ]");
//Geometry (Resolution)
// mainwindow.setGeometry(10,40,800,600);
mainwindow.show();
//Event Loop
return app.exec();
}
|
C
|
UTF-8
| 12,849
| 2.703125
| 3
|
[] |
no_license
|
//
// Created by Dylan La Frenz on 9/27/16.
//
int line=1;
//timers tcp protocol
//rtt = estimated rtt + estimated volatility
//rtt = 1 - alpha + sample rtt alpha - .125
//offered load
#include "includes.h"
//creating a struct for sphere camera and plane
#include "parse.h"
int next_c(FILE* json) {
int c = fgetc(json);
#ifdef DEBUG
printf("next_c: '%c'\n", c);
#endif
if (c == '\n') {
line += 1;
}
if (c == EOF) {
fprintf(stderr, "Error: Unexpected end of file on line number %d.\n", line);
exit(1);
}
return c;
}
// expect_c() checks that the next character is d. If it is not it emits
// an error.
void expect_c(FILE* json, int d) {
int c = next_c(json);
if (c == d) return;
fprintf(stderr, "Error: Expected '%c' on line %d.\n", d, line);
exit(1);
}
// skip_ws() skips white space in the file.
void skip_ws(FILE* json) {
int c = next_c(json);
while (isspace(c)) {
c = next_c(json);
}
ungetc(c, json);
}
// next_string() gets the next string from the file handle and emits an error
// if a string can not be obtained.
char* next_string(FILE* json) {
char buffer[129];
int c = next_c(json);
if (c != '"') {
fprintf(stderr, "Error: Expected string on line %d.\n", line);
exit(1);
}
c = next_c(json);
int i = 0;
while (c != '"') {
if (i >= 128) {
fprintf(stderr, "Error: Strings longer than 128 characters in length are not supported.\n");
exit(1);
}
if (c == '\\') {
fprintf(stderr, "Error: Strings with escape codes are not supported.\n");
exit(1);
}
if (c < 32 || c > 126) {
fprintf(stderr, "Error: Strings may contain only ascii characters.\n");
exit(1);
}
buffer[i] = c;
i += 1;
c = next_c(json);
}
buffer[i] = 0;
return strdup(buffer);
}
double next_number(FILE* json) {
double value;
int fail;
fail =fscanf(json, "%lf", &value);
if (fail==EOF||fail==0){
fprintf(stderr,"Not a valid Number on Line Number%d",line);
exit(1);
}
return value;
}
double* next_vector(FILE* json) {
double* v = malloc(3*sizeof(double));
expect_c(json, '[');
skip_ws(json);
v[0] = next_number(json);
skip_ws(json);
expect_c(json, ',');
skip_ws(json);
v[1] = next_number(json);
skip_ws(json);
expect_c(json, ',');
skip_ws(json);
v[2] = next_number(json);
skip_ws(json);
expect_c(json, ']');
//printf("%f\n",v[0]);
return v;
}
void read_scene(char* filename,Object* object,Light* lights) {
int c,i=0,cameras=0,j=0;
FILE* json = fopen(filename, "r");
if (json == NULL) {
fprintf(stderr, "Error: Could not open file \"%s\"\n", filename);
exit(1);
}
skip_ws(json);
// Find the beginning of the list
expect_c(json, '[');
skip_ws(json);
// Find the objects
while (1) {
//creating temporary Objects to assign to Object array later
Plane plane;
Sphere sphere;
Camera cam;
char type;
c = fgetc(json);
if (c == ']') {
fprintf(stderr, "Error: This is the worst scene file EVER.\n");
fclose(json);
exit(1);
}
if (c == '{') {
skip_ws(json);
// Parse the object
char* key = next_string(json);
if (strcmp(key, "type") != 0) {
fprintf(stderr, "Error: Expected \"type\" key on line number %d.\n", line);
exit(1);
}
skip_ws(json);
expect_c(json, ':');
skip_ws(json);
char* value = next_string(json);
//assigning kind values to temporary objects
if (strcmp(value, "camera") == 0) {
if (cameras==1){
fprintf(stderr,"Too many camera Objects");
exit(1);
}
object[i].kind=0;
type ='o';
cameras=1;
} else if (strcmp(value, "sphere") == 0) {
object[i].kind = 1;
type ='o';
} else if (strcmp(value, "plane") == 0) {
object[i].kind = 2;
type ='o';
}
else if(strcmp(value,"light")==0){
type ='l';
} else
{
fprintf(stderr, "Error: Unknown type, \"%s\", on line number %d.\n", value, line);
exit(1);
}
skip_ws(json);
while (1) {
// , }
c = next_c(json);
if (c == '}') {
// stop parsing this object
break;
} else if (c == ',') {
// read another field
skip_ws(json);
char* key = next_string(json);
skip_ws(json);
expect_c(json, ':');
skip_ws(json);
//checking which json value is next
if ((strcmp(key, "width") == 0) ||
(strcmp(key, "height") == 0) ||
(strcmp(key, "radius") == 0)) {
double value = next_number(json);
char* err;
//based upon which value is there put value in correct temporary value
if (strcmp(key, "width")==0 && object[i].kind==0) {
cam.width=value;
err = "width";
}
else if (strcmp(key, "height") == 0 && object[i].kind==0) {
cam.height=value;
err = "height";
} else if (strcmp(key, "radius") == 0&& object[i].kind==1) {
sphere.radius=value;
err = "radius";
}
else{
fprintf(stderr,"unexpected %s value on line %i",err,line);
exit(1);
}
}
//based upon which value is there put value in correct temporary value
else if ((strcmp(key, "specular_color") == 0) ||
(strcmp(key, "position") == 0) ||
(strcmp(key, "normal") == 0) ||
(strcmp(key,"diffuse_color")==0)) {
double* value = next_vector(json);
if (strcmp(key, "specular_color") == 0) {
if (object[i].kind == 1||object[i].kind==2) {
if (object[i].kind == 1) {
sphere.specular[0] = value[0];
sphere.specular[1] = value[1];
sphere.specular[2] = value[2];
}
if (object[i].kind == 2) {
plane.specular[0] = value[0];
plane.specular[1] = value[1];
plane.specular[2] = value[2];
}
}
else{
fprintf(stderr,"unexpected position value on line: %i",line);
exit(1);
}
}
if (strcmp(key,"diffuse_color")==0){
if (object[i].kind == 1) {
sphere.diffuse[0] = value[0];
sphere.diffuse[1] = value[1];
sphere.diffuse[2] = value[2];
}
if (object[i].kind == 2) {
plane.diffuse[0] = value[0];
plane.diffuse[1] = value[1];
plane.diffuse[2] = value[2];
}
}
if (strcmp(key, "position") == 0) {
if (type=='l'){
lights[j].position[0]=value[0];
lights[j].position[1]=value[1];
lights[j].position[2]=value[2];
}
else if (object[i].kind == 1||object[i].kind==2){
if (object[i].kind == 1) {
sphere.center[0] = value[0];
sphere.center[1] = value[1];
sphere.center[2] = value[2];
}
if (object[i].kind == 2) {
plane.position[0] = value[0];
plane.position[1] = value[1];
plane.position[2] = value[2];
}
}
else {
fprintf(stderr,"unexpected position value on line: %i",line);
exit(1);
}
}
if (strcmp(key, "normal") == 0) {
if (object[i].kind == 2) {
plane.normal[0] = value[0];
plane.normal[1] = value[1];
plane.normal[2] = value[2];
}
else{
fprintf(stderr,"unexpected normal value on line: %i",line);
exit(1);
}
}
}
else if(strcmp(key,"radial-a2")==0){
double value = next_number(json);
lights->radA2=value;
}
else if(strcmp(key,"radial-a1")==0){
double value = next_number(json);
lights->radA1=value;
}
else if(strcmp(key,"radial-a0")==0){
double value = next_number(json);
lights->radA0=value;
}
else if(strcmp(key,"angular-a0")==0){
double value = next_number(json);
lights->angA0=value;
}
else if(strcmp(key,"color")==0&&type=='l'){
double* value = next_vector(json);
lights[j].color[0]=value[0];
lights[j].color[1]=value[1];
lights[j].color[2]=value[2];
//printf("%f",lights[j].color[1]);
}
else if(strcmp(key,"direction")==0){
double* value = next_vector(json);
lights[j].direction[0]=value[0];
lights[j].direction[1]=value[1];
lights[j].direction[2]=value[2];
}
else if(strcmp(key,"theta")==0){
double value = next_number(json);
lights[j].theta=value;
}
else {
fprintf(stderr, "Error: Unknown property, \"%s\", on line %d.\n",
key, line);
exit(1);
//char* value = next_string(json);
}
skip_ws(json);
} else {
fprintf(stderr, "Error: Unexpected non comma value on line %d\n", line);
exit(1);
}
//assigning values in object array to temporary Objects
object[i].cam=cam;
object[i].sphere=sphere;
object[i].plane=plane;
}
skip_ws(json);
c = next_c(json);
if (c == ',') {
if(type =='o'){i++;}
if(type=='l'){j++;}
skip_ws(json);
} else if (c == ']') {
fclose(json);
return;
} else {
fprintf(stderr, "Error: Expecting ',' or ']' on line %d.\n", line);
exit(1);
}
}
}
}
|
Markdown
|
UTF-8
| 973
| 2.6875
| 3
|
[] |
no_license
|
---
layout: page
title: The First Amendment
permalink: /learn/first-amendment.html
left_navigation: learn
related:
- title: "Learn more about the related laws and policies"
url: "https://www.ucsc.edu/"
- title: "Report hate and bias"
url: "https://reporthate.ucsc.edu/"
---
The First Amendment to the U.S. Constitution is only 45 words long, yet it protects our most basic freedoms. It reads in full:
"Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the Government for a redress of grievances."
>*“But, above all else, the First Amendment means that government has no power to restrict expression because of its message, its ideas, its subject matter, or its content.”<br/><br />
—Supreme Court Justice Thurgood Marshall, Police Department of Chicago v. Mosley (1972)*
|
Python
|
UTF-8
| 75
| 2.796875
| 3
|
[] |
no_license
|
from turtle import*
a = int(input())
shape("turtle")
circle(a)
mainloop()
|
C++
|
WINDOWS-1251
| 3,057
| 3.09375
| 3
|
[] |
no_license
|
#include <SFML/Graphics.hpp>
#include <vector>
#include "functions.hpp"
using namespace std;
using namespace sf;
class Background
{
Texture texture;
int starsCount, lowerScaleLimit, upperScaleLimit, windowWidth, windowHeight;
float speedMult;
RenderWindow &window;
public:
// , , , , ,
// , , ( (5) )
// , ( scale = 1 / randomLimit)
Background(Image &image, int StarsCount, float SpeedMult, int LowerScaleLimit, int UpperScaleLimit, RenderWindow &Window)
: starsCount(StarsCount), lowerScaleLimit(LowerScaleLimit), upperScaleLimit(UpperScaleLimit), speedMult(SpeedMult), window(Window)
{
texture.loadFromImage(image);
windowWidth = window.getSize().x;
windowHeight = window.getSize().y;
for (int i = 0; i < starsCount; i++)
{
Star star(texture);
stars.push_back(star);
stars[i].createNew(speedMult, lowerScaleLimit, upperScaleLimit, windowWidth, windowHeight, true);
}
}
void update(float &mainTime)
{
for (int i = 0; i < starsCount; i++)
{
stars[i].sprite.move(0, stars[i].speed * mainTime);
stars[i].y += stars[i].speed * mainTime;
if (stars[i].y > windowHeight + 10) stars[i].createNew(speedMult, lowerScaleLimit, upperScaleLimit, windowWidth);
window.draw(stars[i].sprite);
}
}
private:
class Star
{
public:
Sprite sprite;
float scale, speed, y;
Star(Texture &texture)
{
sprite.setTexture(texture);
sprite.setOrigin(texture.getSize().x / 2, texture.getSize().y);
}
void createNew(float &speedMult, int &lowerScaleLimit, int &upperScaleLimit, int &windowWidth, int windowHeight = 0, bool firstTime = false)
{
scale = 1 / (float)randomNumber(lowerScaleLimit, upperScaleLimit);
sprite.setScale(scale, scale);
speed = scale * speedMult;
if (firstTime) y = randomNumber(0, windowHeight);
else y = 0;
sprite.setPosition(randomNumber(0, windowWidth), y);
}
};
vector <Star> stars;
};
|
JavaScript
|
UTF-8
| 1,228
| 3.59375
| 4
|
[] |
no_license
|
const LinkedList = require('./linkedlist');
const Node = require('./node');
module.exports = class Graph {
constructor(vertices) {
this.vertices = vertices;
this.list = [];
var it;
for (it = 0; it < vertices; it++) {
let temp = new LinkedList();
this.list.push(temp);
}
}
addEdge(source, destination) {
if (source < this.vertices && destination < this.vertices)
this.list[source].insertAtHead(destination);
return this;
}
printGraph() {
console.log(">>Adjacency List of Directed Graph<<");
var i;
for (i = 0; i < this.list.length; i++) {
process.stdout.write("|" + String(i) + "| => ");
let temp = this.list[i].getHead();
while (temp != null) {
process.stdout.write("[" + String(temp.data) + "] -> ");
temp = temp.nextElement;
}
console.log("null ");
}
}
strGraph() {
let str = "";
var i;
for (i = 0; i < this.list.length; i++) {
str = str + "|" + String(i) + "| => ";
let temp = this.list[i].getHead();
while (temp != null) {
str += ("[" + String(temp.data) + "] -> ");
temp = temp.nextElement;
}
str += "null ";
}
return str;
}
}
|
JavaScript
|
UTF-8
| 895
| 3.90625
| 4
|
[] |
no_license
|
// ** Leetcode: Arrays Reps Challenge ~ Traversal Edition ~
// ** --> { #94 Binary Tree Inorder Traversal }
// T A SK !!!
// Given the root of a binary tree, return the inorder traversal of its nodes' values
// * first attempt ~
// * time complexity: O(N)
// * space complexity: O(N)
const inorderTraversal = (root, output = []) => {
// edge case check
if(!root) return output;
if(root !== null) {
inorderTraversal(root.left, output);
output.push(root.value);
inorderTraversal(root.right, output);
}
return output;
}
// * second attempt: iteratively ~
const inorderTraversal2 = (root) => {
const stack = [];
const output = [];
let node = root;
while(node || stack.length) {
if(node) {
stack.push(node);
node = node.left;
} else {
node = stack.pop();
output.push(node.val);
node = node.right;
}
}
return output;
}
|
PHP
|
UTF-8
| 2,813
| 3.34375
| 3
|
[] |
no_license
|
<?php
class FileModifier {
private $inputFile;
private $outputFile;
private $replaceLines = array();
private $optionalReplaceLines = array();
private $addAfterLines = array();
private $optionalAddAfterLines = array();
private $deleteLines = array();
private $optionalDeleteLines = array();
private $missingLines;
function __construct($inputFile, $outputFile = null) {
$this->inputFile = $inputFile;
if($outputFile == null) {
$this->outputFile = $inputFile;
}
else {
$this->outputFile = $outputFile;
}
}
public function replaceLine($search, $replace, $optional = false) {
$this->replaceLines[$search] = $replace;
if($optional === true) {
$this->optionalReplaceLines[$search] = $replace;
}
}
public function addAfterLine($search, $add, $optional = false) {
$this->addAfterLines[$search] = $add;
if($optional === true) {
$this->optionalAddAfterLines[$search] = $add;
}
}
public function deleteLine($search, $numberOfLines, $optional = false) {
$this->deleteLines[$search] = $numberOfLines;
if($optional === true) {
$this->optionalDeleteLines[$search] = $numberOfLines;
}
}
public function execute() {
$lines = file($this->inputFile);
$newLines = '';
$numberOfLinesToDelete = 0;
foreach($lines as $line) {
$delete = false;
if($numberOfLinesToDelete != 0) {
$numberOfLinesToDelete--;
$delete = true;
}
// Delete
if ($delete === false) {
foreach ($this->deleteLines as $key => $numberOfLines) {
if(strpos($line, $key) !== false) {
$delete = true;
$numberOfLinesToDelete = $numberOfLines - 1;
unset($this->deleteLines[$key]);
break;
}
}
}
if($delete === false) {
// Replace
foreach ($this->replaceLines as $key => $replaceLine) {
if(strpos($line, $key) !== false) {
$line = str_replace($key, $replaceLine, $line);
unset($this->replaceLines[$key]);
}
}
$newLines .= $line;
}
// Add
foreach ($this->addAfterLines as $key => $addAfterLine) {
if(strpos($line, $key) !== false) {
$newLines .= $addAfterLine;
unset($this->addAfterLines[$key]);
break;
}
}
}
$missingReplaceLines = array_diff_key($this->replaceLines, $this->optionalReplaceLines);
$missingDeleteLines = array_diff_key($this->deleteLines, $this->optionalDeleteLines);
$missingAddAfterLines = array_diff_key($this->addAfterLines, $this->optionalAddAfterLines);
$this->missingLines = array_merge($missingReplaceLines, $missingDeleteLines, $missingAddAfterLines);
$success = empty($this->missingLines);
if($success) {
$file = fopen($this->outputFile, 'w');
fwrite($file, $newLines);
fclose($file);
}
return $success;
}
public function getMissingLines() {
return $this->missingLines;
}
}
?>
|
JavaScript
|
UTF-8
| 153
| 3.859375
| 4
|
[] |
no_license
|
// Defining the function
function greeting_three(string) {
console.log("Hello " + string + "!");
}
// Calling the function
greeting_three("World");
|
Go
|
UTF-8
| 408
| 2.59375
| 3
|
[] |
no_license
|
package model
import (
"finalProject/cmd/service/grpc-model/user"
)
type User struct {
Id int32 `gorm:"primary_key"`
Name string
Email string
Password string
}
func (p *User) Set(in *user.CreateUserReq) {
p.Name = in.Name
p.Email = in.Email
p.Password = in.Password
}
func (p *User) Fill(in *user.User) {
in.Id = p.Id
in.Name = p.Name
in.Email = p.Email
in.Password = p.Password
}
|
Python
|
UTF-8
| 734
| 3.15625
| 3
|
[] |
no_license
|
# A very simple Flask Hello World app for you to get started with...
from flask import Flask, render_template
from os import environ
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello from Flask!'
@app.route('/asw')
def hello_from_me():
return 'Hello from me'
@app.route("/hello/<name>")
def hello_person(name):
html = """
<h1>
Hello {}!
</h1>
<p>
Here's a picture of a kitten. Awww...
</p>
<img src="http://placekitten.com/g/200/300">
"""
return html.format(name.title())
@app.route("/test")
def template_test():
return render_template('template.html')
if __name__ == "__main__":
app.run(host=environ['IP'],
port=int(environ['PORT']))
|
Java
|
UTF-8
| 2,234
| 2.234375
| 2
|
[] |
no_license
|
package com.avatar.maintenance.service.impl;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.avatar.maintenance.dto.Person;
import com.avatar.maintenance.repository.PersonRepository;
import com.avatar.maintenance.service.PersonService;
@Service("personService")
public class PersonServiceImpl implements PersonService{
@Autowired
PersonRepository pRepository;
@Override
public int save(Person person) {
int resultado = 0;
RestTemplate rt = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
String url = "https://swapi.co/api/planets/";
ResponseEntity<String> res = rt.exchange(url, HttpMethod.GET, entity, String.class);
JSONObject json;
try {
json = new JSONObject(res.getBody());
if(json.getJSONArray("results").getJSONObject(0).getString("name").equals(person.getPlanet().toString())){
pRepository.save(person);
resultado = 1;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultado;
}
@Override
public int delete(Integer id) {
int result = 0;
Optional<Person> person = pRepository.findById(id);
if (person!=null) {
pRepository.deleteById(id);
result = 1;
}
return result;
}
@Override
public List<Person> lista(){
List<Person> listPerson = (List<Person>) pRepository.findAll();
return listPerson;
}
}
|
Markdown
|
UTF-8
| 4,026
| 3.640625
| 4
|
[] |
no_license
|
# 作用
> 用来匹配符合某种规则的字符串 , **字符串匹配**
>
> 是一个对象
# 创建
## 字面量方式创建
```js
let reg = /+86\d{11}/g
```
## 构造函数方式创建
麻烦,但正则规则可通过字符串拼接,有些场景不得不用
```js
let reg = new RegExp('+86\d{11}','g')
```
## 修饰符
| 修饰符 | 含义 |
| ------ | ---------- |
| g | 全局搜索 |
| i | 忽略大小写 |
| m | 多行搜索 |
# 常用方法
## test()
作用: 检查字符串是否符合正则对象的规则
```js
let reg = /+86\d{11}/g
reg.test(`+863i2794723`)
```
## 字符串的方法
> 正则对象作为字符串方法的参数 , 对字符串进行验证
| 方法 | 说明 |
| -------------------- | ------------------------------------ |
| search(reg) | 判断字符串是否匹配 |
| match(reg) | 返回一个数组 , 里面放着匹配的字符串 |
| replace(reg , str) | 用str 替换掉匹配规则的字符串 |
| split(reg) | 返回一个数组 , 里面放着字符串切片 |
# 专用字符
| 字符 | 含义 |
| ------ | ----------------------------------------------------- |
| . | 匹配除了空格和回车的任意字符 <==>`[^\r\n]` |
| /xxxx/ | 字符匹配 |
| [xxx] | 范围匹配 : 匹配范围内的一个字符 [0-9] or [a-zA-Z] |
| [^] | 不是 ==> 取反 |
| \d | 匹配一个数字字符 <==> [0-9] |
| \D | <==> `[^0-9]` |
| \s | 匹配一个空格 |
| \S | 匹配非空格 |
| \w | <==> [a-zA-Z_0-9] |
# 量词
> 匹配多个字符
| 量词 | 作用 |
| ----- | ------------------------------------------ |
| ? | 前面的字符出现0次或者1次 ==>有没有都可以 |
| + | 前的字符 : 必须有 , 有多少次无所谓 |
| * | 前面的字符 : 0次 or n次 |
| {n} | 前面的字符出现n次 |
| {n,m} | q前面的字符出现n到m次 |
| {n,} | 至少出现n次 |
| | |
# 边界区分
> 以 xxx 开头 或者 以xxx结尾
| 正则 | 含义 |
| --------- | ----------------- |
| /^xxx/ | 以xxx开头 |
| /xxx$/ | 以xxx结尾 |
| /\bxxx\b/ | 匹配是单词的xxx |
| /\Bxxx\B/ | 匹配不是单词的xxx |
| | |
| | |
| | |
# 常用正则
## 匹配手机号
```js
let reg = /^1\d{10}$/
```
## 匹配邮箱
```js
let reg=/^[^@\s]+@[^@\s]+\.[^@\s]+$/
```
## 匹配用户名
```js
```
# 贪婪模式和非贪婪模式
> 默认是贪婪模式
>
> 在量词情况下{n.m} , 究竟选n匹配还是选m匹配??
>
> 默认是选m匹配 ,
{n,m}? 开启非贪婪模式 , 选n匹配
```js
let s = '123456789'
s.match(/\d{3,5}/g)
s.match(/\d{3,5}?/g)
```
## 实用举例
```js
`aa"helloworld"ok"jirengu"`.match(/".+"/g)
```
> 贪婪
会尽可能匹配 , 得到一个数组
`[""helloworld"ok"jirengu""]`
这不是我们希望的 , 我们希望得到["helloworld", "jirengu"]
> 非贪婪
```js
`aa"helloworld"ok"jirengu"`.match(/".+?"/g)
```
`["helloworld", "jirengu"]`
# 分组
```js
(xxx){3}
```
(xx) 被这些字符看撑一个整体去匹配
$n 来引用!!
# 前瞻
格式:
```js
exp1(?=exp2) 匹配后面是exp2的exp1
exp1(?exp2) 匹配后面不是exp2的 exp1
```
如:
```js
/hello(?=jirengu)/.test('hellojirengu') //true
```
|
C
|
UTF-8
| 15,328
| 2.984375
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "contents.h"
#include "filecontents1.h"
#include "filecontents2.h"
#include "filecontents3.h"
#include "filecontents4.h"
#include "filecontents5.h"
#include "filecontents6.h"
int writ() {
char ch1[50];
char file1[50];
char file2[50];
char file3[50];
char line1[200];
char line2[200];
char line3[200];
char line4[200];
char line5[200];
char line6[200];
char line7[200];
char line8[200];
char line9[200];
char line10[200];
char line11[200];
char line12[200];
char line13[200];
char line14[200];
char line15[200];
char filename[50];
printf("You have entered file editor write system.\n");
conten1();
printf("\n");
conten2();
printf("\n");
conten3();
printf("\n");
conten4();
printf("\n");
conten5();
printf("\n");
conten6();
printf("\nSelection: ");
scanf("%s", ch1);
printf("\n\nYou have selected ");
printf("%s", ch1);
printf(". Now please write the lines:\n");
printf("1: ");
scanf("%s", line1);
printf("2: ");
scanf("%s", line2);
printf("3: ");
scanf("%s", line3);
printf("4: ");
scanf("%s", line4);
printf("5: ");
scanf("%s", line5);
printf("6: ");
scanf("%s", line6);
printf("7: ");
scanf("%s", line7);
printf("8: ");
scanf("%s", line8);
printf("9: ");
scanf("%s", line9);
printf("10: ");
scanf("%s", line10);
printf("11: ");
scanf("%s", line11);
printf("12: ");
scanf("%s", line12);
printf("13: ");
scanf("%s", line13);
printf("14: ");
scanf("%s", line14);
printf("15: ");
scanf("%s", line15);
printf("\nPlease give this file a name (No Spaces): ");
scanf("%s", filename);
FILE * writetable;
FILE * writefile;
if(!strcmp("file1", ch1) == 1) {
writefile = fopen("file1", "w");
fprintf(writefile, "1: ");
fprintf(writefile, "%s", line1);
fprintf(writefile, "\n");
fprintf(writefile, "2: ");
fprintf(writefile, "%s", line2);
fprintf(writefile, "\n");
fprintf(writefile, "3: ");
fprintf(writefile, "%s", line3);
fprintf(writefile, "\n");
fprintf(writefile, "4: ");
fprintf(writefile, "%s", line4);
fprintf(writefile, "\n");
fprintf(writefile, "5: ");
fprintf(writefile, "%s", line5);
fprintf(writefile, "\n");
fprintf(writefile, "6: ");
fprintf(writefile, "%s", line6);
fprintf(writefile, "\n");
fprintf(writefile, "7: ");
fprintf(writefile, "%s", line7);
fprintf(writefile, "\n");
fprintf(writefile, "8: ");
fprintf(writefile, "%s", line8);
fprintf(writefile, "\n");
fprintf(writefile, "9: ");
fprintf(writefile, "%s", line9);
fprintf(writefile, "\n");
fprintf(writefile, "10: ");
fprintf(writefile, "%s", line10);
fprintf(writefile, "\n");
fprintf(writefile, "11: ");
fprintf(writefile, "%s", line11);
fprintf(writefile, "\n");
fprintf(writefile, "12: ");
fprintf(writefile, "%s", line12);
fprintf(writefile, "\n");
fprintf(writefile, "13: ");
fprintf(writefile, "%s", line13);
fprintf(writefile, "\n");
fprintf(writefile, "14: ");
fprintf(writefile, "%s", line14);
fprintf(writefile, "\n");
fprintf(writefile, "15: ");
fprintf(writefile, "%s", line15);
fprintf(writefile, "\n");
writetable = fopen("file1data.c", "w");
fprintf(writetable, "#include <stdio.h>\n");
fprintf(writetable, "#include <string.h>\n");
fprintf(writetable, "#include <stdlib.h>\n");
fprintf(writetable, "int conten1(void) {\n");
fprintf(writetable, " char file1[50] = \"");
fprintf(writetable, "%s", filename);
fprintf(writetable, "\";\n printf(\"File 1: \");\n printf(\"\%%s\", file1);");
fprintf(writetable, "\n}");
}
if(!strcmp("file2", ch1) == 1) {
writefile = fopen("file2", "w");
fprintf(writefile, "1: ");
fprintf(writefile, "%s", line1);
fprintf(writefile, "\n");
fprintf(writefile, "2: ");
fprintf(writefile, "%s", line2);
fprintf(writefile, "\n");
fprintf(writefile, "3: ");
fprintf(writefile, "%s", line3);
fprintf(writefile, "\n");
fprintf(writefile, "4: ");
fprintf(writefile, "%s", line4);
fprintf(writefile, "\n");
fprintf(writefile, "5: ");
fprintf(writefile, "%s", line5);
fprintf(writefile, "\n");
fprintf(writefile, "6: ");
fprintf(writefile, "%s", line6);
fprintf(writefile, "\n");
fprintf(writefile, "7: ");
fprintf(writefile, "%s", line7);
fprintf(writefile, "\n");
fprintf(writefile, "8: ");
fprintf(writefile, "%s", line8);
fprintf(writefile, "\n");
fprintf(writefile, "9: ");
fprintf(writefile, "%s", line9);
fprintf(writefile, "\n");
fprintf(writefile, "10: ");
fprintf(writefile, "%s", line10);
fprintf(writefile, "\n");
fprintf(writefile, "11: ");
fprintf(writefile, "%s", line11);
fprintf(writefile, "\n");
fprintf(writefile, "12: ");
fprintf(writefile, "%s", line12);
fprintf(writefile, "\n");
fprintf(writefile, "13: ");
fprintf(writefile, "%s", line13);
fprintf(writefile, "\n");
fprintf(writefile, "14: ");
fprintf(writefile, "%s", line14);
fprintf(writefile, "\n");
fprintf(writefile, "15: ");
fprintf(writefile, "%s", line15);
fprintf(writefile, "\n");
writetable = fopen("file2data.c", "w");
fprintf(writetable, "#include <stdio.h>\n");
fprintf(writetable, "#include <string.h>\n");
fprintf(writetable, "#include <stdlib.h>\n");
fprintf(writetable, "int conten2(void) {\n");
fprintf(writetable, " char file2[50] = \"");
fprintf(writetable, "%s", filename);
fprintf(writetable, "\";\n printf(\"File 2: \");\n printf(\"\%%s\", file2);");
fprintf(writetable, "\n}");
}
if(!strcmp("file3", ch1) == 1) {
writefile = fopen("file3", "w");
fprintf(writefile, "1: ");
fprintf(writefile, "%s", line1);
fprintf(writefile, "\n");
fprintf(writefile, "2: ");
fprintf(writefile, "%s", line2);
fprintf(writefile, "\n");
fprintf(writefile, "3: ");
fprintf(writefile, "%s", line3);
fprintf(writefile, "\n");
fprintf(writefile, "4: ");
fprintf(writefile, "%s", line4);
fprintf(writefile, "\n");
fprintf(writefile, "5: ");
fprintf(writefile, "%s", line5);
fprintf(writefile, "\n");
fprintf(writefile, "6: ");
fprintf(writefile, "%s", line6);
fprintf(writefile, "\n");
fprintf(writefile, "7: ");
fprintf(writefile, "%s", line7);
fprintf(writefile, "\n");
fprintf(writefile, "8: ");
fprintf(writefile, "%s", line8);
fprintf(writefile, "\n");
fprintf(writefile, "9: ");
fprintf(writefile, "%s", line9);
fprintf(writefile, "\n");
fprintf(writefile, "10: ");
fprintf(writefile, "%s", line10);
fprintf(writefile, "\n");
fprintf(writefile, "11: ");
fprintf(writefile, "%s", line11);
fprintf(writefile, "\n");
fprintf(writefile, "12: ");
fprintf(writefile, "%s", line12);
fprintf(writefile, "\n");
fprintf(writefile, "13: ");
fprintf(writefile, "%s", line13);
fprintf(writefile, "\n");
fprintf(writefile, "14: ");
fprintf(writefile, "%s", line14);
fprintf(writefile, "\n");
fprintf(writefile, "15: ");
fprintf(writefile, "%s", line15);
fprintf(writefile, "\n");
writetable = fopen("file3data.c", "w");
fprintf(writetable, "#include <stdio.h>\n");
fprintf(writetable, "#include <string.h>\n");
fprintf(writetable, "#include <stdlib.h>\n");
fprintf(writetable, "int conten3(void) {\n");
fprintf(writetable, " char file3[50] = \"");
fprintf(writetable, "%s", filename);
fprintf(writetable, "\";\n printf(\"File 3: \");\n printf(\"\%%s\", file3);");
fprintf(writetable, "\n}");
}
if(!strcmp("file4", ch1) == 1) {
writefile = fopen("file4", "w");
fprintf(writefile, "1: ");
fprintf(writefile, "%s", line1);
fprintf(writefile, "\n");
fprintf(writefile, "2: ");
fprintf(writefile, "%s", line2);
fprintf(writefile, "\n");
fprintf(writefile, "3: ");
fprintf(writefile, "%s", line3);
fprintf(writefile, "\n");
fprintf(writefile, "4: ");
fprintf(writefile, "%s", line4);
fprintf(writefile, "\n");
fprintf(writefile, "5: ");
fprintf(writefile, "%s", line5);
fprintf(writefile, "\n");
fprintf(writefile, "6: ");
fprintf(writefile, "%s", line6);
fprintf(writefile, "\n");
fprintf(writefile, "7: ");
fprintf(writefile, "%s", line7);
fprintf(writefile, "\n");
fprintf(writefile, "8: ");
fprintf(writefile, "%s", line8);
fprintf(writefile, "\n");
fprintf(writefile, "9: ");
fprintf(writefile, "%s", line9);
fprintf(writefile, "\n");
fprintf(writefile, "10: ");
fprintf(writefile, "%s", line10);
fprintf(writefile, "\n");
fprintf(writefile, "11: ");
fprintf(writefile, "%s", line11);
fprintf(writefile, "\n");
fprintf(writefile, "12: ");
fprintf(writefile, "%s", line12);
fprintf(writefile, "\n");
fprintf(writefile, "13: ");
fprintf(writefile, "%s", line13);
fprintf(writefile, "\n");
fprintf(writefile, "14: ");
fprintf(writefile, "%s", line14);
fprintf(writefile, "\n");
fprintf(writefile, "15: ");
fprintf(writefile, "%s", line15);
fprintf(writefile, "\n");
writetable = fopen("file4data.c", "w");
fprintf(writetable, "#include <stdio.h>\n");
fprintf(writetable, "#include <string.h>\n");
fprintf(writetable, "#include <stdlib.h>\n");
fprintf(writetable, "int conten4(void) {\n");
fprintf(writetable, " char file4[50] = \"");
fprintf(writetable, "%s", filename);
fprintf(writetable, "\";\n printf(\"File 4: \");\n printf(\"\%%s\", file4);");
fprintf(writetable, "\n}");
}
if(!strcmp("file5", ch1) == 1) {
writefile = fopen("file5", "w");
fprintf(writefile, "1: ");
fprintf(writefile, "%s", line1);
fprintf(writefile, "\n");
fprintf(writefile, "2: ");
fprintf(writefile, "%s", line2);
fprintf(writefile, "\n");
fprintf(writefile, "3: ");
fprintf(writefile, "%s", line3);
fprintf(writefile, "\n");
fprintf(writefile, "4: ");
fprintf(writefile, "%s", line4);
fprintf(writefile, "\n");
fprintf(writefile, "5: ");
fprintf(writefile, "%s", line5);
fprintf(writefile, "\n");
fprintf(writefile, "6: ");
fprintf(writefile, "%s", line6);
fprintf(writefile, "\n");
fprintf(writefile, "7: ");
fprintf(writefile, "%s", line7);
fprintf(writefile, "\n");
fprintf(writefile, "8: ");
fprintf(writefile, "%s", line8);
fprintf(writefile, "\n");
fprintf(writefile, "9: ");
fprintf(writefile, "%s", line9);
fprintf(writefile, "\n");
fprintf(writefile, "10: ");
fprintf(writefile, "%s", line10);
fprintf(writefile, "\n");
fprintf(writefile, "11: ");
fprintf(writefile, "%s", line11);
fprintf(writefile, "\n");
fprintf(writefile, "12: ");
fprintf(writefile, "%s", line12);
fprintf(writefile, "\n");
fprintf(writefile, "13: ");
fprintf(writefile, "%s", line13);
fprintf(writefile, "\n");
fprintf(writefile, "14: ");
fprintf(writefile, "%s", line14);
fprintf(writefile, "\n");
fprintf(writefile, "15: ");
fprintf(writefile, "%s", line15);
fprintf(writefile, "\n");
writetable = fopen("file5data.c", "w");
fprintf(writetable, "#include <stdio.h>\n");
fprintf(writetable, "#include <string.h>\n");
fprintf(writetable, "#include <stdlib.h>\n");
fprintf(writetable, "int conten5(void) {\n");
fprintf(writetable, " char file5[50] = \"");
fprintf(writetable, "%s", filename);
fprintf(writetable, "\";\n printf(\"File 5: \");\n printf(\"\%%s\", file5);");
fprintf(writetable, "\n}");
}
if(!strcmp("file6", ch1) == 1) {
writefile = fopen("file6", "w");
fprintf(writefile, "1: ");
fprintf(writefile, "%s", line1);
fprintf(writefile, "\n");
fprintf(writefile, "2: ");
fprintf(writefile, "%s", line2);
fprintf(writefile, "\n");
fprintf(writefile, "3: ");
fprintf(writefile, "%s", line3);
fprintf(writefile, "\n");
fprintf(writefile, "4: ");
fprintf(writefile, "%s", line4);
fprintf(writefile, "\n");
fprintf(writefile, "5: ");
fprintf(writefile, "%s", line5);
fprintf(writefile, "\n");
fprintf(writefile, "6: ");
fprintf(writefile, "%s", line6);
fprintf(writefile, "\n");
fprintf(writefile, "7: ");
fprintf(writefile, "%s", line7);
fprintf(writefile, "\n");
fprintf(writefile, "8: ");
fprintf(writefile, "%s", line8);
fprintf(writefile, "\n");
fprintf(writefile, "9: ");
fprintf(writefile, "%s", line9);
fprintf(writefile, "\n");
fprintf(writefile, "10: ");
fprintf(writefile, "%s", line10);
fprintf(writefile, "\n");
fprintf(writefile, "11: ");
fprintf(writefile, "%s", line11);
fprintf(writefile, "\n");
fprintf(writefile, "12: ");
fprintf(writefile, "%s", line12);
fprintf(writefile, "\n");
fprintf(writefile, "13: ");
fprintf(writefile, "%s", line13);
fprintf(writefile, "\n");
fprintf(writefile, "14: ");
fprintf(writefile, "%s", line14);
fprintf(writefile, "\n");
fprintf(writefile, "15: ");
fprintf(writefile, "%s", line15);
fprintf(writefile, "\n");
writetable = fopen("file6data.c", "w");
fprintf(writetable, "#include <stdio.h>\n");
fprintf(writetable, "#include <string.h>\n");
fprintf(writetable, "#include <stdlib.h>\n");
fprintf(writetable, "int conten6(void) {\n");
fprintf(writetable, " char file6[50] = \"");
fprintf(writetable, "%s", filename);
fprintf(writetable, "\";\n printf(\"File 6: \");\n printf(\"\%%s\", file6);");
fprintf(writetable, "\n}");
}
printf("\nThe operation was successfull!\n");
}
|
Markdown
|
UTF-8
| 17,445
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
---
layout: post
title: rocketmq系列-2
subtitle: rocketmq系列
date: 2021-09-07
author: CodingAndLiving
header-img: img/com01.jpg
catalog: true
tags:
- rocketmq
- 原理
- 底层
---
# 前言
> 在繁杂的世界,能够沉下心来,梳理下知识体系,其实是一件很放松的诗意。
# 使用案例
1. 生产者发送消息方式:
1. 同步发送
2. 异步发送
3. 单向发送
4. 具体案例可以参考rocketmq源码的案例
2. 消费者接收消息方式:
1. 推
2. 拉
3. 实现顺序消息
1. 生产者
2. 消费者
3. 案例请查看rocketmq的源码中的example
4. RocketMQ保证的是消息的局部有序,而不是全局有序。要保证最终消费到的消息是有序的,需要从Producer、Broker、Consumer三个步骤都保证消息有序才行。
1. 首先在发送者端:在默认情况下,消息发送者会采取Round Robin轮询方式把消息发送到不同的MessageQueue(分区队列),而消费者消费的时候也从多个MessageQueue上拉取消息,这种情况下消息是不能保证顺序的。而只有当一组有序的消息发送到同一个MessageQueue上时,才能利用MessageQueue先进先出的特性保证这一组消息有序。而Broker中一个队列内的消息是可以保证有序的。
2. 然后在消费者端:消费者会从多个消息队列上去拿消息。这时虽然每个消息队列上的消息是有序的,但是多个队列之间的消息仍然是乱序的。消费者端要保证消息有序,就需要按队列一个一个来取消息,即取完一个队列的消息后,再去取下一个队列的消息。而给consumer注入的MessageListenerOrderly对象,在RocketMQ内部就会通过锁队列的方式保证消息是一个一个队列来取的。MessageListenerConcurrently这个消息监听器则不会锁队列,每次都是从多个Message中取一批数据(默认不超过32条)。因此也无法保证消息有序。
4. 广播消息
1. 广播消息并没有特定的消息消费者样例,这是因为这涉及到消费者的集群消费模式。在集群状态(MessageModel.CLUSTERING)下,每一条消息只会被同一个消费者组中的一个实例消费到(这跟kafka和rabbitMQ的集群模式是一样的)。而广播模式则是把消息发给了所有订阅了对应主题的消费者,而不管消费者是不是同一个消费者组。
5. 延迟消息
1. 延迟消息实现的效果就是在调用producer.send方法后,消息并不会立即发送出去,而是会等一段时间再发送出去。这是RocketMQ特有的一个功能。
2. 那会延迟多久呢?延迟时间的设置就是在Message消息对象上设置一个延迟级别message.setDelayTimeLevel(3);
6. 批量消息
1. 批量消息是指将多条消息合并成一个批量消息,一次发送出去。这样的好处是可以减少网络IO,提升吞吐量。
2. 测试代码中都看到了关键的注释:如果批量消息大于1MB就不要用一个批次发送,而要拆分成多个批次消息发送。也就是说,一个批次消息的大小不要超过1MB
3. 批量消息的使用是有一定限制的,这些消息应该有相同的Topic,相同的waitStoreMsgOK。而且不能是延迟消息、事务消息等
7. 过滤消息
1. 在大多数情况下,可以使用Message的Tag属性来简单快速的过滤信息。
2. 主要是看消息消费者。consumer.subscribe("TagFilterTest", "TagA || TagC"); 这句只订阅TagA和TagC的消息。
3. TAG是RocketMQ中特有的一个消息属性。RocketMQ的最佳实践中就建议,使用RocketMQ时,一个应用可以就用一个Topic,而应用中的不同业务就用TAG来区分。
4. 但是,这种方式有一个很大的限制,就是一个消息只能有一个TAG,这在一些比较复杂的场景就有点不足了。这时候,可以使用SQL表达式来对消息进行过滤。
8. 事务消息
1. 之前有个博客里面写到了柔性分布式事务中的一个实现方案,就需要mq的消息确认机制,也就是这里描述的事务消息
2. 事务消息不支持延迟消息和批量消息。
3. 为了避免单个消息被检查太多次而导致半队列消息累积,我们默认将单个消息的检查次数限制为15 次,但是用户可以通过 Broker 配置文件的 transactionCheckMax 参数来修改此限制。如果已经检查某条消息超过 N 次的话( N = transactionCheckMax ) 则 Broker 将丢弃此消息,并在默认情况下同时打印错误日志。用户可以通过重写 AbstractTransactionCheckListener 类来修改这个行为。
4. 事务消息将在 Broker 配置文件中的参数 transactionMsgTimeout 这样的特定时间长度之后被检查。当发送事务消息时,用户还可以通过设置用户属性 CHECK_IMMUNITY_TIME_IN_SECONDS 来改变这个限制,该参数优先于 transactionMsgTimeout 参数。
5. 事务性消息可能不止一次被检查或消费。
6. 提交给用户的目标主题消息可能会失败,目前这依日志的记录而定。它的高可用性通过RocketMQ 本身的高可用性机制来保证,如果希望确保事务消息不丢失、并且事务完整性得到保证,建议使用同步的双重写入机制。
7. 事务消息的生产者 ID 不能与其他类型消息的生产者 ID 共享。与其他类型的消息不同,事务消息
允许反向查询、MQ服务器能通过它们的生产者 ID 查询到消费者。
8. 事务消息机制的关键是在发送消息时,会将消息转为一个half半消息,并存入RocketMQ内部的一个RMQ_SYS_TRANS_HALF_TOPIC 这个Topic,这样对消费者是不可见的。再经过一系列事务检查通过后,再将消息转存到目标Topic,这样对消费者就可见了。
9. acl权限
1. 权限控制(ACL)主要为RocketMQ提供Topic资源级别的用户访问控制。用户在使用RocketMQ权限控制时,可以在Client客户端通过 RPCHook注入AccessKey和SecretKey签名;同时,将对应的权限控制属性(包括Topic访问权限、IP白名单和AccessKey和SecretKey签名等)设置在$ROCKETMQ_HOME/conf/plain_acl.yml的配置文件中。Broker端对AccessKey所拥有的权限进行校验,校验不过,抛出异常;
2. Broker端具体的配置信息可以参见源码包下docs/cn/acl/user_guide.md。主要是在broker.conf中打开acl的标志:aclEnable=true。然后就可以用plain_acl.yml来进行权限配置了。并且这个配置文件是热加载的,也就是说要修改配置时,只要修改配置文件就可以了,不用重启Broker服务。
# 源码探究
## Name Server
1. NameServer的核心作用其实就只有两个
1. 一是维护Broker的服务地址并进行及时的更新。
2. 二是给Producer和Consumer提供服务获取Broker列表。
### 源码
1. 从这里入口开始org.apache.rocketmq.namesrv.NamesrvStartup#main0
2. 主要是下面两行代码
```
NamesrvController controller = createNamesrvController(args);
start(controller);
```
3. org.apache.rocketmq.namesrv.NamesrvStartup#createNamesrvController 这个方法主要解析了命令行参数,且解析了配置,放在两个参数中:NameSrvConfig包含NameServer自身运行的参数,NettyServerConfig 包含Netty服务端的配置参数,Netty服务端口默认指定了9876。
4. 解析完毕参数后,实例化了对象NamesrvController
5. 接下来看看start方法:
```
public static NamesrvController start(final NamesrvController controller) throws Exception {
if (null == controller) {
throw new IllegalArgumentException("NamesrvController is null");
}
//初始化,主要是初始化几个定时任务
boolean initResult = controller.initialize();
if (!initResult) {
controller.shutdown();
System.exit(-3);
}
Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(log, new Callable<Void>() {
@Override
public Void call() throws Exception {
controller.shutdown();
return null;
}
}));
controller.start();
return controller;
}
```
```
public boolean initialize() {
//加载KV配置
this.kvConfigManager.load();
//创建NettyServer网络处理对象
this.remotingServer = new NettyRemotingServer(this.nettyServerConfig, this.brokerHousekeepingService);
//Netty服务器的工作线程池
this.remotingExecutor =
Executors.newFixedThreadPool(nettyServerConfig.getServerWorkerThreads(), new ThreadFactoryImpl("RemotingExecutorThread_"));
//注册Processor,把remotingExecutor注入到remotingServer中
this.registerProcessor();
//开启定时任务:每隔10s扫描一次Broker,移除不活跃的Broker
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
NamesrvController.this.routeInfoManager.scanNotActiveBroker();
}
}, 5, 10, TimeUnit.SECONDS);
//开启定时任务:每隔10min打印一次KV配置
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
NamesrvController.this.kvConfigManager.printAllPeriodically();
}
}, 1, 10, TimeUnit.MINUTES);
if (TlsSystemConfig.tlsMode != TlsMode.DISABLED) {
// Register a listener to reload SslContext
try {
fileWatchService = new FileWatchService(
new String[] {
TlsSystemConfig.tlsServerCertPath,
TlsSystemConfig.tlsServerKeyPath,
TlsSystemConfig.tlsServerTrustCertPath
},
new FileWatchService.Listener() {
boolean certChanged, keyChanged = false;
@Override
public void onChanged(String path) {
if (path.equals(TlsSystemConfig.tlsServerTrustCertPath)) {
log.info("The trust certificate changed, reload the ssl context");
reloadServerSslContext();
}
if (path.equals(TlsSystemConfig.tlsServerCertPath)) {
certChanged = true;
}
if (path.equals(TlsSystemConfig.tlsServerKeyPath)) {
keyChanged = true;
}
if (certChanged && keyChanged) {
log.info("The certificate and private key changed, reload the ssl context");
certChanged = keyChanged = false;
reloadServerSslContext();
}
}
private void reloadServerSslContext() {
((NettyRemotingServer) remotingServer).loadSslContext();
}
});
} catch (Exception e) {
log.warn("FileWatchService created error, can't load the certificate dynamically");
}
}
return true;
}
```
```
public void start() throws Exception {
this.remotingServer.start();
if (this.fileWatchService != null) {
this.fileWatchService.start();
}
}
```
## broker启动
1. BrokerController.this.registerBrokerAll方法会发起向NameServer注册心跳。启动时会立即注册,同
时也会启动一个线程池,以10秒延迟,默认30秒的间隔 持续向NameServer发送心跳。
## producer
1. Producer需要拉取Broker列表,然后跟Broker建立连接等等很多
核心的流程,其实都是在发送消息时建立的。因为在启动时,还不知道要拉取哪个Topic的Broker列表
呢。
2. Producer在发送Netty请求时,实际上是指定的MessageQueue,而不是Topic。Topic只是用来找MessageQueue。然后根据MessageQueue再找所在的Broker,往Broker发送请求。
## 存储
消息存储的入口在:DefaultMessageStore.putMessage
1. commitLog写入
CommitLog的doAppend方法就是Broker写入消息的实际入口。这个方法最终会把消息追加到
MappedFile映射的一块内存里,并没有直接写入磁盘。写入消息的过程是串行的,一次只会允许一个
线程写入。
2. 分发ConsumeQueue和IndexFile
当CommitLog写入一条消息后,在DefaultMessageStore的start方法中,会启动一个后台线程
reputMessageService每隔1毫秒就会去拉取CommitLog中最新更新的一批消息,然后分别转发到
ComsumeQueue和IndexFile里去,这就是他底层的实现逻辑。
并且,如果服务异常宕机,会造成CommitLog和ConsumeQueue、IndexFile文件不一致,有消息写
入CommitLog后,没有分发到索引文件,这样消息就丢失了。DefaultMappedStore的load方法提供了
恢复索引文件的方法,入口在load方法。
3. 文件同步刷盘与异步刷盘
入口:CommitLog.putMessage -> CommitLog.handleDiskFlush
其中主要涉及到是否开启了对外内存。TransientStorePoolEnable。如果开启了堆外内存,会在启动
时申请一个跟CommitLog文件大小一致的堆外内存,这部分内存就可以确保不会被交换到虚拟内存
中。
4. 过期文件删除
入口: DefaultMessageStore.addScheduleTask ->
DefaultMessageStore.this.cleanFilesPeriodically()
默认情况下, Broker会启动后台线程,每60秒,检查CommitLog、ConsumeQueue文件。然后对
超过72小时的数据进行删除。也就是说,默认情况下, RocketMQ只会保存3天内的数据。这个时间可
以通过fileReservedTime来配置。注意他删除时,并不会检查消息是否被消费了。
整个文件存储的核心入口入口在DefaultMessageStore的start方法中。
5. 总结
1. RocketMQ的存储文件包括消息文件(Commitlog)、消息消费队列文件(ConsumerQueue)、Hash
索引文件(IndexFile)、监测点文件(checkPoint)、abort(关闭异常文件)。单个消息存储文件、
消息消费队列文件、Hash索引文件长度固定以便使用内存映射机制进行文件的读写操作。RocketMQ组
织文件以文件的起始偏移量来命令文件,这样根据偏移量能快速定位到真实的物理文件。
2. RocketMQ基于内存映射文件机制提供了同步刷盘和异步刷盘两种机制,异步刷盘是指在消息存储时先追加到内存映
射文件,然后启动专门的刷盘线程定时将内存中的文件数据刷写到磁盘。
3. CommitLog,消息存储文件,RocketMQ为了保证消息发送的高吞吐量,采用单一文件存储所有主题消
息,保证消息存储是完全的顺序写,但这样给文件读取带来了不便,为此RocketMQ为了方便消息消费
构建了消息消费队列文件,基于主题与队列进行组织,同时RocketMQ为消息实现了Hash索引,可以为
消息设置索引键,根据所以能够快速从CommitLog文件中检索消息。
4. 当消息达到CommitLog后,会通过ReputMessageService线程接近实时地将消息转发给消息消费队列
文件与索引文件。为了安全起见,RocketMQ引入abort文件,记录Broker的停机是否是正常关闭还是
异常关闭,在重启Broker时为了保证CommitLog文件,消息消费队列文件与Hash索引文件的正确性,
分别采用不同策略来恢复文件。
5. RocketMQ不会永久存储消息文件、消息消费队列文件,而是启动文件过期机制并在磁盘空间不足或者
默认凌晨4点删除过期文件,文件保存72小时并且在删除文件时并不会判断该消息文件上的消息是否被
消费。
## 消费者
1. 拉取消息。PullRequest里有messageQueue和processQueue,其中messageQueue负责拉取消息,拉取到后,
将消息存入processQueue,进行处理。 存入后就可以清空messageQueue,继续拉取了。
2. 在消费者示例的start方法中,启动RebalanceService,这个是客户端进行负载均衡策略的启动服务。他
只负责根据负载均衡策略获取当前客户端分配到的MessageQueue
3. 并发消费与顺序消费的过程。消费的过程依然是在DefaultMQPushConsumerImpl的 consumeMessageService中。他有两个子类
ConsumeMessageConcurrentlyService和ConsumeMessageOrderlyService。其中最主要的差别是ConsumeMessageOrderlyService会在消费前把队列锁起来,优先保证拉取同一个队列里的消息。消费过程的入口在DefaultMQPushConsumerImpl的pullMessage中定义的PullCallback中。
## 延迟消息
延迟消息的核心使用方法就是在Message中设定一个MessageDelayLevel参数,对应18个延迟级别。然
后Broker中会创建一个默认的Schedule_Topic主题,这个主题下有18个队列,对应18个延迟级别。消
息发过来之后,会先把消息存入Schedule_Topic主题中对应的队列。然后等延迟时间到了,再转发到目
标队列,推送给消费者进行消费。
|
Java
|
UTF-8
| 1,665
| 2.453125
| 2
|
[] |
no_license
|
package com.certiorem.microservices.ModelDataService;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "COMPETICION")
public class Competition {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "NOMBRE", nullable = false)
private String nombre;
@Column(name = "RESPONSABLE", nullable = false)
private String responsable;
@Column(name="AÑO", nullable = false)
private Integer año;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "category_id", referencedColumnName = "id")
private Category category;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getResponsable() {
return responsable;
}
public void setResponsable(String responsable) {
this.responsable = responsable;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Integer getAño() {
return año;
}
public void setAño(Integer año) {
this.año = año;
}
@Override
public String toString() {
return "Competition [id=" + id + ", nombre=" + nombre + ", responsable=" + responsable + ", año=" + año
+ ", category=" + category + "]";
}
}
|
Markdown
|
UTF-8
| 274
| 2.625
| 3
|
[] |
no_license
|
# Spring-Boot-Login-Registration-With-Spring-Security
This is a Login Registration Spring boot project using Spring Security.
Database Name: springbootdb.
You have to Insert a row like this (INSERT into springbootdb.role value(1, 'ADMIN'); )
before registration.
|
Swift
|
UTF-8
| 871
| 3.0625
| 3
|
[] |
no_license
|
//
// Player.swift
// Bet Buddy
//
// Created by Jordan Lee on 2/2/21.
//
import Foundation
import UIKit
struct Player : Codable {
var name: String
var title: String
var profilePicture: Data?
var playerID: Int?
var initialBalance: Double?
var balance: Double?
var roundBet: Double?
var isReady: Bool = false
var outcomeIndex: Int?
var multiplier: Int?
var payout: Double?
mutating func calculatePayout() {
if multiplier == nil {
multiplier = 1
}
if outcomeIndex == nil {
outcomeIndex = 0
}
var tempPayout = roundBet! * Double(multiplier!)
if outcomeIndex == 0 {
tempPayout = -tempPayout
}
else if outcomeIndex == 1 {
tempPayout = 0
}
payout = tempPayout
}
}
|
Markdown
|
UTF-8
| 23,810
| 2.578125
| 3
|
[
"CC-BY-4.0",
"MIT",
"CC-BY-3.0"
] |
permissive
|
<properties
pageTitle="Cifrar el contenido con el cifrado de almacenamiento con la API de REST de AMS"
description="Obtenga información sobre cómo cifrar el contenido con cifrado de almacenamiento mediante las API de REST de AMS."
services="media-services"
documentationCenter=""
authors="Juliako"
manager="erikre"
editor=""/>
<tags
ms.service="media-services"
ms.workload="media"
ms.tgt_pltfrm="na"
ms.devlang="na"
ms.topic="article"
ms.date="09/26/2016"
ms.author="juliako"/>
#<a name="encrypting-your-content-with-storage-encryption-using-ams-rest-api"></a>Cifrar el contenido con el cifrado de almacenamiento con la API de REST de AMS
Se recomienda para cifrar el contenido localmente mediante el cifrado AES de 256 bits y luego cárguelo en el almacenamiento de Azure donde se almacenarán cifrados en el resto.
Este artículo proporciona una descripción general de cifrado de almacenamiento de AMS y muestra cómo cargar el contenido de almacenamiento cifrado:
- Crear una clave de contenido.
- Crear un activo. Establezca el AssetCreationOption en StorageEncryption cuando se crea el activo.
Cifrado activos tienen que estar asociadas con teclas de contenido.
- Vincular la clave de contenido activo.
- Establecer el cifrado de los parámetros en las entidades AssetFile relacionados.
>[AZURE.NOTE]Si desea ofrecer a un activo cifrado de almacenamiento, debe configurar Directiva de entrega del activo. Antes de que puedan transmitir su activo, el servidor de transmisión quita el cifrado de almacenamiento y transmite el contenido con la directiva de entrega especificado. Para obtener más información, vea [Configuración de directivas de entrega activos](media-services-rest-configure-asset-delivery-policy.md).
>[AZURE.NOTE] Cuando se trabaja con la API de REST de servicios de medios, se aplican las consideraciones siguientes:
>
>Al acceder a las entidades de Media Services, debe establecer los campos de encabezado específico y los valores en las solicitudes HTTP. Para obtener más información, consulte [configuración de desarrollo de API de REST de servicios de multimedia](media-services-rest-how-to-use.md).
>Después de conectarse correctamente a https://media.windows.net, recibirá una redirección 301 especificando otro URI de servicios de medios. Debe realizar las siguientes llamadas para el nuevo URI tal como se describe en [Conectar con Media Services con la API de REST](media-services-rest-connect-programmatically.md).
##<a name="storage-encryption-overview"></a>Introducción al cifrado de almacenamiento
El cifrado de almacenamiento AMS aplica el cifrado **AES CTR** modo a todo el archivo. Modo de CTR AES es un cifrado de bloques que puede cifrar datos de longitud arbitrario sin necesidad de relleno. Funciona mediante el cifrado de un bloque de contador con el algoritmo AES y luego xo-ión la salida de AES con los datos para cifrar o descifrar. El bloque de contador utilizado se construye copiando el valor de la InitializationVector en bytes 0 a 7 del valor contador y bytes 8 a 15 del valor contador están establecidos en cero. Del bloque de contador 16 bytes, bytes 8 a 15 (es decir, los bytes menos significativos) se utilizan como un entero simple de 64 bits que se incrementa en uno para cada bloque de datos subsiguientes procesa y se guarda en el orden de bytes de red. Tenga en cuenta que si este entero alcanza el valor máximo (0xFFFFFFFFFFFFFFFF) luego incrementar el restablecimiento del contador bloque a cero (bytes 8 a 15) sin afectar a los 64 bits del contador (es decir, bytes 0 a 7). Para mantener la seguridad de la AES CTR modo de cifrado, el valor de InitializationVector para un determinado identificador de clave para cada clave contenido deberá ser único para cada archivo y archivos será menor que 2 ^ 64 bloques de longitud. Esto es para asegurarse de que un valor de contador nunca se reutiliza con una clave determinada. Para obtener más información sobre el modo CTR, consulte [esta página wiki](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#CTR) (el artículo wiki utiliza el término "Valor de seguridad" en lugar de "InitializationVector").
Uso del **Cifrado de almacenamiento** para cifrar el contenido de borrar localmente mediante el cifrado AES de 256 bits y luego cárguelo en el almacenamiento de Azure donde esté almacenado cifrado al resto. Activos protegidos con cifrado de almacenamiento automáticamente sin cifrar y colocados en un sistema de archivos cifrados antes de codificación y, opcionalmente, cifrados de nuevo antes de cargarlo como un nuevo activo de salida. El caso de uso principal para el cifrado de almacenamiento es cuando desea proteger los archivos de medios de entrada de alta calidad con cifrado almacenados en disco.
Para poder ofrecer a un activo cifrado de almacenamiento, debe configurar Directiva de entrega del activo para que Media Services sepa cómo desea entregar el contenido. Antes de que puedan transmitir su activo, el servidor de transmisión quita el cifrado de almacenamiento y transmite el contenido con la directiva de entrega especificada (por ejemplo, AES, cifrado comunes o sin cifrado).
##<a name="create-contentkeys-used-for-encryption"></a>Crear ContentKeys utilizado para el cifrado
Cifrado activos tienen que estar asociadas a la clave de cifrado de almacenamiento. Debe crear la clave de contenido que se utilizará para el cifrado antes de crear los archivos de activos. Esta sección describe cómo crear una clave de contenido.
Los siguientes son los pasos generales para generar claves de contenido que se asociará con activos que desea cifrar.
1. Cifrado de almacenamiento aleatoriamente generar una clave AES de 32 bytes.
Se trata de la clave de contenido para su activo, lo que significa que todos los archivos asociados con ese activo tendrá que utilizar la misma clave de contenido durante el descifrado.
2. Llamar a los métodos [GetProtectionKeyId](https://msdn.microsoft.com/library/azure/jj683097.aspx#getprotectionkeyid) y [GetProtectionKey](https://msdn.microsoft.com/library/azure/jj683097.aspx#getprotectionkey) para obtener el certificado X.509 correcto que se debe usar para cifrar la clave de contenido.
3. Cifrar la clave de contenido con la clave pública del certificado X.509.
Media Services .NET SDK utiliza RSA con OAEP cuando se realiza el cifrado. Puede ver un ejemplo de .NET en la [función EncryptSymmetricKeyData](https://github.com/Azure/azure-sdk-for-media-services/blob/dev/src/net/Client/Common/Common.FileEncryption/EncryptionUtils.cs).
4. Crear un valor de suma de comprobación calculado utilizando el identificador de clave y la clave de contenido. En el siguiente ejemplo .NET calcula la suma de comprobación mediante el elemento GUID del identificador clave y la clave de borrar contenido.
public static string CalculateChecksum(byte[] contentKey, Guid keyId)
{
const int ChecksumLength = 8;
const int KeyIdLength = 16;
byte[] encryptedKeyId = null;
// Checksum is computed by AES-ECB encrypting the KID
// with the content key.
using (AesCryptoServiceProvider rijndael = new AesCryptoServiceProvider())
{
rijndael.Mode = CipherMode.ECB;
rijndael.Key = contentKey;
rijndael.Padding = PaddingMode.None;
ICryptoTransform encryptor = rijndael.CreateEncryptor();
encryptedKeyId = new byte[KeyIdLength];
encryptor.TransformBlock(keyId.ToByteArray(), 0, KeyIdLength, encryptedKeyId, 0);
}
byte[] retVal = new byte[ChecksumLength];
Array.Copy(encryptedKeyId, retVal, ChecksumLength);
return Convert.ToBase64String(retVal);
}
5. Crear la clave de contenido con **EncryptedContentKey** (que se convierten en cadena codificado base 64), **ProtectionKeyId**, **ProtectionKeyType**, **ContentKeyType**y **suma** los valores que ha recibido en los pasos anteriores.
Para el cifrado de almacenamiento, las siguientes propiedades deben incluirse en el cuerpo de la solicitud.
Solicitud de cuerpo (propiedad) | Descripción
---|---
Id. | El identificador de ContentKey que se genera nosotros con el siguiente formato, "nb:kid:UUID:<NEW GUID>".
ContentKeyType | Este es el tipo de clave de contenido como un número entero de esta clave de contenido. Se pasa el valor 1 para el cifrado de almacenamiento.
EncryptedContentKey | Crear un nuevo valor de clave contenido que es un valor de 256 bits (32 bytes). La clave se cifra utilizando el certificado X.509 cifrado de almacenamiento que se recupera desde Microsoft Azure Media Services mediante la ejecución de una solicitud HTTP GET para los métodos de GetProtectionKey y GetProtectionKeyId. Por ejemplo, vea el siguiente código .NET: el método **EncryptSymmetricKeyData** definido [aquí](https://github.com/Azure/azure-sdk-for-media-services/blob/dev/src/net/Client/Common/Common.FileEncryption/EncryptionUtils.cs).
ProtectionKeyId | Este es el identificador de clave de protección para el certificado X.509 cifrado de almacenamiento que se usó para cifrar la clave de contenido.
ProtectionKeyType | Este es el tipo de cifrado para la clave de protección que se usó para cifrar la clave de contenido. Este valor es StorageEncryption(1) en nuestro ejemplo.
Suma de comprobación |Suma de comprobación calculada MD5 para la clave de contenido. Se calcula mediante el cifrado el identificador de contenido con la clave de contenido. El código de ejemplo muestra cómo calcular la suma de comprobación.
###<a name="retrieve-the-protectionkeyid"></a>Recuperar el ProtectionKeyId
En el ejemplo siguiente se muestra cómo recuperar la ProtectionKeyId, una huella digital de certificado para el certificado que se debe usar para cifrar la clave de contenido. Realizar este paso para asegurarse de que ya tiene el certificado apropiado en su equipo.
Solicitar:
GET https://media.windows.net/api/GetProtectionKeyId?contentKeyType=0 HTTP/1.1
MaxDataServiceVersion: 3.0;NetFx
Accept: application/json
Accept-Charset: UTF-8
User-Agent: Microsoft ADO.NET Data Services
Authorization: Bearer http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=juliakoams1&urn%3aSubscriptionId=zbbef702-2233-477b-9f16-bc4d3aa97387&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&Audience=urn%3aWindowsAzureMediaServices&ExpiresOn=1423034908&Issuer=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&HMACSHA256=7eSLe1GHnxgilr3F2FPCGxdL2%2bwy%2f39XhMPGY9IizfU%3d
x-ms-version: 2.11
Host: media.windows.net
Respuesta:
HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Length: 139
Content-Type: application/json;odata=minimalmetadata;streaming=true;charset=utf-8
Server: Microsoft-IIS/8.5
request-id: 2b6aa7a4-3a09-4b08-b581-26b55667f817
x-ms-request-id: 2b6aa7a4-3a09-4b08-b581-26b55667f817
X-Content-Type-Options: nosniff
DataServiceVersion: 3.0;
X-Powered-By: ASP.NET
Strict-Transport-Security: max-age=31536000; includeSubDomains
Date: Wed, 04 Feb 2015 02:42:52 GMT
{"odata.metadata":"https://wamsbayclus001rest-hs.cloudapp.net/api/$metadata#Edm.String","value":"7D9BB04D9D0A4A24800CADBFEF232689E048F69C"}
###<a name="retrieve-the-protectionkey-for-the-protectionkeyid"></a>Recuperar la ProtectionKey para el ProtectionKeyId
En el ejemplo siguiente se muestra cómo recuperar el certificado X.509 utilizando la ProtectionKeyId que ha recibido en el paso anterior.
Solicitar:
GET https://media.windows.net/api/GetProtectionKey?ProtectionKeyId='7D9BB04D9D0A4A24800CADBFEF232689E048F69C' HTTP/1.1
MaxDataServiceVersion: 3.0;NetFx
Accept: application/json
Accept-Charset: UTF-8
User-Agent: Microsoft ADO.NET Data Services
Authorization: Bearer http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=juliakoams1&urn%3aSubscriptionId=zbbef702-e769-2233-9f16-bc4d3aa97387&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&Audience=urn%3aWindowsAzureMediaServices&ExpiresOn=1423141026&Issuer=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&HMACSHA256=lDBz5YXKiWe5L7eXOHsLHc9kKEUcUiFJvrNFFSksgkM%3d
x-ms-version: 2.11
x-ms-client-request-id: 78d1247a-58d7-40e5-96cc-70ff0dfa7382
Host: media.windows.net
Respuesta:
HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Length: 1227
Content-Type: application/json;odata=minimalmetadata;streaming=true;charset=utf-8
Server: Microsoft-IIS/8.5
x-ms-client-request-id: 78d1247a-58d7-40e5-96cc-70ff0dfa7382
request-id: 1523e8f3-8ed2-40fe-8a9a-5d81eb572cc8
x-ms-request-id: 1523e8f3-8ed2-40fe-8a9a-5d81eb572cc8
X-Content-Type-Options: nosniff
DataServiceVersion: 3.0;
X-Powered-By: ASP.NET
Strict-Transport-Security: max-age=31536000; includeSubDomains
Date: Thu, 05 Feb 2015 07:52:30 GMT
{"odata.metadata":"https://wamsbayclus001rest-hs.cloudapp.net/api/$metadata#Edm.String",
"value":"MIIDSTCCAjGgAwIBAgIQqf92wku/HLJGCbMAU8GEnDANBgkqhkiG9w0BAQQFADAuMSwwKgYDVQQDEyN3YW1zYmx1cmVnMDAxZW5jcnlwdGFsbHNlY3JldHMtY2VydDAeFw0xMjA1MjkwNzAwMDBaFw0zMjA1MjkwNzAwMDBaMC4xLDAqBgNVBAMTI3dhbXNibHVyZWcwMDFlbmNyeXB0YWxsc2VjcmV0cy1jZXJ0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzR0SEbXefvUjb9wCUfkEiKtGQ5Gc328qFPrhMjSo+YHe0AVviZ9YaxPPb0m1AaaRV4dqWpST2+JtDhLOmGpWmmA60tbATJDdmRzKi2eYAyhhE76MgJgL3myCQLP42jDusWXWSMabui3/tMDQs+zfi1sJ4Ch/lm5EvksYsu6o8sCv29VRwxfDLJPBy2NlbV4GbWz5Qxp2tAmHoROnfaRhwp6WIbquk69tEtu2U50CpPN2goLAqx2PpXAqA+prxCZYGTHqfmFJEKtZHhizVBTFPGS3ncfnQC9QIEwFbPw6E5PO5yNaB68radWsp5uvDg33G1i8IT39GstMW6zaaG7cNQIDAQABo2MwYTBfBgNVHQEEWDBWgBCOGT2hPhsvQioZimw8M+jOoTAwLjEsMCoGA1UEAxMjd2Ftc2JsdXJlZzAwMWVuY3J5cHRhbGxzZWNyZXRzLWNlcnSCEKn/dsJLvxyyRgmzAFPBhJwwDQYJKoZIhvcNAQEEBQADggEBABcrQPma2ekNS3Wc5wGXL/aHyQaQRwFGymnUJ+VR8jVUZaC/U/f6lR98eTlwycjVwRL7D15BfClGEHw66QdHejaViJCjbEIJJ3p2c9fzBKhjLhzB3VVNiLIaH6RSI1bMPd2eddSCqhDIn3VBN605GcYXMzhYp+YA6g9+YMNeS1b+LxX3fqixMQIxSHOLFZ1G/H2xfNawv0VikH3djNui3EKT1w/8aRkUv/AAV0b3rYkP/jA1I0CPn0XFk7STYoiJ3gJoKq9EMXhit+Iwfz0sMkfhWG12/XO+TAWqsK1ZxEjuC9OzrY7pFnNxs4Mu4S8iinehduSpY+9mDd3dHynNwT4="}
### <a name="create-the-content-key"></a>Crear la clave de contenido
Después de recuperar el certificado X.509 y usa su clave pública para cifrar la clave de contenido, cree una entidad de **ContentKey** y establezca sus valores de propiedad según corresponda.
Uno de los valores que debe establecer cuándo crear el contenido de la clave es el tipo. En caso de que el cifrado de almacenamiento, el valor es '1'.
En el ejemplo siguiente se muestra cómo crear un **ContentKey** con un conjunto de **ContentKeyType** para el cifrado de almacenamiento ("1") y la **ProtectionKeyType** se establece en "0" para indicar que la clave de protección Id es la huella digital del certificado X.509.
Solicitar
POST https://media.windows.net/api/ContentKeys HTTP/1.1
Content-Type: application/json
DataServiceVersion: 1.0;NetFx
MaxDataServiceVersion: 3.0;NetFx
Accept: application/json
Accept-Charset: UTF-8
User-Agent: Microsoft ADO.NET Data Services
Authorization: Bearer http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=juliakoams1&urn%3aSubscriptionId=zbbef702-2233-477b-9f16-bc4d3aa97387&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&Audience=urn%3aWindowsAzureMediaServices&ExpiresOn=1423034908&Issuer=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&HMACSHA256=7eSLe1GHnxgilr3F2FPCGxdL2%2bwy%2f39XhMPGY9IizfU%3d
x-ms-version: 2.11
Host: media.windows.net
{
"Name":"ContentKey",
"ProtectionKeyId":"7D9BB04D9D0A4A24800CADBFEF232689E048F69C",
"ContentKeyType":"1",
"ProtectionKeyType":"0",
"EncryptedContentKey":"your encrypted content key",
"Checksum":"calculated checksum"
}
Respuesta:
HTTP/1.1 201 Created
Cache-Control: no-cache
Content-Length: 777
Content-Type: application/json;odata=minimalmetadata;streaming=true;charset=utf-8
Location: https://media.windows.net/api/ContentKeys('nb%3Akid%3AUUID%3A9c8ea9c6-52bd-4232-8a43-8e43d8564a99')
Server: Microsoft-IIS/8.5
request-id: 76e85e0f-5cf1-44cb-b689-b3455888682c
x-ms-request-id: 76e85e0f-5cf1-44cb-b689-b3455888682c
X-Content-Type-Options: nosniff
DataServiceVersion: 3.0;
X-Powered-By: ASP.NET
Strict-Transport-Security: max-age=31536000; includeSubDomains
Date: Wed, 04 Feb 2015 02:37:46 GMT
{"odata.metadata":"https://wamsbayclus001rest-hs.cloudapp.net/api/$metadata#ContentKeys/@Element",
"Id":"nb:kid:UUID:9c8ea9c6-52bd-4232-8a43-8e43d8564a99","Created":"2015-02-04T02:37:46.9684379Z",
"LastModified":"2015-02-04T02:37:46.9684379Z",
"ContentKeyType":1,
"EncryptedContentKey":"your encrypted content key",
"Name":"ContentKey",
"ProtectionKeyId":"7D9BB04D9D0A4A24800CADBFEF232689E048F69C",
"ProtectionKeyType":0,
"Checksum":"calculated checksum"}
## <a name="create-an-asset"></a>Crear un activo
En el ejemplo siguiente se muestra cómo crear un activo.
**Solicitud HTTP**
POST https://media.windows.net/api/Assets HTTP/1.1
Content-Type: application/json
DataServiceVersion: 1.0;NetFx
MaxDataServiceVersion: 3.0;NetFx
Accept: application/json
Accept-Charset: UTF-8
Authorization: Bearer http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=amstestaccount001&urn%3aSubscriptionId=z7f09258-6753-2233-b1ae-193798e2c9d8&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&Audience=urn%3aWindowsAzureMediaServices&ExpiresOn=1421640053&Issuer=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&HMACSHA256=vlG%2fPYdFDMS1zKc36qcFVWnaNh07UCkhYj3B71%2fk1YA%3d
x-ms-version: 2.11
Host: media.windows.net
{"Name":"BigBuckBunny" "Options":1}
**Respuesta HTTP**
Si es correcto, se devuelve lo siguiente:
HTP/1.1 201 Created
Cache-Control: no-cache
Content-Length: 452
Content-Type: application/json;odata=minimalmetadata;streaming=true;charset=utf-8
Location: https://wamsbayclus001rest-hs.cloudapp.net/api/Assets('nb%3Acid%3AUUID%3A9bc8ff20-24fb-4fdb-9d7c-b04c7ee573a1')
Server: Microsoft-IIS/8.5
x-ms-client-request-id: c59de965-bc89-4295-9a57-75d897e5221e
request-id: e98be122-ae09-473a-8072-0ccd234a0657
x-ms-request-id: e98be122-ae09-473a-8072-0ccd234a0657
X-Content-Type-Options: nosniff
DataServiceVersion: 3.0;
Strict-Transport-Security: max-age=31536000; includeSubDomains
Date: Sun, 18 Jan 2015 22:06:40 GMT
{
"odata.metadata":"https://wamsbayclus001rest-hs.cloudapp.net/api/$metadata#Assets/@Element",
"Id":"nb:cid:UUID:9bc8ff20-24fb-4fdb-9d7c-b04c7ee573a1",
"State":0,
"Created":"2015-01-18T22:06:40.6010903Z",
"LastModified":"2015-01-18T22:06:40.6010903Z",
"AlternateId":null,
"Name":"BigBuckBunny.mp4",
"Options":1,
"Uri":"https://storagetestaccount001.blob.core.windows.net/asset-9bc8ff20-24fb-4fdb-9d7c-b04c7ee573a1",
"StorageAccountName":"storagetestaccount001"
}
##<a name="associate-the-contentkey-with-an-asset"></a>Asociar el ContentKey de un activo
Después de crear el ContentKey, asociarlo a su activo mediante la operación $links, tal como se muestra en el ejemplo siguiente:
Solicitar:
POST https://media.windows.net/api/Assets('nb%3Acid%3AUUID%3Afbd7ce05-1087-401b-aaae-29f16383c801')/$links/ContentKeys HTTP/1.1
DataServiceVersion: 1.0;NetFx
MaxDataServiceVersion: 3.0;NetFx
Accept: application/json
Accept-Charset: UTF-8
Content-Type: application/json
Authorization: Bearer http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=juliakoams1&urn%3aSubscriptionId=zbbef702-2233-477b-9f16-bc4d3aa97387&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&Audience=urn%3aWindowsAzureMediaServices&ExpiresOn=1423141026&Issuer=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&HMACSHA256=lDBz5YXKiWe5L7eXOHsLHc9kKEUcUiFJvrNFFSksgkM%3d
x-ms-version: 2.11
Host: media.windows.net
{"uri":"https://wamsbayclus001rest-hs.cloudapp.net/api/ContentKeys('nb%3Akid%3AUUID%3A01e6ea36-2285-4562-91f1-82c45736047c')"}
Respuesta:
HTTP/1.1 204 No Content
##<a name="create-an-assetfile"></a>Crear un AssetFile
La entidad [AssetFile](http://msdn.microsoft.com/library/azure/hh974275.aspx) representa un archivo de audio o vídeo que se almacena en un contenedor de blob. Un archivo de activos siempre está asociado a un activo y un recurso puede contener uno o varios archivos de activos. Se produce un error en la tarea de servicios de Media Encoder si un objeto de archivo activo no está asociado a un archivo digital en un contenedor de blob.
Tenga en cuenta que la instancia de **AssetFile** y el archivo multimedia reales son dos objetos. La instancia de AssetFile contiene metadatos acerca del archivo multimedia, mientras que el archivo multimedia contiene el contenido multimedia real.
Después de cargar el archivo de medios digitales en un contenedor de blob, usará la solicitud HTTP **Combinar** para actualizar la AssetFile con información sobre el archivo multimedia (no se muestra en este tema).
**Solicitud HTTP**
POST https://media.windows.net/api/Files HTTP/1.1
Content-Type: application/json
DataServiceVersion: 1.0;NetFx
MaxDataServiceVersion: 3.0;NetFx
Accept: application/json
Accept-Charset: UTF-8
Authorization: Bearer http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=amstestaccount001&urn%3aSubscriptionId=z7f09258-6753-4ca2-2233-193798e2c9d8&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&Audience=urn%3aWindowsAzureMediaServices&ExpiresOn=1421640053&Issuer=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&HMACSHA256=vlG%2fPYdFDMS1zKc36qcFVWnaNh07UCkhYj3B71%2fk1YA%3d
x-ms-version: 2.11
Host: media.windows.net
Content-Length: 164
{
"IsEncrypted":"true",
"EncryptionScheme" : "StorageEncryption",
"EncryptionVersion" : "1.0",
"EncryptionKeyId" : "nb:kid:UUID:32e6efaf-5fba-4538-b115-9d1cefe43510",
"InitializationVector" : "397304628502661816</d:InitializationVector",
"Options":0,
"IsPrimary":"false",
"MimeType":"video/mp4",
"Name":"BigBuckBunny.mp4",
"ParentAssetId":"nb:cid:UUID:9bc8ff20-24fb-4fdb-9d7c-b04c7ee573a1"
}
**Respuesta HTTP**
HTTP/1.1 201 Created
Cache-Control: no-cache
Content-Length: 535
Content-Type: application/json;odata=minimalmetadata;streaming=true;charset=utf-8
Location: https://wamsbayclus001rest-hs.cloudapp.net/api/Files('nb%3Acid%3AUUID%3Af13a0137-0a62-9d4c-b3b9-ca944b5142c5')
Server: Microsoft-IIS/8.5
request-id: 98a30e2d-f379-4495-988e-0b79edc9b80e
x-ms-request-id: 98a30e2d-f379-4495-988e-0b79edc9b80e
X-Content-Type-Options: nosniff
DataServiceVersion: 3.0;
X-Powered-By: ASP.NET
Strict-Transport-Security: max-age=31536000; includeSubDomains
Date: Mon, 19 Jan 2015 00:34:07 GMT
{
"odata.metadata":"https://wamsbayclus001rest-hs.cloudapp.net/api/$metadata#Files/@Element",
"Id":"nb:cid:UUID:f13a0137-0a62-9d4c-b3b9-ca944b5142c5",
"Name":"BigBuckBunny.mp4",
"ContentFileSize":"0",
"ParentAssetId":"nb:cid:UUID:9bc8ff20-24fb-4fdb-9d7c-b04c7ee573a1",
"EncryptionVersion": "1.0",
"EncryptionScheme": "StorageEncryption",
"IsEncrypted":true,
"EncryptionKeyId":"nb:kid:UUID:32e6efaf-5fba-4538-b115-9d1cefe43510",
"InitializationVector":"397304628502661816</d:InitializationVector",
"IsPrimary":false,
"LastModified":"2015-01-19T00:34:08.1934137Z",
"Created":"2015-01-19T00:34:08.1934137Z",
"MimeType":"video/mp4",
"ContentChecksum":null
}
|
C++
|
GB18030
| 2,149
| 3.8125
| 4
|
[] |
no_license
|
#include<iostream>
using namespace std;
//ĵһڵ
//ָ뷨
struct ListNode
{
int _data;
ListNode* _pNext;
ListNode(int x = 0)
:_data(x)
,_pNext(NULL)
{}
};
ListNode* Create(int arr[],int n)
{
ListNode* head = new ListNode(arr[0]);
ListNode* prev = head;
ListNode* cur = prev;
for(int i = 1; i < n; ++i)
{
cur = new ListNode(arr[i]);
prev->_pNext = cur;
prev = cur;
}
return head;
}
size_t GetLength(ListNode* head)
{
size_t len = 0;
ListNode* cur = head;
while(cur)
{
++len;
cur = cur->_pNext;
}
return len;
}
ListNode* GetFirstCommonNode(ListNode* head1,ListNode* head2)
{
size_t len1 = GetLength(head1);
size_t len2 = GetLength(head2);
ListNode* pLong = head1;
ListNode* pShort = head2;
int diff = len1 - len2;
if(diff < 0)//һȵڶ
{
pLong = head2;
pShort = head1;
diff = len2 - len1;
}
//ódiff
for(int i = 0; i < diff; ++i)
{
pLong = pLong->_pNext;
}
//һҵһ
while(pLong != NULL && pShort != NULL && pLong != pShort)
{
pLong = pLong->_pNext;
pShort = pShort->_pNext;
}
if(pLong && pShort == 0)//ûҵ
return NULL;
else
return pShort;
}
void Destroy(ListNode* head)
{
ListNode* cur = head;
ListNode* del = NULL;
while(cur)
{
del = cur;
cur = cur->_pNext;
delete del;
}
}
ListNode* FindNode(ListNode* head,int data)
{
ListNode* cur = head;
while(cur)
{
if(cur->_data == data)
return cur;
cur = cur->_pNext;
}
return NULL;
}
int main()
{
int arr1[] = {3,4,5,6,7,8};
int arr2[] = {8,7};
//
ListNode* head1 = Create(arr1,sizeof(arr1)/sizeof(arr1[0]));
ListNode* head2 = Create(arr2,sizeof(arr2)/sizeof(arr2[0]));
//콻
ListNode* Node1 = FindNode(head1,6);
ListNode* Node2 = FindNode(head2,7);
Node2->_pNext = Node1;
//
ListNode* ret = GetFirstCommonNode(head1,head2);
if(ret)
cout<<"ֵǣ"<<ret->_data <<endl;
else
cout<<"ûн"<<endl;
//ɢ
Destroy(head1);
Node2->_pNext = NULL;
Destroy(head2);
system("pause");
return 0;
}
|
Python
|
UTF-8
| 2,063
| 4
| 4
|
[] |
no_license
|
# Exercise 27 Memorizing logic
# Truth Tables
# NOT
not False # True
not True # False
# OR
True or False # True
True or True # True
False or True # True
False or False # False
# AND
True and False # False
True and True # True
False and True # False
False and False # False
# NOT OR
not (True or False) # False
not (True or True) # False
not (False or True) # False
not (False or False) # True
# NOT AND
not (True and False) # True
not (True and True) # False
not (False and True) # True
not (False and False) # True
# != (Not equal)
1 != 0 # True
1 != 1 # False
0 != 1 # True
0 != 0 # False
# == (Equal)
1 == 0 # False
1 == 1 # True
0 == 1 # False
0 == 0 # True
# >= (Greater than equal)
1 >= 0 # True
1 >= 1 # True
0 >= 1 # False
0 >= 0 # True
# <= (Less than equal)
1 <= 0 # False
1 <= 1 # True
0 <= 1 # True
0 <= 0 # True
# Practice
not(True and False) # True*
35 >= 23 # True
1 <= 4 # True
147 == 162 # False
47 != 14 # True
True and False # False
False and False # False
False or True # True
not(False and False) # True*
37 > 34 and 40 < 8 # False
"funeral" == "fun" # False
57 - 34 >= 12 + 16 # False
not(32 > 19 and 29 != 14) # False
not(False and True) # True
False and True # False
49 + 32 <= 54 # False
True and True # True
not False # True
23 > 24 # False
True or False # True
True # True
not(False or True) # False
23 >= 12 + 11 # True
not(True or False) # False
0 != 4 # True
False or False # False
not(False or False) # True
90 <= 42 # False
False and True # False
43 >= 32 and True # True
"pending" == "pending" # True
False and True # False
True or True # True
43 <= 33 # False
False or True # True
0 - 2 == (-2 + 2) # False
not True # False
False or False # False
12 >= 43 # False
not(False and True) # True
True and False # False
34 >= 22 or 23 - 12 == 11 # True
not False # True
True or True # True
312 != 32 or 32 * 4 <= 12**2 # True
not(False and True) # True
34 == 10 + 24 or 2 + 10 <= 14 - 2 # True
not(True or False) # False
False or False # False
True and 12 >= 10 # True
15 >= 16 and 43 <= 54 # False
|
Markdown
|
UTF-8
| 418
| 3.03125
| 3
|
[] |
no_license
|
# Hello World! (when the document is ready)
You have to take the first steps in every frontend app:
* Connect `jQuery` - located in `bower_components` to the `index.html` file
* Connect `app.js` to the `index.html` file
* Alert a message, using `alert(message)`, when the document is ready!
In order to understand wether the document is ready or not, we can use:
```javascript
$(document).ready(someCallback);
```
|
C#
|
UTF-8
| 1,148
| 2.859375
| 3
|
[] |
no_license
|
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Mvvm;
using System;
using System.Windows;
using System.Windows.Input;
using WpfExperiments.Interceptors;
namespace WpfExperiments.ViewModels
{
public class FirstViewModel : BindableBase
{
private string _name;
private readonly Lazy<ICommand> _sendCommand;
public FirstViewModel()
{
_sendCommand = new Lazy<ICommand>(() => new DelegateCommand(Send));
}
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
base.OnPropertyChanged(() => Name);
// Don't use SetProperty as it have bug related to interception
}
}
}
public ICommand SendCommand
{
get { return _sendCommand.Value; }
}
[ShitHappened]
protected virtual void Send()
{
MessageBox.Show(Name);
throw new Exception("Fuck you people!");
}
}
}
|
Java
|
GB18030
| 3,037
| 3.1875
| 3
|
[] |
no_license
|
package behavior.pattern.command2.main;
import behavior.pattern.command2.Delete;
import behavior.pattern.command2.Edit;
import behavior.pattern.command2.OrderList;
/**
* <PRE>
ģʽ
ģʽCommand PatternһģʽΪģʽ
ʽڶУööѰҿԴĺʵĶѸӦĶöִ
ͼ
һװһӶʹòͬԿͻв
Ҫ
ϵͳУΪΪʵͨһֽϵĹϵijЩϣҪΪм¼ȴʱ
仯ĽϵƾͲ̫ʡ
ʱʹã
ijЩϣҪΪ"¼/"ȴ仯ĽDzʵġ£
ν"Ϊ""Ϊʵ"һΪΪʵֶ֮ϡ
ν
ͨߵýִ˳ߡߡ
ؼ룺
ɫ
1received ִж
2Command
3invoker ʹ
Ӧʵ
struts 1 е action Ŀ ActionServlet ֻһ൱ InvokerģͲŲͬӦвͬģ࣬൱ھ Command
ŵ㣺
1ϵͳ϶ȡ
2µԺӵϵͳȥ
ȱ㣺ʹģʽܻᵼijЩϵͳйľࡣ
ʹó
Ϊĵطʹģʽ磺
1GUI ÿһťһ
2ģ CMD
ע
ϵͳҪ֧ij(Undo)ͻָ(Redo)ҲԿʹģʽģʽչ
* </PRE>
*
* Ŀƣdesign_pattern</BR>
* ֧֣㶫ͨƼɷ˾ (c) 2017</BR>
*
* @version 1.0 201956
* @author xiangning
* @since JDK1.8
*/
public class CommandMain2 {
public static void main(String[] args) {
OrderList orders = new OrderList();
{
Edit edit = new Edit();
orders.execute(edit);
}
{
Delete delete = new Delete();
orders.execute(delete);
}
{
Edit edit = new Edit();
orders.execute(edit);
}
{
Edit edit = new Edit();
orders.execute(edit);
}
{
Delete delete = new Delete();
orders.execute(delete);
}
System.out.println("----------------------------");
orders.cancel();
orders.cancel();
orders.cancel();
orders.cancel();
orders.cancel();
orders.cancel();
orders.cancel();
System.out.println(orders.getStack().size());
}
}
|
Markdown
|
UTF-8
| 8,398
| 2.90625
| 3
|
[] |
no_license
|
# 6/18~6/24 の学習目標
## Progate で React の学習をする
## 6/18 ReactⅢ
1. コンポネートを作ろう
| 学習項目 | どんなことをやるか | わかったこと | 疑問 その他 |
| ----------------------- | -------------------------------------------------------- | --------------------------------------------------------------- | ---------------------- |
| 目標物を確認しよう | 制作物の完成形の確認 | 完成形を参考に組み立て方を考える | 訓練が必要 |
| ----------------------- | -------------------------------------------------------- | ------------ | ---------------------- |
| コンポネートを作成 | Lesson コンポネートの作成 | rendar メソッドの使い方 | 忘れたころに復習する |
| コンポネートの表示 1 個 | Lesson コンポネートを this.props を使って 1 個表示させる | </Lesson> 内で props 名 = props 値 を設定し this.props で渡し方 | |
| コンポネートの表示 複数 | map メソッドを使って 4 つのコンポネートを表示させる | map メソッドに上記を組み込んで複数のコンポネートを表示する方法 | |
## 6/19 ReactⅢ
1. モーダルの準備を使用しよう
| 学習項目 | どんなことをやるか | わかったこと | 疑問 その他 |
| ------------------ | ------------------------------------------------------------------------------------- | ------------ | ----------- |
| モーダルの JSX | introduction のコンポネートを作って props として渡す方法 | | |
| モーダルを隠そう 1 | state を false に定義してモーダルを隠す準備をする | | |
| モーダルの隠そう 2 | if 文を使って true の時のみ JSX が代入されるようにして false の時には表示させない方法 | | |
2. モーダルを完成させよう
| 学習項目 | どんなことをやるか | わかったこと | 疑問 その他 |
| ------------------------ | ------------------------------------------------------------------------------------------ | ------------ | ----------- |
| モーダルを表示しよう | handClick() を使ってクリックしたときに値を true にして JSX が代入されるようにする | | |
| モーダルを非表示にしよう | oneClick() を使って閉じるボタンをクリックしたときに値を false にしてモーダルを非表示にする | | |
## 6/20 ReactⅣ
1. 目標物の確認をしよう
| 学習項目 | どんなことをやるか | わかったこと | よくわからなかったこと |
| -------------------------- | ------------------------------------------ | ------------ | ---------------------- |
| お問い合わせフォームの確認 | 完成形から逆算して何をやるのかイメージする | | |
2. 送信完了メッセージを表示させよう
| 学習項目 | どんなことをやるか | わかったこと | よくわからなかったこと |
| ------------------------ | ---------------------------------------------------------------------------- | ------------ | ---------------------- |
| input と textra | 入力欄と送信ボタンを JSX で作る | | |
| 送信完了メッセージの作成 | if 文を使って送信前を false 送信後を true にして true の時のメッセージを作る | | |
| onSubmit と state の更新 | 送信ボタンが押されたときに値を true に変える処理をしてメッセージを表示させる | | |
3. 23 日以降の学習の準備
4. JSX とは何かを理解するにあたって
- React を React.createElement を使って書く部分を html のように記入することができる言語
- React.createElement は DOM でやった書き方に似ていた
- JSX は javascript に変換される、つまり JSX を入力するとそれが React.createElement に変換してから処理される
- JSX は React.createElement をシンプルに見やすく置き換えるもので使わなくても入力は可能ではある
## 6/21 ReactⅣ
1. 入力値を state で管理しよう
| 学習項目 | どんなことをやるか | わかったこと | よくわからなかったこと |
| ----------------------- | ------------------------------------------------------------- | ------------ | ---------------------- |
| 入力値の state 管理 | 入力値と state を紐づけしておく | | |
| onChange と入力値の習得 | oneCange イベントを使って入力したものを表示させる | | |
| state の更新 | メソッドを作って入力値を引数として受け取らせ state を更新する | | |
2. 入力チェックしよう
| 学習項目 | どんなことをやるか | わかったこと | よくわからなかったこと |
| ------------------------- | -------------------------------------------------------------------------- | ------------ | ------------------------------ |
| エラーメッセージの作成 | 入力値がからの時にエラーが表示される if 文を作る | | 定義の仕方がよくわからなかった |
| onChange と入力のチェック | 入力値がからかどうかを確認する条件文を作って true の時にエラーを表示させる | | |
## 6/22 ReactⅣ
1. チャレンジ問題に挑戦
| 学習項目 | どんなことをやるか | わかったこと | よくわからなかったこと |
| -------------- | ----------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------ |
| チャレンジ問題 | ReactⅣ の内容を一通り通してお問い合わせフォームを作る | state の追加は`名前:初期値`で入力する | if 文の条件の this.state.state値 がどこで切り替わっているか |
2. zチャレンジ問題を通して全体をとおした復習と 23 日からの学習の準備
## 6/23-6/24 React.js & Next.js 超入門 3 コンポネート
1. 実際に入力して動きを確認する
2. 使い方を簡単にまとめ理解する
3. 利用したメソッドの名前使い方をリスト化しいつでも引き出せるようにする
4. これを 2 日行う
## 入力したこと やってみたことのポイント
- クラスの承継を使って作ったファイルを連動させる
- App.jsにコンポネートを作って画面に表示させる → うまくできなかった
## メソッドのリスト 6/23 更新無し
| メソッド名 | どう使うか | 気づいたこと その他 |
| ---------- | ---------- | ------------------- |
| | | |
| | | |
| | | |
| | | |
|
C
|
UTF-8
| 401
| 3.515625
| 4
|
[] |
no_license
|
/*
* Daniel Goncalves > 1151452@isep.ipp.pt
* SCOMP - Turma 2DD
*
* programa1.c
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/*
* PL 2 - Exercise 16 - Programa 2
*/
int main(void)
{
int temp = 0, sum = 0;
do
{
scanf("%d*c", &temp);
if (temp > 0)
{
printf("%d\n", temp);
sum += temp;
}
} while (temp > 0);
sleep(1);
printf("\n+======+\n\nSUM : %d\n", sum);
return 0;
}
|
C++
|
UTF-8
| 425
| 2.875
| 3
|
[] |
no_license
|
#include <cstdio>
#include <cmath>
using namespace std;
int N;
void dfs(int pos, int curr){
if(pos == N){
printf("%d\n", curr);
return;
}
for(int d=1; d<10; d+=2){
int next = curr*10 + (pos==0 && d==1 ? 2 : d);
bool prime = true;
for(int i=2; i<=round(sqrt(next)); i++){
if(next%i == 0){
prime = false;
break;
}
}
if(prime) dfs(pos+1, next);
}
}
int main(){
scanf("%d", &N);
dfs(0, 0);
}
|
Markdown
|
UTF-8
| 751
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|

# InverterRemote
Control a chinese inverter On/Off/Reset switch with arduino nano, ethernet shield and Android app.
The "worker" controls the inverter with a relay contected to the pin `A0`.
Default "worker" IP `192.168.1.140` with MAC `90:A2:DA:0D:78:EE`.
The "sentinel" is optional and checks the status of the "worker". It also works as a physical remote to reset the "worker".
Default "sentinel" IP `192.168.1.141` with MAC `90:A2:DA:0D:78:EF`.
Example http request:
```http
http://192.168.1.140?s=1
```
Parameter `s` can be `0` (off) or `1` (on)
Note: You must be on the same network in order to work.
|
TypeScript
|
UTF-8
| 2,402
| 2.515625
| 3
|
[] |
no_license
|
import { Next, Request, RequestHandler, Response } from 'restify';
import * as errs from 'restify-errors';
import { Service, ServiceMetadata } from '../../../core';
import { SessionService, LoginData } from '../_service/session.service';
export const USER_DATA_KEY = 'user-data';
export { LoginData as UserData } from '../_service/session.service';
export const REF = 'auth.middleware';
const GLOBAL = true;
const DEPS = [
SessionService.REF
];
export class AuthMiddleware implements Service {
public static REF: string = REF;
constructor(
private sessionService: SessionService
) {}
/**
* Create a middleware to check user credentials
*
* Check JWT present in 'Authorization' header,
* add in request[USER_DATA_KEY] data as a UserData object if logged, null otherwise,
* pass to next middleware in everycase if 'authMandatory' is set to false,
* an only when credentials are valid otherwise (return HTTP 401 (not authorized) when credentials are invalid).
*
* @param authMandatory If true, return 401 (not authorized) when credentials are invalid (default: true)
*
* @returns A RequestHandler that either add user data in request or throw a 401 (not authorized) error
* */
public checkAuthorization(authMandatory: boolean = true): RequestHandler {
const sessionService = this.sessionService;
return function(req: Request, res: Response, next: Next): void {
const bearerToken = req.headers['authorization'];
if (!bearerToken || typeof bearerToken !== 'string') {
if (authMandatory) {
next(new errs.NotAuthorizedError('No bearer token found'));
} else {
req[USER_DATA_KEY] = null;
next();
}
return;
}
sessionService.checkSession(bearerToken)
.then((loginData: LoginData | null) => {
if (loginData === null && authMandatory) {
next(new errs.NotAuthorizedError('Bearer token not valid'));
return;
} else {
req[USER_DATA_KEY] = loginData;
next();
}
}).catch(e => {
console.error('CheckSession: Something unexpected happened : ', e);
next(new errs.InternalServerError(e));
});
}
}
}
export const authMiddleware: ServiceMetadata = {
ref: REF,
globalScope: GLOBAL,
dependenciesRefs: DEPS,
factory: AuthMiddleware
};
|
C
|
UTF-8
| 228
| 2.921875
| 3
|
[] |
no_license
|
#include<stdio.h>
main()
{
int n,r=0,rem;
while(n!=0)
{
rem=!=0;
r=r*10+rem;
n=n/10;
}
if(n==r)
{
printf("\n num is palindrome");
}
else
{
printf(" the num is not a palindrome");
}
return 0;
}
|
Shell
|
UTF-8
| 264
| 2.84375
| 3
|
[] |
no_license
|
#!/bin/bash
# Build the application with Maven
./canner.sh
REQUIRES="quinzical.jar run.sh README.md src/ categories/ wiki/"
for R in $REQUIRES; do
if [[ ! -e "$R" ]]; then
echo "No \`$R\` found" >& 2
exit 1
fi
done
zip -r quinzical28.zip $REQUIRES
|
Java
|
UTF-8
| 1,420
| 2.546875
| 3
|
[] |
no_license
|
package com.example.springmongoexample;
import com.example.springmongoexample.model.Person;
import com.example.springmongoexample.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@SpringBootApplication
public class SpringMongoExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringMongoExampleApplication.class, args);
}
}
@Component
class InitRunner implements CommandLineRunner {
private final PersonRepository personRepository;
@Autowired
public InitRunner(PersonRepository personRepository) {
this.personRepository = personRepository;
}
@Override
public void run(String... args) throws Exception {
Person person1 = new Person("li", "jiaming");
Person person2 = new Person("li", "wei");
Person person3 = new Person("xiong", "juanjuan");
Person person4 = new Person("qing", "xiangzhi");
Person person5 = new Person("yao", "chuancun");
Person person6 = new Person("cao", "yang");
this.personRepository.save(Arrays.asList(person1, person2, person3, person4, person5, person6));
}
}
|
Java
|
UTF-8
| 2,765
| 2.359375
| 2
|
[] |
no_license
|
package com.starshine.test.waterprogress.activity;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.starshine.test.waterprogress.R;
import com.starshine.test.waterprogress.view.WaterProgress;
public class MyActivity extends ActionBarActivity {
private WaterProgress mWaterProgress;
private int mProgress;
private Handler mHandler; // the handler
private Runnable mRunnable; // the runnable
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mWaterProgress = (WaterProgress) findViewById(R.id.wpb);
mWaterProgress.setBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.default_wallpaper))
.setFirstWaterARGB(255, 255, 0, 0)
.setFirstWaterHeight(10)
.setFirstWaterWidth(0.5f)
.setFirstWaterSpeed(40)
.isNeedDoubleWater(true)
.setSecondWaterARGB(128, 0, 255, 0)
.setSecondWaterHeight(7)
.setSecondWaterWidth(0.7f)
.setSecondWaterSpeed(25)
.setRefreshTime(10)
.setProgress(mProgress)
.start();
mHandler = new Handler();
mRunnable = new Run();
mHandler.post(mRunnable);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class Run implements Runnable{
@Override
public void run() {
try{
if (mProgress > 100){
mProgress -= 100;
}else{
mProgress += 1;
}
mWaterProgress.setProgress(mProgress);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.post(this);
}
}
}
|
C
|
UTF-8
| 2,543
| 2.890625
| 3
|
[] |
no_license
|
#include "comm.h"
/*
typedef enum {
MESSAGE_KEY_ready, // Status of the communication
MESSAGE_KEY_Index = 0, // Index of data chunk in whole array
MESSAGE_KEY_DataLength, // Length of the array being transmitted
MESSAGE_KEY_DataChunk, // The chunk of image data
MESSAGE_KEY_ChunkSize, // Size of any particular chunk
MESSAGE_KEY_Complete // Signal that all data has been transferred
} MessageKey;*/
static uint8_t *s_img_data;
static int s_img_size;
static bool s_ready;
uint32_t message_cmd;
static void inbox_received_handler(DictionaryIterator *iter, void *context) {
//Ready chunk
Tuple *ready_t = dict_find(iter, MESSAGE_KEY_Ready);
if(ready_t) {
APP_LOG(APP_LOG_LEVEL_INFO, "JS Ready!");
s_ready = true;
send_request(message_cmd);
}
// Get the received image chunk
Tuple *img_size_t = dict_find(iter, MESSAGE_KEY_DataLength);
if (img_size_t) {
s_img_size = img_size_t->value->int32;
// Allocate buffer for image data
s_img_data = (uint8_t *)malloc(s_img_size * sizeof(uint8_t));
}
// An image chunk
Tuple *chunk_t = dict_find(iter, MESSAGE_KEY_DataChunk);
if (chunk_t) {
uint8_t *chunk_data = chunk_t->value->data;
Tuple *chunk_size_t = dict_find(iter, MESSAGE_KEY_ChunkSize);
int chunk_size = chunk_size_t->value->int32;
Tuple *index_t = dict_find(iter, MESSAGE_KEY_Index);
int index = index_t->value->int32;
// Save the chunk
memcpy(&s_img_data[index], chunk_data, chunk_size);
}
// Complete?
Tuple *complete_t = dict_find(iter, MESSAGE_KEY_Complete);
if (complete_t) {
// Show the image
s_qr_window_set_data(s_img_data, s_img_size);
}
}
void send_request(uint32_t command) {
APP_LOG(APP_LOG_LEVEL_INFO, "I was told to send request command %d", (int) command);
if(!s_ready){
APP_LOG(APP_LOG_LEVEL_INFO, "JS not yet ready, saving until it is OK");
message_cmd = command;
return;
}
DictionaryIterator *iter;
app_message_outbox_begin(&iter);
dict_write_int(iter, MESSAGE_KEY_qr_outbound, &command, sizeof(command), true);
app_message_outbox_send();
}
void comm_init() {
app_message_register_inbox_received(inbox_received_handler);
const int inbox_size = 32000;
const int outbox_size = 64;
APP_LOG(APP_LOG_LEVEL_DEBUG, "%d", (int) app_message_inbox_size_maximum);
app_message_open(inbox_size, outbox_size);
}
void comm_deinit() {
// Free image data buffer
if (s_img_data) {
free(s_img_data);
}
}
|
Java
|
UTF-8
| 2,772
| 2.046875
| 2
|
[] |
no_license
|
package org.leesia.median;
import org.apache.commons.lang3.StringUtils;
import org.leesia.dataio.service.IntDataService;
import org.leesia.dataio.service.impl.IntDataServiceImpl;
import org.leesia.median.schedule.Schedule;
import org.leesia.median.util.LeesiaUtil;
import org.leesia.median.util.SpringUtil;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import java.util.List;
/**
* @Auther: leesia
* @Date: 2018/5/22 13:44
* @Description:
*/
@MapperScan("org.leesia.dataio.dao")
@SpringBootApplication
@EnableCaching
@ComponentScan(basePackages={"org.leesia"})
public class Application {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
SpringUtil.setApplicationContext(ctx);
int total = 100_000_000;
try {
if (StringUtils.isNotEmpty(args[0])) {
total = Integer.parseInt(args[0]);
}
} catch (Exception e) {
logger.warn("参数args[0]读取异常");
}
int singleBatchCount = 1_000_000;
try {
if (StringUtils.isNotEmpty(args[1])) {
singleBatchCount = Integer.parseInt(args[1]);
}
} catch (Exception e) {
logger.warn("参数args[1]读取异常");
}
int batchCount = 10_000;
try {
if (StringUtils.isNotEmpty(args[2])) {
batchCount = Integer.parseInt(args[2]);
}
} catch (Exception e) {
logger.warn("参数args[2]读取异常");
}
long start = System.currentTimeMillis();
Schedule schedule = new Schedule(total, singleBatchCount, batchCount);
List<Integer> result = schedule.schedule();
long end = System.currentTimeMillis();
logger.info("调度结束,调度时间:{},中位数:{}", LeesiaUtil.convertTimeToString(end - start), result);
}
@Bean
public IntDataService intDataService() {
return new IntDataServiceImpl();
}
}
|
JavaScript
|
UTF-8
| 2,405
| 2.8125
| 3
|
[] |
no_license
|
class Bullet {
constructor(plane) {
this.plane = plane;
this.buffetBullet = false;
this.allShots = [];
this.shotBuffer = []
this.maxIdProccessed = 0;
this.reloadTime = 4;
this.rayCollider = new THREE.Raycaster(new THREE.Vector3(), new THREE.Vector3(),0,500);
this.hittedShotsBuffer = [];
}
loop() {
this.removeAllOldShots();
if(this.buffetBullet) this.displayCurrentPlaneShot();
this.displayBuffer();
this.buffetBullet = false;
}
shot() {
if(app.t%this.reloadTime == 0) this.buffetBullet = true;
}
addBufferShot(pos,rot,id,color = 0xff9900) {
this.shotBuffer.push({pos:pos,rot:rot,color:color,id:id});
}
displayBuffer() {
let buf = this.shotBuffer.splice(0,this.shotBuffer.length)
for(let s of buf) {
let pos = new THREE.Vector3(parseFloat(s.pos.x),parseFloat(s.pos.y),parseFloat(s.pos.z));
let rotn = this.getRotationDir(s.rot);
rotn.normalize();
this.rayCollider.set(pos,rotn);
const collision = this.rayCollider.intersectObject(this.plane.model)
if(collision.length > 0) {
this.plane.isHit();
if(this.plane.life < 0) this.addHittedShot('dead',s.id);
else this.addHittedShot('touch',s.id)
}
this.displayShot(pos,s.rot,s.color)
}
}
parse() {
return this.buffetBullet;
}
hittedShots() {
return this.hittedShotsBuffer.splice(0,this.hittedShotsBuffer.length);
}
addHittedShot(type,id) {
this.hittedShotsBuffer.push({t:type,i:id});
}
displayCurrentPlaneShot() {
this.displayShot(this.plane.position,this.plane.rotation);
}
getRotationDir(rot,length = 1) {
let dir = new THREE.Vector3(0,0,length);
dir.applyEuler(new THREE.Euler(parseFloat(rot._x),parseFloat(rot._y),parseFloat(rot._z)));
return dir;
}
displayShot(pos,rot,color = 0xff9900) {
if(rot.x && rot.y && rot.z) {
const r = 10;
let geom = new THREE.Geometry();
geom.vertices.push(new THREE.Vector3(pos.x,pos.y,pos.z));
let projection = this.getRotationDir(rot,100);
projection.add(pos);
geom.vertices.push(projection)
let mat = new THREE.LineBasicMaterial( { color: color,linewidth: 3 } );
this.allShots.push(app.three.addObject(new THREE.Line(geom, mat)));
}
}
removeAllOldShots() {
let old = this.allShots.splice(0,this.allShots.length)
for(let shot of old) {
app.three.rmObject(shot);
}
}
setMaxId(id) {
if(id > this.maxIdProccessed) this.maxIdProccessed = id;
return this.maxIdProccessed;
}
}
|
Ruby
|
UTF-8
| 375
| 3.15625
| 3
|
[] |
no_license
|
# Using the DIR class in Ruby#
#Display the current working directory
puts path = "#{Dir.pwd}"
# Create a new directory temp under working directory
Dir.mkdir("#{path}/tmp")
# change working directory to tmp
Dir.chdir("#{path}/tmp")
# display current directory
puts "#{Dir.pwd}"
# go back to current directory
Dir.chdir(path)
#delete tmp directory
Dir.delete("#{path}/tmp")
|
Java
|
UTF-8
| 3,539
| 2.515625
| 3
|
[] |
no_license
|
/**
*
*/
package it.unical.mat.moviesquik.model.business;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import it.unical.mat.moviesquik.persistence.DBManager;
/**
* @author Agostino
*
*/
public class CDNUsageChart
{
private static CDNUsageChart instance = null;
private final Map<String, CDNUsageSamples> serversUsageSamplesMap = new HashMap<String, CDNUsageSamples>();
private final List<String> allServersKeys = new ArrayList<String>();
private CDNUsageChartUpdateCallback updateCallback = null;
private final Lock lock = new ReentrantLock();
public static CDNUsageChart getInstance()
{
if ( instance == null )
instance = new CDNUsageChart();
return instance;
}
private CDNUsageChart()
{
final List<CDNServer> allServers = DBManager.getInstance().getDaoFactory().getCDNServerDao().findAll();
if ( allServers != null )
for ( final CDNServer server : allServers )
{
final String serverKey = server.getKey();
allServersKeys.add(serverKey);
update(serverKey, null);
}
}
public void setUpdateCallback( final CDNUsageChartUpdateCallback callback )
{
lock.lock();
updateCallback = callback;
lock.unlock();
}
public void update( final String serverKey, final Float[] samples )
{
final CDNUsageSamples usageSamples = new CDNUsageSamples(samples);
lock.lock();
serversUsageSamplesMap.put(serverKey, usageSamples);
if ( updateCallback != null )
updateCallback.onUpdate( getCurrentUsageChart(usageSamples.getTimestamp()) );
lock.unlock();
}
public Map<String, Float[]> getCurrentChartSamples()
{
lock.lock();
try { return getCurrentUsageChart( System.currentTimeMillis() ); }
finally { lock.unlock(); }
}
public List<String> getAllServersKeysList()
{
lock.lock();
try { return new ArrayList<String>(allServersKeys); }
finally { lock.unlock(); }
}
private Map<String, Float[]> getCurrentUsageChart( final long currentTimestamp )
{
final Map<String, Float[]> usageChart = new HashMap<String, Float[]>();
final Set<String> serversKeys = serversUsageSamplesMap.keySet();
for ( final String serverKey : serversKeys )
usageChart.put(serverKey, CDNUsageSamples.createNewSamplesArray());
long timestamp;
int i=0;
for( int t=CDNUsageSamples.CDN_USAGE_CHART_SAMPLES_WINDOW; t>0; --t )
{
timestamp = currentTimestamp - ( t * CDNUsageSamples.CDN_USAGE_CHART_SAMPLES_INTERVAL );
for ( final String serverKey : serversKeys )
usageChart.get(serverKey)[i] = getServerUsageValue(serverKey, timestamp);
++i;
}
return usageChart;
}
private Float getServerUsageValue( final String serverKey, long timestamp )
{
final CDNUsageSamples usageSamples = serversUsageSamplesMap.get(serverKey);
final long sampleEndTime = usageSamples.getTimestamp();
if ( timestamp >= sampleEndTime )
return 0.0f;
final long samplesStartTime = sampleEndTime -
(CDNUsageSamples.CDN_USAGE_CHART_SAMPLES_WINDOW * CDNUsageSamples.CDN_USAGE_CHART_SAMPLES_INTERVAL);
if ( timestamp < samplesStartTime )
return 0.0f;
timestamp -= samplesStartTime;
final int sampleIndex = (int) (timestamp / CDNUsageSamples.CDN_USAGE_CHART_SAMPLES_INTERVAL);
return usageSamples.getSamples()[sampleIndex];
}
}
|
C++
|
UTF-8
| 1,405
| 2.546875
| 3
|
[] |
no_license
|
#ifndef _SIFT
#define _SIFT
#define SQARTPI 0.39894228 //根号2 pi
#include<opencv2/opencv.hpp>
using namespace cv;
enum Channels{B, G, R};
//自定义的矩阵
struct xjMat
{
unsigned char* data;
int rows, cols, channels;
public:
xjMat(const Mat& M);
xjMat(unsigned char* ,int inrows, int incols, int inc);
inline unsigned char get(int i, int j, int k) const;
inline unsigned char& set(int i, int j, int);
};
class Gaussy
{
protected:
float keno;
int length;
public:
Gaussy(){}
virtual ~Gaussy(){}
virtual void working(Mat& M, const Mat& source) = 0;
virtual void working(xjMat&, const xjMat& ) = 0;
};
//分离高斯模糊算子类
class GaussSeparate:public Gaussy
{
//分别代表二维方向的模糊
//范围是(6keno+1)*(6keno+1);
double* x;
public:
GaussSeparate(float keno);
~GaussSeparate();
//对图像进行高斯模糊,结果放在M 中
void working(Mat& M, const Mat& source);
void working(xjMat& M, const xjMat& source);
};
//二维高斯模糊算子类
class GaussTwoDimen:public Gaussy
{
double* x;
public:
GaussTwoDimen(float keno);
~GaussTwoDimen();
//对图像进行高斯模糊,结果放在M 中
void working(Mat& M, const Mat& source);
void working(xjMat& M, const xjMat& source);
};
void SIFT(const Mat& image);
#endif
|
Markdown
|
UTF-8
| 1,927
| 2.953125
| 3
|
[] |
no_license
|
续 [上文](https://zhuanlan.zhihu.com/p/339033162),对重复引用的各种方式作了更多测试,基于当前理解作一小结。
简言之,由于每次引用模块都对其执行(exec)一次,在多处引用同一模块的情况下,引用顺序和模块位置不同会导致不同结果。暂没想到此种行为的应用场景。
比如在 TypeDef 模块中定义一个类:
```
type Type1 { ; }
```
在同层目录下 Instance1 模块中声明一个个体:
```
using * in TypeDef
instance1 = Type1()
```
那么在另一模块中,先后引用 TypeDef 和 Instance1,如下的 isa 判断(对应 python 的 isinstance)返回 true,意料之中:
```
using * in TypeDef
using * in Instance1
print(isa(instance1, Type1))
```
但是以下的三种情况,全都返回 false:
- 情况 1:
```
using * in Instance1
using * in TypeDef
print(isa(instance1, Type1))
```
- 情况 2:
```
using TypeDef
using Instance1
print(isa(Instance1.instance1, TypeDef.Type1))
```
- 情况 3:
```
using Instance1
using TypeDef
print(isa(Instance1.instance1, TypeDef.Type1))
```
而如果 TypeDef 和 Instance1 在包内,行为又略有不同。如下返回 true(注意 TypeDef 在 Instance1 后引用)
```
using * in test.Instance1
using * in test.TypeDef
print(isa(instance1, Type1))
```
以下的三种情况,全都返回 false:
- 情况 4:
```
using * in test.TypeDef
using * in test.Instance1
print(isa(instance1, Type1))
```
- 情况 5:
```
using * in test.TypeDef
using test.Instance1
print(isa(test.Instance1.instance1, Type1))
```
- 情况 6:
```
using * in test.Instance1
using test.TypeDef
print(isa(instance1, test.TypeDef.Type1))
```
测试用例 [集结在此](https://gitee.com/MulanRevive/mulan-rework/tree/master/%E6%B5%8B%E8%AF%95/%E5%BC%95%E7%94%A8/isa)。
为规避,在应用中尽量保持“树式引用”,即一个模块只直接引用一次。
|
C#
|
UTF-8
| 2,853
| 2.90625
| 3
|
[] |
no_license
|
using Spike3.DBObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using AccessAssistant;
namespace Spike3.Controllers
{
public static class VehicleControl
{
public static int PURCHASE_RATE = 100;
public static void AddVehicle(Vehicle v)
{
DBController.Save(v, DBObject.SaveTypes.Insert);
}
public static Vehicle FindVehicle(string id)
{
int numID = Convert.ToInt32(id);
Vehicle v = DBController.GetAllRecords<Vehicle>().Where(vehicle => vehicle.VehicleID == numID).FirstOrDefault();
return v;
}
public static List<string> DisplayCarInfo(string id)
{
Vehicle v = FindVehicle(id);
string carType = v.Type.ToString();
string carColor = v.Color.ToString();
string carYear = v.VehicleYear.ToString();
string carModel = v.Model.ToString();
string carMake = v.Make.ToString();
bool rightHandControl = v.RightHandControlled;
bool manualTransmission = v.ManualTransmission;
string rate = v.Rate.ToString();
List<string> list = new List<string>() { carType, carColor, carYear, carModel, carMake, rightHandControl.ToString(), manualTransmission.ToString() };
return list;
}
public static bool RemoveVehicle(Vehicle v)
{
return DBController.Delete(v);
}
public static bool ModifyVehicle(Vehicle v)
{
return DBController.Save(v, DBObject.SaveTypes.Update);
}
public static List<Vehicle> GetAllVehicles()
{
List<Vehicle> v = DBController.GetAllRecords<Vehicle>();
return v;
}
public static List<Vehicle> FilterCar(string carType, string carColor, string makeType, int carYearFirst, int carYearSecond, bool rightHand, bool manual, string location)
{
List<Vehicle> lv = GetAllVehicles();
lv = lv.Where(vehicle => !vehicle.IsRented).ToList();
if (carType != null && carType != "None")
lv = lv.Where(vehicle => vehicle.Type == carType).ToList();
if (carColor != null && carColor != "None")
lv = lv.Where(vehicle => vehicle.Color == carColor).ToList();
if (makeType != null && makeType != "None")
lv = lv.Where(vehicle => vehicle.Make == makeType).ToList();
if (location != null && location != "None")
lv = lv.Where(vehicle => vehicle.CurrentLocation == location).ToList();
lv = lv.Where(vehicle => vehicle.VehicleYear >= carYearFirst && vehicle.VehicleYear <= carYearSecond && vehicle.RightHandControlled == rightHand && vehicle.ManualTransmission == manual).ToList();
return lv;
}
public static int DeterminePrice(Vehicle v)
{
return v.Rate * PURCHASE_RATE;
}
}
}
|
Markdown
|
UTF-8
| 11,387
| 3.015625
| 3
|
[] |
no_license
|
---
title: RESTful接口版本管理
date: 2019-03-12 11:36:22
tags:
- java
- Java Web
- Spring Boot
- RESTful
categories:
- 工作笔记
- Java Web
- Spring Boot
keywords:
- rest
- restful
- version
- 接口版本管理
---
# REST简介
REST,全称是`Representational State Transfer`,译为表现层状态转化。REST并不是一个标准,而是一种软件架构风格。
在REST风格下,客户端通过url访问网络上的一个资源,通过HTTP动词请求服务端对资源进行操作。
# 接口版本
服务端接口是会不断变化更新的,一个好的设计,是提供不同版本的接口,而不是在一个接口上进行修改。部署时,服务端包含不同版本的接口,客户端可以依旧使用老版本的接口,也可以随服务端升级到新版本。当所有客户端都升级到新版本时,服务端可以考虑移除旧版本的接口。
在REST风格下,我们可以通过对接口增加版本号的概念,去区分不同版本的接口。版本号有两种表现形式,一种是包含在url中,一种是包含在HTTP头中。例如:
{% codeblock url %}
http://somewhere.com/xxx/v1/user
Accept: application/json; version=v1
{% endcodeblock %}
# Spring Boot starter源码
{% link 接口版本管理源码 https://github.com/it-linnan/api-version-spring-boot-starter %}
# 实现思路
Spring Boot提供了starter的标准,starter完成自动配置,开发者只需要引用starter,就可以实现功能。我们可以通过开发一个api-version-spring-boot-starter,帮助应用快速实现接口版本管理。
Spring Boot对于自定义starter提出的指导有以下几点:
1. 项目包含两个模块,一个是autoconfigure,一个是starter
2. autoconfigure模块包含自动配置相关的代码,和一个清单文件,清单文件中包含自动加载bean的class名
3. starter需引用autoconfigure模块和其他必要的依赖
因此,我们定义了两个模块,一个是autoconfigure,一个是starter,在autoconfigure中完成接口版本管理的功能和自动配置,实现在url中标明版本号。
<!-- more -->
## ApiVersion注解
首先,定义一个注解,注解的作用是标识controller的版本
{% codeblock ApiVersion.java lang:java %}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ApiVersion {
/**
* 版本号
*
* @return 版本号
*/
@AliasFor("value")
String version() default "";
/**
* 版本号
*
* @return 版本号
*/
@AliasFor("version")
String value() default "";
}
{% endcodeblock %}
## 扩展RequestMappingHandlerMapping
`RequestMappingHandlerMapping`提供了url-controller方法间映射的能力,可以理解为在启动阶段,Spring扫描标注了`@Controller`注解的类,对其中标注了`@RequestMapping`注解的方法进行注册,key为`@RequestMaping`指定的url,value为方法。`@Controller`注解的变体有`@RestController`,`@RequestMapping`注解的变体有`@GetMapping`、`@PostMapping`等。当客户端发起请求时,`DispatcherServlet`在分发请求时,根据启动阶段注册的url和方法映射进行分发。
因此我们需要扩展两个类,一个是`RequestMappingHandlerMapping`,在注册url时,将url注册为统配符的形式,如`{version}/user`。另外一个是`RequestCondition`,提供具体的匹配规则。
具体工作原理是:
1. 服务端启动阶段,Spring扫描Controller,注册能力由`ApiVersionUrlRequestMappingHandlerMapping`提供,将标注了`@ApiVersion`注解的Controller,url统一注册为统配符的形式,形如`{version}/user`,同时将定义的版本号也作为url的属性,注册到Spring容器中
2. 客户端发起请求,请求的url形如`v1/user`
3. `DispathcerServlet`接受到请求,对请求的url与注册的url进行匹配。匹配规则由`ApiVersionUrlRequestCondition`提供,即注册url符合请求的url,且注册版本号与请求的版本号一致,即为匹配成功
{% codeblock ApiVersionUrlRequestCondition.java lang:java %}
@NoArgsConstructor
public class ApiVersionUrlRequestCondition implements RequestCondition<ApiVersionUrlRequestCondition>, ApplicationContextAware {
@Getter
private String version;
private static String regexFormat = "";
public ApiVersionUrlRequestCondition(String version) {
this.version = version;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (regexFormat == null || regexFormat.length() == 0) {
ApiVersionProperties apiVersionProperties = applicationContext.getBean(ApiVersionProperties.class);
ServerProperties serverProperties = applicationContext.getBean(ServerProperties.class);
if (serverProperties.getServlet().getContextPath() != null) {
regexFormat = serverProperties.getServlet().getContextPath();
}
regexFormat += "/" + apiVersionProperties.getPrefix() + "%s/**";
}
}
@Override
public ApiVersionUrlRequestCondition combine(ApiVersionUrlRequestCondition other) {
return new ApiVersionUrlRequestCondition(other.getVersion());
}
@Override
public ApiVersionUrlRequestCondition getMatchingCondition(HttpServletRequest request) {
PathMatcher pathMatcher = new AntPathMatcher();
boolean match = pathMatcher.match(String.format(regexFormat, version), request.getRequestURI());
return match ? this : null;
}
@Override
public int compareTo(ApiVersionUrlRequestCondition other, HttpServletRequest request) {
return other.getVersion().compareTo(this.version);
}
}
{% endcodeblock %}
{% codeblock ApiVersionUrlRequestMappingHandlerMapping.java lang:java %}
@Slf4j
public class ApiVersionUrlRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
public static final String VERSION_PREFIX = "/{version}";
public static final String PATH_KEY = "path";
public static final String VALUE_CACHE_KEY = "valueCache";
@Override
protected RequestCondition<ApiVersionUrlRequestCondition> getCustomTypeCondition(Class<?> handlerType) {
ApiVersion apiVersion = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
return createCondition(apiVersion);
}
@Override
protected RequestCondition<ApiVersionUrlRequestCondition> getCustomMethodCondition(Method method) {
ApiVersion apiVersion = AnnotationUtils.findAnnotation(method, ApiVersion.class);
return createCondition(apiVersion);
}
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
RequestMappingInfo info = createRequestMappingInfo(method);
if (info != null) {
RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
if (typeInfo != null) {
info = typeInfo.combine(info);
}
}
return info;
}
@Nullable
private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
ApiVersion apiVersion = AnnotationUtils.findAnnotation(element, ApiVersion.class);
if (apiVersion != null) {
InvocationHandler invocationHandler = Proxy.getInvocationHandler(requestMapping);
Class<? extends InvocationHandler> clazz = invocationHandler.getClass();
try {
Field declaredField = clazz.getDeclaredField(VALUE_CACHE_KEY);
declaredField.setAccessible(true);
Map<String, Object> valueCache = (Map) declaredField.get(invocationHandler);
String[] path = requestMapping.path();
if (path != null) {
for (int i = 0; i < path.length; i++) {
path[i] = VERSION_PREFIX + path[i];
}
valueCache.put(PATH_KEY, path);
declaredField.set(invocationHandler, valueCache);
}
} catch (NoSuchFieldException | IllegalAccessException e) {
log.error("这是不可能发生的事。。", e);
}
}
RequestCondition<?> condition = (element instanceof Class ?
getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element));
return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
}
private RequestCondition<ApiVersionUrlRequestCondition> createCondition(ApiVersion apiVersion) {
return apiVersion == null ? null : new ApiVersionUrlRequestCondition(apiVersion.version());
}
}
{% endcodeblock %}
## 配置RequestMappingHandlerMapping
自定义了`RequestMappingHandlerMapping`后,我们需要注册自定义处理类,让Spring容器使用自定义处理类进行url注册。注册自定义处理类的方法非常简单,只需要扩展`WebMvcRegistrations`,覆写`getRequestMappingHandlerMapping`方法即可。
{% codeblock ApiVersionUrlWebConfig.java lang:java %}
public class ApiVersionUrlWebConfig implements WebMvcRegistrations {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new ApiVersionUrlRequestMappingHandlerMapping();
}
}
{% endcodeblock %}
## 配置版本号前缀
考虑到有些人习惯将版本号定义为`v1`,有的人则习惯定义为`1`,我们还需要提供版本号前缀的配置项。
{% codeblock ApiVersionProperties.java lang:java %}
@Data
@ConfigurationProperties(prefix = "api.version")
public class ApiVersionProperties {
/**
* 全局版本号前缀
*/
private String prefix = "v";
}
{% endcodeblock %}
## 自动配置
Spring Boot starter的核心思想是自动配置,因此,我们需要注册以上所有的bean到Spring容器中。
### 自动配置类
{% codeblock ApiVersionHttpConfiguration.java lang:java %}
@Configuration
@EnableConfigurationProperties
@ConditionalOnWebApplication
public class ApiVersionHttpConfiguration {
@Bean
public ApiVersionUrlWebConfig apiVersionUrlWebConfig() {
return new ApiVersionUrlWebConfig();
}
@ConditionalOnMissingBean
@Bean
public ApiVersionProperties apiVersionProperties() {
return new ApiVersionProperties();
}
@ConditionalOnMissingBean
@Bean
public ApiVersionUrlRequestCondition apiVersionUrlRequestCondition() {
return new ApiVersionUrlRequestCondition();
}
}
{% endcodeblock %}
### 配置清单
Spring规定了清单文件的路径resources/META-IN/spring.factories,我们需要在清单文件中标注自动配置类的路径
{% codeblock spring.factories lang:properties %}
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
priv.ln.api.version.spring.boot.autoconfigure.ApiVersionHttpConfiguration
{% endcodeblock %}
# 在Spring Boot项目中使用接口版本管理
在pom.xml中添加依赖,引用starter。
在Controler中添加注解
{% codeblock lang:java %}
@ApiVersion("1")
@Controller
@RequestMapping("/xxx")
public class XxxController{
}
{% endcodeblock %}
访问该接口时,通过url`/v1/xxx`访问
|
Java
|
UTF-8
| 1,098
| 2.734375
| 3
|
[] |
no_license
|
package model;
public class Mensalidade {
private int Registro;
private double Valor_da_Mensalidade;
private String Serie, Forma_de_Pagamento;
public Mensalidade() {}
public Mensalidade(int Registro, double Valor_da_Mensalidade, String Serie, String Forma_de_Pagamento) {
this.Registro = Registro;
this.Valor_da_Mensalidade = Valor_da_Mensalidade;
this.Serie = Serie;
this.Forma_de_Pagamento = Forma_de_Pagamento;
}
public int getRegistro() {
return Registro;
}
public void setRegistro(int registro) {
Registro = registro;
}
public String getSerie() {
return Serie;
}
public void setSerie(String serie) {
Serie = serie;
}
public double getValor_da_Mensalidade() {
return Valor_da_Mensalidade;
}
public void setValor_da_Mensalidade(double valor_da_Mensalidade) {
Valor_da_Mensalidade = valor_da_Mensalidade;
}
public String getForma_de_Pagamento() {
return Forma_de_Pagamento;
}
public void setForma_de_Pagamento(String forma_de_Pagamento) {
Forma_de_Pagamento = forma_de_Pagamento;
}
}
|
Java
|
UTF-8
| 938
| 1.804688
| 2
|
[] |
no_license
|
package io.pageobject.generator.element;
import io.pageobject.generator.GeneratorContext;
import io.pageobject.generator.locator.LocatorSources;
import org.jsoup.nodes.Element;
import java.util.List;
import java.util.Map;
import static com.google.common.collect.Lists.newArrayList;
import static io.pageobject.generator.Expressions.hasExpression;
public class Ng2BindingProcessor extends AbstractElementProcessor {
@Override
public boolean isMatchingElement(Element element, GeneratorContext context) {
return hasExpression(element.ownText());
}
@Override
protected LocatorSources[] getElementLocatorCandidates(
GeneratorContext context) {
return new LocatorSources[] { LocatorSources.ID, LocatorSources.NAME,
LocatorSources.CSS };
}
@Override
protected List<String> getTemplates(GeneratorContext context,
Map<String, Object> templateModel) {
return newArrayList(ASSERTION_TEXT, ASSERTION_HAS_CLASS);
}
}
|
Shell
|
UTF-8
| 713
| 3.421875
| 3
|
[] |
no_license
|
#!/bin/bash -ex
#get script location
SCRIPTDIR=`dirname $0`
SCRIPTDIR=`(cd $SCRIPTDIR ; pwd)`
#get working directory
TOP=`pwd`
isDelivery=`echo $1 | grep delivery` || true
# define version
cd ${TOP}/.repo/manifests
VERSION=`git describe --always --dirty --tags --long --abbrev=8 2>/dev/null`
cd ${TOP}
if [ ! "$isDelivery" ] ; then
VERSION=`date +%Y%m%d-%H%M%S`-${VERSION}
fi
# delete previous versions
rm -f ${TOP}/out/asset-runtime-*
#######################################################################################################
# not really a build but tar part of scratch test directory
cd ${TOP}
tar -C scratch/test --atime-preserve --exclude='.git' -czf out/asset-runtime-${VERSION}.tgz .
|
PHP
|
UTF-8
| 1,632
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model {
/**
* These fields could be mass assigned
*/
protected $fillable = ['user_id', 'body', 'senderid', 'senderprofileimage', 'sendername'];
/**
* A message belongs to Many Users.
*
* @return Collection
*/
public function users()
{
return $this->belongsToMany('App\User')->withTimestamps();
}
/**
* Create a new message object.
*
* @param string body
* @param int senderId
* @param string senderProfileImage
* @param string senderName
*
* @return static
*/
public static function createMessage($body, $senderId, $senderProfileImage, $senderName)
{
$message = new static([
'body' => $body,
'senderid' => $senderId,
'senderprofileimage' => $senderProfileImage,
'sendername' => $senderName]);
return $message;
}
/**
* A Message has a many message responses.
*
* @return Collection
*/
public function messageResponses()
{
return $this->hasMany('App\MessageResponse')->orderBy('created_at', 'desc');
}
/**
* Get the last receiver id from the first response attached to an message.
*
* @return mixed
*/
public function getLastReceiverId()
{
return $this->messageResponses()->first()->receiverid;
}
/**
* Determine if a message belongs to a user.
*
* @param int $userId
*
* @return mixed
*/
public function belongsToUser($userId)
{
$users = $this->users()->get();
$userIds = [];
foreach ($users as $user) {
$userIds[] = $user->id;
}
return in_array($userId, $userIds);
}
}
|
Python
|
UTF-8
| 2,555
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env python3
import os, glob, itertools
def add_line_prefix_to_file(fname, out_name, line_transform, validate):
with open(fname) as f_in:
with open(out_name, 'w') as f_out:
print('Write:', fname, '->', out_name)
for line in f_in:
line = line.strip()
if validate(line):
f_out.write(line_transform(line) + '\n')
def find_files(f_pattern):
return sorted(f for f in glob.glob(f_pattern)
if os.path.isfile(f))
def add_line_prefix_to_matches(f_pattern, out_dir, fname_transform, line_transform, validate):
file_path = None
for file_path in find_files(f_pattern):
in_dir, fname = os.path.split(file_path)
out_name = fname_transform(fname)
out_path = os.path.join(out_dir, out_name)
add_line_prefix_to_file(file_path, out_path, line_transform, validate)
if file_path is None:
print('Error: No files matching pattern: ""'.format(f_pattern))
def main():
def fname_transform(fname):
fbase, fext = os.path.splitext(fname)
return 'results-' + fbase + '.log'
def validate(line):
try:
val = float(line)
return True
except ValueError:
print('Warning: Invalid line: "{}"'.format(line))
return False
out_dir = '../results-2018-11-pranav/'
def run(pattern, params):
prefix = params + ': 0.1.0 -1 '
line_transform = lambda line: prefix + line
add_line_prefix_to_matches(pattern, out_dir, fname_transform, line_transform, validate)
# cnx-btb
# cnx-lin
# cnx-lin-borrowed-1
# sc-current
# sc
# sc-better-t1
# sc-better-gates
# sc-better-t1-and-gates
# ti-qubit
# ti-bare
# ti-dressed
run('bare-qutrit-*.txt', '{"n": 14, "noise": "ti-bare", "circ": "cnx-btb"}')
run('dressed-qutrit-*.txt', '{"n": 14, "noise": "ti-dressed", "circ": "cnx-btb"}')
run('current-sc-qutrit-*.txt', '{"n": 14, "noise": "sc-current", "circ": "cnx-btb"}')
run('future-better-gates-and-t1-qutrit-*.txt', '{"n": 14, "noise": "sc-better-t1-and-gates", "circ": "cnx-btb"}')
run('future-better-gates-qutrit-*.txt', '{"n": 14, "noise": "sc-better-gates", "circ": "cnx-btb"}')
run('future-better-t1-qutrit-*.txt', '{"n": 14, "noise": "sc-better-t1", "circ": "cnx-btb"}')
run('future-sc-qutrit-*.txt', '{"n": 14, "noise": "sc", "circ": "cnx-btb"}')
# TODO: Fix the file names and add more
if __name__ == '__main__':
main()
|
C
|
UHC
| 924
| 3.921875
| 4
|
[] |
no_license
|
//α 6.5 Ʈ
// Ʈ
#include <stdio.h>
#include <memory.h>
typedef struct node_type * node_ptr;
typedef struct node_type
{
int data;
node_ptr link;
};
int length_list(node_ptr list);
void main()
{
node_ptr list, node1, node2, node3;
node1 = (node_ptr)malloc(sizeof(struct node_type));
node1->data = 100;
node1->link = NULL;
list = node1;
node2 = (node_ptr)malloc(sizeof(struct node_type));
node2->data = 150;
node2->link = NULL;
node1->link = node2;
node3 = (node_ptr)malloc(sizeof(struct node_type));
node3->data = 200;
node3->link = NULL;
node2->link = node3;
printf("list length is %d\n", length_list(list));
}
int length_list(node_ptr list)
{
int count = 0; //ī
node_ptr temp = list; //ӽͰ list Ŵ
while (temp)//Ʈ empty
{
count += 1;
temp = temp->link;
}
return count;
}
|
Python
|
UTF-8
| 880
| 2.609375
| 3
|
[] |
no_license
|
from lxml import html
from datetime import date
from datetime import timedelta
import requests
import sqlite3
conn = sqlite3.connect('testDB.db')
conn.execute("CREATE TABLE TITLES(Id INTEGER PRIMARY KEY NOT NULL, Title STRING NOT NULL, Date STRING NOT NULL)")
startDate = date(1999, 9, 6)
todayDate = date.today()
id = 1
delta = (todayDate-startDate).days
for x in range(0, delta):
dateToString = startDate.strftime("%Y/%m/%d")
page = requests.get('https://lenta.ru/%s/' % dateToString)
tree = html.fromstring(page.content.decode('utf_8', 'ignore'))
news = tree.xpath('/html/body/div[*]/section[*]/div[*]/div/div[*]/section/div[*]/div[*]/h3/a/text()')
for new in news:
conn.execute("INSERT INTO TITLES VALUES (?, ?, ?)", (id, new, dateToString))
id += 1
startDate = startDate + timedelta(days=1)
print x
conn.commit()
|
JavaScript
|
UTF-8
| 401
| 3.28125
| 3
|
[] |
no_license
|
Array.prototype.removeNum = function(num){
let abc= this;
return new Promise(function(resolve,reject){
resolve(abc.filter(x=>x!=num))
});
}
async function processRemoveNum (){
try {
console.log(await [1,2,3,4,1].removeNum(1));
} catch (error) {
console.log(error);
}
}
console.log("first");
processRemoveNum();
console.log("finally");
|
Java
|
UTF-8
| 5,721
| 1.75
| 2
|
[] |
no_license
|
package com.mitkoindo.smartcollection.module.laporan.agenttracking;
import android.databinding.DataBindingUtil;
import android.databinding.Observable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
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 com.mikepenz.fastadapter.FastAdapter;
import com.mikepenz.fastadapter.IAdapter;
import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter;
import com.mitkoindo.smartcollection.R;
import com.mitkoindo.smartcollection.base.BaseFragment;
import com.mitkoindo.smartcollection.databinding.FragmentStaffDownlineBinding;
import com.mitkoindo.smartcollection.objectdata.StaffItem;
import com.mitkoindo.smartcollection.utils.SimpleListItemDecoration;
import com.mitkoindo.smartcollection.utils.Utils;
import butterknife.OnClick;
/**
* Created by ericwijaya on 9/19/17.
*/
public class ListStaffDownlineFragment extends BaseFragment {
private static final String EXTRA_USER_ID = "extra_user_id";
private StaffDownlineViewModel mStaffDownlineViewModel;
private FragmentStaffDownlineBinding mBinding;
private FastItemAdapter mFastAdapter;
private String mUserId;
public static ListStaffDownlineFragment getInstance(String userId) {
ListStaffDownlineFragment fragment = new ListStaffDownlineFragment();
Bundle bundle = new Bundle();
bundle.putString(EXTRA_USER_ID, userId);
fragment.setArguments(bundle);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_staff_downline, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle args = getArguments();
mUserId = args.getString(EXTRA_USER_ID);
mStaffDownlineViewModel = new StaffDownlineViewModel(getAccessToken());
addViewModel(mStaffDownlineViewModel);
mBinding = DataBindingUtil.bind(view);
mBinding.setStaffDownlineViewModel(mStaffDownlineViewModel);
mStaffDownlineViewModel.obsIsLoading.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(Observable sender, int propertyId) {
if (mStaffDownlineViewModel.obsIsLoading.get()) {
showLoadingDialog();
} else {
mBinding.swipeRefreshLayoutStaffDownline.setRefreshing(false);
hideLoadingDialog();
}
}
});
mStaffDownlineViewModel.error.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(Observable sender, int propertyId) {
if (getUserVisibleHint()) {
// displayMessage(R.string.GagalMendapatkanData);
}
mFastAdapter.clear();
mStaffDownlineViewModel.obsIsEmpty.set(true);
}
});
mStaffDownlineViewModel.obsStaffItemResponse.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(Observable sender, int propertyId) {
if (mStaffDownlineViewModel.obsStaffItemResponse.get() != null) {
mFastAdapter.clear();
mFastAdapter.add(mStaffDownlineViewModel.obsStaffItemResponse.get());
if (mStaffDownlineViewModel.obsStaffItemResponse.get().size() > 0) {
mStaffDownlineViewModel.obsIsEmpty.set(false);
} else {
mStaffDownlineViewModel.obsIsEmpty.set(true);
}
}
}
});
setupRecyclerView();
mStaffDownlineViewModel.getStaff(mUserId);
}
private void setupRecyclerView() {
mFastAdapter = new FastItemAdapter<>();
int divider = getResources().getDimensionPixelSize(R.dimen.padding_medium_large);
RecyclerView.ItemDecoration itemDecoration = new SimpleListItemDecoration(divider, RecyclerView.VERTICAL);
mBinding.recyclerViewStaffDownline.addItemDecoration(itemDecoration);
mBinding.recyclerViewStaffDownline.setLayoutManager(new LinearLayoutManager(getActivity()));
mBinding.recyclerViewStaffDownline.setAdapter(mFastAdapter);
mFastAdapter.withSelectable(true);
mFastAdapter.withOnClickListener(new FastAdapter.OnClickListener<StaffItem>() {
@Override
public boolean onClick(View v, IAdapter<StaffItem> adapter, StaffItem item, int position) {
startActivity(AgentTrackingActivity.instantiate(getContext(), item.getUserId()));
return true;
}
});
mBinding.swipeRefreshLayoutStaffDownline.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
mBinding.swipeRefreshLayoutStaffDownline.setRefreshing(true);
mStaffDownlineViewModel.getStaff(mUserId);
}
});
}
@OnClick(R.id.image_view_search)
public void onSearchClicked(View view) {
mStaffDownlineViewModel.getStaff(mUserId);
Utils.hideKeyboard(view);
}
}
|
Java
|
UTF-8
| 1,267
| 2.015625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.evolveum.midpoint.studio.action.environment;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.evolveum.midpoint.studio.MidPointConstants;
import com.evolveum.midpoint.studio.ui.EnvironmentListDialog;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Created by Viliam Repan (lazyman).
*/
public class EditEnvironments extends AnAction {
public static final String ACTION_ID = MidPointConstants.ACTION_ID_PREFIX + EditEnvironments.class.getSimpleName();
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
showDialog(e.getProject());
}
@Nullable
private EnvironmentListDialog showDialog(Project project) {
final Ref<EnvironmentListDialog> dialog = Ref.create();
ApplicationManager.getApplication().invokeAndWait(() -> {
dialog.set(new EnvironmentListDialog(project));
dialog.get().show();
}, ModalityState.any());
return dialog.get();
}
}
|
Swift
|
UTF-8
| 718
| 2.578125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// CachVideoTest
//
// Created by Charanbir sandhu on 28/09/20.
// Copyright © 2020 Charan Sandhu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var playerVw: UIView!
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.asyncAfter(deadline: .now()+1) {
self.setupPlayer()
}
}
private func setupPlayer() {
let url = "https://scanmedia.s3-ap-southeast-1.amazonaws.com/152_13_p_e818603f33c4472b88210f50bd77f7ea.mp4"
if let vw = Player.newPlayer(height: playerVw.frame.size.height, url: url) {
playerVw.addSubview(vw)
vw.play()
}
}
}
|
C#
|
UTF-8
| 1,014
| 3.421875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExampleProblem204_1
{
class Prgram
{
static void Main(string[] args)
{
//月を入力
Console.Write("月(1~12)を入力してください:");
int m = int.Parse(Console.ReadLine());
string d = "";
if(m >= 1 && m <= 12)
{
if(m == 2)
{
d = "28か29";
}
else if(m == 4 || m == 6 || m == 9 || m == 11)
{
d = "30";
}
else
{
d = "31";
}
Console.WriteLine("{0}月の長さは{1}日です", m, d);
}
else
{
Console.WriteLine("適切な値を入力してください");
}
}
}
}
|
JavaScript
|
UTF-8
| 2,939
| 3.390625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
function Dictionary() {
this.items = {};
};
Dictionary.prototype.containsKey = function(key) {
return exports.hasOwn(this.items, key);
};
Dictionary.prototype.set = function(key, value) {
this.items[key] = value;
};
Dictionary.prototype.get = function(key) {
return this.items[key];
};
Dictionary.prototype.removeKey = function(key) {
delete this.items[key];
};
Dictionary.prototype.keys = function() {
return exports.propertyNames(this.items);
};
Dictionary.prototype.values = function() {
return exports.propertyValues(this.items);
};
Dictionary.prototype.eachValue = function(callback) {
exports.visitPropertyValues(this.items, callback);
};
Dictionary.prototype.size = function() {
return exports.numberOfProperties(this.items);
};
function Set() {
this.elements = {};
};
Set.prototype.add = function(value) {
this.elements[value] = true;
};
Set.prototype.contains = function(value) {
return exports.hasOwn(this.elements, value);
};
Set.prototype.size = function() {
return exports.numberOfProperties(this.elements);
};
Set.prototype.values = function() {
return exports.propertyNames(this.elements);
};
exports.Dictionary = Dictionary;
exports.Set = Set;
exports.each = function(items, callback) {
for (var i = 0; i < items.length; i += 1) {
callback(items[i]);
}
};
exports.where = function(items, predicate) {
var ans = [];
exports.each(items, function(item) {
if (predicate(item)) {
ans.push(item);
}
});
return ans;
};
exports.hasOwn = function(obj, property) {
return Object.prototype.hasOwnProperty.call(obj, property);
};
exports.propertyNames = function(obj) {
return exports.visitorBuffer(obj, exports.visitPropertyNames);
};
exports.propertyValues = function(obj) {
return exports.visitorBuffer(obj, exports.visitPropertyValues);
};
exports.visitorBuffer = function(obj, visitor) {
var ans = [];
visitor(obj, function(value) {
ans.push(value);
});
return ans;
};
exports.visitPropertyNames = function(obj, callback) {
for (var property in obj) {
if (exports.hasOwn(obj, property)) {
callback(property);
}
}
};
exports.visitPropertyValues = function(obj, callback) {
exports.visitPropertyNames(obj, function(property) {
callback(obj[property]);
});
};
exports.visitPropertyPairs = function(obj, callback) {
exports.visitPropertyNames(obj, function(property) {
callback(property, obj[property]);
});
};
exports.numberOfProperties = function(obj) {
var ans = 0;
exports.visitPropertyNames(obj, function() {
ans += 1;
});
return ans;
};
exports.shuffle = function(v) {
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [rev. #1]
for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
return v;
};
|
Java
|
UTF-8
| 898
| 2.25
| 2
|
[] |
no_license
|
package htos.common.util.swftools;
import htos.common.util.FileUtilBetas;
public class DocConverter {
private PDFConverter pdfConverter;
private SWFConverter swfConverter;
public DocConverter(PDFConverter pdfConverter, SWFConverter swfConverter) {
super();
this.pdfConverter = pdfConverter;
this.swfConverter = swfConverter;
}
public void convert(String inputFile, String swfFile, String extend) {
this.pdfConverter.convert2PDF(inputFile, extend);
String pdfFile = FileUtilBetas.getFilePrefix(inputFile) + ".pdf";
this.swfConverter.convert2SWF(pdfFile, swfFile);
}
public void convert(String inputFile, String extend) {
this.pdfConverter.convert2PDF(inputFile, extend);
String pdfFile = FileUtilBetas.getFilePrefix2(inputFile) + ".pdf";
extend = FileUtilBetas.getExtend(pdfFile);
this.swfConverter.convert2SWF(pdfFile, extend);
}
}
|
Python
|
UTF-8
| 1,986
| 2.9375
| 3
|
[] |
no_license
|
## Neal Trischitta ##
#!/usr/bin/env python2.7
from sys import argv
from PIL import Image
import numpy
import math
import random
import argparse
# Return k centroids RGB triples.
def get_centroids(im,k):
cents=[]
for i in range(k):
x=random.randrange(im.size[0])
y=random.randrange(im.size[1])
cents.append(im.getpixel((x,y)))
return cents
# Finds the nearest centroid and set the custers
def argmindistance(pixel, centroids):
distance=[]
for c in centroids:
distance.append(math.sqrt((c[0]-pixel[0])**2+(c[1]-pixel[1])**2+(c[2]-pixel[2])**2))
minindex=numpy.argmin(distance)
clusters[minindex].append(pixel)
return minindex
def getAverageRGB(arr):
r = 0
g = 0
b = 0
counter=len(arr)
for x in xrange(len(arr)):
r+=arr[x][0]
g+=arr[x][1]
b+=arr[x][2]
rAvg = r/counter
gAvg = g/counter
bAvg = b/counter
return (rAvg, gAvg, bAvg)
def kmeans(im,k):
h=im.size[0]
w=im.size[1]
centroids=get_centroids(im,k)
oldcentroids= [[] for i in xrange(k)]
labels=numpy.zeros((h,w))
while not(centroids == oldcentroids):
for x in xrange(h):
for y in xrange(w):
labels[x][y]=argmindistance(im.getpixel((x,y)),centroids)
index=0
for cluster in clusters:
if(len(cluster) !=0):
oldcentroids[index] = centroids[index]
centroids[index]=getAverageRGB(cluster)
index+=1
print("Image has Coverged")
centers=numpy.array(centroids)
labels=numpy.transpose(numpy.uint8(labels))
res=centers[labels]
Image.fromarray(res.astype('uint8')).show()
# im.show()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Kmeans Clustering: Image Segmenation")
parser.add_argument('-i', '--source_img', help='Source Image', required=True)
parser.add_argument('-k', '--bin_size', type=int, help='Bin size', required=True)
args = parser.parse_args()
##Open image for processing in RGB colorspace.
im = Image.open(args.source_img).convert('RGB')
global clusters
clusters= [[] for i in range(args.bin_size)]
kmeans(im,args.bin_size)
|
C++
|
UTF-8
| 1,432
| 2.96875
| 3
|
[] |
no_license
|
#include <iostream>
#include <deque>
using namespace std;
deque<char> dq[5];
void move(int n, int d) {
if (d == 1) {
char ch = dq[n].back();
dq[n].pop_back();
dq[n].push_front(ch);
}
else {
char ch = dq[n].front();
dq[n].pop_front();
dq[n].push_back(ch);
}
}
void solve(int n, int d) {
if (n == 1) {
if (dq[1].at(2) != dq[2].at(6)) {
if (dq[2].at(2) != dq[3].at(6)) {
if (dq[3].at(2) != dq[4].at(6)) move(4, -d);
move(3, d);
}
move(2, -d);
}
move(1, d);
}
if (n == 2) {
if (dq[2].at(6) != dq[1].at(2)) move(1, -d);
if (dq[2].at(2) != dq[3].at(6)) {
if (dq[3].at(2) != dq[4].at(6)) move(4, d);
move(3, -d);
}
move(2, d);
}
if (n == 3) {
if (dq[3].at(6) != dq[2].at(2)) {
if (dq[2].at(6) != dq[1].at(2)) move(1, d);
move(2, -d);
}
if (dq[3].at(2) != dq[4].at(6)) move(4, -d);
move(3, d);
}
if (n == 4) {
if (dq[4].at(6) != dq[3].at(2)) {
if (dq[3].at(6) != dq[2].at(2)) {
if (dq[2].at(6) != dq[1].at(2)) move(1, -d);
move(2, d);
}
move(3, -d);
}
move(4, d);
}
}
int main() {
for (int i = 1; i <= 4; i++) {
for (int j = 0; j < 8; j++) {
char ch;
cin >> ch;
dq[i].push_back(ch);
}
}
int k;
cin >> k;
for (int i = 0; i < k; i++) {
int n, d;
cin >> n >> d;
solve(n, d);
}
int sum = 0, ret = 1;
for (int i = 1; i <= 4; i++) {
if (dq[i].front() == '1') sum += ret;
ret *= 2;
}
cout << sum;
return 0;
}
|
Java
|
UTF-8
| 705
| 2.140625
| 2
|
[
"MIT"
] |
permissive
|
package com.sxu.permission;
import android.app.Activity;
/*******************************************************************************
* 自定义解释申请权限和引导用户开启权限的样式
*
* @author Freeman
*
* @date 2018/11/1
*
*******************************************************************************/
public interface AlertStyle {
/**
* 实现解释权限原因的样式
* @param context
* @param reason 原因说明
*/
void onExplain(Activity context, String reason);
/**
* 实现引导用户去开启权限的样式
* @param context
* @param settingDesc 引导设置权限的描述
*/
void onSettingGuide(Activity context, String settingDesc);
}
|
C++
|
UTF-8
| 4,169
| 3.5
| 4
|
[] |
no_license
|
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <vector>
#include <list>
using namespace std;
template<typename Comparable>
class BST {
private:
//节点结构体
struct BinaryNode {
Comparable element;
BinaryNode *left;
BinaryNode *right;
BinaryNode(const Comparable & ele, BinaryNode * l, BinaryNode *r) :element(ele), left(l), right(r){}
BinaryNode(Comparable &&ele, BinaryNode *l, BinaryNode *r) : element(std::move(ele)), left(l), right(r){}
};
//私有成员为树根
BinaryNode *root;
//操作
void insert(const Comparable &x, BinaryNode *&t) {
//为空树或插入时的基准情形
if (t == nullptr)
t = new BinaryNode(x, nullptr, nullptr);
if (x < t->element)
insert(x, t->left);
else if (x > t->element)
insert(x, t->right);
else
;
}
void insert(Comparable && x, BinaryNode *& t) {
if (t == nullptr)
t = new Node(std::move(x), nullptr, nullptr);
else if (x < t->element)
insert(std::move(x), t->left);
else if (x > t->element)
insert(std::move(x), t->right);
else
;
}
void remove(Comparable &x, BinaryNode *& t) {
if (t == nullptr)
return;
if (x < t->element)//先找到要删除的项
remove(x, t->left);
else if (x > t->element)
remove(x, t->right);
/*如有两个儿子,在右树找到最小项并替代它,再删除替代项
*因右树最小项一定比左儿子大且比右儿子小
*/
else if(t->left != nullptr && t->right != nullptr){
t->element = findMin(t->right)->element;
remove(t->element, t->right);
}
/*只有一个儿子或没有儿子的情形
*如只有一个儿子则指向其儿子并释放自身
*如没有儿子则为空指针并释放
*/
else {
BinaryNode *oldNode = t;
t = (t->left != nullptr) ? t->left : t->right;
delete oldNode;
}
}
BinaryNode *findMax(BinaryNode *t) const {
//确保不为空树
if (t != nullptr)
while (t->right != nullptr)//如果有右儿子则继续找
t = t->right;
return t;
}
BinaryNode *findMin(BinaryNode *t) const {
//确保不为空树
if (t == nullptr)
return t;
if (t->left == nullptr)
return t;
//如果有左儿子则继续找
return findMin(t->left);
}
bool contains(const Comparable &x, BinaryNode *t) const {
if (t == nullprt)
return false;
else if (x < t->element)
return contains(x, t->left);
else if (x > t->element)
return contains(x, t->right);
else
return true;//基准情形,如找到则返回真
}
void makeEmpty(BinaryNode *&t) {
if (t != nullptr) {
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
t = nullptr;
}
void printTree(BinaryNode *t, int depth = 0) const {
if (t == nullptr)
return;
for (int i = 0; i < depth; i++)
cout << " ";
cout << t->element << endl;
printTree(t->left, depth + 1);
printTree(t->right, depth + 1);
}
BinaryNode *clone(BinaryNode *t) const {
if (t == nullptr)
return nullptr;
else
return new BinaryNode(t->element, clone(e->left), clone(t->right));
}
public:
BST() {
root = nullptr;
}
BST(const BST &rhs) {
root = clone(rhs.root);
}
~BST() {
makeEmpty(root);
}
const Comparable &findMax() const {
return findMax(root)->element;
}
const Comparable &findMin() const {
return findMin(root)->element;
}
bool contains(const Comparable &x) const {
return contains(x, root);
}
bool isEmpty() const {
if (root == nullptr)
return true;
else
return false;
}
void printTree() const {
printTree(root);
}
void makeEmpty() {
makeEmpty(root);
}
void insert(const Comparable &x) {
insert(x, root);
}
void insert(Comparable &&x) {
insert(x, root);
}
void remove(const Comparable &x) {
remove(x, root);
}
BST &operator=(const BST &rhs);
BST &operator=(BST &&rhs);
};
int main()
{
BST<int> tree;
tree.insert(6);
tree.insert(8);
tree.insert(2);
tree.insert(1);
tree.insert(5);
tree.insert(3);
tree.insert(4);
tree.printTree();
return 0;
}
|
Java
|
UTF-8
| 1,963
| 2.625
| 3
|
[] |
no_license
|
package sample;
import leit.flug.Schedule;
import leit.flug.ScheduledFlight;
import leit.flug.DatabaseManager;
import leit.flug.Flight;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Flights {
public static void AllFlights() {
Schedule lol = new Schedule();
DatabaseManager hl = new DatabaseManager();
//ScheduledFlight[] hello = lol.searchFlights("RKV", "GJR", "2019-1-3");
//Flight realflight = hello[0].getFlight();
//System.out.println(realflight.getTripPrice());
// Flight[] flights = hl.getFlights();
//System.out.println(flights[30]);
// ScheduledFlight[] helleo = lol.searchFlightss();
// ScheduledFlight[] hlll = hl.getScheduledFlights();
//int i;
//for (i = 0; i < flights.length; i++) {
// System.out.println(flights[i]);
// }
}
public static void AllPrufa() {
JSONParser parser = new JSONParser();
List<Flight> flightList = new ArrayList<>();
try {
Object obj = parser.parse(new FileReader("src/leit/flug/resources/Database.txt"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray flights = (JSONArray) jsonObject.get("Flights");
for (int i = 0; i < flights.size(); i++) {
JSONObject flightObj = (JSONObject) flights.get(i);
System.out.print(flightObj.get("DepartureAirport")+(" til "));
System.out.println(flightObj.get("ArrivalAirport"));
}
}
catch (IOException | ParseException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// Flights.AllFlights();
// Flights.AllPrufa();
}
}
|
Python
|
UTF-8
| 4,793
| 4
| 4
|
[] |
no_license
|
'''--- Day 10: Balance Bots ---
You come upon a factory in which many robots are zooming around handing small microchips to each other.
Upon closer examination, you notice that each bot only proceeds when it has two microchips, and once it does, it gives each one to a different bot or puts it in a marked "output" bin. Sometimes, bots take microchips from "input" bins, too.
Inspecting one of the microchips, it seems like they each contain a single number; the bots must use some logic to decide what to do with each chip. You access the local control computer and download the bots' instructions (your puzzle input).
Some of the instructions specify that a specific-valued microchip should be given to a specific bot; the rest of the instructions indicate what a given bot should do with its lower-value or higher-value chip.
For example, consider the following instructions:
value 5 goes to bot 2
bot 2 gives low to bot 1 and high to bot 0
value 3 goes to bot 1
bot 1 gives low to output 1 and high to bot 0
bot 0 gives low to output 2 and high to output 0
value 2 goes to bot 2
Initially, bot 1 starts with a value-3 chip, and bot 2 starts with a value-2 chip and a value-5 chip.
Because bot 2 has two microchips, it gives its lower one (2) to bot 1 and its higher one (5) to bot 0.
Then, bot 1 has two microchips; it puts the value-2 chip in output 1 and gives the value-3 chip to bot 0.
Finally, bot 0 has two microchips; it puts the 3 in output 2 and the 5 in output 0.
In the end, output bin 0 contains a value-5 microchip, output bin 1 contains a value-2 microchip, and output bin 2 contains a value-3 microchip. In this configuration, bot number 2 is responsible for comparing value-5 microchips with value-2 microchips.
Based on your instructions, what is the number of the bot that is responsible for comparing value-61 microchips with value-17 microchips?
'''
from collections import defaultdict
from collections import Counter
class Instruction():
def __init__(self, low, high):
self.low = low
self.high = high
def __str__(self):
return str(self.low) + ", " + str(self.high)
def __repr__(self):
return str(self.low) + ", " + str(self.high)
class Bot(object):
def __init__(self, chip1=None, chip2=None, instruction=None):
self._chip_counter = Counter() #empty Counter of chips.
if chip1: self._chip_counter[chip1] = 1
if chip2: self._chip_counter[chip2] = 1
self.instruction = instruction
#self.name = name
def chips(self):
return str(self._chip_counter)
def num_chips(self):
return len(self._chip_counter) # a bin should hever have more than one value chip...
def __str__(self):
return "Bot has chips {} and instruction {}".format(self._chip_counter.keys(), self.instruction)
def __repr__(self):
return "Bot has chips {} and instruction {}".format(self._chip_counter.keys(), self.instruction)
def pop_chip(self):
return self._chip_counter.popitem()[0] #just return "key" aka "chip value"
def receive_chip(self, value):
self._chip_counter[value] += 1 # key is "chip value"
def bot_to_process(bot_bank):
"""
returns set of bots with 2 chips to process
"""
set_of_bots = {0}-{0}
for robot in bot_bank:
if bot_bank[robot].num_chips() == 2:
#print("Bot {} will do work".format(robot))
set_of_bots.add(robot)
return set_of_bots
def do_work(botname, bot_bank):
chip1 = bot_bank[botname].pop_chip()
chip2 = bot_bank[botname].pop_chip()
if chip1 == 61 and chip2 == 17: print(botname)
elif chip2 == 61 and chip1 == 17: print(botname)
if chip1 < chip2:
bot_bank[bot_bank[botname].instruction.low].receive_chip(chip1)
bot_bank[bot_bank[botname].instruction.high].receive_chip(chip2)
else:
bot_bank[bot_bank[botname].instruction.low].receive_chip(chip2)
bot_bank[bot_bank[botname].instruction.high].receive_chip(chip1)
if __name__ == "__main__":
with open("day10input.txt") as fp:
set_of_bots = {'na'}
instructions = fp.readlines()
bot_bank = defaultdict(Bot)
for line in instructions:
chunk = line.rstrip("\n").split(" ")
if len(chunk) == 6:
value = int(chunk[1])
botname = "bot " + chunk[5]
bot_bank[botname].receive_chip(value)
elif len(chunk) == 12:
botname = "bot " + chunk[1]
low = chunk[5] + " " + chunk[6] # first item is bot/bin , 2nd is name
high = chunk[10] + " " + chunk[11]
bot_bank[botname].instruction = Instruction(low, high)
#print(bot_bank)
while len(set_of_bots) > 0:
set_of_bots = bot_to_process(bot_bank)
#print(set_of_bots)
for robot in set_of_bots:
do_work(robot, bot_bank)
set_of_bots = bot_to_process(bot_bank)
#print(bot_bank)
|
Java
|
UTF-8
| 3,724
| 2.25
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.jgrades.lic.service;
import com.google.common.collect.Lists;
import org.jgrades.lic.api.model.Licence;
import org.jgrades.lic.api.model.LicenceProperty;
import org.jgrades.lic.api.model.Product;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class DateRuleTest {
private DateRule dateRule;
private Licence licence;
private DateTime dateTimeNow;
@Before
public void setUp() throws Exception {
dateRule = new DateRule();
licence = new Licence();
dateTimeNow = DateTime.now();
}
@Test
public void shouldValid_whenNowIsBetweenDateTimes_andExpiredDaysModeIsDisabled() throws Exception {
// given
licence.setProduct(getProduct(dateTimeNow.minusDays(1), dateTimeNow.plusDays(1)));
licence.setProperties(Lists.newArrayList());
// when
boolean isValid = dateRule.isValid(licence);
// then
assertThat(isValid).isTrue();
}
@Test
public void shouldValid_whenNowIsAfterFinishDate_andExpiredDaysModeIsEnabled_andActive() throws Exception {
// given
licence.setProduct(getProduct(dateTimeNow.minusDays(3), dateTimeNow.minusDays(1)));
licence.setProperties(getExpiredDaysProperty(2));
// when
boolean isValid = dateRule.isValid(licence);
// then
assertThat(isValid).isTrue();
}
@Test
public void shouldNotValid_whenNowIsBeforeStartDate_andExpiredDaysModeIsDisabled() throws Exception {
// given
licence.setProduct(getProduct(dateTimeNow.plusDays(1), dateTimeNow.plusDays(5)));
licence.setProperties(Lists.newArrayList());
// when
boolean isValid = dateRule.isValid(licence);
// then
assertThat(isValid).isFalse();
}
@Test
public void shouldNotValid_whenNowIsBeforeStartDate_andExpiredDaysModeIsEnabled_andActive() throws Exception {
// given
licence.setProduct(getProduct(dateTimeNow.plusHours(1), dateTimeNow.plusHours(2)));
licence.setProperties(getExpiredDaysProperty(14));
// when
boolean isValid = dateRule.isValid(licence);
// then
assertThat(isValid).isFalse();
}
@Test
public void shouldNotValid_whenNowIsAfterEndDate_andExpiredDaysModeIsDisabled() throws Exception {
// given
licence.setProduct(getProduct(dateTimeNow.minusDays(14), dateTimeNow.minusDays(7)));
licence.setProperties(Lists.newArrayList());
// when
boolean isValid = dateRule.isValid(licence);
// then
assertThat(isValid).isFalse();
}
@Test
public void shouldNotValid_whenNowIsAfterEndDate_andExpiredDaysModeIsEnabled_butNotActive() throws Exception {
// given
licence.setProduct(getProduct(dateTimeNow.minusDays(14), dateTimeNow.minusDays(7)));
licence.setProperties(getExpiredDaysProperty(3));
// when
boolean isValid = dateRule.isValid(licence);
// then
assertThat(isValid).isFalse();
}
private Product getProduct(DateTime validFrom, DateTime validTo) {
Product product = new Product();
product.setName("JG-BASE");
product.setValidFrom(validFrom);
product.setValidTo(validTo);
product.setVersion("0.4");
return product;
}
private List<LicenceProperty> getExpiredDaysProperty(int days) {
LicenceProperty property = new LicenceProperty();
property.setName("expiredDays");
property.setValue(Integer.toString(days));
return Lists.newArrayList(property);
}
}
|
PHP
|
UTF-8
| 1,164
| 2.828125
| 3
|
[] |
no_license
|
<?php
namespace Wead\ZipCode\WS;
use Wead\ZipCode\Contracts\ProviderContract;
class ApiCEP extends ProviderContract
{
public function getAddressFromZipcode($zipCode)
{
$zipCode = preg_replace('/[^0-9]/im', '', $zipCode);
$endPoint = "https://ws.apicep.com/cep/{$zipCode}.json";
$content = file_get_contents($endPoint);
$response = json_decode($content);
return $this->normalizeResponse((array)$response);
}
private function normalizeResponse($address)
{
if (sizeof($address) > 0 && strlen($address['address']) > 0) {
return [
"status" => true,
"address" => $address["address"],
"district" => $address["district"],
"city" => $address["city"],
"state" => $address["state"],
"api" => "ApiCEP"
];
} else {
return [
"status" => false,
"address" => null,
"district" => null,
"city" => null,
"state" => null,
"api" => "ApiCEP"
];
}
}
}
|
PHP
|
UTF-8
| 3,485
| 2.578125
| 3
|
[] |
no_license
|
<?php
if (isset($_POST['addItem'])) {
//Category
$category = $_POST['itemCategory']; //Remove html tags
//Title
$title = strip_tags($_POST['itemTitle']); //Remove html tags
$title = ucfirst(strtolower($title)); //Uppercase first letter
//Item Name
$itemName = strip_tags($_POST['itemName']); //Remove html tags
$itemName = ucfirst(strtolower($itemName)); //Uppercase first letter
//Item Price
$itemPrice = strip_tags($_POST['itemPrice']); //Remove html tags
$itemPrice = str_replace(' ', '', $itemPrice); //remove spaces
$itemPrice = ucfirst(strtolower($itemPrice)); //Uppercase first letter
//Item Duration
$itemDuration = $_POST['itemDuration']; //Remove html tags
//Item Age
$itemAge = strip_tags($_POST['itemAge']); //Remove html tags
//Item Condition
$itemCondition = strip_tags($_POST['itemCondition']); //Remove html tags
//Item Description
$itemDescription = strip_tags($_POST['itemDescription']); //Remove html tags
$itemDescription = ucfirst(strtolower($itemDescription)); //Uppercase first letter
//Item Field
$itemField = $_POST['itemField'];
$itemField = implode( ',', $itemField );
$user = $_SESSION['email'];
$product_query = $con->prepare("INSERT INTO product VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?, 'Available', '', ?, ?)");
$product_query->bind_param("sssssdiiii", $title, $itemName, $itemDescription, $itemAge, $itemField, $itemPrice, $category, $itemCondition, $_SESSION['user_id'], $itemDuration);
$product_query->execute();
// File upload configuration
$targetDir = "../images/";
$allowTypes = array('jpg', 'png', 'jpeg');
$statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
$fileNames = array_filter($_FILES['itemImage']['name']);
$last_id = $con->insert_id;
if (!empty($fileNames)) {
foreach ($_FILES['itemImage']['name'] as $key => $val) {
// File upload path
$fileName = basename($_FILES['itemImage']['name'][$key]);
$targetFilePath = $targetDir . $fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
if (in_array($fileType, $allowTypes)) {
// Upload file to server
if (move_uploaded_file($_FILES["itemImage"]["tmp_name"][$key], $targetFilePath)) {
// Image db insert sql
$insertValuesSQL .= "('" . $fileName . "', '" . $last_id . "'),";
} else {
$errorUpload .= $_FILES['itemImage']['name'][$key] . ' | ';
}
} else {
$errorUploadType .= $_FILES['itemImage']['name'][$key] . ' | ';
}
}
if (!empty($insertValuesSQL)) {
$insertValuesSQL = trim($insertValuesSQL, ',');
// Insert image file name into database
$insert = $con->query("INSERT INTO product_image (source, product_id) VALUES $insertValuesSQL");
if ($insert) {
$errorUpload = !empty($errorUpload) ? 'Upload Error: ' . trim($errorUpload, ' | ') : '';
$errorUploadType = !empty($errorUploadType) ? 'File Type Error: ' . trim($errorUploadType, ' | ') : '';
$errorMsg = !empty($errorUpload) ? '<br/>' . $errorUpload . '<br/>' . $errorUploadType : '<br/>' . $errorUploadType;
}
}
}
}
|
Markdown
|
UTF-8
| 1,153
| 2.96875
| 3
|
[] |
no_license
|
# L'Usine
Site en production: [usine.ch](https://usine.ch)
Une version de développement est disponible: [dev.usine.ch](https://dev.usine.ch).
## Contribuer
[Comment contribuer au site de L'Usine](https://dev.usine.ch/contribuer)
## Développement local
**Prérequis**
- git
- php
**1. Cloner le site en local**
```sh
git clone git@github.com:usine/usine.ch.git
cd usine.ch
```
**2. Installer les dépendances**
```sh
composer install
```
**3. Préparer la base de données**
Créer une base de données MySQL avec les accès corrects
**4. .env**
Dupliquer le fichier `.env.example` en `.env` et remplir les différentes variables.
Pour la variable APP_KEY, vous pouvez utiliser la commande suivante:
```sh
php artisan key:generate
```
**5. Migration**
Lancer les migrations de la base de données.
Avec données de test:
```sh
php artisan migrate:fresh --seed
```
Sans données de test:
```sh
php artisan migrate:fresh
```
**6. Création d'un premier utilisateur**
```sh
php artisan tinker
```
Puis, en remplaçant les valeurs:
```
DB::table('users')->insert(['name'=>'name','email'=>'email@example.com','password'=>Hash::make('password')])
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.