blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7968f1351079623e5cb4c83d6a20bfde74caff03 | f1c50db4786ac945c7da4f44e728a3bee0e84378 | /Hanoi/pointer.h | f453f36010ce1962928d8f2ffaf699586ca00e25 | [] | no_license | ddodds399/Tower-of-Hanoi | d87bcc7286b7e7396404fd90d8ebf45954d809e1 | b6470cc4f6b48b92ba5f278b1c1934156f7793da | refs/heads/master | 2021-01-20T19:56:38.475244 | 2016-06-19T19:11:23 | 2016-06-19T19:11:23 | 61,495,781 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,218 | h | #ifndef POINTER_H
#define POINTER_H
#include "transform.h"
#include "mesh.h"
#include <GL\glew.h>
//Pointer Object
class Pointer
{
public:
//Constructor sets mesh to the pointer.obj in resources and initialises it position variable.
Pointer() {
point.setMesh("./res/models/pointer.obj");
currPos = 1;
}
//Calls the mesh draw method
void Draw() {
point.Draw();
}
//Gets transformation matrix of mesh
inline Transform GetTransformMat() { return transformP; }
//Sets global position in world co-ordinates
void SetPos(float x, float y, float z) {
transformP.SetPos(glm::vec3(x, y, z));
}
//Sets x position
void SetPosx(float x) {
transformP.GetPos().x = x;
}
//Sets y position
void SetPosy(float y) {
transformP.GetPos().y = y;
}
//Sets z position
void SetPosz(float z) {
transformP.GetPos().z = z;
}
//Sets scale of mesh
void SetScale(float scale) {
transformP.SetScale(glm::vec3(scale, scale, scale));
}
//Returns refernce of current position, can be used to set.
inline int &GetCurrPos() { return currPos; }
protected:
private:
Pointer(const Pointer& other) {}
void operator=(const Pointer& other) {}
Mesh point;
Transform transformP;
int currPos;
};
#endif //POINTER_H | [
"dddodds@hotmail.co.uk"
] | dddodds@hotmail.co.uk |
40f1abcc35f3ee51bc002feeb179935d28afca35 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_4176_git-2.13.1.cpp | 1b05f28df68e132216236287810d64c996ddd149 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 629 | cpp | static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
{
const char *error;
int erroffset;
int options = PCRE_MULTILINE;
if (opt->ignore_case) {
if (has_non_ascii(p->pattern))
p->pcre_tables = pcre_maketables();
options |= PCRE_CASELESS;
}
if (is_utf8_locale() && has_non_ascii(p->pattern))
options |= PCRE_UTF8;
p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
p->pcre_tables);
if (!p->pcre_regexp)
compile_regexp_failed(p, error);
p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
if (!p->pcre_extra_info && error)
die("%s", error);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
535e077037176f84ffad44125e457f46f169fbd5 | f520fb1d1a66ae8c2837c1d34b2436535596035d | /drone_v0/src/library/tranformVar/transformVar.cpp | 700a30ba8e489919ae375e7a759fb5cdca0d5c1f | [] | no_license | danielggc/avrProjec | eccc89ff9aa6fdcb84de7052e4a5ce62f5ca8664 | 756245c8c83ecdc67cf041eab55a9d1d55cf5a64 | refs/heads/master | 2023-04-05T00:19:08.210760 | 2021-01-09T19:55:02 | 2021-01-09T19:55:02 | 286,812,545 | 0 | 0 | null | 2020-11-04T17:27:35 | 2020-08-11T17:55:54 | C++ | UTF-8 | C++ | false | false | 2,769 | cpp | #include "transformVar.hpp"
#include "../UART/UART.hpp"
int int_to_binario(int8_t numero){
UART pantalla1;
pantalla1.uart_init();
for(int i=7;i!=-1;i--){
if(numero & (1<<i)){
pantalla1.USART0SendByte('1');
}
else{
pantalla1.USART0SendByte('0');
}
}
pantalla1.USART0SendByte('\n');
}
int char_to_int(char *direccionCaracter){
UART pantalla1;
long numero=0;
int contador=0;
pantalla1.USART0SendByte('\n');
while (*direccionCaracter!=' '){
pantalla1.USART0SendByte(*direccionCaracter);
direccionCaracter++;
contador++;
}
pantalla1.USART0SendByte('\n');
direccionCaracter--;
int multiplicador=10;
for(int a=0;a<contador;a++){
if(a==0){
numero=(*direccionCaracter-'0');
}
else
{
numero=(*direccionCaracter-'0')*multiplicador+numero;
multiplicador=multiplicador*10;
}
direccionCaracter--;
}
pantalla1.USART0SendByte('\n');
char dato[6];
char *direcciondato=&dato[0];
int largo=numeroUnidades(numero);
int_to_char(numero,direcciondato,largo);
for(int d=0;d<largo;d++){
pantalla1.USART0SendByte(dato[d]);
}
pantalla1.USART0SendByte('\n');
return numero;
}
long numeroUnidades(long _numero){
long numero=_numero;
int contador=0;
if (numero==0){
return 1;
}
else{
if(numero<0){
numero=numero*-1;
contador++;
}
while (numero>0){
numero=numero/10;
contador++;
}
return contador++;
}
}
void int_to_char(int _numero ,char* cadenaChar , int largo){
UART pantalla1;
pantalla1.uart_init();
int contador=0;
long numero=_numero;
bool banderaSigno=true;
if(numero<0){
numero=numero*-1;
banderaSigno=false;
}
if(largo>0){
long respaldo=numero;
respaldo=numero;
int d=largo-1;
int inicio=largo-1;
long divisor=1;
for(;d>-1;d--){
for(int i=0;i<d;i++){
divisor=divisor*10;
}
long respaldoResta=respaldo;
respaldo=numero/divisor;
if(d==inicio){
cadenaChar[contador]=respaldo+'0';
}
else{
long resta=(respaldoResta*10);
long numeroSeparado=respaldo-resta;
cadenaChar[contador]=numeroSeparado+'0';
_delay_ms(100);
}
contador++;
divisor=1;
}
}
if(banderaSigno==false)cadenaChar[1]='-';
else if(largo==0){
cadenaChar[0]=numero;
}
} | [
"danielgrecia7@gmail.com"
] | danielgrecia7@gmail.com |
250346fe0d7dbb8e1a8e0d45d2313baac5065ec5 | 1a2b0004be47ec7572448ca16a04b59eaaf5103c | /src/mp_betting_tree.cpp | b78f865bf7bde69a3332db011be17765d1c73e1b | [
"MIT"
] | permissive | zhanjunxiong/slumbot2019 | 15e87fc8ebbbc1a022d05980225ce3246c2adad0 | a1b65b84c89ab2eff9e2e0c16cedcfcbd479dffd | refs/heads/master | 2023-08-21T10:30:51.475541 | 2021-10-21T23:45:59 | 2021-10-21T23:45:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,538 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "betting_abstraction.h"
#include "betting_tree_builder.h"
#include "betting_tree.h"
#include "fast_hash.h"
#include "game.h"
using std::shared_ptr;
using std::string;
using std::unique_ptr;
using std::unordered_map;
using std::vector;
static void AddStringToKey(const string &s, string *key) {
*key += s;
}
static void AddIntToKey(int i, string *key) {
char buf[10];
sprintf(buf, "%i", i);
*key += buf;
}
static unsigned long long int HashKey(const string &key) {
return fasthash64((void *)key.c_str(), key.size(), 0);
}
bool BettingTreeBuilder::FindReentrantNode(const string &key, shared_ptr<Node> *node) {
unordered_map< unsigned long long int, shared_ptr<Node> >::iterator it;
unsigned long long int h = HashKey(key);
it = node_map_->find(h);
if (it != node_map_->end()) {
*node = it->second;
return true;
} else {
return false;
}
}
void BettingTreeBuilder::AddReentrantNode(const string &key, shared_ptr<Node> node) {
unsigned long long int h = HashKey(key);
(*node_map_)[h] = node;
}
// Determine the next player to act, taking into account who has folded.
// Pass in first candidate for next player to act.
static int NextPlayerToAct(int p, bool *folded) {
int num_players = Game::NumPlayers();
while (folded[p]) {
p = (p + 1) % num_players;
}
return p;
}
void BettingTreeBuilder::GetAllowableBetTos(int old_bet_to, int last_bet_size, bool *bet_to_seen) {
int stack_size = betting_abstraction_.StackSize();
int min_bet;
if (last_bet_size == 0) {
min_bet = betting_abstraction_.MinBet();
} else {
min_bet = last_bet_size;
}
for (int bet_to = old_bet_to + min_bet; bet_to <= stack_size; ++bet_to) {
if (betting_abstraction_.AllowableBetTo(bet_to)) {
bet_to_seen[bet_to] = true;
}
}
}
shared_ptr<Node>
BettingTreeBuilder::CreateMPFoldSucc(int street, int last_bet_size, int bet_to, int num_street_bets,
int num_bets, int player_acting, int num_players_to_act,
bool *folded, int target_player, string *key,
int *terminal_id) {
shared_ptr<Node> fold_succ;
int max_street = Game::MaxStreet();
int num_players = Game::NumPlayers();
int num_players_remaining = 0;
for (int p = 0; p < num_players; ++p) {
if (! folded[p]) ++num_players_remaining;
}
if (num_players_remaining <= 1) {
fprintf(stderr, "CreateMPFoldSucc npr %u?!?\n", num_players_remaining);
exit(-1);
}
string new_key = *key;
if (betting_abstraction_.BettingKey(street)) {
AddStringToKey("f", &new_key);
}
if (num_players_remaining == 2) {
// This fold completes the hand
int p;
for (p = 0; p < num_players; ++p) {
if (! folded[p] && p != player_acting) break;
}
if (p == num_players) {
fprintf(stderr, "Everyone folded?!?\n");
fprintf(stderr, "street %u\n", street);
fprintf(stderr, "num_players_to_act %u\n", num_players_to_act);
exit(-1);
}
// Subtract last_bet_size from bet_to so that we get the last amount
// of chips that the last opponent put in. Not sure this is useful
// though, for multiplayer.
fold_succ.reset(new Node((*terminal_id)++, street, p, nullptr, nullptr, nullptr, 1,
bet_to - last_bet_size));
} else if (num_players_to_act == 1 && street == max_street) {
// Showdown
fold_succ.reset(new Node((*terminal_id)++, street, 255, nullptr, nullptr, nullptr,
num_players_remaining - 1, bet_to));
} else {
// Hand is not over
unique_ptr<bool []> new_folded(new bool[num_players]);
for (int p = 0; p < num_players; ++p) {
new_folded[p] = folded[p];
}
new_folded[player_acting] = true;
if (num_players_to_act == 1) {
// This fold completes the street
fold_succ = CreateMPStreet(street + 1, bet_to, num_bets, new_folded.get(), target_player,
&new_key, terminal_id);
} else {
// This is a fold that does not end the street
int next_player_to_act =
NextPlayerToAct((player_acting + 1) % num_players, new_folded.get());
fold_succ = CreateMPSubtree(street, last_bet_size, bet_to, num_street_bets, num_bets,
next_player_to_act, num_players_to_act - 1, new_folded.get(),
target_player, &new_key, terminal_id);
}
}
return fold_succ;
}
// num_players_to_act is (re)initialized when a player bets. It gets
// decremented every time a player calls or folds. When it reaches zero
// the action on the current street is complete.
shared_ptr<Node> BettingTreeBuilder::CreateMPCallSucc(int street, int last_bet_size, int bet_to,
int num_street_bets, int num_bets,
int player_acting, int num_players_to_act,
bool *folded, int target_player,
string *key, int *terminal_id) {
bool advance_street = (num_players_to_act == 1);
shared_ptr<Node> call_succ;
int max_street = Game::MaxStreet();
int num_players = Game::NumPlayers();
int num_players_remaining = 0;
for (int p = 0; p < num_players; ++p) {
if (! folded[p]) ++num_players_remaining;
}
if (folded[player_acting]) {
fprintf(stderr, "CreateMPCallSucc: Player already folded\n");
exit(-1);
}
if (num_players_to_act == 0) exit(-1);
if (num_players_to_act > 1000000) exit(-1);
if (num_players_to_act > num_players_remaining) exit(-1);
string new_key = *key;
if (betting_abstraction_.BettingKey(street)) {
AddStringToKey("c", &new_key);
}
if (street < max_street && advance_street) {
// Call completes action on current street.
call_succ = CreateMPStreet(street + 1, bet_to, num_bets, folded,
target_player, &new_key, terminal_id);
} else if (! advance_street) {
// This is a check or call that does not advance the street
int next_player_to_act =
NextPlayerToAct((player_acting + 1) % num_players, folded);
// Shouldn't happen
if (next_player_to_act == player_acting) exit(-1);
call_succ = CreateMPSubtree(street, 0, bet_to, num_street_bets, num_bets, next_player_to_act,
num_players_to_act - 1, folded, target_player, &new_key,
terminal_id);
} else {
// This is a call on the final street
call_succ.reset(new Node((*terminal_id)++, street, 255, nullptr, nullptr, nullptr,
num_players_remaining, bet_to));
}
return call_succ;
}
// We are contemplating adding a bet. We might or might not be facing a previous bet.
void BettingTreeBuilder::MPHandleBet(int street, int last_bet_size, int last_bet_to, int new_bet_to,
int num_street_bets, int num_bets, int player_acting,
int num_players_to_act, bool *folded, int target_player,
string *key, int *terminal_id,
vector< shared_ptr<Node> > *bet_succs) {
// New bet must be of size greater than zero
if (new_bet_to <= last_bet_to) return;
int new_bet_size = new_bet_to - last_bet_to;
int stack_size = betting_abstraction_.StackSize();
bool all_in_bet = (new_bet_to == stack_size);
// Cannot make a bet that is smaller than the min bet (usually the big blind)
if (new_bet_size < betting_abstraction_.MinBet() && ! all_in_bet) {
return;
}
// In general, cannot make a bet that is smaller than the previous bet size. Exception is that
// you can always raise all-in
if (new_bet_size < last_bet_size && ! all_in_bet) {
return;
}
// If CloseToAllInFrac is set, eliminate some bet sizes that are too close to an all-in bet.
int new_pot_size = new_bet_to * 2;
if (! all_in_bet && betting_abstraction_.CloseToAllInFrac() > 0 &&
new_pot_size >= 2 * stack_size * betting_abstraction_.CloseToAllInFrac()) {
return;
}
string new_key = *key;
if (betting_abstraction_.BettingKey(street)) {
AddStringToKey("b", &new_key);
AddIntToKey(new_bet_size, &new_key);
}
int num_players = Game::NumPlayers();
int num_players_remaining = 0;
for (int p = 0; p < num_players; ++p) {
if (! folded[p]) ++num_players_remaining;
}
int next_player_to_act =
NextPlayerToAct((player_acting + 1) % num_players, folded);
// Shouldn't happen
if (num_players_remaining == 1) {
fprintf(stderr, "Only one player remaining after bet?!?\n");
exit(-1);
}
// For bets we pass in the pot size without the pending bet included
shared_ptr<Node> bet =
CreateMPSubtree(street, new_bet_size, new_bet_to, num_street_bets + 1, num_bets + 1,
next_player_to_act, num_players_remaining - 1, folded, target_player,
&new_key, terminal_id);
bet_succs->push_back(bet);
}
// last_bet_size is the *size* of the last bet. Needed to ensure raises
// are legal. bet_to is what the last bet was *to*.
void BettingTreeBuilder::CreateMPSuccs(int street, int last_bet_size, int bet_to,
int num_street_bets, int num_bets, int player_acting,
int num_players_to_act, bool *folded, int target_player,
string *key, int *terminal_id, shared_ptr<Node> *call_succ,
shared_ptr<Node> *fold_succ,
vector< shared_ptr<Node> > *bet_succs) {
if (folded[player_acting]) {
fprintf(stderr, "CreateMPSuccs: Player already folded\n");
exit(-1);
}
bet_succs->clear();
*call_succ = CreateMPCallSucc(street, last_bet_size, bet_to, num_street_bets, num_bets,
player_acting, num_players_to_act, folded, target_player, key,
terminal_id);
// Allow fold if num_street_bets > 0 OR this is the very first action of
// the hand (i.e., the small blind can open fold).
// Preflop you can fold when num_street_bets is zero if
bool can_fold = (num_street_bets > 0);
if (! can_fold && street == 0) {
// Special case for the preflop. When num_street_bets is zero, everyone
// except the big blind can still fold. The big blind is the player
// prior to the player who is first to act.
int fta = Game::FirstToAct(0);
int bb;
if (fta == 0) bb = Game::NumPlayers() - 1;
else bb = fta - 1;
can_fold = (player_acting != bb);
}
if (can_fold) {
*fold_succ = CreateMPFoldSucc(street, last_bet_size, bet_to, num_street_bets, num_bets,
player_acting, num_players_to_act, folded, target_player, key,
terminal_id);
}
bool our_bet = (target_player == player_acting);
int all_in_bet_to = betting_abstraction_.StackSize();
unique_ptr<bool []> bet_to_seen(new bool[all_in_bet_to + 1]);
for (int bt = 0; bt <= all_in_bet_to; ++bt) bet_to_seen[bt] = false;
if (betting_abstraction_.AllowableBetTosSpecified()) {
if (num_street_bets < betting_abstraction_.MaxBets(street, our_bet)) {
GetAllowableBetTos(bet_to, last_bet_size, bet_to_seen.get());
}
} else {
if (num_street_bets < betting_abstraction_.MaxBets(street, our_bet)) {
if ((! betting_abstraction_.Asymmetric() && betting_abstraction_.AlwaysAllIn()) ||
(betting_abstraction_.Asymmetric() && our_bet && betting_abstraction_.OurAlwaysAllIn()) ||
(betting_abstraction_.Asymmetric() && ! our_bet && betting_abstraction_.OppAlwaysAllIn())) {
// Allow an all-in bet
bet_to_seen[all_in_bet_to] = true;
}
}
if (num_street_bets < betting_abstraction_.MaxBets(street, our_bet)) {
if ((! betting_abstraction_.Asymmetric() &&
betting_abstraction_.AlwaysMinBet(street, num_street_bets)) ||
(betting_abstraction_.Asymmetric() && our_bet &&
betting_abstraction_.OurAlwaysMinBet(street, num_street_bets)) ||
(betting_abstraction_.Asymmetric() && ! our_bet &&
betting_abstraction_.OppAlwaysMinBet(street, num_street_bets))) {
// Allow a min bet
int min_bet;
if (num_street_bets == 0) {
min_bet = betting_abstraction_.MinBet();
} else {
min_bet = last_bet_size;
}
int new_bet_to = bet_to + min_bet;
if (new_bet_to > all_in_bet_to) {
bet_to_seen[all_in_bet_to] = true;
} else {
if (betting_abstraction_.AllowableBetTo(new_bet_to)) {
bet_to_seen[new_bet_to] = true;
} else {
int old_pot_size = 2 * bet_to;
int nearest_allowable_bet_to =
NearestAllowableBetTo(old_pot_size, new_bet_to, last_bet_size);
bet_to_seen[nearest_allowable_bet_to] = true;
#if 0
if (nearest_allowable_bet_to != new_bet_to) {
fprintf(stderr, "Changed %u to %u\n", new_bet_to - bet_to,
nearest_allowable_bet_to - bet_to);
}
#endif
}
}
}
}
if (num_street_bets < betting_abstraction_.MaxBets(street, our_bet)) {
const vector<double> &pot_fracs =
betting_abstraction_.BetSizes(street, num_street_bets, our_bet, player_acting);
GetNewBetTos(bet_to, last_bet_size, pot_fracs, player_acting, target_player,
bet_to_seen.get());
}
}
for (int new_bet_to = 0; new_bet_to <= all_in_bet_to; ++new_bet_to) {
if (bet_to_seen[new_bet_to]) {
MPHandleBet(street, last_bet_size, bet_to, new_bet_to, num_street_bets, num_bets,
player_acting, num_players_to_act, folded, target_player, key, terminal_id,
bet_succs);
}
}
}
shared_ptr<Node>
BettingTreeBuilder::CreateMPSubtree(int st, int last_bet_size, int bet_to, int num_street_bets,
int num_bets, int player_acting, int num_players_to_act,
bool *folded, int target_player, string *key,
int *terminal_id) {
if (folded[player_acting]) {
fprintf(stderr, "CreateMPSubtree: Player already folded\n");
exit(-1);
}
string final_key;
bool merge = false;
// As it stands, we don't encode which players have folded. But we do
// encode num_players_to_act.
int num_players = Game::NumPlayers();
int num_rem = 0;
for (int p = 0; p < num_players; ++p) {
if (! folded[p]) ++num_rem;
}
if (betting_abstraction_.ReentrantStreet(st) &&
2 * bet_to >= betting_abstraction_.MinReentrantPot() &&
num_bets >= betting_abstraction_.MinReentrantBets(st, num_rem)) {
merge = true;
final_key = *key;
AddStringToKey(":", &final_key);
AddIntToKey(st, &final_key);
AddStringToKey(":", &final_key);
AddIntToKey(player_acting, &final_key);
AddStringToKey(":", &final_key);
AddIntToKey(num_street_bets, &final_key);
AddStringToKey(":", &final_key);
AddIntToKey(bet_to, &final_key);
AddStringToKey(":", &final_key);
AddIntToKey(last_bet_size, &final_key);
AddStringToKey(":", &final_key);
AddIntToKey(num_rem, &final_key);
AddStringToKey(":", &final_key);
AddIntToKey(num_players_to_act, &final_key);
// fprintf(stderr, "Key: %s\n", final_key.c_str());
shared_ptr<Node> node;
if (FindReentrantNode(final_key, &node)) {
return node;
}
}
shared_ptr<Node> call_succ;
shared_ptr<Node> fold_succ;
vector< shared_ptr<Node> > bet_succs;
CreateMPSuccs(st, last_bet_size, bet_to, num_street_bets, num_bets, player_acting,
num_players_to_act, folded, target_player, key, terminal_id, &call_succ, &fold_succ,
&bet_succs);
if (call_succ == nullptr && fold_succ == nullptr && bet_succs.size() == 0) {
fprintf(stderr, "Creating nonterminal with zero succs\n");
fprintf(stderr, "This will cause problems\n");
exit(-1);
}
// Assign nonterminal ID of -1 for now.
shared_ptr<Node> node;
node.reset(new Node(-1, st, player_acting, call_succ, fold_succ, &bet_succs, num_rem, bet_to));
if (merge) {
AddReentrantNode(final_key, node);
}
return node;
}
shared_ptr<Node>
BettingTreeBuilder::CreateMPStreet(int street, int bet_to, int num_bets, bool *folded,
int target_player, string *key, int *terminal_id) {
int num_players = Game::NumPlayers();
int num_players_remaining = 0;
for (int p = 0; p < num_players; ++p) {
if (! folded[p]) ++num_players_remaining;
}
int next_player_to_act =
NextPlayerToAct(Game::FirstToAct(street + 1), folded);
shared_ptr<Node> node =
CreateMPSubtree(street, 0, bet_to, 0, num_bets, next_player_to_act, num_players_remaining,
folded, target_player, key, terminal_id);
return node;
}
shared_ptr<Node>
BettingTreeBuilder::CreateMPTree(int target_player, int *terminal_id) {
int initial_street = betting_abstraction_.InitialStreet();
int player_acting = Game::FirstToAct(initial_street_);
int initial_bet_to = Game::BigBlind();
int last_bet_size = Game::BigBlind() - Game::SmallBlind();
int num_players = Game::NumPlayers();
unique_ptr<bool []> folded(new bool[num_players]);
for (int p = 0; p < num_players; ++p) {
folded[p] = false;
}
string key;
return CreateMPSubtree(initial_street, last_bet_size, initial_bet_to, 0, 0, player_acting,
Game::NumPlayers(), folded.get(), target_player, &key, terminal_id);
}
| [
"eric.jackson@gmail.com"
] | eric.jackson@gmail.com |
bb9d46fedc5ac569fe67549cc3b64a264c67965a | 2019d94fe0d8b32959190d02dd1ee367f524878e | /Practice for C++/Inheritance/05_magic_spells.cpp | 202118de7e723dd3e42ffaeaa2324198816b1f08 | [] | no_license | yang4978/Hackerrank_for_Cpp | bfd9065bd4924b26b30961d4d734a7bb891fe2e2 | 4c3dde90bcc72a0a7e14eda545257c128db313f7 | refs/heads/master | 2020-05-21T06:05:26.451065 | 2019-08-11T15:19:13 | 2019-08-11T15:19:13 | 185,934,553 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,663 | cpp | //https://www.hackerrank.com/challenges/magic-spells/problem
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Spell {
private:
string scrollName;
public:
Spell(): scrollName("") { }
Spell(string name): scrollName(name) { }
virtual ~Spell() { }
string revealScrollName() {
return scrollName;
}
};
class Fireball : public Spell {
private: int power;
public:
Fireball(int power): power(power) { }
void revealFirepower(){
cout << "Fireball: " << power << endl;
}
};
class Frostbite : public Spell {
private: int power;
public:
Frostbite(int power): power(power) { }
void revealFrostpower(){
cout << "Frostbite: " << power << endl;
}
};
class Thunderstorm : public Spell {
private: int power;
public:
Thunderstorm(int power): power(power) { }
void revealThunderpower(){
cout << "Thunderstorm: " << power << endl;
}
};
class Waterbolt : public Spell {
private: int power;
public:
Waterbolt(int power): power(power) { }
void revealWaterpower(){
cout << "Waterbolt: " << power << endl;
}
};
class SpellJournal {
public:
static string journal;
static string read() {
return journal;
}
};
string SpellJournal::journal = "";
void counterspell(Spell *spell) {
if (spell->revealScrollName()!=""){
string s1 = spell->revealScrollName();
string s2 = SpellJournal::journal;
int l1 = s1.size();
int l2 = s2.size();
int chess[l1+1][l2+1];
for(int i=0;i<=l1;i++){
for(int j=0;j<=l2;j++){
if(i==0 || j==0){
chess[i][j] = 0;
}
else if(s1[i-1]==s2[j-1]){
chess[i][j] = chess[i-1][j-1]+1;
}
else{
chess[i][j] = max(chess[i-1][j],chess[i][j-1]);
}
}
}
cout<<chess[l1][l2]<<endl;
}
else{
if(Fireball *fire_temp = dynamic_cast<Fireball*> (spell)){
fire_temp->revealFirepower();
delete fire_temp;
}
else if (Frostbite *frost_temp = dynamic_cast<Frostbite *>(spell)) {
frost_temp->revealFrostpower();
delete frost_temp;
}
else if (Waterbolt *water_temp = dynamic_cast<Waterbolt *>(spell)) {
water_temp->revealWaterpower();
delete water_temp;
}
else if(Thunderstorm *thunder_temp = dynamic_cast<Thunderstorm*> (spell)){
thunder_temp->revealThunderpower();
delete thunder_temp;
}
}
}
class Wizard {
public:
Spell *cast() {
Spell *spell;
string s; cin >> s;
int power; cin >> power;
if(s == "fire") {
spell = new Fireball(power);
}
else if(s == "frost") {
spell = new Frostbite(power);
}
else if(s == "water") {
spell = new Waterbolt(power);
}
else if(s == "thunder") {
spell = new Thunderstorm(power);
}
else {
spell = new Spell(s);
cin >> SpellJournal::journal;
}
return spell;
}
};
int main() {
int T;
cin >> T;
Wizard Arawn;
while(T--) {
Spell *spell = Arawn.cast();
counterspell(spell);
}
return 0;
}
| [
"yang_4978@foxmail.com"
] | yang_4978@foxmail.com |
fff125adba1a17dae922574053e4f5e83b31ddf4 | eddc84bbf831f58c5b70d9fad0c53b7c2b12af43 | /practice/SHIFTPAL.cpp | 9c52cd43fb7a9226f916e61d832e99e88d4b227f | [] | no_license | amitray1608/PCcodes | 79a91a85203b488eeca695ec8048e607269882e0 | e0d49c0b0c05d80d4d813e4a706a8b900de55a91 | refs/heads/master | 2023-06-20T02:01:05.875982 | 2021-07-23T02:25:54 | 2021-07-23T02:25:54 | 305,299,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,144 | cpp |
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1.0e9 + 7;
const ll maxn = 2e6 + 1;
const ll base = 31;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t = 1;
cin >> t;
vector<ll> power(maxn, 1);
for (int i = 1; i < maxn; i++) {
power[i] = (power[i - 1] * base) % MOD;
}
for (int tt = 1; tt <= t; ++tt) {
string s;
cin >> s;
s = s + s;
int n = (int)s.size() * 2;
vector<ll> hash(n + 1, 0);
hash[0] = (s[0] - 'a' + 1);
for (int i = 1; i < n; i++) {
hash[i] = (hash[i - 1] + (s[i] - 'a' + 1) * power[i]) % MOD;
}
string st = string(s.rbegin(), s.rend());
vector<ll> hashr(n + 1, 0);
hashr[0] = (st[0] - 'a' + 1);
for (int i = 1; i < n; i++) {
hashr[i] = (hashr[i - 1] + (st[i] - 'a' + 1) * power[i]) % MOD;
}
ll count = 0;
for (int i = 0; i < n / 2; i++) {
ll pre = ((hash[i + n] - (!i ? 0 : hash[i - 1])) * power[i]) % MOD;
ll suf = ((hashr[n - i] - (!i ? 0 : hashr[i - 1]) * power[i]) % MOD;
if (pre == suf) count++;
}
cout << count << '\n';
}
return 0;
} //Hajimemashite
| [
"amitray1608@gmail.com"
] | amitray1608@gmail.com |
46013a7c2101bbeaaddc0f269aaef690e53ce21d | 8481f6130c15c7e60329634012a9706f131b8ec0 | /code/1009.cpp | d7fc41141ba6667a1d313550cf9f10a76c6df467 | [] | no_license | Double-Wen/codeup | d7faa931e8dbaffe7de51456530032ef09537431 | 71dc8ffefd234102888037ae9085def67ccdfe5a | refs/heads/master | 2020-12-04T03:57:24.221901 | 2020-01-03T14:00:56 | 2020-01-03T14:00:56 | 231,600,498 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 407 | cpp | //
// Created by ubuntu on 1/1/20.
//
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
char buffer[100];
double count=0;
for(int i=0;i<12;i++)
{
scanf("%[^\n]%*c", buffer);
double temp=strtod(buffer, nullptr);
// printf("%.2f\n", temp);
count+=temp;
// printf("%.2f\n", count);
}
printf("¥%.2f\n", count/12);
}
| [
"1047377010@qq.com"
] | 1047377010@qq.com |
b237b16742ed73039be30696123e2e6aa79c3b63 | 6856a769e725ee24b9aee57c87bde802d716e2fb | /Code/Core/EventManager.cpp | ed702982c29ec68e79c51dcfcc3110b40c8abd8d | [
"MIT"
] | permissive | ttangeman/TangeChess | 6f4aa0ea0fcd0fe0941be1784879a618f3d3491c | 3950bef11c511083b4436e128384e3f88d803b7a | refs/heads/main | 2023-03-31T19:59:08.283524 | 2021-04-10T17:43:43 | 2021-04-10T17:43:43 | 331,004,109 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,007 | cpp | #include "Core/EventManager.h"
namespace Tange
{
EventManager EventManager::s_instance;
bool EventManager::IsRegisteredEvent(int32 index)
{
// The index should never be greater than the number of handlers.
ASSERT(index <= s_instance.m_eventHandlers.size());
if (index == s_instance.m_eventHandlers.size())
{
return false;
}
return true;
}
template<typename DerivedEvent>
void EventManager::BindHandler(int32 id, const std::function<void(const IEvent&)>& callback)
{
if (!IsRegisteredEvent(DerivedEvent::GetIndex()))
{
// Lazily register a vector of handlers if it is not registered.
// The index gets lazily initialized in the if-statement too,
// if it was never before used.
s_instance.m_eventHandlers.emplace_back(std::vector<EventHandler> {});
}
auto& handlers = s_instance.m_eventHandlers.at(DerivedEvent::GetIndex());
handlers.emplace_back(EventHandler(id, callback));
}
template<typename DerivedEvent>
void EventManager::DetachHandler(int32 id)
{
// Make sure that we have handlers to actually detach.
// This could probably be omitted, as the m_eventHandlers would throw
// an out_of_bounds exception.
ASSERT(IsRegisteredEvent(DerivedEvent::GetIndex()));
if (IsRegisteredEvent(DerivedEvent::GetIndex()))
{
auto& handlers = s_instance.m_eventHandlers.at(DerivedEvent::GetIndex());
for (auto i = 0; i < handlers.size(); i++)
{
auto& it = handlers[i];
// NOTE: An id can have multiple of the same handler bound,
// so this if does not break the loop.
if (it.Id == id)
{
handlers.erase(handlers.begin() + i);
}
}
}
}
void EventManager::DetachAllHandlers(int32 id)
{
for (auto& handlers : s_instance.m_eventHandlers)
{
for (auto i = 0; i < handlers.size(); i++)
{
auto& it = handlers[i];
// NOTE: An id can have multiple of the same handler bound,
// so this if does not break the loop.
if (it.Id == id)
{
handlers.erase(handlers.begin() + i);
}
}
}
}
template<typename DerivedEvent>
void EventManager::Dispatch(IEvent&& payload)
{
if (IsRegisteredEvent(DerivedEvent::GetIndex()))
{
auto& handler = s_instance.m_eventHandlers.at(DerivedEvent::GetIndex());
for (auto i = 0; i < handler.size(); i++)
{
auto& it = handler[i];
ASSERT(it.Callback);
it.Callback(payload);
}
}
else
{
// Lazily register a vector of handlers if it is not registered.
// The index gets lazily initialized in the if-statement too,
// if it was never before used.
s_instance.m_eventHandlers.emplace_back(std::vector<EventHandler> {});
}
}
template <typename DerivedEvent>
void EventManager::DispatchTo(int32 id, IEvent&& payload)
{
if (!IsRegisteredEvent(DerivedEvent::GetIndex()))
{
for (auto& it : s_instance.m_eventHandlers.at(DerivedEvent::GetIndex()))
{
if (it.Id == id)
{
it.Callback(payload);
}
}
}
else
{
// Lazily register a vector of handlers if it is not registered.
// The index gets lazily initialized in the if-statement too,
// if it was never before used.
s_instance.m_eventHandlers.emplace_back(std::vector<EventHandler> {});
}
}
} | [
"ttangeman97@gmail.com"
] | ttangeman97@gmail.com |
23782c97d8c8c099b43da2522d820d52076c019f | 6b5c26e017b41b9df802b6865a3842d69778f3b2 | /src/other/API_similardetect/v1.0.0_app/API_imagequality.cpp | b4f2d9c0c0ddb431bdeadaae9b4ad8fc78e75f00 | [] | no_license | lvchigo/caffe_image_classfication | ae1f5d4e970ffc345affdb6d6db91918fe07c56d | 6b9b05323b0c5efe41c368ff22ec8ed05cd07c8b | refs/heads/master | 2020-12-29T02:19:51.445761 | 2017-01-12T07:08:58 | 2017-01-12T07:08:58 | 50,634,240 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 13,617 | cpp | #include <vector>
#include <math.h>
#include <iostream>
#include <string.h>
#include "API_imagequality.h"
#include "TErrorCode.h"
using namespace std;
/***********************************Init*************************************/
/// construct function
API_IMAGEQUALITY::API_IMAGEQUALITY()
{
}
/// destruct function
API_IMAGEQUALITY::~API_IMAGEQUALITY(void)
{
}
/***********************************ExtractFeat*************************************/
//blur
//reference No-reference Image Quality Assessment using blur and noisy
//write by Min Goo Choi, Jung Hoon Jung and so on
int API_IMAGEQUALITY::ExtractFeat_Blur(
unsigned char *pSrcImg,
int width,
int height,
int nChannel,
vector< float > &fBlur ) //45D=5*9D
{
if( !pSrcImg || nChannel != 3 ) {
printf("ExtractFeat_Blur err!!\n");
return TEC_INVALID_PARAM;
}
int i,j,k,nRet=0;
int Imgwidth = width;
int Imgheight = height;
int Bl_width = Imgwidth, Bl_height = Imgheight;
unsigned char *pGrayImg = api_imageprocess.ImageRGB2Gray(pSrcImg, width, height, nChannel);
vector< float > blockBlur;
fBlur.clear();
blockBlur.clear();
//nRet = ExtractFeat_Blur_Block( pGrayImg, width, height, 1, blockBlur );
nRet = ExtractFeat_Blur_Block_App( pGrayImg, width, height, 1, blockBlur );
if (nRet != 0)
{
cout<<"ExtractFeat_Blur_Block err!!" << endl;
if (pGrayImg) {delete [] pGrayImg;pGrayImg = NULL;}
return TEC_INVALID_PARAM;
}
/**********************push data*************************************/
for( k=0;k<blockBlur.size();k++ )
fBlur.push_back( blockBlur[k] );
/**********************cvReleaseImage*************************************/
if (pGrayImg) {delete [] pGrayImg;pGrayImg = NULL;}
return nRet;
}
//only for gray image
int API_IMAGEQUALITY::ExtractFeat_Blur_Block(
unsigned char *pSrcImg,
int width,
int height,
int nChannel,
vector< float > &fBlur) //5D
{
if( (!pSrcImg) || (nChannel!=1) )
return TEC_INVALID_PARAM;
//for mean filter
unsigned char *pNoisyData = api_imageprocess.ImageMedianFilter( pSrcImg, width, height, nChannel, 3 );
//printf("ImageMedianFilter:0-%d,1-%d,2-%d\n",pNoisyData[0],pNoisyData[1],pNoisyData[2]);
int nWid = width;
int nHei = height;
int total = (nWid)*(nHei);
int iLineBytes = nWid*nChannel;
int iNoisyBytes = nWid*nChannel;
int steps = 0;
//result
//blur
double blur_mean = 0;
double blur_ratio = 0;
//noisy
double nosiy_mean = 0;
double nosiy_ratio = 0;
//means DhMean and DvMean in paper
//for edge
// it is global mean in paper i will try local later
double ghMean = 0;
double gvMean = 0;
//for noisy
double gNoisyhMean = 0;
double gNoisyvMean = 0;
//Nccand-mean
double gNoisyMean = 0;
//tmp color value for h v
double ch = 0;
double cv = 0;
//The Thresh blur value best detected
const double blur_th = 0.1;
//blur value sum
double blurvalue = 0;
//blur count
int blur_cnt = 0;
//edge count
int h_edge_cnt = 0;
int v_edge_cnt = 0;
//noisy count
int noisy_cnt = 0;
// noisy value
double noisy_value = 0;
//mean Dh(x,y) in the paper
// in code it means Dh(x,y) and Ax(x,y)
double* phEdgeMatric = new double[total];
double* pvEdgeMatric = new double[total];
// for noisy
//Dh Dv in the paper
double* phNoisyMatric = new double[total];
double* pvNoisyMatric = new double[total];
//Ncond in the paper
double * NoisyM = new double[total];
//means Ch(x,y) Cv(x,y) in the paper
double* tmpH = new double[total];
double* tmpV = new double[total];
//for blur and noisy
//loop 1
for(int i = 0; i < nHei; i ++)
{
unsigned char* pOffset = pSrcImg;
unsigned char* pNoisyOff = pNoisyData;
steps = i*nWid;
for(int j = 0; j < nWid; j ++)
{
int nSteps = steps + j;
if(i == 0 || i == nHei -1)
{
//for edge
phEdgeMatric[nSteps] = 0;
pvEdgeMatric[nSteps] = 0;
//for noisy
phNoisyMatric[nSteps] = 0;
pvNoisyMatric[nSteps] = 0;
}
else if(j == 0 || j == nWid -1)
{
//for edge
phEdgeMatric[nSteps] = 0;
pvEdgeMatric[nSteps] = 0;
//for noisy
phNoisyMatric[nSteps] = 0;
pvNoisyMatric[nSteps] = 0;
}
else
{
//for edge
ch = fabs(*(pOffset-1) - *(pOffset+1)) * 1.0 / 255.0;
phEdgeMatric[nSteps] = ch;
ghMean += ch;
cv = fabs(*(pOffset-nWid) - *(pOffset+nWid)) * 1.0 / 255.0;
pvEdgeMatric[nSteps] = cv;
gvMean += cv;
//for noisy
ch = fabs(*(pNoisyOff-1) - *(pNoisyOff+1)) * 1.0 / 255.0;
phNoisyMatric[nSteps] = ch;
gNoisyhMean += ch;
cv = fabs(*(pNoisyOff-nWid) - *(pNoisyOff+nWid)) * 1.0 / 255.0;
pvNoisyMatric[nSteps] = cv;
gNoisyvMean += cv;
}
double tmp_blur_value = 0;
double tmp_ch = 0;
double tmp_cv = 0;
ch = (phEdgeMatric[nSteps] / 2);
if(ch != 0)
tmp_ch = fabs((*pOffset) * 1.0 / 255 - ch) * 1.0 / ch;
cv = (pvEdgeMatric[nSteps] / 2);
if(cv != 0)
tmp_cv = fabs((*pOffset) * 1.0 / 255 - cv) * 1.0 / cv;
tmp_blur_value = max(tmp_ch,tmp_cv);
// blurvalue += tmp_blur_value;
if(tmp_blur_value > blur_th)
{
blur_cnt ++;
blurvalue += tmp_blur_value;
}
pOffset ++;
pNoisyOff ++;
}
pSrcImg += iLineBytes;
pNoisyData += iNoisyBytes;
}
//for edge and noisy
//for edge
ghMean /= (total);
gvMean /= (total);
//noisy
gNoisyhMean /= total;
gNoisyvMean /= total;
//loop 2
for(int i = 0; i < nHei; i ++)
{
steps = i*nWid;
for(int j = 0; j < nWid; j ++)
{
int nSteps = steps + j;
ch = phEdgeMatric[nSteps];
tmpH[nSteps] = ch > ghMean ? ch : 0;
cv = pvEdgeMatric[nSteps];
tmpV[nSteps] = cv > gvMean ? cv : 0;
ch = phNoisyMatric[nSteps];
cv = pvNoisyMatric[nSteps];
if(ch <= gNoisyhMean && cv <= gNoisyvMean)
{
NoisyM[nSteps] = max(ch,cv);
}
else
NoisyM[nSteps] = 0;
gNoisyMean += NoisyM[nSteps];
}
}
gNoisyMean /= total;
//loop 3
for(int i = 0; i < nHei; i ++)
{
steps = i*(nWid);
for(int j = 0; j < nWid; j ++)
{
int nSteps = steps + j;
//for edge
if(i == 0 || i == nHei -1)
{
// phEdge[steps+j] = 0;
// pvEdge[steps+j] = 0;
}
else if(j == 0 || j == nWid -1)
{
// phEdge[steps+j] = 0;
// pvEdge[steps+j] = 0;
}
else
{
//for edge
if(tmpH[nSteps] > tmpH[nSteps-1] && tmpH[nSteps] > tmpH[nSteps+1])
{
// phEdge[steps+j] = 1;
h_edge_cnt ++;
}
//else phEdge[steps+j] = 0;
if(tmpV[nSteps] > tmpV[steps-nWid] && tmpV[nSteps] > tmpV[steps+nWid])
{
// pvEdge[steps+j] = 1;
v_edge_cnt ++;
}
// else pvEdge[steps+j] = 0;
if(NoisyM[nSteps] > gNoisyMean)
{
noisy_cnt++;
noisy_value += NoisyM[nSteps];
}
}
}
}
if(phEdgeMatric){delete []phEdgeMatric; phEdgeMatric = NULL;}
if(pvEdgeMatric){delete []pvEdgeMatric; pvEdgeMatric = NULL;}
if(phNoisyMatric){delete []phNoisyMatric; phNoisyMatric = NULL;}
if(pvNoisyMatric){delete []pvNoisyMatric; pvNoisyMatric = NULL;}
if(NoisyM){delete []NoisyM; NoisyM = NULL;}
if(tmpH){delete []tmpH; tmpH = NULL;}
if(tmpV){delete []tmpV; tmpV = NULL;}
if ( blur_cnt == 0 )
blur_mean = 0;
else
blur_mean = blurvalue * 1.0 / blur_cnt;
if ( (h_edge_cnt+v_edge_cnt) == 0 )
blur_ratio = 0;
else
blur_ratio = blur_cnt * 1.0 / (h_edge_cnt+v_edge_cnt);
if ( noisy_cnt == 0 )
nosiy_mean = 0;
else
nosiy_mean = noisy_value * 1.0 / noisy_cnt;
if ( total == 0 )
nosiy_ratio = 0;
else
nosiy_ratio = noisy_cnt * 1.0 / total;
//the para is provided by paper
//another para 1.55 0.86 0.24 0.66
double gReulst = 1 -( blur_mean + blur_ratio*0.95 + nosiy_mean*0.3 + nosiy_ratio*0.75 );
fBlur.push_back( blur_mean );
fBlur.push_back( blur_ratio );
fBlur.push_back( nosiy_mean );
fBlur.push_back( nosiy_ratio );
fBlur.push_back( gReulst );
return TOK;
}
//only for gray image
int API_IMAGEQUALITY::ExtractFeat_Blur_Block_App(
unsigned char *pSrcImg,
int width,
int height,
int nChannel,
vector< float > &fBlur) //5D
{
if( (!pSrcImg) || (nChannel!=1) )
return TEC_INVALID_PARAM;
//for mean filter
unsigned char *pNoisyData = api_imageprocess.ImageMedianFilter( pSrcImg, width, height, nChannel, 3 );
//printf("ImageMedianFilter:0-%d,1-%d,2-%d\n",pNoisyData[0],pNoisyData[1],pNoisyData[2]);
int nWid = width;
int nHei = height;
int total = (nWid)*(nHei);
int iLineBytes = nWid*nChannel;
int iNoisyBytes = nWid*nChannel;
int steps = 0;
//result
//blur
double blur_mean = 0;
double blur_ratio = 0;
//means DhMean and DvMean in paper
//for edge
// it is global mean in paper i will try local later
double ghMean = 0;
double gvMean = 0;
//tmp color value for h v
double ch = 0;
double cv = 0;
//The Thresh blur value best detected
const double blur_th = 0.1;
//blur value sum
double blurvalue = 0;
//blur count
int blur_cnt = 0;
//edge count
int h_edge_cnt = 0;
int v_edge_cnt = 0;
//noisy count
int noisy_cnt = 0;
// noisy value
double noisy_value = 0;
//mean Dh(x,y) in the paper
// in code it means Dh(x,y) and Ax(x,y)
double* phEdgeMatric = new double[total];
double* pvEdgeMatric = new double[total];
//means Ch(x,y) Cv(x,y) in the paper
double* tmpH = new double[total];
double* tmpV = new double[total];
//for blur and noisy
//loop 1
for(int i = 0; i < nHei; i ++)
{
unsigned char* pOffset = pSrcImg;
steps = i*nWid;
for(int j = 0; j < nWid; j ++)
{
int nSteps = steps + j;
if(i == 0 || i == nHei -1)
{
//for edge
phEdgeMatric[nSteps] = 0;
pvEdgeMatric[nSteps] = 0;
}
else if(j == 0 || j == nWid -1)
{
//for edge
phEdgeMatric[nSteps] = 0;
pvEdgeMatric[nSteps] = 0;
}
else
{
//for edge
ch = fabs(*(pOffset-1) - *(pOffset+1)) * 1.0 / 255.0;
phEdgeMatric[nSteps] = ch;
ghMean += ch;
cv = fabs(*(pOffset-nWid) - *(pOffset+nWid)) * 1.0 / 255.0;
pvEdgeMatric[nSteps] = cv;
gvMean += cv;
}
double tmp_blur_value = 0;
double tmp_ch = 0;
double tmp_cv = 0;
ch = (phEdgeMatric[nSteps] / 2);
if(ch != 0)
tmp_ch = fabs((*pOffset) * 1.0 / 255 - ch) * 1.0 / ch;
cv = (pvEdgeMatric[nSteps] / 2);
if(cv != 0)
tmp_cv = fabs((*pOffset) * 1.0 / 255 - cv) * 1.0 / cv;
tmp_blur_value = max(tmp_ch,tmp_cv);
// blurvalue += tmp_blur_value;
if(tmp_blur_value > blur_th)
{
blur_cnt ++;
blurvalue += tmp_blur_value;
}
pOffset ++;
}
pSrcImg += iLineBytes;
pNoisyData += iNoisyBytes;
}
//for edge and noisy
//for edge
ghMean /= (total);
gvMean /= (total);
//loop 2
for(int i = 0; i < nHei; i ++)
{
steps = i*nWid;
for(int j = 0; j < nWid; j ++)
{
int nSteps = steps + j;
ch = phEdgeMatric[nSteps];
tmpH[nSteps] = ch > ghMean ? ch : 0;
cv = pvEdgeMatric[nSteps];
tmpV[nSteps] = cv > gvMean ? cv : 0;
}
}
//loop 3
for(int i = 0; i < nHei; i ++)
{
steps = i*(nWid);
for(int j = 0; j < nWid; j ++)
{
int nSteps = steps + j;
//for edge
if(i == 0 || i == nHei -1)
{
// phEdge[steps+j] = 0;
// pvEdge[steps+j] = 0;
}
else if(j == 0 || j == nWid -1)
{
// phEdge[steps+j] = 0;
// pvEdge[steps+j] = 0;
}
else
{
//for edge
if(tmpH[nSteps] > tmpH[nSteps-1] && tmpH[nSteps] > tmpH[nSteps+1])
{
// phEdge[steps+j] = 1;
h_edge_cnt ++;
}
//else phEdge[steps+j] = 0;
if(tmpV[nSteps] > tmpV[steps-nWid] && tmpV[nSteps] > tmpV[steps+nWid])
{
// pvEdge[steps+j] = 1;
v_edge_cnt ++;
}
// else pvEdge[steps+j] = 0;
}
}
}
if(phEdgeMatric){delete []phEdgeMatric; phEdgeMatric = NULL;}
if(pvEdgeMatric){delete []pvEdgeMatric; pvEdgeMatric = NULL;}
if(tmpH){delete []tmpH; tmpH = NULL;}
if(tmpV){delete []tmpV; tmpV = NULL;}
if ( blur_cnt == 0 )
blur_mean = 0;
else
blur_mean = blurvalue * 1.0 / blur_cnt;
if ( (h_edge_cnt+v_edge_cnt) == 0 )
blur_ratio = 0;
else
blur_ratio = blur_cnt * 1.0 / (h_edge_cnt+v_edge_cnt);
//the para is provided by paper
//another para 1.55 0.86 0.24 0.66
double gReulst = 1 -( blur_mean + blur_ratio*0.95 );
fBlur.push_back( blur_mean );
fBlur.push_back( blur_ratio );
fBlur.push_back( gReulst );
return TOK;
}
int API_IMAGEQUALITY::ExtractFeat_Blur_test(
unsigned char *pSrcImg,
int width,
int height,
int nChannel,
float &fBlur )
{
if( !pSrcImg || nChannel != 3 ) {
printf("ExtractFeat_Blur err!!\n");
return TEC_INVALID_PARAM;
}
int i,j,k,nRet=0;
float Entropy,tmp = 0;
unsigned char *pGrayImg = api_imageprocess.ImageRGB2Gray(pSrcImg, width, height, nChannel);
//unsigned char *pFilterImg = api_imageprocess.ImageMedianFilter( pGrayImg, width, height, 1, 3 );
Entropy = 0;
for (i=1; i<(height-1); ++i)
{
for (j=1; j<(width-1); ++j)
{
tmp = 0;
//tmp = 2*fabs(pGrayImg[i*(width-2)+j]-pFilterImg[i*(width-2)+j]);
tmp += fabs(pGrayImg[i*(width-2)+(j+1)]-pGrayImg[i*(width-2)+(j-1)]);
tmp += fabs(pGrayImg[(i+1)*(width-2)+j]-pGrayImg[(i-1)*(width-2)+j]);
//tmp += fabs(pFilterImg[i*(width-2)+(j+1)]-pFilterImg[i*(width-2)+(j-1)]);
//tmp += fabs(pFilterImg[(i+1)*(width-2)+j]-pFilterImg[(i-1)*(width-2)+j]);
tmp = (tmp<0)?0:tmp;
tmp = (tmp>255)?255:tmp;
if(tmp>0)
Entropy = Entropy-(tmp*1.0/255)*(log(tmp*1.0/255)/log(2.0));
}
}
fBlur = Entropy*127.0/20000;
fBlur = (fBlur<0)?0:fBlur;
fBlur = (fBlur>127)?127:fBlur;
/**********************cvReleaseImage*************************************/
if (pGrayImg) {delete [] pGrayImg;pGrayImg = NULL;}
//if (pFilterImg) {delete [] pFilterImg;pFilterImg = NULL;}
return nRet;
}
| [
"xiaogao@in66.com"
] | xiaogao@in66.com |
e538f7ca695b6a26c43af8ca2a1468d775f72e00 | 5bad25ebc0daf25864f57752d93c040b30a1d8eb | /src/cell_writer.cpp | 6d135b3d17072c8cd06992c19ae1883829411fc8 | [] | no_license | katiya-cw/EncLib | c6c201643af4ea3afc91163b5d74ae634af0b20a | ba8547abe7f2fa02132076227fe4b93b37f3de0c | refs/heads/master | 2021-12-02T11:17:29.840453 | 2010-12-13T22:24:27 | 2010-12-13T22:24:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 994 | cpp | //*****************************************************************************
//** Copyright (C) 2010 Kai R. Neufeldt, Ahrensburg, Germany
//** This file is part of the ENClib
//** The ENC lib may be used unter the GPL General Public License Version 2
//** or with a Commercial License granted by Kai R. Neufeldt
//** contact Kai R. Neufeldt, Manhagener Allee 65, 22926 Ahrensburg, Germany
//*****************************************************************************
#include "cell_writer.h"
#include <QtCore/QFile>
using namespace Enc;
void CellWriter::setCell(const CellS57_Base * cell)
{
cellS57 = cell;
}
void CellWriter::writeS57Cell(QString cellName)
{
if (!cellS57) throw QString("ERROR: Cannot write S-57 Cell %1 No Cell Pointer!").arg(cellName);
QFile iso8211file(cellName);
if (!iso8211file.open(QIODevice::WriteOnly)) throw QString("ERROR: cannot open S-57 File %1 for writing").arg(cellName);
writeS57Cell(&iso8211file);
iso8211file.close();
}
| [
"KaiAbuSir@gmx.de"
] | KaiAbuSir@gmx.de |
7e37a2f9985af0f94d32de367e12fd6cdd029df5 | 30b7ffd17845db982883a91ce8d04551281658c4 | /Self Marathon/Practice/September 2020 :: Codificador Rojo/Day 9/test-J.cpp | 0d43b2a16dded49d0e3dbd1550bf72b75bf91f01 | [] | no_license | shas9/codehub | 95418765b602b52edb0d48a473ad7e7a798f76e5 | bda856bf6ca0f3a1d59980895cfab82f690c75a2 | refs/heads/master | 2023-06-21T01:09:34.275708 | 2021-07-26T14:54:03 | 2021-07-26T14:54:03 | 389,404,954 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,164 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(0);
int n, q; cin >> n >> q;
vector<int> a(n+1), ans(q), leftBound(q);
vector<vector<int>> endHere(n+1);
for (int i = 1; i <= n; ++i) {
cin >> a[i];
a[i] = i - a[i];
}
for (int i = 0; i < q; ++i) {
int x, y; cin >> x >> y;
int l = 1+x, r = n-y;
leftBound[i] = l;
endHere[r].push_back(i);
}
vector<int> BIT(n+1);
int global = 0;
for (int r = 1; r <= n; ++r) {
int target = a[r];
if (target >= 0) {
// Find rightmost pos such that s[pos] >= target
int pos = 0, cur = global;
for (int jump = 1 << __lg(n); jump >= 1; jump /= 2)
if (pos+jump <= r && cur - BIT[pos+jump] >= target)
pos += jump, cur -= BIT[pos];
// Increment prefix (+1 on whole array, -1 on suffix)
++global;
cout << r << ": " << global << " " << pos << " " << target << endl;
for (int i = pos+1; i <= n; i += i & -i)
++BIT[i];
}
for (int iQuery : endHere[r]) {
ans[iQuery] = global;
for (int i = leftBound[iQuery]; i > 0; i -= i & -i)
ans[iQuery] -= BIT[i];
}
}
for (int i = 0; i < q; ++i)
cout << ans[i] << "\n";
}
| [
"shahwathasnaine@gmail.com"
] | shahwathasnaine@gmail.com |
a84596bb95953e05e389f2fa3384003246301893 | 967901498a9cba019f54e2ed62920f976491f8b2 | /winapi/CWindow/SetWindowText/src/CWindow/CWindow/MainApplication.cpp | c765d12d0616e1302843ce5426aef0b7145b8ac8 | [
"MIT"
] | permissive | bg1bgst333/Test | 732e07a92e0fa52f3c364d1a65348f518ec6d849 | 40291a30a2b344bdbbae677958112e279374411f | refs/heads/master | 2023-08-18T04:59:58.947454 | 2023-08-09T04:28:23 | 2023-08-09T04:28:23 | 239,051,674 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,175 | cpp | // ヘッダのインクルード
// 独自のヘッダ
#include "MainApplication.h" // CMainApplication
#include "MainWindow.h" // CMainWindow
// インスタンス初期化関数InitInstance.
BOOL CMainApplication::InitInstance(HINSTANCE hInstance, LPTSTR lpCmdLine, int nShowCmd) {
// ウィンドウクラスの登録.
CMainWindow::RegisterClass(hInstance, MAKEINTRESOURCE(IDR_MAINMENU)); // CMainWindow::RegisterClassでメニューIDR_MAINMENUを指定してウィンドウクラスを登録.
// CMainWindowオブジェクトの作成.
m_pMainWnd = new CMainWindow(); // CMainWindowオブジェクトを作成し, m_pMainWndに格納.
// ウィンドウの作成.
if (!m_pMainWnd->Create(_T("CWindow"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance)) { // m_pMainWnd->Createでウィンドウ作成し, 失敗した場合.
// エラー処理
return FALSE; // returnでFALSEを返して異常終了.
}
// ウィンドウの表示.
m_pMainWnd->ShowWindow(SW_SHOW); // m_pMainWnd->ShowWindowで表示.
// TRUEを返す.
return TRUE; // returnでTRUEを返す.
} | [
"bg1bgst333@gmail.com"
] | bg1bgst333@gmail.com |
6b67c04753110c7a97ebc89e70cf09bbc980d02d | fa4a53826c501e5b6f318a0f6bd91b0e6bb25af3 | /lib/src/ui/UILabel.cpp | 92bb1e00d0f7121b2ff2a095343a3c75d922eecf | [
"Apache-2.0"
] | permissive | hahahuahai/Viry3D | b365d69842dd15dc26ccec166b87ca6823037a30 | f4788dc335ee0a5cb5125c2da5183eb6df58d0f4 | refs/heads/master | 2020-03-24T00:00:58.444849 | 2018-07-25T06:35:25 | 2018-07-25T06:35:25 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 18,464 | cpp | /*
* Viry3D
* Copyright 2014-2018 by Stack - stackos@qq.com
*
* 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.
*/
#include "UILabel.h"
#include "graphics/Texture2D.h"
#include "graphics/Material.h"
#include "math/Mathf.h"
#include <ft2build.h>
#include FT_FREETYPE_H
#include "ftoutln.h"
namespace Viry3D
{
DEFINE_COM_CLASS(UILabel);
enum class TagType
{
Color,
Shadow,
Outline,
Underline,
Bold,
Italic
};
struct TagInfo
{
String tag;
TagType type;
String value;
int begin;
int end;
};
UILabel::UILabel():
m_font_style(FontStyle::Normal),
m_font_size(20),
m_line_space(1),
m_rich(false),
m_mono(false),
m_alignment(TextAlignment::UpperLeft),
m_horizontal_overflow(HorizontalWrapMode::Wrap),
m_vertical_overflow(VerticalWrapMode::Overflow)
{
}
void UILabel::DeepCopy(const Ref<Object>& source)
{
UIView::DeepCopy(source);
auto src = RefCast<UILabel>(source);
m_font = src->m_font;
m_font_style = src->m_font_style;
m_font_size = src->m_font_size;
m_text = src->m_text;
m_line_space = src->m_line_space;
m_rich = src->m_rich;
m_alignment = src->m_alignment;
}
void UILabel::SetFont(const Ref<Font>& font)
{
if (m_font != font)
{
m_font = font;
m_dirty = true;
MarkRendererDirty();
}
}
void UILabel::SetFontStyle(FontStyle style)
{
if (m_font_style != style)
{
m_font_style = style;
m_dirty = true;
MarkRendererDirty();
}
}
void UILabel::SetFontSize(int size)
{
if (m_font_size != size)
{
m_font_size = size;
m_dirty = true;
MarkRendererDirty();
}
}
void UILabel::SetText(const String& text)
{
if (m_text != text)
{
m_text = text;
m_dirty = true;
MarkRendererDirty();
}
}
void UILabel::SetLineSpace(int space)
{
if (m_line_space != space)
{
m_line_space = space;
m_dirty = true;
MarkRendererDirty();
}
}
void UILabel::SetRich(bool rich)
{
if (m_rich != rich)
{
m_rich = rich;
m_dirty = true;
MarkRendererDirty();
}
}
void UILabel::SetMono(bool mono)
{
if (m_mono != mono)
{
m_mono = mono;
m_dirty = true;
MarkRendererDirty();
}
}
void UILabel::SetAlignment(TextAlignment alignment)
{
if (m_alignment != alignment)
{
m_alignment = alignment;
m_dirty = true;
MarkRendererDirty();
}
}
void UILabel::SetHorizontalOverflow(HorizontalWrapMode mode)
{
if (m_horizontal_overflow != mode)
{
m_horizontal_overflow = mode;
m_dirty = true;
MarkRendererDirty();
}
}
void UILabel::SetVerticalOverflow(VerticalWrapMode mode)
{
if (m_vertical_overflow != mode)
{
m_vertical_overflow = mode;
m_dirty = true;
MarkRendererDirty();
}
}
static bool check_tag_begin(Vector<char32_t>& str, int& char_index, const String& tag_str, int value_length, TagInfo& tag)
{
bool match = true;
auto tag_cstr = tag_str.CString();
for (int i = 0; i < tag_str.Size(); i++)
{
if (tag_cstr[i] != str[char_index + i])
{
match = false;
break;
}
}
if (match)
{
if (value_length > 0)
{
Vector<char32_t> value;
for (int i = 0; i < value_length; i++)
{
value.Add(str[char_index + tag_str.Size() + i]);
}
value.Add(0);
tag.tag = tag_str.Substring(1, tag_str.Size() - 3);
tag.value = String(&value[0]);
str.RemoveRange(char_index, tag_str.Size() + value_length + 1);
}
else
{
tag.tag = tag_str.Substring(1, tag_str.Size() - 2);
str.RemoveRange(char_index, tag_str.Size());
}
tag.begin = char_index--;
}
return match;
}
static bool check_tag_end(Vector<char32_t>& str, int& char_index, const String& tag_str, Vector<TagInfo>& tag_find, Vector<TagInfo>& tags)
{
bool match = true;
auto tag_cstr = tag_str.CString();
for (int i = 0; i < tag_str.Size(); i++)
{
if (tag_cstr[i] != str[char_index + i])
{
match = false;
break;
}
}
if (match)
{
auto tag = tag_str.Substring(2, tag_str.Size() - 3);
for (int i = tag_find.Size() - 1; i >= 0; i--)
{
auto &t = tag_find[i];
if (t.tag == tag)
{
str.RemoveRange(char_index, tag_str.Size());
t.end = char_index--;
tags.Add(t);
tag_find.Remove(i);
break;
}
}
}
return match;
}
static const String TAG_COLOR_BEGIN = "<color=#";
static const String TAG_COLOR_END = "</color>";
static const String TAG_SHADOW_BEGIN = "<shadow>";
static const String TAG_SHADOW_VALUE_BEGIN = "<shadow=#";
static const String TAG_SHADOW_END = "</shadow>";
static const String TAG_OUTLINE_BEGIN = "<outline>";
static const String TAG_OUTLINE_VALUE_BEGIN = "<outline=#";
static const String TAG_OUTLINE_END = "</outline>";
static const String TAG_UNDERLINE_BEGIN = "<underline>";
static const String TAG_UNDERLINE_END = "</underline>";
static const String TAG_BOLD_BEGIN = "<bold>";
static const String TAG_BOLD_END = "</bold>";
static const String TAG_ITALIC_BEGIN = "<italic>";
static const String TAG_ITALIC_END = "</italic>";
static Vector<TagInfo> parse_rich_tags(Vector<char32_t>& str)
{
Vector<TagInfo> tags;
Vector<TagInfo> tag_find;
for (int i = 0; i < str.Size(); i++)
{
TagInfo tag;
if (check_tag_begin(str, i, TAG_COLOR_BEGIN, 8, tag))
{
tag.type = TagType::Color;
tag_find.Add(tag);
}
else if (check_tag_end(str, i, TAG_COLOR_END, tag_find, tags))
{
}
else if (check_tag_begin(str, i, TAG_SHADOW_BEGIN, 0, tag))
{
tag.type = TagType::Shadow;
tag.value = "000000ff";
tag_find.Add(tag);
}
else if (check_tag_begin(str, i, TAG_SHADOW_VALUE_BEGIN, 8, tag))
{
tag.type = TagType::Shadow;
tag_find.Add(tag);
}
else if (check_tag_end(str, i, TAG_SHADOW_END, tag_find, tags))
{
}
else if (check_tag_begin(str, i, TAG_OUTLINE_BEGIN, 0, tag))
{
tag.type = TagType::Outline;
tag.value = "000000ff";
tag_find.Add(tag);
}
else if (check_tag_begin(str, i, TAG_OUTLINE_VALUE_BEGIN, 8, tag))
{
tag.type = TagType::Outline;
tag_find.Add(tag);
}
else if (check_tag_end(str, i, TAG_OUTLINE_END, tag_find, tags))
{
}
else if (check_tag_begin(str, i, TAG_UNDERLINE_BEGIN, 0, tag))
{
tag.type = TagType::Underline;
tag_find.Add(tag);
}
else if (check_tag_end(str, i, TAG_UNDERLINE_END, tag_find, tags))
{
}
else if (check_tag_begin(str, i, TAG_BOLD_BEGIN, 0, tag))
{
tag.type = TagType::Bold;
tag_find.Add(tag);
}
else if (check_tag_end(str, i, TAG_BOLD_END, tag_find, tags))
{
}
else if (check_tag_begin(str, i, TAG_ITALIC_BEGIN, 0, tag))
{
tag.type = TagType::Italic;
tag_find.Add(tag);
}
else if (check_tag_end(str, i, TAG_ITALIC_END, tag_find, tags))
{
}
}
return tags;
}
static Color string_to_color(const String& str)
{
auto str_lower = str.ToLower();
std::stringstream ss;
ss << std::hex << str_lower.CString();
unsigned int color_i = 0;
ss >> color_i;
int r = (color_i & 0xff000000) >> 24;
int g = (color_i & 0xff0000) >> 16;
int b = (color_i & 0xff00) >> 8;
int a = (color_i & 0xff);
float div = 1 / 255.f;
return Color((float) r, (float) g, (float) b, (float) a) * div;
}
void UILabel::ProcessText(int& actual_width, int& actual_height)
{
auto chars = m_text.ToUnicode32();
Vector<TagInfo> tags;
if (m_rich)
{
tags = parse_rich_tags(chars);
}
auto face = (FT_Face) m_font->GetFont();
auto label_size = GetSize();
float v_size = 1.0f / TEXTURE_SIZE_MAX;
int vertex_count = 0;
auto has_kerning = FT_HAS_KERNING(face);
FT_UInt previous = 0;
int pen_x = 0;
int pen_y = 0;
int x_max = 0;
int y_min = 0;
int y_max = INT_MIN;
int line_x_max = 0;
int line_y_min = 0;
LabelLine line;
for (int i = 0; i < chars.Size(); i++)
{
char32_t c = chars[i];
int font_size = m_font_size;
Color color = m_color;
bool bold = m_font_style == FontStyle::Bold || m_font_style == FontStyle::BoldAndItalic;
bool italic = m_font_style == FontStyle::Italic || m_font_style == FontStyle::BoldAndItalic;
bool mono = m_mono;
Ref<Color> color_shadow;
Ref<Color> color_outline;
bool underline = false;
if (c == '\n')
{
line.width = line_x_max;
line.height = pen_y - line_y_min;
line_x_max = 0;
line_y_min = 0;
pen_x = 0;
pen_y += -(font_size + m_line_space);
m_lines.Add(line);
line.Clear();
continue;
}
if (m_rich)
{
for (auto& j : tags)
{
if (i >= j.begin && i < j.end)
{
switch (j.type)
{
case TagType::Color:
color = string_to_color(j.value);
break;
case TagType::Bold:
bold = true;
break;
case TagType::Italic:
italic = true;
break;
case TagType::Shadow:
color_shadow = RefMake<Color>(string_to_color(j.value));
break;
case TagType::Outline:
color_outline = RefMake<Color>(string_to_color(j.value));
break;
case TagType::Underline:
underline = true;
break;
}
}
}
}
GlyphInfo info = m_font->GetGlyph(c, font_size, bold, italic, mono);
// limit width
if (m_horizontal_overflow == HorizontalWrapMode::Wrap)
{
if (pen_x + info.bearing_x + info.uv_pixel_w > label_size.x)
{
pen_x = 0;
pen_y += -(font_size + m_line_space);
previous = 0;
}
}
// kerning
if (has_kerning && previous && info.glyph_index)
{
FT_Vector delta;
FT_Get_Kerning(face, previous, info.glyph_index, FT_KERNING_UNFITTED, &delta);
pen_x += delta.x >> 6;
}
auto base_info = m_font->GetGlyph('A', font_size, bold, italic, mono);
int base_y0 = base_info.bearing_y;
int base_y1 = base_info.bearing_y - base_info.uv_pixel_h;
int baseline = Mathf::RoundToInt(base_y0 + (font_size - base_y0 + base_y1) * 0.5f);
const int char_space = 0;
int x0 = pen_x + info.bearing_x;
int y0 = pen_y + info.bearing_y - baseline;
int x1 = x0 + info.uv_pixel_w;
if (c == ' ')
{
x1 = pen_x + info.advance_x + char_space;
}
int y1 = y0 - info.uv_pixel_h;
if (x_max < x1)
{
x_max = x1;
}
if (y_min > y1)
{
y_min = y1;
}
if (y_max < y0)
{
y_max = y0;
}
if (line_x_max < x1)
{
line_x_max = x1;
}
if (line_y_min > y1)
{
line_y_min = y1;
}
pen_x += info.advance_x + char_space;
int uv_x0 = info.uv_pixel_x;
int uv_y0 = info.uv_pixel_y;
int uv_x1 = uv_x0 + info.uv_pixel_w;
int uv_y1 = uv_y0 + info.uv_pixel_h;
if (color_shadow)
{
Vector2 offset = Vector2(1, -1);
line.vertices.Add(Vector2((float) x0, (float) y0) + offset);
line.vertices.Add(Vector2((float) x0, (float) y1) + offset);
line.vertices.Add(Vector2((float) x1, (float) y1) + offset);
line.vertices.Add(Vector2((float) x1, (float) y0) + offset);
line.uv.Add(Vector2(uv_x0 * v_size, uv_y0 * v_size));
line.uv.Add(Vector2(uv_x0 * v_size, uv_y1 * v_size));
line.uv.Add(Vector2(uv_x1 * v_size, uv_y1 * v_size));
line.uv.Add(Vector2(uv_x1 * v_size, uv_y0 * v_size));
line.colors.Add(*color_shadow);
line.colors.Add(*color_shadow);
line.colors.Add(*color_shadow);
line.colors.Add(*color_shadow);
line.indices.Add(vertex_count + 0);
line.indices.Add(vertex_count + 1);
line.indices.Add(vertex_count + 2);
line.indices.Add(vertex_count + 0);
line.indices.Add(vertex_count + 2);
line.indices.Add(vertex_count + 3);
vertex_count += 4;
}
if (color_outline)
{
Vector2 offsets[4];
offsets[0] = Vector2(-1, 1);
offsets[1] = Vector2(-1, -1);
offsets[2] = Vector2(1, -1);
offsets[3] = Vector2(1, 1);
for (int j = 0; j < 4; j++)
{
line.vertices.Add(Vector2((float) x0, (float) y0) + offsets[j]);
line.vertices.Add(Vector2((float) x0, (float) y1) + offsets[j]);
line.vertices.Add(Vector2((float) x1, (float) y1) + offsets[j]);
line.vertices.Add(Vector2((float) x1, (float) y0) + offsets[j]);
line.uv.Add(Vector2(uv_x0 * v_size, uv_y0 * v_size));
line.uv.Add(Vector2(uv_x0 * v_size, uv_y1 * v_size));
line.uv.Add(Vector2(uv_x1 * v_size, uv_y1 * v_size));
line.uv.Add(Vector2(uv_x1 * v_size, uv_y0 * v_size));
line.colors.Add(*color_outline);
line.colors.Add(*color_outline);
line.colors.Add(*color_outline);
line.colors.Add(*color_outline);
line.indices.Add(vertex_count + 0);
line.indices.Add(vertex_count + 1);
line.indices.Add(vertex_count + 2);
line.indices.Add(vertex_count + 0);
line.indices.Add(vertex_count + 2);
line.indices.Add(vertex_count + 3);
vertex_count += 4;
}
}
line.vertices.Add(Vector2((float) x0, (float) y0));
line.vertices.Add(Vector2((float) x0, (float) y1));
line.vertices.Add(Vector2((float) x1, (float) y1));
line.vertices.Add(Vector2((float) x1, (float) y0));
line.uv.Add(Vector2(uv_x0 * v_size, uv_y0 * v_size));
line.uv.Add(Vector2(uv_x0 * v_size, uv_y1 * v_size));
line.uv.Add(Vector2(uv_x1 * v_size, uv_y1 * v_size));
line.uv.Add(Vector2(uv_x1 * v_size, uv_y0 * v_size));
line.colors.Add(color);
line.colors.Add(color);
line.colors.Add(color);
line.colors.Add(color);
line.indices.Add(vertex_count + 0);
line.indices.Add(vertex_count + 1);
line.indices.Add(vertex_count + 2);
line.indices.Add(vertex_count + 0);
line.indices.Add(vertex_count + 2);
line.indices.Add(vertex_count + 3);
line.chars.Add(c);
line.char_bounds.Add(Bounds(Vector3((float) x0, (float) y1, 0), Vector3((float) x1, (float) y0, 0)));
vertex_count += 4;
previous = info.glyph_index;
if (underline)
{
int ux0 = pen_x - (info.advance_x + char_space);
int uy0 = pen_y - baseline - 2;
int ux1 = ux0 + info.advance_x + char_space;
int uy1 = uy0 - 1;
line.vertices.Add(Vector2((float) ux0, (float) uy0));
line.vertices.Add(Vector2((float) ux0, (float) uy1));
line.vertices.Add(Vector2((float) ux1, (float) uy1));
line.vertices.Add(Vector2((float) ux1, (float) uy0));
line.uv.Add(Vector2(0 * v_size, 0 * v_size));
line.uv.Add(Vector2(0 * v_size, 1 * v_size));
line.uv.Add(Vector2(1 * v_size, 1 * v_size));
line.uv.Add(Vector2(1 * v_size, 0 * v_size));
line.colors.Add(color);
line.colors.Add(color);
line.colors.Add(color);
line.colors.Add(color);
line.indices.Add(vertex_count + 0);
line.indices.Add(vertex_count + 1);
line.indices.Add(vertex_count + 2);
line.indices.Add(vertex_count + 0);
line.indices.Add(vertex_count + 2);
line.indices.Add(vertex_count + 3);
vertex_count += 4;
}
}
// ×îºóÒ»ÐÐ
if (!line.vertices.Empty())
{
line.width = line_x_max;
line.height = pen_y - line_y_min;
m_lines.Add(line);
}
actual_width = x_max;
actual_height = -y_min;
}
void UILabel::ApplyAlignment(Vector3& v, const Vector2& min, const Vector2& max, const Vector2& size, int line_width, int actual_width, int actual_height)
{
switch (m_alignment)
{
case TextAlignment::UpperLeft:
case TextAlignment::MiddleLeft:
case TextAlignment::LowerLeft:
v.x += min.x;
break;
case TextAlignment::UpperCenter:
case TextAlignment::MiddleCenter:
case TextAlignment::LowerCenter:
v.x += min.x + (size.x - line_width) / 2;
break;
case TextAlignment::UpperRight:
case TextAlignment::MiddleRight:
case TextAlignment::LowerRight:
v.x += min.x + (size.x - line_width);
break;
}
switch (m_alignment)
{
case TextAlignment::UpperLeft:
case TextAlignment::UpperCenter:
case TextAlignment::UpperRight:
v.y += max.y;
break;
case TextAlignment::MiddleLeft:
case TextAlignment::MiddleCenter:
case TextAlignment::MiddleRight:
v.y += max.y - (size.y - actual_height) / 2;
break;
case TextAlignment::LowerLeft:
case TextAlignment::LowerCenter:
case TextAlignment::LowerRight:
v.y += max.y - (size.y - actual_height);
break;
}
}
void UILabel::FillVertices(Vector<Vector3>& vertices, Vector<Vector2>& uv, Vector<Color>& colors, Vector<unsigned short>& indices)
{
if (!m_font)
{
return;
}
Vector2 size = this->GetSize();
Vector2 min = Vector2(-m_pivot.x * size.x, -m_pivot.y * size.y);
Vector2 max = Vector2((1 - m_pivot.x) * size.x, (1 - m_pivot.y) * size.y);
int actual_width;
int actual_height;
m_lines.Clear();
this->ProcessText(actual_width, actual_height);
Matrix4x4 mat;
this->GetVertexMatrix(mat);
int index_begin = vertices.Size();
for (int i = 0; i < m_lines.Size(); i++)
{
auto& line = m_lines[i];
for (int j = 0; j < line.vertices.Size(); j++)
{
Vector3 v = line.vertices[j];
this->ApplyAlignment(v, min, max, size, line.width, actual_width, actual_height);
vertices.Add(mat.MultiplyPoint3x4(v));
}
if (!line.vertices.Empty())
{
uv.AddRange(&line.uv[0], line.uv.Size());
colors.AddRange(&line.colors[0], line.colors.Size());
}
for (int j = 0; j < line.indices.Size(); j++)
{
indices.Add(line.indices[j] + index_begin);
}
for (int j = 0; j < line.char_bounds.Size(); j++)
{
Vector3 bounds_min = line.char_bounds[j].Min();
Vector3 bounds_max = line.char_bounds[j].Max();
this->ApplyAlignment(bounds_min, min, max, size, line.width, actual_width, actual_height);
this->ApplyAlignment(bounds_max, min, max, size, line.width, actual_width, actual_height);
line.char_bounds[j] = Bounds(mat.MultiplyPoint3x4(bounds_min), mat.MultiplyPoint3x4(bounds_max));
}
}
}
void UILabel::FillMaterial(Ref<Material>& mat)
{
if (m_font)
{
mat->SetMainTexture(m_font->GetTexture());
}
}
}
| [
"stackos@qq.com"
] | stackos@qq.com |
1a3cc700228ef5ce0fc3a6d59534482b07000476 | 288281ea9d5c6344706f267731d9798d527d71d3 | /taint-tracking/src/ins_clear_op.cpp | 84937ff48f851b1a83e1fff9fa06550e99e40d00 | [
"MIT"
] | permissive | UzL-ITS/cipherfix | 58847e6454a5888c6345d460b9b8242a375d9f9d | 0d05fcbe48498acc827ad0373cd7244c590b27c4 | refs/heads/master | 2023-07-04T12:13:33.801949 | 2023-04-14T15:22:30 | 2023-04-14T15:22:30 | 556,843,329 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,102 | cpp | #include "ins_clear_op.h"
#include "ins_helper.h"
/* threads context */
extern thread_ctx_t *threads_ctx;
static void PIN_FAST_ANALYSIS_CALL r_clrl4(THREADID tid) {
for (size_t i = 0; i < 8; i++) {
RTAG[DFT_REG_RDX][i] = tag_traits<tag_t>::cleared_val;
RTAG[DFT_REG_RCX][i] = tag_traits<tag_t>::cleared_val;
RTAG[DFT_REG_RBX][i] = tag_traits<tag_t>::cleared_val;
RTAG[DFT_REG_RAX][i] = tag_traits<tag_t>::cleared_val;
}
}
static void PIN_FAST_ANALYSIS_CALL r_clrl2(THREADID tid) {
for (size_t i = 0; i < 8; i++) {
RTAG[DFT_REG_RDX][i] = tag_traits<tag_t>::cleared_val;
RTAG[DFT_REG_RAX][i] = tag_traits<tag_t>::cleared_val;
}
}
static void PIN_FAST_ANALYSIS_CALL r_clrb_l(THREADID tid, uint32_t reg) {
RTAG[reg][0] = tag_traits<tag_t>::cleared_val;
}
static void PIN_FAST_ANALYSIS_CALL r_clrb_u(THREADID tid, uint32_t reg) {
RTAG[reg][1] = tag_traits<tag_t>::cleared_val;
}
static void PIN_FAST_ANALYSIS_CALL r_clrw(THREADID tid, uint32_t reg) {
for (size_t i = 0; i < 2; i++) {
RTAG[reg][i] = tag_traits<tag_t>::cleared_val;
}
}
static void PIN_FAST_ANALYSIS_CALL r_clrl(THREADID tid, uint32_t reg) {
for (size_t i = 0; i < 4; i++) {
RTAG[reg][i] = tag_traits<tag_t>::cleared_val;
}
}
static void PIN_FAST_ANALYSIS_CALL r_clrq(THREADID tid, uint32_t reg) {
for (size_t i = 0; i < 8; i++) {
RTAG[reg][i] = tag_traits<tag_t>::cleared_val;
}
}
static void PIN_FAST_ANALYSIS_CALL r_clrx(THREADID tid, uint32_t reg) {
for (size_t i = 0; i < 16; i++) {
RTAG[reg][i] = tag_traits<tag_t>::cleared_val;
}
}
static void PIN_FAST_ANALYSIS_CALL r_clry(THREADID tid, uint32_t reg) {
for (size_t i = 0; i < 32; i++) {
RTAG[reg][i] = tag_traits<tag_t>::cleared_val;
}
}
void ins_clear_op(INS ins) {
if (INS_OperandIsMemory(ins, OP_0)) {
INT32 n = INS_OperandWidth(ins, OP_0) / 8;
M_CLEAR_N(n);
} else {
REG reg_dst = INS_OperandReg(ins, OP_0);
if (REG_is_gr64(reg_dst)) {
R_CALL(r_clrq, reg_dst);
} else if (REG_is_gr32(reg_dst)) {
R_CALL(r_clrl, reg_dst);
} else if (REG_is_gr16(reg_dst)) {
R_CALL(r_clrw, reg_dst);
} else if (REG_is_xmm(reg_dst)) {
R_CALL(r_clrx, reg_dst);
} else if (REG_is_mm(reg_dst)) {
R_CALL(r_clrq, reg_dst);
} else if (REG_is_ymm(reg_dst)) {
R_CALL(r_clry, reg_dst);
} else {
if (REG_is_Upper8(reg_dst))
R_CALL(r_clrb_u, reg_dst);
else
R_CALL(r_clrb_l, reg_dst);
}
}
}
void ins_clear_op_predicated(INS ins) {
// one byte
if (INS_MemoryOperandCount(ins) == 0) {
REG reg_dst = INS_OperandReg(ins, OP_0);
if (REG_is_Upper8(reg_dst))
INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)r_clrb_u,
IARG_FAST_ANALYSIS_CALL, IARG_THREAD_ID,
IARG_UINT32, REG_INDX(reg_dst), IARG_END);
else
INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)r_clrb_l,
IARG_FAST_ANALYSIS_CALL, IARG_THREAD_ID,
IARG_UINT32, REG_INDX(reg_dst), IARG_END);
} else
INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)tagmap_clrn,
IARG_FAST_ANALYSIS_CALL, IARG_MEMORYWRITE_EA,
IARG_UINT32, 1, IARG_END);
}
void ins_clear_op_l2(INS ins) {
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)r_clrl2, IARG_FAST_ANALYSIS_CALL,
IARG_THREAD_ID, IARG_END);
}
void ins_clear_op_l4(INS ins) {
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)r_clrl4, IARG_FAST_ANALYSIS_CALL,
IARG_THREAD_ID, IARG_END);
}
VOID clear_ymm_upper(THREADID tid)
{
// YMM upper bytes are from DFT_REGs 19 - 34 (XMM0 - XMM15)
// Iterate over all registers and clear the taint of the upper 128 bits
for (int i = 19; i < 35; ++i)
{
for (size_t j = 16; j < 32; ++j)
{
RTAG[i][j] = tag_traits<tag_t>::cleared_val;
}
}
}
void ins_vzeroupper_op(INS ins)
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)clear_ymm_upper, IARG_THREAD_ID, IARG_END);
} | [
"j.wichelmann@uni-luebeck.de"
] | j.wichelmann@uni-luebeck.de |
f12ed198f5ac8358723ecdae9fde47cd68b150c3 | f279c5a1df1dacf422cf7d47fb01a2fb41510838 | /8. Parallel programming/OpenMP/critical_section.cpp | eba59009f08318f0a49cc1cebf90e259cf15d0cc | [] | no_license | newmersedez/multithreaded_programming | a939821b4b55383f67e0b309859b46a15f030593 | 351abd39b422c7c23d9069b1dead22e6983d69bc | refs/heads/main | 2023-08-27T04:00:27.156899 | 2021-10-24T01:15:46 | 2021-10-24T01:15:46 | 415,411,020 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 166 | cpp | #include <iostream>
int main(int argc, char *argv[])
{
#pragma omp parallel
{
#pragma omp critical
{
std::cout << "output" << std::endl;
}
}
return 0;
} | [
"trishkk2001@gmail.com"
] | trishkk2001@gmail.com |
90edbad12c809559a87086ba4c0a58f9205fa49b | 9fbbf9cda869bc318fe99874ebeb7ca8dd1a3799 | /Utils/interface/FitSolution.hh | 9041a56ff16520746c30f500b7de7019b49abe9c | [] | no_license | ssevova/ttbarAnaSolver | d92cfdadfa7b482f8850708732f84e82bdabd583 | 57720f740c84737e25e6ef8028c4f7934444defd | refs/heads/master | 2021-01-11T23:02:10.403805 | 2017-01-18T17:47:14 | 2017-01-18T17:47:14 | 78,534,297 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 547 | hh | #ifndef FIT_SOLUTION
#define FIT_SOLUTION
class FitSolution {
public:
FitSolution():
numSol(-1.)
{}
~FitSolution(){}
std::vector<TLorentzVector> nu1; std::vector<TLorentzVector> nu2;
int numSol;
std::vector<double> mass1;
std::vector<double> mass2;
std::vector<double> weight;
std::vector<double> cudisc;
std::vector<double> mtt;
// KH
void reset() {
mass1.clear();
mass2.clear();
weight.clear();
cudisc.clear();
mtt.clear();
nu1.clear();
nu2.clear();
numSol=0;
}
};
#endif
| [
"ssevova@gmail.com"
] | ssevova@gmail.com |
d4145d7364f4715ba3f4b1c0bdf733bfd9997688 | d9254711a4bdade616d2707b3df157b14a4e9750 | /multidimension_newton_root.h | b52f47f7b88bce5f483f826997011972ff3d1a59 | [
"MIT"
] | permissive | aofenghanyue/numericalAnalysisHomework | b3203fcec09eef205a743858e82c0cb968f4b85e | ed4db5a5d693a3973ca1c3c5f1fc3847b8f5118e | refs/heads/master | 2020-11-25T10:18:53.045904 | 2019-12-18T06:24:07 | 2019-12-18T06:24:07 | 228,615,577 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 156 | h | #pragma once
#include "Gauss.h"
#include "commons.h"
class MultidimensionNewtonRoot {
private:
int n;
public:
MatrixD jac_mat(void *jac(VectorD &x));
};
| [
"1772155440@qq.com"
] | 1772155440@qq.com |
ee57983d0a23b55dc24fdcb1f7ac03ed21286737 | 67d9a8912f2e04f341de00c83dcf9a1ebfa13320 | /CangJian.cpp | 24608afe0e14964c702c79ada810cdecfeca07f1 | [] | no_license | thysm008/CardHero | 1d98fcc7d730d84fded22562feb4dc1d795b4b35 | 32b97e168f024b63dda994fd40249885d1ab5a2d | refs/heads/master | 2020-05-30T00:34:08.741651 | 2017-03-08T14:48:36 | 2017-03-08T14:48:36 | 82,621,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 968 | cpp | #include "stdafx.h"
#include "CangJian.h"
#include "Character.h"
CCangJian::CCangJian(CString name, CString pro, int char_id_, int pro_id_, int camp_)
{
char_name = name;
pro_name = pro;
char_id = char_id_;
pro_id = pro_id_;
camp = camp_;
}
void CCangJian::setJianQi(int n)
{
cur_jianqi = n;
}
void CCangJian::addJianQi(int n)
{
cur_jianqi = cur_jianqi + n;
if (cur_jianqi > MAX_JIANQI)
cur_jianqi = 7;
}
void CCangJian::subJianQi(int n)
{
cur_jianqi = cur_jianqi - n;
if (cur_jianqi < 0)
cur_jianqi = 0;
}
int CCangJian::getJianQi()
{
if (cur_jianqi < 0)
return 0;
else if (cur_jianqi > MAX_JIANQI)
return MAX_JIANQI;
else
return cur_jianqi;
}
void CCangJian::setStatus(int i)
{
sword_status = i;
}
int CCangJian::getStatus()
{
return sword_status;
}
void CCangJian::setShield(int i)
{
shield = i;
}
void CCangJian::subShield(int i)
{
shield -= i;
if (shield < 0)
shield = 0;
}
int CCangJian::getShield()
{
return shield;
} | [
"thysm008@qq.com"
] | thysm008@qq.com |
b3ac7272ffb47ad427600885fef6c840bc36db3a | 63426e63712da8b1f01ae584cd780c660c2969c3 | /NineMansMorris/NineMansMorris/BoardFactory.h | b58e3ff3c843d43bf998de9a0ad3710f01b7c1f3 | [] | no_license | TinEnglman/NineMansMorris | 1b5af909bcef09e39a2f45e14fa288bbc07c199e | 2c483ff19900e84e8df1a56c0b69a5b62fea0467 | refs/heads/master | 2020-05-22T16:04:58.017414 | 2019-05-27T09:34:28 | 2019-05-27T09:34:28 | 186,418,576 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 215 | h | #pragma once
#include "Board.h"
#include "CellData.h"
class BoardFactory
{
public:
BoardFactory();
~BoardFactory();
Board* CreateBoard();
private:
const unsigned int NUM_SLOTS = 24;
CellData* _cellData;
};
| [
"gonzoglizli@gmail.com"
] | gonzoglizli@gmail.com |
96e94a8b346463092364f768ae3f28ecf734054a | 59115bea46bcf235852e1308d79f07bd07406894 | /aieBootstrap-physics/2dTest/Sphere.cpp | afe47b27a51dad1cd6aae92196e8aa1cb593dff9 | [
"MIT"
] | permissive | AnonUser676/PhysicsAIE | bb4ba3f081fbcac5f85b3385012bd3fc7cdc6297 | f21dce33481740270f82ce33c8323d215d97269c | refs/heads/master | 2021-05-03T10:26:45.650164 | 2018-03-07T00:36:28 | 2018-03-07T00:36:28 | 120,534,737 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 598 | cpp | #include "Sphere.h"
Sphere::Sphere(vec2 position, vec2 velocity, float mass, float radius, vec4 color):Rigidbody(SPHERE, position,velocity,0,mass)
{
m_radius = radius;
m_color = color;
m_position = position;
m_velocity = velocity;
m_mass = mass;
}
Sphere::~Sphere()
{
}
void Sphere::makeGizmo()
{
Gizmos::add2DCircle(m_position, m_radius, 12, m_color);
}
bool Sphere::checkCollision(PhysicsObject* pOther)
{
Sphere* other = dynamic_cast<Sphere*>(pOther);
if (other)
{
return ((other->m_radius + this->m_radius) > distance(other->m_position, this->m_position));
}
return false;
} | [
"rouie.ortega@live.com"
] | rouie.ortega@live.com |
1acace2a393a159457a549e245240eb1048b365b | 1dd825971ed4ec0193445dc9ed72d10618715106 | /examples/extended/electromagnetic/TestEm7/include/PrimaryGeneratorMessenger.hh | 63e1ef7324487d4529372a1fa3f0351085964f9c | [] | no_license | gfh16/Geant4 | 4d442e5946eefc855436f4df444c245af7d3aa81 | d4cc6c37106ff519a77df16f8574b2fe4ad9d607 | refs/heads/master | 2021-06-25T22:32:21.104339 | 2020-11-02T13:12:01 | 2020-11-02T13:12:01 | 158,790,658 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,718 | hh | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
/// \file electromagnetic/TestEm7/include/PrimaryGeneratorMessenger.hh
/// \brief Definition of the PrimaryGeneratorMessenger class
//
// $Id$
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#ifndef PrimaryGeneratorMessenger_h
#define PrimaryGeneratorMessenger_h 1
#include "G4UImessenger.hh"
#include "globals.hh"
class PrimaryGeneratorAction;
class G4UIdirectory;
class G4UIcmdWithADoubleAndUnit;
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
class PrimaryGeneratorMessenger: public G4UImessenger
{
public:
PrimaryGeneratorMessenger(PrimaryGeneratorAction*);
~PrimaryGeneratorMessenger();
virtual void SetNewValue(G4UIcommand*, G4String);
private:
PrimaryGeneratorAction* fAction;
G4UIdirectory* fGunDir;
G4UIcmdWithADoubleAndUnit* fRndmCmd;
};
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#endif
| [
"gfh16@mails.tsinghua.edu.cn"
] | gfh16@mails.tsinghua.edu.cn |
5cec04916076ef0f0cd79ae646b4e289f08d56aa | 4fd358a4e26f678077770db11c4f7461123351c5 | /mp2/test.cpp | 510709b4ec9f59bf7c52b9db4930ebd2373d32a4 | [] | no_license | arjanirh/cs425 | e89fe45206a5dffb7204c15f39eaa93a67811a35 | 94761c40633f1af172e58662814f20bfbafe8e41 | refs/heads/master | 2020-05-19T13:45:44.622065 | 2012-05-18T23:59:10 | 2012-05-18T23:59:10 | 3,635,798 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 202 | cpp | #include<iostream>
#include<string>
using namespace std;
int main () {
string str;
cout << "Please enter full name: ";
getline (cin,str);
cout << "Thank you, " << str << ".\n";
}
| [
"nirh1@linux7.ews.illinois.edu"
] | nirh1@linux7.ews.illinois.edu |
a481020995d835dff9b4d9e8bc0d37537958aed2 | c04e49371d98c136fb484c541a0fb479c96001ff | /deprecated/include/Graphics/Native/WindowModes.h | fb4cd0481f48eef7970bddaf93daf916e05872b1 | [
"MIT"
] | permissive | Arzana/Plutonium | 0af59b6ffee010eed7c6c8f6182c87480ef45dc3 | 5a17c93e5072ac291b96347a4df196e1609fabe2 | refs/heads/master | 2021-05-09T02:20:42.528906 | 2020-10-31T20:36:57 | 2020-10-31T20:36:57 | 119,201,274 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | h | #pragma once
namespace Plutonium
{
/* Defines the modes of a window. */
enum class WindowMode
{
/* A sizeable window with a header. */
Windowed,
/* A sizeable window without a header. */
Borderless,
/* A sizeable window that takes up the whole display. */
BorderlessFullscreen,
/* A fullscreen window. */
Fullscreen
};
} | [
"largewowfan@gmail.com"
] | largewowfan@gmail.com |
9227f7155eb70070e1969c7a5440b7547a526d6e | 14029a914f030ac5301fdabdc99299f5e322a1a5 | /Cryptography_Algorithm/2018_01_DES/My des.cpp | 601040a7faacf27b4363220949475b629fee4d0f | [] | no_license | joseoyeon/Cryptography | bc3a7ef8ce4db2d8acdd79bfe35f663222dc9a55 | db6691d59b7676a816e3f6f076c40d569f78368b | refs/heads/master | 2022-04-09T02:01:43.297934 | 2020-03-13T09:33:15 | 2020-03-13T09:33:15 | 187,388,602 | 0 | 1 | null | null | null | null | UHC | C++ | false | false | 12,354 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned long long KEY;
unsigned C , D;
void print_binary(const unsigned long long t) { //size 는 원래 없어ok 수정하다 보니 생긴 변수
int i,b = 0;
unsigned long long tmp =1LL;
for (i=63; i>=0; i--,b++) {
printf("%d",(t) & ((tmp << i) )? 1:0);
if(b%4 == 3){printf(" ");}
if(b%32== 31){printf("\n");};
}
printf("\n\n");
}
void print_hex(unsigned long long t)
{
int i=0;
for(i = 15; i>=0; i--)
{
printf("%x", ((t >> (i*4))&0x000000F));
}
printf("\n\n");
}
void print_char(unsigned long long t)
{
int i=0;
for(i = 7; i>=0; i--)
{
printf("%c", ((t >> (i*8))&0x000000FF));
}
printf("\n\n\n");
}
unsigned long long PC1(unsigned long long source)
{
char i;
unsigned long long tmp = (1LL<<55), res = 0LL;
static char perm[] = {57,49,41,33,25,17,
9,1,58,50,42,34,26,18,
10, 2,59,51,43,35,27,
19,11, 3,60,52,44,36,
63,55,47,39,31,23,15,
7,62,54,46,38,30,22,
14, 6,61,53,45,37,29,
21,13, 5,28,20,12, 4};
for(i = 0; i < 56; i++, tmp = tmp >> 1LL)
if (source & (1LL << (64-perm[i]))) res |= tmp;
return res;
}
unsigned long long PC2()
{
char i;
unsigned long long tmp = (1LL<<47), res = 0LL;
static char perm[] = {14,17,11,24, 1, 5,
3,28,15, 6,21,10,
23,19,12, 4,26, 8,
16, 7,27,20,13, 2,
41,52,31,37,47,55,
30,40,51,45,33,48,
44,49,39,56,34,53,
46,42,50,36,29,32};
for(i = 0; i < 48; i++, tmp = tmp >> 1LL)
if (KEY & (1LL << (56-perm[i]))) res |= tmp; //전치
/*
printf("PC2 후\n");
print_hex(res);
*/
return res;
}
unsigned long long IP(unsigned long long source)
{
char i;
unsigned long long tmp = (1LL<<63), res = 0LL;
static char perm[] = {58, 50, 42, 34, 26 ,18 ,10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7};
for(i = 0; i < 64; i++, tmp = tmp >> 1LL)
if (source & (1LL << (64-perm[i]))) res |= tmp; //전 치
return res;
}
unsigned long long FP(unsigned long long source)
{
char i;
unsigned long long tmp = (1LL<<63), res = 0LL;
static char perm[] = {40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25};
for(i = 0; i < 64; i++, tmp = tmp >> 1LL)
if (source & (1LL << (64-perm[i]))) res |= tmp; //전 치
return res;
}
unsigned long long EX(unsigned source)
{
char i;
unsigned long long tmp = (1LL<<47), res = 0LL;
static char perm[] = {32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9,10,11,12,13,
12,13,14,15,16,17,
16,17,18,19,20,21,
20,21,22,23,24,25,
24,25,26,27,28,29,
28,29,30,31,32, 1};
for(i = 0; i < 48; i++, tmp = tmp >> 1LL)
if (source & (1 << (32-perm[i]))) res |= tmp;
return res;
}
unsigned P(unsigned source)
{
char i;
unsigned tmp = (1<<31), res = 0;
static char perm[] = {16, 7,20,21,
29,12,28,17,
1,15,23,26,
5,18,31,10,
2, 8,24,14,
32,27, 3, 9,
19,13,30, 6,
22,11, 4,25};
for(i = 0; i < 32; i++, tmp = tmp >> 1)
if (source & (1 << (32-perm[i]))) res |= tmp;
/*
printf("평문 P\n");
print_binary((unsigned long long)res, 4);
*/
return res;
}
unsigned S(unsigned long long source){ //32bit out
static char perm[8][64] = { { 14, 4,13, 1, 2,15,11, 8, 3,10, 6,12, 5, 9, 0, 7,
0,15, 7, 4,14, 2,13, 1,10, 6,12,11, 9, 5, 3, 8,
4, 1,14, 8,13, 6, 2,11,15,12, 9, 7, 3,10, 5, 0,
15,12, 8, 2, 4, 9, 1, 7, 5,11, 3,14,10, 0, 6,13 },
{ 15, 1, 8,14, 6,11, 3, 4, 9, 7, 2,13,12, 0, 5,10,
3,13, 4, 7,15, 2, 8,14,12, 0, 1,10, 6, 9,11, 5,
0,14, 7,11,10, 4,13, 1, 5, 8,12, 6, 9, 3, 2,15,
13, 8,10, 1, 3,15, 4, 2,11, 6, 7,12, 0, 5,14, 9 },
{ 10, 0, 9,14, 6, 3,15, 5, 1,13,12, 7,11, 4, 2, 8,
13, 7, 0, 9, 3, 4, 6,10, 2, 8, 5,14,12,11,15, 1,
13, 6, 4, 9, 8,15, 3, 0,11, 1, 2,12, 5,10,14, 7,
1,10,13, 0, 6, 9, 8, 7, 4,15,14, 3,11, 5, 2,12 },
{ 7,13,14, 3, 0, 6, 9,10, 1, 2, 8, 5,11,12, 4,15,
13, 8,11, 5, 6,15, 0, 3, 4, 7, 2,12, 1,10,14, 9,
10, 6, 9, 0,12,11, 7,13,15, 1, 3,14, 5, 2, 8, 4,
3,15, 0, 6,10, 1,13, 8, 9, 4, 5,11,12, 7, 2,14 },
{ 2,12, 4, 1, 7,10,11, 6, 8, 5, 3,15,13, 0,14, 9,
14,11, 2,12, 4, 7,13, 1, 5, 0,15,10, 3, 9, 8, 6,
4, 2, 1,11,10,13, 7, 8,15, 9,12, 5, 6, 3, 0,14,
11, 8,12, 7, 1,14, 2,13, 6,15, 0, 9,10, 4, 5, 3 },
{ 12, 1,10,15, 9, 2, 6, 8, 0,13, 3, 4,14, 7, 5,11,
10,15, 4, 2, 7,12, 9, 5, 6, 1,13,14, 0,11, 3, 8,
9,14,15, 5, 2, 8,12, 3, 7, 0, 4,10, 1,13,11, 6,
4, 3, 2,12, 9, 5,15,10,11,14, 1, 7, 6, 0, 8,13 },
{ 4,11, 2,14,15, 0, 8,13, 3,12, 9, 7, 5,10, 6, 1,
13, 0,11, 7, 4, 9, 1,10,14, 3, 5,12, 2,15, 8, 6,
1, 4,11,13,12, 3, 7,14,10,15, 6, 8, 0, 5, 9, 2,
6,11,13, 8, 1, 4,10, 7, 9, 5, 0,15,14, 2, 3,12 },
{ 13, 2, 8, 4, 6,15,11, 1,10, 9, 3,14, 5, 0,12, 7,
1,15,13, 8,10, 3, 7, 4,12, 5, 6,11, 0,14, 9, 2,
7,11, 4, 1, 9,12,14, 2, 0, 6,10,13,15, 3, 5, 8,
2, 1,14, 7, 4,10, 8,13,15,12, 9, 0, 3, 5, 6,11 } };
int i;
unsigned int z=0; //저장
unsigned res=0;
/*
printf("평문 S- source \n");
print_binary(source, 8);
*/
for(i = 0, res = 0; i < 8; i++)
{
z = ((source >> (((7-i)* 6))) & 0x3F);
(res |= (perm[i][((z&0x20)|((z<<4)&0x10)|(z>>1)&0x0F)]));
(i!=7)? res <<=4 : 0;
}
/*
printf("평문 S\n");
print_binary((unsigned long long)res, 4);
*/
return res;
}
unsigned rotation(unsigned source, char c, char f)
{
static char rotation_sheet[] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 };
c = rotation_sheet[c];
if (f) while(c-- > 0) source = (source >> 1) | ((source & 1) << 27);
else while(c-- > 0) source = ((source << 1) & 0x0FFFFFFF) | (source >> 27); // 0, 암호화
return source;
}
unsigned long long EN(unsigned long long source)
{
int i = -1;
unsigned Ln, L, R;
source = IP(source);
/*
printf("평문 IP \n");
print_binary(&source, 8);
*/
L = (unsigned)((source) >> 32);
R = ((unsigned)source);
/*
printf("평문 L\n");
print_binary((unsigned long long)L);//4
printf("평문 R \n");
print_binary((unsigned long long)R);//4
unsigned long long tmp= EX(L);
printf("L EX \n");
print_binary((unsigned long long*)&tmp, 6);
*/
C = (KEY>>28);
D = (KEY&0x0FFFFFFF);
/*라운드 함수 실행*/
while(++i < 16)
{
Ln = R;
C = rotation(C, i, 0);
D = rotation(D, i, 0);
KEY = ((unsigned long long)C <<28| D);
/* printf("KEY C \n");
print_binary((unsigned long long*)&C, 4);
printf("KEY D \n");
print_binary((unsigned long long*)&D, 4);
printf("KEY K \n");
print_binary(&K, 8);
unsigned long long PC= PC2();
printf("KEY PC2 \n");
puts_hex(&PC);
print_binary(&PC, 8);
*/
R = (L^P(S(EX(R)^PC2())));
L = Ln;
/* unsigned long long tmp = (((unsigned long long)L << 32) | R);
printf("[L + R] ");
print_binary(&tmp, 8);
/*printf("[L] ");
print_binary((unsigned long long *)&L, 4);
/*
unsigned long long tmp = FP(((unsigned long long)R<< 32) | L);
printf("[FP] ");
print_binary(&tmp, 8);
unsigned long long tmp = (((unsigned long long)L << 32) | R);
printf("[L + R] ");
print_hex(tmp);
print_binary(tmp);*/
}
return FP(((unsigned long long)R<< 32) | L);
}
unsigned long long DE(unsigned long long source)
{
char i = 16;
unsigned Ln, L, R;
source = IP(source);
L = (unsigned)((source) >> 32);
R = ((unsigned)source);
C = (KEY>>28);
D = (KEY&0x0FFFFFFF);
while(--i >= 0)
{
Ln = R;
R = L^P(S(EX(R)^PC2()));
L = Ln;
/*
printf("KEY C \n");
print_binary((unsigned long long*)&C, 4);
printf("KEY D \n");
print_binary((unsigned long long*)&D, 4);
printf("KEY K \n");
print_binary(&K, 8);
*/
C = rotation(C, i, 1);
D = rotation(D, i, 1);
KEY = ((unsigned long long)C <<28| D);
//printf("%d \n",16-i);
/* printf("rotation 후\n");
print_hex(KEY);
*/}
return FP(((unsigned long long)R << 32) | L);
}
void encryption(unsigned long long src, unsigned long long*encrypted_str, unsigned long long key)
{
KEY = PC1(key);
/*
printf("KEY PC1 \n");
print_binary(KEY,8);
*/
*(encrypted_str) = EN(src);
return;
}
void decryption(unsigned long long src, unsigned long long*decrypted_str, unsigned long long key)
{
KEY = PC1(key);
/*
printf("PC1 후\n");
print_hex(KEY);
*/
*(decrypted_str) = DE(src);
return;
}
int main(){
unsigned long long decrypted_source_str= 0x9d96ce27e370975c;
unsigned long long source_key= 0LL;
unsigned long long encrypted_str, decrypted_str= 0LL;
unsigned int i,j,d=0;
printf("[암호] : ");
print_hex(decrypted_source_str);
print_binary(decrypted_source_str);
/* printf("[키] : ");
print_hex(source_key);
print_binary(source_key);*/
for(i=10000; i>1000; i-=2){
source_key =i;
decryption(decrypted_source_str, &decrypted_str, source_key);
//printf("[복호] : ");
//print_hex(decrypted_str);
//print_binary(decrypted_str);
// printf("%d. ",i);
if(
(((i&0xFF000000)>=48)|((i&0xFF000000)<=57)) & (((i&0xFF000000)>=65)|((i&0xFF000000)<=90)) & (((i&0xFF000000)>=97)|(i&0xFF000000)<=122)&
(((i&0x00FF0000)>=48)|((i&0x00FF0000)<=57)) & (((i&0x00FF0000)>=65)|((i&0x00FF0000)<=90)) & (((i&0x00FF0000)>=97)|(i&0x00FF0000)<=122)&
(((i&0x0000FF00)>=48)|((i&0x0000FF00)<=57)) & (((i&0x0000FF00)>=65)|((i&0x0000FF00)<=90)) & (((i&0x0000FF00)>=97)|(i&0x0000FF00)<=122)&
(((i&0x000000FF)>=48)|((i&0x000000FF)<=57)) & (((i&0x000000FF)>=65)|((i&0x000000FF)<=90)) & (((i&0x000000FF)>=97)|(i&0x000000FF)<=122))
{
printf("%d ",i);
print_char(decrypted_str);
}}
encryption(decrypted_str, &encrypted_str, source_key);
encryption(decrypted_str, &encrypted_str, source_key);
printf("[다시 암호] : ");
print_hex(encrypted_str);
print_binary(encrypted_str);
system("pause");
return 0;
}
/*unsigned long long decrypted_source_str= 0xda02ce3a89ecac3b;
unsigned long long source_key= 0x0f1571c947d9e859;
unsigned long long encrypted_str, decrypted_str= 0LL;*/
/*unsigned long long decrypted_source_str= 0x9d96ce27e370975c;
unsigned long long source_key= 0LL;
unsigned long long encrypted_str, decrypted_str= 0LL;
unsigned int i=0; */
| [
"joseoyeon60@gmail.com"
] | joseoyeon60@gmail.com |
491efed239743bd0db34996e1a91932ede547540 | 60ccc97366c43b0f83275c2c7aabd569939f8a43 | /lcpfw/net/third_party/quiche/src/quic/core/http/quic_send_control_stream_test.cc | fe849733c8207fffe779641dfdf184f834ebdec9 | [
"BSD-3-Clause"
] | permissive | VestasWey/mysite | d89c886c333e5aae31a04584e592bd108ead8dd3 | 41ea707007b688a3ef27eec55332500e369a191f | refs/heads/master | 2022-12-09T10:02:19.268154 | 2022-10-03T03:14:16 | 2022-10-03T03:14:16 | 118,091,757 | 1 | 1 | null | 2022-11-26T14:29:04 | 2018-01-19T07:22:23 | C++ | UTF-8 | C++ | false | false | 8,142 | cc | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "quic/core/http/quic_send_control_stream.h"
#include <utility>
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "quic/core/crypto/null_encrypter.h"
#include "quic/platform/api/quic_flags.h"
#include "quic/test_tools/quic_config_peer.h"
#include "quic/test_tools/quic_spdy_session_peer.h"
#include "quic/test_tools/quic_test_utils.h"
#include "common/platform/api/quiche_text_utils.h"
namespace quic {
namespace test {
namespace {
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::Invoke;
using ::testing::StrictMock;
struct TestParams {
TestParams(const ParsedQuicVersion& version, Perspective perspective)
: version(version), perspective(perspective) {
QUIC_LOG(INFO) << "TestParams: " << *this;
}
TestParams(const TestParams& other)
: version(other.version), perspective(other.perspective) {}
friend std::ostream& operator<<(std::ostream& os, const TestParams& tp) {
os << "{ version: " << ParsedQuicVersionToString(tp.version)
<< ", perspective: "
<< (tp.perspective == Perspective::IS_CLIENT ? "client" : "server")
<< "}";
return os;
}
ParsedQuicVersion version;
Perspective perspective;
};
// Used by ::testing::PrintToStringParamName().
std::string PrintToString(const TestParams& tp) {
return absl::StrCat(
ParsedQuicVersionToString(tp.version), "_",
(tp.perspective == Perspective::IS_CLIENT ? "client" : "server"));
}
std::vector<TestParams> GetTestParams() {
std::vector<TestParams> params;
ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
for (const auto& version : AllSupportedVersions()) {
if (!VersionUsesHttp3(version.transport_version)) {
continue;
}
for (Perspective p : {Perspective::IS_SERVER, Perspective::IS_CLIENT}) {
params.emplace_back(version, p);
}
}
return params;
}
class QuicSendControlStreamTest : public QuicTestWithParam<TestParams> {
public:
QuicSendControlStreamTest()
: connection_(new StrictMock<MockQuicConnection>(
&helper_,
&alarm_factory_,
perspective(),
SupportedVersions(GetParam().version))),
session_(connection_) {
ON_CALL(session_, WritevData(_, _, _, _, _, _))
.WillByDefault(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
}
void Initialize() {
EXPECT_CALL(session_, OnCongestionWindowChange(_)).Times(AnyNumber());
session_.Initialize();
connection_->SetEncrypter(
ENCRYPTION_FORWARD_SECURE,
std::make_unique<NullEncrypter>(connection_->perspective()));
send_control_stream_ = QuicSpdySessionPeer::GetSendControlStream(&session_);
QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(
session_.config(), kMinimumFlowControlSendWindow);
QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesUnidirectional(
session_.config(), kMinimumFlowControlSendWindow);
QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(session_.config(), 3);
session_.OnConfigNegotiated();
}
Perspective perspective() const { return GetParam().perspective; }
MockQuicConnectionHelper helper_;
MockAlarmFactory alarm_factory_;
StrictMock<MockQuicConnection>* connection_;
StrictMock<MockQuicSpdySession> session_;
QuicSendControlStream* send_control_stream_;
};
INSTANTIATE_TEST_SUITE_P(Tests,
QuicSendControlStreamTest,
::testing::ValuesIn(GetTestParams()),
::testing::PrintToStringParamName());
TEST_P(QuicSendControlStreamTest, WriteSettings) {
SetQuicFlag(FLAGS_quic_enable_http3_grease_randomness, false);
session_.set_qpack_maximum_dynamic_table_capacity(255);
session_.set_qpack_maximum_blocked_streams(16);
session_.set_max_inbound_header_list_size(1024);
Initialize();
testing::InSequence s;
std::string expected_write_data = absl::HexStringToBytes(
"00" // stream type: control stream
"04" // frame type: SETTINGS frame
"0b" // frame length
"01" // SETTINGS_QPACK_MAX_TABLE_CAPACITY
"40ff" // 255
"06" // SETTINGS_MAX_HEADER_LIST_SIZE
"4400" // 1024
"07" // SETTINGS_QPACK_BLOCKED_STREAMS
"10" // 16
"4040" // 0x40 as the reserved settings id
"14" // 20
"4040" // 0x40 as the reserved frame type
"01" // 1 byte frame length
"61"); // payload "a"
auto buffer = std::make_unique<char[]>(expected_write_data.size());
QuicDataWriter writer(expected_write_data.size(), buffer.get());
// A lambda to save and consume stream data when QuicSession::WritevData() is
// called.
auto save_write_data =
[&writer, this](QuicStreamId /*id*/, size_t write_length,
QuicStreamOffset offset, StreamSendingState /*state*/,
TransmissionType /*type*/,
absl::optional<EncryptionLevel> /*level*/) {
send_control_stream_->WriteStreamData(offset, write_length, &writer);
return QuicConsumedData(/* bytes_consumed = */ write_length,
/* fin_consumed = */ false);
};
EXPECT_CALL(session_, WritevData(send_control_stream_->id(), 1, _, _, _, _))
.WillOnce(Invoke(save_write_data));
EXPECT_CALL(session_, WritevData(send_control_stream_->id(),
expected_write_data.size() - 5, _, _, _, _))
.WillOnce(Invoke(save_write_data));
EXPECT_CALL(session_, WritevData(send_control_stream_->id(), 4, _, _, _, _))
.WillOnce(Invoke(save_write_data));
send_control_stream_->MaybeSendSettingsFrame();
EXPECT_EQ(expected_write_data,
absl::string_view(writer.data(), writer.length()));
}
TEST_P(QuicSendControlStreamTest, WriteSettingsOnlyOnce) {
Initialize();
testing::InSequence s;
EXPECT_CALL(session_, WritevData(send_control_stream_->id(), 1, _, _, _, _));
EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _))
.Times(2);
send_control_stream_->MaybeSendSettingsFrame();
// No data should be written the second time MaybeSendSettingsFrame() is
// called.
send_control_stream_->MaybeSendSettingsFrame();
}
// Send stream type and SETTINGS frame if WritePriorityUpdate() is called first.
TEST_P(QuicSendControlStreamTest, WritePriorityBeforeSettings) {
Initialize();
testing::InSequence s;
// The first write will trigger the control stream to write stream type, a
// SETTINGS frame, and a greased frame before the PRIORITY_UPDATE frame.
EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _))
.Times(4);
PriorityUpdateFrame frame;
send_control_stream_->WritePriorityUpdate(frame);
EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _));
send_control_stream_->WritePriorityUpdate(frame);
}
TEST_P(QuicSendControlStreamTest, CloseControlStream) {
Initialize();
EXPECT_CALL(*connection_,
CloseConnection(QUIC_HTTP_CLOSED_CRITICAL_STREAM, _, _));
send_control_stream_->OnStopSending(QUIC_STREAM_CANCELLED);
}
TEST_P(QuicSendControlStreamTest, ReceiveDataOnSendControlStream) {
Initialize();
QuicStreamFrame frame(send_control_stream_->id(), false, 0, "test");
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_DATA_RECEIVED_ON_WRITE_UNIDIRECTIONAL_STREAM, _, _));
send_control_stream_->OnStreamFrame(frame);
}
TEST_P(QuicSendControlStreamTest, SendGoAway) {
Initialize();
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_.set_debug_visitor(&debug_visitor);
QuicStreamId stream_id = 4;
EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _))
.Times(AnyNumber());
EXPECT_CALL(debug_visitor, OnSettingsFrameSent(_));
EXPECT_CALL(debug_visitor, OnGoAwayFrameSent(stream_id));
send_control_stream_->SendGoAway(stream_id);
}
} // namespace
} // namespace test
} // namespace quic
| [
"Vestas.Wey@qq.com"
] | Vestas.Wey@qq.com |
199a1bf825f3d2d3a6303a16d9fc8f73ad0a7497 | 51b69d63e603c010d8955013a3b67bcb567228df | /codeforces/978B.cpp | 70e4fe182b331c07b30ca0ef649666fd2d437717 | [] | no_license | AugustoCalaca/competitive-programming | abcb8df9b6b741d5e6ae0c9020b58c11ec4fbd2d | 96bb034faaf44606970771e8a294bdf45e7a9356 | refs/heads/master | 2021-04-27T10:57:18.782352 | 2019-04-13T03:34:59 | 2019-04-13T03:34:59 | 122,549,144 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | cpp | #include <iostream>
#include <string>
using namespace std;
int main() {
int n;
string s;
cin >> n >> s;
int c = 0;
for(int i = 0; i < n; i++) {
if(s[i] == 'x')
c++;
else c = 0;
if(c == 3) break;
}
if(c != 3) {
cout << "0\n";
return 0;
}
int ans = 0;
c = 0;
for(int i = 0; i < n; i++) {
if(s[i] == 'x') {
c++;
if(c >= 3) ans++;
}
else c = 0;
}
cout << ans << "\n";
return 0;
}
| [
"augusto@Calaca.Augusto"
] | augusto@Calaca.Augusto |
f68f908f6da483c9d3667b60cb52d5f0aa68a59f | 51e8260df21001498150dc4dcadd36a364300e24 | /src/test/resources/results/armadillo/detectionObjectDetector2/l1/detection_objectDetector2_spectralClusterer_1_.h | 0c91a3a67b04422ff37ecfeb1fa1410aab053f71 | [] | no_license | Qwertzimus/EMAM2Cpp | f733a19eaf8619df921aaff9ee401d1c4e8314e8 | 6f5a7ffa880fa223fd5e3d828239b7d3bbd2efa1 | refs/heads/master | 2020-03-20T22:34:50.299533 | 2018-05-22T16:51:38 | 2018-05-22T16:51:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,669 | h | #ifndef DETECTION_OBJECTDETECTOR2_SPECTRALCLUSTERER_1_
#define DETECTION_OBJECTDETECTOR2_SPECTRALCLUSTERER_1_
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#include "armadillo.h"
#include "detection_objectDetector2_spectralClusterer_1__similarity.h"
#include "detection_objectDetector2_spectralClusterer_1__normalizedLaplacian.h"
#include "detection_objectDetector2_spectralClusterer_1__eigenSolver.h"
#include "detection_objectDetector2_spectralClusterer_1__kMeansClustering.h"
using namespace arma;
class detection_objectDetector2_spectralClusterer_1_{
const int n = 50;
const int elements = 2500;
const int k = 4;
const int maximumClusters = 1;
public:
mat red;
mat green;
mat blue;
mat clusters;
detection_objectDetector2_spectralClusterer_1__similarity similarity;
detection_objectDetector2_spectralClusterer_1__normalizedLaplacian normalizedLaplacian;
detection_objectDetector2_spectralClusterer_1__eigenSolver eigenSolver;
detection_objectDetector2_spectralClusterer_1__kMeansClustering kMeansClustering;
void init()
{
red=mat(n,n);
green=mat(n,n);
blue=mat(n,n);
clusters=mat(elements,maximumClusters);
similarity.init();
normalizedLaplacian.init();
eigenSolver.init();
kMeansClustering.init();
}
void execute()
{
similarity.red = red;
similarity.green = green;
similarity.blue = blue;
similarity.execute();
normalizedLaplacian.degree = similarity.degree;
normalizedLaplacian.similarity = similarity.similarity;
normalizedLaplacian.execute();
eigenSolver.matrix = normalizedLaplacian.nLaplacian;
eigenSolver.execute();
kMeansClustering.vectors = eigenSolver.eigenvectors;
kMeansClustering.execute();
clusters = kMeansClustering.clusters;
}
};
#endif
| [
"sascha.schneiders@rwth-aachen.de"
] | sascha.schneiders@rwth-aachen.de |
e03e4b1ceba6a9616803784840edefa1b0db8ac6 | 825e64b1cb17aac2a4d5c396d7bbeaca91aaaa10 | /src/transport/Messages/Packer.cpp | 4626f52164dff26b9fdb253afca694a8263c0e28 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | cpshereda/hxhim | 7cf7643228f44a7ce336bedf05762ad95d5b72bd | 1ef69e33d320e629779df27fb36de102f587c829 | refs/heads/master | 2023-01-29T12:53:21.008388 | 2020-12-08T19:50:24 | 2020-12-08T19:50:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,023 | cpp | #include "datastore/constants.hpp"
#include "transport/Messages/Packer.hpp"
#include "utils/little_endian.hpp"
#include "utils/memory.hpp"
namespace Transport {
static char *pack_addr(char *&dst, void *ptr) {
// // skip check
// if (!dst) {
// return nullptr;
// }
little_endian::encode(dst, ptr);
dst += sizeof(ptr);
return dst;
}
int Packer::pack(const Request::Request *req, void **buf, std::size_t *bufsize) {
int ret = TRANSPORT_ERROR;
if (!req) {
return ret;
}
// mlog(THALLIUM_DBG, "Packing Request type %d", req->op);
switch (req->op) {
case hxhim_op_t::HXHIM_PUT:
ret = pack(static_cast<const Request::BPut *>(req), buf, bufsize);
break;
case hxhim_op_t::HXHIM_GET:
ret = pack(static_cast<const Request::BGet *>(req), buf, bufsize);
break;
case hxhim_op_t::HXHIM_GETOP:
ret = pack(static_cast<const Request::BGetOp *>(req), buf, bufsize);
break;
case hxhim_op_t::HXHIM_DELETE:
ret = pack(static_cast<const Request::BDelete *>(req), buf, bufsize);
break;
case hxhim_op_t::HXHIM_HISTOGRAM:
ret = pack(static_cast<const Request::BHistogram *>(req), buf, bufsize);
break;
default:
break;
}
// mlog(THALLIUM_DBG, "Done Packing Request type %d", req->op);
return ret;
}
int Packer::pack(const Request::BPut *bpm, void **buf, std::size_t *bufsize) {
char *curr = nullptr;
if (pack(static_cast<const Request::Request *>(bpm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) {
return TRANSPORT_ERROR;
}
for(std::size_t i = 0; i < bpm->count; i++) {
// subject + len
bpm->subjects[i].pack(curr, true);
// subject addr
pack_addr(curr, bpm->subjects[i].data());
// predicate + len
bpm->predicates[i].pack(curr, true);
// predicate addr
pack_addr(curr, bpm->predicates[i].data());
// object + len
bpm->objects[i].pack(curr, true);
}
return TRANSPORT_SUCCESS;
}
int Packer::pack(const Request::BGet *bgm, void **buf, std::size_t *bufsize) {
char *curr = nullptr;
if (pack(static_cast<const Request::Request *>(bgm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) {
return TRANSPORT_ERROR;
}
for(std::size_t i = 0; i < bgm->count; i++) {
// subject
bgm->subjects[i].pack(curr, true);
// subject addr
pack_addr(curr, bgm->subjects[i].data());
// predicate
bgm->predicates[i].pack(curr, true);
// predicate addr
pack_addr(curr, bgm->predicates[i].data());
// object type
little_endian::encode(curr, bgm->object_types[i], sizeof(bgm->object_types[i]));
curr += sizeof(bgm->object_types[i]);
}
return TRANSPORT_SUCCESS;
}
int Packer::pack(const Request::BGetOp *bgm, void **buf, std::size_t *bufsize) {
char *curr = nullptr;
if (pack(static_cast<const Request::Request *>(bgm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) {
return TRANSPORT_ERROR;
}
for(std::size_t i = 0; i < bgm->count; i++) {
// operation to run
little_endian::encode(curr, bgm->ops[i], sizeof(bgm->ops[i]));
curr += sizeof(bgm->ops[i]);
if ((bgm->ops[i] != hxhim_getop_t::HXHIM_GETOP_FIRST) &&
(bgm->ops[i] != hxhim_getop_t::HXHIM_GETOP_LAST)) {
// subject
bgm->subjects[i].pack(curr, true);
// predicate
bgm->predicates[i].pack(curr, true);
}
// object type
little_endian::encode(curr, bgm->object_types[i], sizeof(bgm->object_types[i]));
curr += sizeof(bgm->object_types[i]);
// number of records to get back
little_endian::encode(curr, bgm->num_recs[i], sizeof(bgm->num_recs[i]));
curr += sizeof(bgm->num_recs[i]);
}
return TRANSPORT_SUCCESS;
}
int Packer::pack(const Request::BDelete *bdm, void **buf, std::size_t *bufsize) {
char *curr = nullptr;
if (pack(static_cast<const Request::Request *>(bdm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) {
return TRANSPORT_ERROR;
}
for(std::size_t i = 0; i < bdm->count; i++) {
// subject
bdm->subjects[i].pack(curr, true);
// subject addr
pack_addr(curr, bdm->subjects[i].data());
// predicate
bdm->predicates[i].pack(curr, true);
// predicate addr
pack_addr(curr, bdm->predicates[i].data());
}
return TRANSPORT_SUCCESS;
}
int Packer::pack(const Request::BHistogram *bhm, void **buf, std::size_t *bufsize) {
char *curr = nullptr;
if (pack(static_cast<const Request::Request *>(bhm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) {
return TRANSPORT_ERROR;
}
for(std::size_t i = 0; i < bhm->count; i++) {
// histogram names
bhm->names[i].pack(curr, false);
}
return TRANSPORT_SUCCESS;
}
int Packer::pack(const Response::Response *res, void **buf, std::size_t *bufsize) {
int ret = TRANSPORT_ERROR;
if (!res) {
return ret;
}
// mlog(THALLIUM_DBG, "Packing Response type %d", res->op);
switch (res->op) {
case hxhim_op_t::HXHIM_PUT:
ret = pack(static_cast<const Response::BPut *>(res), buf, bufsize);
break;
case hxhim_op_t::HXHIM_GET:
ret = pack(static_cast<const Response::BGet *>(res), buf, bufsize);
break;
case hxhim_op_t::HXHIM_GETOP:
ret = pack(static_cast<const Response::BGetOp *>(res), buf, bufsize);
break;
case hxhim_op_t::HXHIM_DELETE:
ret = pack(static_cast<const Response::BDelete *>(res), buf, bufsize);
break;
case hxhim_op_t::HXHIM_HISTOGRAM:
ret = pack(static_cast<const Response::BHistogram *>(res), buf, bufsize);
break;
default:
break;
}
// mlog(THALLIUM_DBG, "Done Packing Response type %d", res->op);
return ret;
}
int Packer::pack(const Response::BPut *bpm, void **buf, std::size_t *bufsize) {
char *curr = nullptr;
if (pack(static_cast<const Response::Response *>(bpm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) {
return TRANSPORT_ERROR;
}
for(std::size_t i = 0; i < bpm->count; i++) {
little_endian::encode(curr, bpm->statuses[i], sizeof(bpm->statuses[i]));
curr += sizeof(bpm->statuses[i]);
// original subject addr + len
bpm->orig.subjects[i].pack_ref(curr, true);
// original predicate addr + len
bpm->orig.predicates[i].pack_ref(curr, true);
}
return TRANSPORT_SUCCESS;
}
int Packer::pack(const Response::BGet *bgm, void **buf, std::size_t *bufsize) {
char *curr = nullptr;
if (pack(static_cast<const Response::Response *>(bgm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) {
return TRANSPORT_ERROR;
}
for(std::size_t i = 0; i < bgm->count; i++) {
little_endian::encode(curr, bgm->statuses[i], sizeof(bgm->statuses[i]));
curr += sizeof(bgm->statuses[i]);
// original subject addr + len
bgm->orig.subjects[i].pack_ref(curr, true);
// original predicate addr + len
bgm->orig.predicates[i].pack_ref(curr, true);
// object
if (bgm->statuses[i] == DATASTORE_SUCCESS) {
bgm->objects[i].pack(curr, true);
}
}
return TRANSPORT_SUCCESS;
}
int Packer::pack(const Response::BGetOp *bgm, void **buf, std::size_t *bufsize) {
char *curr = nullptr;
if (pack(static_cast<const Response::Response *>(bgm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) {
return TRANSPORT_ERROR;
}
for(std::size_t i = 0; i < bgm->count; i++) {
little_endian::encode(curr, bgm->statuses[i], sizeof(bgm->statuses[i]));
curr += sizeof(bgm->statuses[i]);
// num_recs
little_endian::encode(curr, bgm->num_recs[i], sizeof(bgm->num_recs[i]));
curr += sizeof(bgm->num_recs[i]);
for(std::size_t j = 0; j < bgm->num_recs[i]; j++) {
// subject
bgm->subjects[i][j].pack(curr, true);
// predicate
bgm->predicates[i][j].pack(curr, true);
// object
if (bgm->statuses[i] == DATASTORE_SUCCESS) {
bgm->objects[i][j].pack(curr, true);
}
}
}
return TRANSPORT_SUCCESS;
}
int Packer::pack(const Response::BDelete *bdm, void **buf, std::size_t *bufsize) {
char *curr = nullptr;
if (pack(static_cast<const Response::Response *>(bdm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) {
return TRANSPORT_ERROR;
}
for(std::size_t i = 0; i < bdm->count; i++) {
little_endian::encode(curr, bdm->statuses[i], sizeof(bdm->statuses[i]));
curr += sizeof(bdm->statuses[i]);
// original subject addr + len
bdm->orig.subjects[i].pack_ref(curr, true);
// original predicate addr + len
bdm->orig.predicates[i].pack_ref(curr, true);
}
return TRANSPORT_SUCCESS;
}
int Packer::pack(const Response::BHistogram *bhm, void **buf, std::size_t *bufsize) {
char *curr = nullptr;
if (pack(static_cast<const Response::Response *>(bhm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) {
return TRANSPORT_ERROR;
}
std::size_t avail = *bufsize - (curr - (char *) *buf);
for(std::size_t i = 0; i < bhm->count; i++) {
little_endian::encode(curr, bhm->statuses[i], sizeof(bhm->statuses[i]));
curr += sizeof(bhm->statuses[i]);
// histogram
bhm->histograms[i]->pack(curr, avail, nullptr);
}
return TRANSPORT_SUCCESS;
}
int Packer::pack(const Message *msg, void **buf, std::size_t *bufsize, char **curr) {
if (!msg || !buf || !bufsize || !curr) {
return TRANSPORT_ERROR;
}
*bufsize = msg->size();
// only allocate space if a nullptr is provided; otherwise, assume *buf has enough space
if (!*buf) {
if (!(*buf = alloc(*bufsize))) {
*bufsize = 0;
return TRANSPORT_ERROR;
}
}
*curr = (char *) *buf;
// copy header into *buf
little_endian::encode(*curr, msg->direction);
*curr += sizeof(msg->direction);
little_endian::encode(*curr, msg->op);
*curr += sizeof(msg->op);
little_endian::encode(*curr, msg->src);
*curr += sizeof(msg->src);
little_endian::encode(*curr, msg->dst);
*curr += sizeof(msg->dst);
little_endian::encode(*curr, msg->count);
*curr += sizeof(msg->count);
return TRANSPORT_SUCCESS;
}
int Packer::pack(const Request::Request *req, void **buf, std::size_t *bufsize, char **curr) {
return pack(static_cast<const Message *>(req), buf, bufsize, curr);
}
int Packer::pack(const Response::Response *res, void **buf, std::size_t *bufsize, char **curr) {
return pack(static_cast<const Message *>(res), buf, bufsize, curr);
}
}
| [
"jasonlee@lanl.gov"
] | jasonlee@lanl.gov |
53ae6d240054548fe6180e5891a066453db5d113 | 38b9daafe39f937b39eefc30501939fd47f7e668 | /tutorials/2WayCouplingOceanWave3D/EvalResults180628-Eta-W/95.6/uniform/time | 91a0a29ea7edd45b72de7dbef11c1668bcc786c5 | [] | no_license | rubynuaa/2-way-coupling | 3a292840d9f56255f38c5e31c6b30fcb52d9e1cf | a820b57dd2cac1170b937f8411bc861392d8fbaa | refs/heads/master | 2020-04-08T18:49:53.047796 | 2018-08-29T14:22:18 | 2018-08-29T14:22:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,006 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 3.0.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "95.6/uniform";
object time;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
value 95.6000000000000085;
name "95.6";
index 12870;
deltaT 0.00714286;
deltaT0 0.00714286;
// ************************************************************************* //
| [
"abenaz15@etudiant.mines-nantes.fr"
] | abenaz15@etudiant.mines-nantes.fr | |
ce4a0f0ea26bc34057c2fb79a106fec4b24cc951 | 791c9de4ec8b5778bb6327da5fe967f5c4e1ed95 | /src/PhoneBook.hpp | 03c96acd59537574fc9fccac6ee266ffa03f6778 | [] | no_license | sv99/sms_gate | 528cf0b567046af4a1642ed6400e09bf3fa02fd3 | f277aba9739e5952ffd4de1702a90c16a41d89f6 | refs/heads/master | 2020-04-14T22:41:53.148696 | 2018-04-05T14:41:59 | 2018-04-05T14:41:59 | 68,000,957 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 493 | hpp | //
// Created by Volkov on 09.09.16.
//
#ifndef SMS_GATE_PHONEBOOK_H
#define SMS_GATE_PHONEBOOK_H
#include <string>
#include <vector>
class Number {
public:
int m_id{0};
std::string m_number{""};
std::string to_string();
};
class Record {
public:
int m_id{0};
std::string m_FirstName{};
std::string m_SecondName{};
std::vector<Number> numbers{};
std::string to_string();
};
class PhoneBook {
public:
std::vector<Record> records{};
};
#endif //SMS_GATE_PHONEBOOK_H
| [
"sv99@inbox.ru"
] | sv99@inbox.ru |
668d5caa75249dc3a94d500bc45f1ccd01617d13 | 1739bf1e1512c11f3d096beaed009677d349575d | /Sources/Engine/TRtxPipeline.h | 21a89a6c4895ed211a3fd172d9a48cfe7aa9250b | [] | no_license | TiraX/tix2 | 60eebd345097e80d59c8a1d2887a2413ddc1fa11 | ebdab17e400764abfb9ea7a9d4db3fbdada8f293 | refs/heads/master | 2023-02-18T05:28:38.956220 | 2023-01-28T14:41:10 | 2023-01-28T14:41:10 | 129,262,369 | 10 | 2 | null | 2021-03-30T01:32:13 | 2018-04-12T14:16:02 | C++ | UTF-8 | C++ | false | false | 1,334 | h | /*
TiX Engine v2.0 Copyright (C) 2018~2021
By ZhaoShuai tirax.cn@gmail.com
*/
#pragma once
namespace tix
{
enum E_HITGROUP
{
HITGROUP_ANY_HIT,
HITGROUP_CLOSEST_HIT,
HITGROUP_INTERSECTION,
HITGROUP_NUM
};
struct TRtxPipelineDesc
{
uint32 Flags;
TShaderPtr ShaderLib;
TVector<TString> ExportNames;
TString HitGroupName;
TString HitGroup[HITGROUP_NUM];
int32 MaxAttributeSizeInBytes;
int32 MaxPayloadSizeInBytes;
int32 MaxTraceRecursionDepth;
TRtxPipelineDesc()
: Flags(0)
, MaxAttributeSizeInBytes(0)
, MaxPayloadSizeInBytes(0)
, MaxTraceRecursionDepth(0)
{
}
};
class TRtxPipeline : public TResource
{
public:
TRtxPipeline();
virtual ~TRtxPipeline();
void SetShaderLib(TShaderPtr InShaderLib);
void AddExportName(const TString& InName);
void SetHitGroupName(const TString& InName);
void SetHitGroup(E_HITGROUP HitGroup, const TString& InName);
void SetMaxAttributeSizeInBytes(int32 InSize);
void SetMaxPayloadSizeInBytes(int32 InSize);
void SetMaxTraceRecursionDepth(int32 InDepth);
virtual void InitRenderThreadResource() override;
virtual void DestroyRenderThreadResource() override;
const TRtxPipelineDesc& GetDesc() const
{
return Desc;
}
FRtxPipelinePtr PipelineResource;
protected:
protected:
TRtxPipelineDesc Desc;
};
}
| [
"zhaoshuai2@kingsoft.com"
] | zhaoshuai2@kingsoft.com |
b4e505e38b7e7375a9a3cc64761eb9b0d791b862 | 64684646c96123397d60052d7d04bb370a182b42 | /game/dragon3d-core/test/com/dragon3d/util/assets/AssetsManagerTest.cc | 05141b1ec3ed4998690f9e02ad7bf849b8da773a | [] | no_license | yubing744/dragon | e6ca32726df8fe8e9e1d0586058b8628245efb55 | eca9b4b6823c98ddc56ccedde486099653b13920 | refs/heads/master | 2020-05-22T09:11:15.052073 | 2017-01-02T01:30:53 | 2017-01-02T01:30:53 | 33,351,592 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,499 | cc | /*
* Copyright 2013 the original author or authors.
*
* 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.
*/
/**********************************************************************
* Author: Owen Wu/wcw/yubing
* Email: yubing744@163.com
* Created: 2014/04/27
**********************************************************************/
#include <gtest/gtest.h>
#include <dragon/lang/System.h>
#include <dragon/io/File.h>
#include <com/dragon3d/util/assets/AssetsManager.h>
Import dragon::io;
Import dragon::lang;
Import com::dragon3d::util::assets;
/*
TEST(Com_Dragon3d_Util_Assets_AssetsManagerTest, getResources) {
const String* base = System::getProperty("HOME");
String* filePath = new String(L"/dragon_test/model_load_test/");
File* file = new File(base, filePath);
//List<Resource>* reses = AssetsManager::getInstance()->getResources("/dragon_test/model_load_test/", true);
//ASSERT_TRUE(reses != null);
SafeRelease(file);
SafeRelease(filePath);
}
*/
| [
"yubing744@163.com"
] | yubing744@163.com |
ccc5ff6e2cea566c23d70eab3fa42f9354c44dfe | e39b3fad5b4ee23f926509a7e5fc50e84d9ebdc8 | /AtCoder/Companies/AISing-Programming-Contest/2019/c.cpp | d5bca632ec2a2584cf7aa0a701cdae7c3c0af3c3 | [] | no_license | izumo27/competitive-programming | f755690399c5ad1c58d3db854a0fa21eb8e5f775 | e721fc5ede036ec5456da9a394648233b7bfd0b7 | refs/heads/master | 2021-06-03T05:59:58.460986 | 2021-05-08T14:39:58 | 2021-05-08T14:39:58 | 123,675,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,858 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define REP(i, n) for(int i=0; i<(n); ++i)
#define FOR(i, a, b) for(int i=(a); i<(b); ++i)
#define FORR(i, a, b) for(int i=(b)-1; i>=(a); --i)
#define DEBUG(x) cout<<#x<<": "<<x<<'\n'
#define DEBUG_VEC(v) cout<<#v<<":";REP(i, v.size())cout<<' '<<v[i];cout<<'\n'
#define ALL(a) (a).begin(), (a).end()
#define CHMIN(a, b) a=min((a), (b))
#define CHMAX(a, b) a=max((a), (b))
const ll MOD=1000000007ll;
// const ll MOD=998244353ll;
#define FIX(a) ((a)%MOD+MOD)%MOD
const double EPS=1e-11;
#define EQ0(x) (abs((x))<EPS)
#define EQ(a, b) (abs((a)-(b))<EPS)
bool used[404][404];
int dx[4]={-1, 0, 1, 0}, dy[4]={0, -1, 0, 1};
int h, w;
string s[404];
pll bfs(int sx, int sy){
queue<pair<pii, bool>> q;
q.push(make_pair(pii(sx, sy), true));
ll cnt1=0, cnt2=0;
while(q.size()){
pair<pii, bool> p=q.front();
q.pop();
REP(i, 4){
int nx=p.first.first+dx[i];
int ny=p.first.second+dy[i];
if(nx>=0 && nx<h && ny>=0 && ny<w && !used[nx][ny]){
if(p.second){
if(s[nx][ny]=='.'){
++cnt2;
q.push(make_pair(pii(nx, ny), false));
used[nx][ny]=true;
}
}
else{
if(s[nx][ny]=='#'){
++cnt1;
q.push(make_pair(pii(nx, ny), true));
used[nx][ny]=true;
}
}
}
}
}
return pll(cnt1, cnt2);
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>h>>w;
REP(i, h){
cin>>s[i];
}
ll ans=0;
REP(i, h){
REP(j, w){
if(s[i][j]!='#'){
continue;
}
pll cnt=bfs(i, j);
ans+=cnt.first*cnt.second;
}
}
cout<<ans<<'\n';
return 0;
}
| [
"22386882+izumo27@users.noreply.github.com"
] | 22386882+izumo27@users.noreply.github.com |
0d0eb7de6a48d48b1894abb0e16055230a1bb461 | 260a59fb9e70d043b4208abd871bf559b4cfa874 | /src/frame.cpp | 828df7e04482adf8ff8fbdbb8adf7f316d52a2b2 | [] | no_license | softwareCxw/signature2 | 0cf15c84e272637904c5145a4e01e337ba250cd6 | 8cf33164bc121719bf8f6de7eb2b43aba367e413 | refs/heads/master | 2020-12-31T04:29:15.346025 | 2015-11-25T08:58:40 | 2015-11-25T08:58:40 | 46,849,268 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,875 | cpp | #include "frame.h"
void frame::setup()
{
i_choose = CHOOSE;
_fbo.allocate(1920, 1080);
_chooseBack.setup();
_signature.setup();
}
void frame::update()
{
switch(i_choose)
{
case CHOOSE :
_chooseBack.update();
break;
case SIGNATURE :
_signature.update();
break;
default:
break;
}
}
void frame::draw()
{
_fbo.begin();
ofClear(0);
switch(i_choose)
{
case CHOOSE :
_chooseBack.draw();
break;
case SIGNATURE :
_signature.draw();
break;
default:
break;
}
_fbo.end();
_fbo.draw(0, 0, ofGetWidth(), ofGetHeight());
}
void frame::mouseMoved( int x, int y )
{
}
void frame::mouseDragged( int x, int y, int button )
{
x = _fbo.getWidth() / ofGetWidth() * x;
y = _fbo.getHeight() / ofGetHeight() *y;
switch(i_choose)
{
case CHOOSE :
_chooseBack.mouseTrigger(MOUSE_DRAGGED, x, y, button);
break;
case SIGNATURE :
_signature.mouseTrigger(MOUSE_DRAGGED, x, y, button);
break;
default:
break;
}
}
void frame::mousePressed( int x, int y, int button )
{
x = _fbo.getWidth() / ofGetWidth() * x;
y = _fbo.getHeight() / ofGetHeight() *y;
switch(i_choose)
{
case CHOOSE :
_chooseBack.mouseTrigger(MOUSE_PRESSED, x, y, button);
break;
case SIGNATURE :
_signature.mouseTrigger(MOUSE_PRESSED, x, y, button);
break;
default:
break;
}
}
void frame::mouseReleased( int x, int y, int button )
{
x = _fbo.getWidth() / ofGetWidth() * x;
y = _fbo.getHeight() / ofGetHeight() *y;
switch(i_choose)
{
case CHOOSE :
_chooseBack.mouseTrigger(MOUSE_RELEASED, x, y, button);
if(_chooseBack.is_next()) {
i_choose = SIGNATURE;
_signature.setSignatureImg(_chooseBack.getSignatureImg());
_chooseBack.revect();
}
break;
case SIGNATURE :
_signature.mouseTrigger(MOUSE_RELEASED, x, y, button);
if(_signature.is_next()) {
i_choose = CHOOSE;
_signature.revect();
}
break;
default:
break;
}
}
| [
"825873709@qq.com"
] | 825873709@qq.com |
8f50de6868bc5e48af09ee9b5878ef0a50e1c04f | 4628e5e79389f7d9a012778c15deaefd9b5a07f1 | /modules/task_2/napylov_e_contrast/contrast.cpp | 16d61512db3c3c270e7914df2ef9264f90bfab4b | [
"BSD-3-Clause"
] | permissive | BFDestroyeer/pp_2021_spring_informatics | 6fdcd299b7860fe0f5f71a4967b63be93b8b59f0 | 508879cdc00fcf168268f9f4c99f024021719f5e | refs/heads/master | 2023-03-28T00:55:23.106817 | 2021-03-26T06:53:45 | 2021-03-26T06:53:45 | 345,943,620 | 0 | 0 | BSD-3-Clause | 2021-03-09T09:00:28 | 2021-03-09T09:00:27 | null | UTF-8 | C++ | false | false | 3,319 | cpp | // Copyright 2021 Napylov Evgenii
#include <iostream>
#include <cassert>
#include <random>
#include <ctime>
#include <algorithm>
#include "../../../modules/task_2/napylov_e_contrast/contrast.h"
void print_vec(const VecImage& vec) {
for (auto val : vec) {
std::cout << static_cast<int>(val) << ' ';
}
std::cout << std::endl;
}
VecImage image_to_vec(const Image& image, int w, int h) {
VecImage res(w * h);
int k = 0;
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
res[k++] = image[i][j];
}
}
return res;
}
Image vec_to_image(const VecImage& vec, int w, int h) {
Image res(w);
for (int i = 0; i < w; i++) {
res[i].resize(h);
for (int j = 0; j < h; j++) {
res[i][j] = vec[h * i + j];
}
}
return res;
}
VecImage RandomVector(int size) {
static std::mt19937 gen(time(0));
VecImage result(size);
std::uniform_int_distribution<unsigned int> distr(0, 255);
for (int i = 0; i < size; i++) {
result[i] = static_cast<unsigned char>(distr(gen));
}
return result;
}
VecImage add_contrast(VecImage image, unsigned char down, unsigned char up) {
assert(up > down);
unsigned char min = *std::min_element(image.begin(), image.end());
unsigned char max = *std::max_element(image.begin(), image.end());
if (max == min) {
return image;
} else {
for (size_t i = 0; i < image.size(); i++) {
image[i] = round((static_cast<double>((image[i] - min))
/ static_cast<double>((max - min)))* (up - down));
}
return image;
}
}
std::pair<unsigned char, unsigned char> minmax_omp(const VecImage& image) {
unsigned char min_col = 255;
unsigned char max_col = 0;
// MSVC19 does not support the min/max reduction :(
// -> Each thread searches for a local min max.
std::vector<unsigned char> min_vec(omp_get_max_threads());
std::fill(min_vec.begin(), min_vec.end(), 255);
std::vector<unsigned char> max_vec(omp_get_max_threads());
std::fill(max_vec.begin(), max_vec.end(), 0);
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(image.size()); i++) {
if (image[i] > max_vec[omp_get_thread_num()]) {
max_vec[omp_get_thread_num()] = image[i];
}
if (image[i] < min_vec[omp_get_thread_num()]) {
min_vec[omp_get_thread_num()] = image[i];
}
}
// Reduction
max_col = *std::max_element(max_vec.begin(), max_vec.end());
min_col = *std::min_element(min_vec.begin(), min_vec.end());
return std::pair<double, double>(min_col, max_col);
}
VecImage add_contrast_omp(VecImage image, unsigned char down,
unsigned char up) {
assert(up > down);
std::pair<double, double> minmax = minmax_omp(image);
unsigned char min_col = minmax.first;
unsigned char max_col = minmax.second;
if (max_col == min_col) {
return image;
} else {
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(image.size()); i++) {
image[i] = round((static_cast<double>((image[i] - min_col))
/ static_cast<double>((max_col - min_col))) * (up - down));
}
return image;
}
}
| [
"vetero4ekcs@mail.ru"
] | vetero4ekcs@mail.ru |
2127fc3dc33e9565b5344f468ad66d666da8a3b0 | 8cfcf7710c2ffe3e6df8dc2d95a90769cc56c779 | /ArmFW.ino | 8a5d8e8afdbd79054de20e6b602e3125d9fd4348 | [] | no_license | AmitSoli/IMU_Glove | eb80adbdc4329fd7d29eadf2c21f2d4a08259dea | da9407e8f0baf91776cbebf93eecf1a75149bb4b | refs/heads/master | 2022-11-27T06:41:09.398665 | 2020-07-31T12:05:52 | 2020-07-31T12:05:52 | 284,027,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,232 | ino |
#include <Wire.h>
#include <BMI160Gen.h>
#define NUM_GYROS (5)
#define TCAADDR 0x70
#define BMI160_RA_GYRO_X_L 0x0C
#define interrupt_lock() (0)
#define interrupt_unlock(flags) while (0) {}
typedef struct BMI_s {
BMI160GenClass bmi160;
float gyroXangle;
float gyroYangle;
float gyroZangle;
float CFangleX;
float CFangleY;
float CFangleZ;
} BMI;
BMI bmi_s_0;
BMI bmi_s_1;
BMI bmi_s_2;
BMI bmi_s_3;
BMI bmi_s_4;
BMI bmi_s_array[] = {bmi_s_0, bmi_s_1, bmi_s_2, bmi_s_3, bmi_s_4};
int entry_array[] = {2, 3, 5, 6, 7};
byte oppos_num_bit[] = {7, 6, 5, 4, 3, 2, 1, 0};
byte shifted_num_bit[] = {0 << 3, 1 << 3, 2 << 3, 3 << 3, 4 << 3, 5 << 3, 6 << 3, 7 << 3};
byte shifted_oppos_num_bit[] = {7 << 3, 6 << 3, 5 << 3, 4 << 3, 3 << 3, 2 << 3, 1 << 3, 0};
byte end_num_bit[] = {0 << 6, 1 << 6, 0 << 6, 1 << 6, 2 << 6, 3 << 6, 2 << 6, 3 << 6};
byte oppos_end_num_bit[] = {3 << 6, 2 << 6, 3 << 6, 2 << 6, 1 << 6, 0 << 6, 1 << 6, 0};
const int i2c_addr = 0x69;
float G_GAIN = 0.0076;
float DT = 0.00001; //20ms, baud = 304bits/DT b = 38400, dt = 0.02
float AA = 0.99;
int g_curr_bmi160_index = 0;
byte g_i = 0;
byte float_to_byte(float num)
{
float abs_num = (num >=0) ? num : -num;
byte b_abs_num = round(abs_num*100);
byte ret = b_abs_num & 0x7F;
if (num < 0)
{
ret = (ret | 0x80);
}
return ret;
}
byte* float_to_ulong(float num, byte* outArray)
{
float abs_num = (num >=0) ? num : -num;
unsigned long b_abs_num = round(abs_num*100000000);
unsigned long toSend = b_abs_num & 0x7FFFFFFF;
if (num < 0)
{
toSend = (toSend | 0x80000000);
}
outArray[0] = (toSend & 0xFF000000) >> 24;
outArray[1] = (toSend & 0xFF0000) >> 16;
outArray[2] = (toSend & 0xFF00) >> 8;
outArray[3] = (toSend & 0xFF);
return outArray;
}
void setup(void)
{
unsigned long startTime = millis();
Serial.begin(115200);
for (int i=0; i<NUM_GYROS; i++)
{
bmi_s_array[i].bmi160.begin(1 << entry_array[i],TCAADDR,BMI160GenClass::I2C_MODE, i2c_addr);
bmi_s_array[i].gyroXangle = 0;
bmi_s_array[i].gyroYangle = 0;
bmi_s_array[i].gyroZangle = 0;
bmi_s_array[i].CFangleX = 0;
bmi_s_array[i].CFangleY = 0;
bmi_s_array[i].CFangleZ = 0;
bmi_s_array[i].bmi160.autoCalibrateGyroOffset();
}
while(Serial.available() >0)
{
Serial.read();
}
while(millis() - startTime < 5000)
{
}
}
void loop(void)
{
int ax, ay, az, gx, gy, gz; // raw values
unsigned long startTime = millis();
bmi_s_array[g_curr_bmi160_index].bmi160.readMotionSensor(ax, ay, az, gx, gy, gz);
// angular velocity
float rateX = gx*G_GAIN;
float rateY = gy*G_GAIN;
float rateZ = gz*G_GAIN;
float accXangle = (atan2(ay,az)+PI)*RAD_TO_DEG;
float accYangle = (atan2(az,ax)+PI)*RAD_TO_DEG;
float accZangle = (atan2(ax,ay)+PI)*RAD_TO_DEG;
if(accXangle>180) accXangle-=360;
if(accYangle>180) accYangle-=360;
if(accZangle>180) accZangle-=360;
/*
//no acc
bmi_s_array[g_curr_bmi160_index].CFangleX = bmi_s_array[g_curr_bmi160_index].CFangleX + rateX*DT*NUM_GYROS;
bmi_s_array[g_curr_bmi160_index].CFangleY = bmi_s_array[g_curr_bmi160_index].CFangleY + rateY*DT*NUM_GYROS;
bmi_s_array[g_curr_bmi160_index].CFangleZ = bmi_s_array[g_curr_bmi160_index].CFangleZ + rateZ*DT*NUM_GYROS;
*/
// original
bmi_s_array[g_curr_bmi160_index].CFangleX = AA*(bmi_s_array[g_curr_bmi160_index].CFangleX + rateX*DT*NUM_GYROS) + (1-AA)*accXangle;
bmi_s_array[g_curr_bmi160_index].CFangleY = AA*(bmi_s_array[g_curr_bmi160_index].CFangleY + rateY*DT*NUM_GYROS) + (1-AA)*accYangle;
bmi_s_array[g_curr_bmi160_index].CFangleZ = AA*(bmi_s_array[g_curr_bmi160_index].CFangleZ + rateZ*DT*NUM_GYROS) + (1-AA)*accZangle;
/* neg
float cos_yaw = cos(bmi_s_array[g_curr_bmi160_index].CFangleZ*DEG_TO_RAD);
float sin_yaw = sin(bmi_s_array[g_curr_bmi160_index].CFangleZ*DEG_TO_RAD);
float cos_roll = cos(bmi_s_array[g_curr_bmi160_index].CFangleY*DEG_TO_RAD);
float sin_roll = sin(bmi_s_array[g_curr_bmi160_index].CFangleY*DEG_TO_RAD);
float sin_pitch = sin(bmi_s_array[g_curr_bmi160_index].CFangleX*DEG_TO_RAD);
float cos_pitch = cos(bmi_s_array[g_curr_bmi160_index].CFangleX*DEG_TO_RAD);
*/
byte delta = millis() - startTime;
float cos_yaw = cos(bmi_s_array[g_curr_bmi160_index].CFangleZ*DEG_TO_RAD);
float cos_roll = cos(bmi_s_array[g_curr_bmi160_index].CFangleY*DEG_TO_RAD);
float cos_pitch = cos(bmi_s_array[g_curr_bmi160_index].CFangleX*DEG_TO_RAD);
float sin_yaw = sin(bmi_s_array[g_curr_bmi160_index].CFangleZ*DEG_TO_RAD);
float sin_roll = sin(bmi_s_array[g_curr_bmi160_index].CFangleY*DEG_TO_RAD);
float sin_pitch = sin(bmi_s_array[g_curr_bmi160_index].CFangleX*DEG_TO_RAD);
byte arr[4];
byte start_seq = entry_array[g_curr_bmi160_index] | shifted_oppos_num_bit[entry_array[g_curr_bmi160_index]] | end_num_bit[entry_array[g_curr_bmi160_index]];
byte end_seq = oppos_num_bit[entry_array[g_curr_bmi160_index]] | shifted_num_bit[entry_array[g_curr_bmi160_index]] | oppos_end_num_bit[entry_array[g_curr_bmi160_index]];
//Serial.print(start_seq);
//Serial.print('\t');
//Serial.println(end_seq);
//byte start_seq = g_curr_bmi160_index | shifted_oppos_num_bit[g_curr_bmi160_index] | end_num_bit[g_curr_bmi160_index];
//byte end_seq = oppos_num_bit[g_curr_bmi160_index] | shifted_num_bit[g_curr_bmi160_index] | oppos_end_num_bit[g_curr_bmi160_index];
Serial.flush();
Serial.write(start_seq);
Serial.write(float_to_ulong(cos_yaw*cos_pitch,arr), 4);
Serial.write(float_to_ulong(cos_yaw*sin_pitch,arr), 4);
Serial.write(float_to_ulong(-sin_yaw,arr), 4);
Serial.write(float_to_ulong(sin_roll*sin_yaw*cos_pitch-cos_roll*sin_pitch,arr), 4);
Serial.write(float_to_ulong(sin_roll*sin_yaw*sin_pitch+cos_roll*cos_pitch,arr), 4);
Serial.write(float_to_ulong(sin_roll*cos_yaw,arr), 4);
Serial.write(float_to_ulong(cos_roll*sin_yaw*cos_pitch+sin_roll*sin_pitch,arr), 4);
Serial.write(float_to_ulong(cos_roll*sin_yaw*sin_pitch-sin_roll*cos_pitch,arr), 4);
Serial.write(float_to_ulong(cos_roll*cos_yaw,arr), 4);
Serial.write(end_seq);
g_curr_bmi160_index = (g_curr_bmi160_index + 1) % NUM_GYROS;
while(millis() - startTime < DT*1000)
{
}
}
| [
"soliamit@gmail.com"
] | soliamit@gmail.com |
6b490e5e6772ed11bb92c37a88cc84d443046655 | d9ee3d21555a856326899f3470140ab1694e49a3 | /HggRazor/CommonTools/include/TableMakerAux.hh | 7525e8517db0d01aad5f933bbbce43204ed8f42d | [] | no_license | cmorgoth/RazorFramework | 47f76e17a00a8aee01e416649db3983a25101dee | ca180336bf5498c8731b360bc70fd5c980b41cea | refs/heads/master | 2020-04-06T06:59:03.881664 | 2016-06-28T21:26:18 | 2016-06-28T21:26:18 | 35,075,908 | 1 | 1 | null | 2016-05-27T00:43:15 | 2015-05-05T03:34:23 | C++ | UTF-8 | C++ | false | false | 51 | hh | #ifndef TableMakerAux
#define TableMakerAux
#endif
| [
"cristian.morgoth@gmail.com"
] | cristian.morgoth@gmail.com |
0b1f7d4a6c6c51dfcc15480bc8f2caa8470c8302 | e4ec5b6cf3cfe2568ef0b5654c019e398b4ecc67 | /aws-sdk-cpp/1.2.10/include/aws/budgets/model/DescribeBudgetRequest.h | 13843bd583a4a95a49d3811afc8fc1668e17629b | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | EnjoyLifeFund/macHighSierra-cellars | 59051e496ed0e68d14e0d5d91367a2c92c95e1fb | 49a477d42f081e52f4c5bdd39535156a2df52d09 | refs/heads/master | 2022-12-25T19:28:29.992466 | 2017-10-10T13:00:08 | 2017-10-10T13:00:08 | 96,081,471 | 3 | 1 | null | 2022-12-17T02:26:21 | 2017-07-03T07:17:34 | null | UTF-8 | C++ | false | false | 3,482 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/budgets/Budgets_EXPORTS.h>
#include <aws/budgets/BudgetsRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Budgets
{
namespace Model
{
/**
* Request of DescribeBudget<p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/budgets-2016-10-20/DescribeBudgetRequest">AWS
* API Reference</a></p>
*/
class AWS_BUDGETS_API DescribeBudgetRequest : public BudgetsRequest
{
public:
DescribeBudgetRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "DescribeBudget"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
inline const Aws::String& GetAccountId() const{ return m_accountId; }
inline void SetAccountId(const Aws::String& value) { m_accountIdHasBeenSet = true; m_accountId = value; }
inline void SetAccountId(Aws::String&& value) { m_accountIdHasBeenSet = true; m_accountId = std::move(value); }
inline void SetAccountId(const char* value) { m_accountIdHasBeenSet = true; m_accountId.assign(value); }
inline DescribeBudgetRequest& WithAccountId(const Aws::String& value) { SetAccountId(value); return *this;}
inline DescribeBudgetRequest& WithAccountId(Aws::String&& value) { SetAccountId(std::move(value)); return *this;}
inline DescribeBudgetRequest& WithAccountId(const char* value) { SetAccountId(value); return *this;}
inline const Aws::String& GetBudgetName() const{ return m_budgetName; }
inline void SetBudgetName(const Aws::String& value) { m_budgetNameHasBeenSet = true; m_budgetName = value; }
inline void SetBudgetName(Aws::String&& value) { m_budgetNameHasBeenSet = true; m_budgetName = std::move(value); }
inline void SetBudgetName(const char* value) { m_budgetNameHasBeenSet = true; m_budgetName.assign(value); }
inline DescribeBudgetRequest& WithBudgetName(const Aws::String& value) { SetBudgetName(value); return *this;}
inline DescribeBudgetRequest& WithBudgetName(Aws::String&& value) { SetBudgetName(std::move(value)); return *this;}
inline DescribeBudgetRequest& WithBudgetName(const char* value) { SetBudgetName(value); return *this;}
private:
Aws::String m_accountId;
bool m_accountIdHasBeenSet;
Aws::String m_budgetName;
bool m_budgetNameHasBeenSet;
};
} // namespace Model
} // namespace Budgets
} // namespace Aws
| [
"Raliclo@gmail.com"
] | Raliclo@gmail.com |
d58288ba4f309b079738e0515c25e608a6852fcf | 7435dd60a9f79be1ffc86e342a61ca68be6c36da | /CSGO Solution/Features/Visuals/World.hpp | bd21207d3d46ae75aa2b13d0421bcf3c6299e47f | [] | no_license | LucQ12/zeeron.su | a1884384874c533ca80dd0df83bc7fdb4c81617b | 7fcc32fc3d693340d2fa0800d4e0a531979905ac | refs/heads/main | 2023-08-13T11:33:47.453906 | 2021-10-05T09:42:36 | 2021-10-05T09:42:36 | 419,263,778 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,135 | hpp | #pragma once
#include <vector>
#include "../SDK/Includes.hpp"
struct ClientImpact_t
{
Vector m_vecPosition;
float_t m_flTime;
float_t m_flExpirationTime;
};
struct C_BulletTrace
{
bool m_bIsLocalTrace = false;
Vector m_vecStartPosition = Vector( 0, 0, 0 );
Vector m_vecEndPosition = Vector( 0, 0, 0 );
};
class C_World
{
public:
virtual void Instance( ClientFrameStage_t Stage );
virtual void SkyboxChanger( );
virtual void DrawClientImpacts( );
virtual void DrawBulletTracers( );
virtual void OnBulletImpact( C_GameEvent* pEvent );
virtual void Clantag( );
virtual void Grenades( );
virtual void DrawScopeLines( );
virtual void PenetrationCrosshair( );
virtual void RemoveShadows( );
virtual void RemoveHandShaking( );
virtual void RemoveSmokeAndPostProcess( );
virtual void PostFrame( ClientFrameStage_t Stage );
virtual void OnRageBotFire( Vector vecStartPosition, Vector vecEndPosition );
virtual void PreserveKillfeed( );
std::vector < C_BulletTrace > m_BulletTracers = { };
private:
int32_t m_iLastProcessedImpact = 0;
bool m_bDidUnlockConvars = false;
};
inline C_World* g_World = new C_World( ); | [
"ptichka.denozavra05@mail.ru"
] | ptichka.denozavra05@mail.ru |
4a51f1d22f9203a68c68126c2f44baf966c74859 | da3c59e9e54b5974648828ec76f0333728fa4f0c | /email/pop3andsmtpmtm/clientmtms/inc/cimfinder.h | d3ceb1596c81fa7646cc4ad91cf8447515b1b67a | [] | no_license | finding-out/oss.FCL.sf.app.messaging | 552a95b08cbff735d7f347a1e6af69fc427f91e8 | 7ecf4269c53f5b2c6a47f3596e77e2bb75c1700c | refs/heads/master | 2022-01-29T12:14:56.118254 | 2010-11-03T20:32:03 | 2010-11-03T20:32:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,710 | h | // Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
// cimfinder.h
//
/**
* @file
* @internalComponent
* @released
*/
#if !defined (__CIMFINDER_H__)
#define __CIMFINDER_H__
class CImFinder : public CMsgActive
/**
@internalComponent
@released
*/
{
public:
IMPORT_C void FindFirstL(TMsvId aRootEntry, TRequestStatus &aStatus);
IMPORT_C ~CImFinder();
IMPORT_C virtual void FindNextL(TRequestStatus &aStatus);
void FindFirstL(const CMsvEntrySelection& aInitialSelection, TRequestStatus &aStatus);
class CImEntryStack : public CBase
{
public:
static CImEntryStack* NewL();
~CImEntryStack();
inline void PushL(TMsvId aId);
inline TMsvId PopL();
inline TBool Empty() const;
inline void Reset();
private:
void ConstructL();
CMsvEntrySelection* iFolders;
};
protected:
void ConstructL();
CImFinder(CMsvEntry& aEntry);
private:
void DoRunL();
virtual void AddChildEntriesL() = 0;
virtual TBool IsRequiredEntryType(TUid aEntryType) const = 0;
protected:
CImEntryStack* iEntryStack;
CMsvEntry& iCurrentEntry;
private:
enum TImmfState
{
EImmfEntryFound,
EImmfFindingEntry,
EImmfNothingFound
};
TImmfState iState;
};
class CImMessageFinder : public CImFinder
/**
@internalComponent
@released
*/
{
public:
IMPORT_C static CImMessageFinder* NewL(CMsvEntry& aEntry);
IMPORT_C static CImMessageFinder* NewLC(CMsvEntry& aEntry);
protected:
virtual void AddChildEntriesL();
virtual TBool IsRequiredEntryType(TUid aEntryType) const;
CImMessageFinder(CMsvEntry& aEntry);
};
class CImEntryFinder : public CImFinder
/**
@internalComponent
@released
*/
{
public:
IMPORT_C static CImEntryFinder* NewL(CMsvEntry& aEntry);
IMPORT_C static CImEntryFinder* NewLC(CMsvEntry& aEntry);
protected:
virtual void AddChildEntriesL();
virtual TBool IsRequiredEntryType(TUid aEntryType) const;
CImEntryFinder(CMsvEntry& aEntry);
};
class CImMessageCounter : public CImFinder
/**
@internalComponent
@released
*/
{
public:
IMPORT_C static CImMessageCounter* NewL(CMsvEntry& aEntry);
IMPORT_C static CImMessageCounter* NewLC(CMsvEntry& aEntry);
IMPORT_C TInt Count();
protected:
virtual void AddChildEntriesL();
virtual TBool IsRequiredEntryType(TUid aEntryType) const;
CImMessageCounter(CMsvEntry& aEntry);
private:
TInt iCount;
};
#endif //__CIMFINDER_H__
| [
"none@none"
] | none@none |
d051b5a7739d0e15dc035b6a255072470e5a548e | 3a64d611b73e036ad01d0a84986a2ad56f4505d5 | /ash/system/holding_space/pinned_files_container.cc | 37f8e6b07948625760b61c65693117d4a0988f02 | [
"BSD-3-Clause"
] | permissive | ISSuh/chromium | d32d1fccc03d7a78cd2fbebbba6685a3e16274a2 | e045f43a583f484cc4a9dfcbae3a639bb531cff1 | refs/heads/master | 2023-03-17T04:03:11.111290 | 2020-09-26T11:39:44 | 2020-09-26T11:39:44 | 298,805,518 | 0 | 0 | BSD-3-Clause | 2020-09-26T12:04:46 | 2020-09-26T12:04:46 | null | UTF-8 | C++ | false | false | 2,836 | cc | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/holding_space/pinned_files_container.h"
#include "ash/public/cpp/holding_space/holding_space_constants.h"
#include "ash/public/cpp/holding_space/holding_space_controller.h"
#include "ash/public/cpp/holding_space/holding_space_item.h"
#include "ash/public/cpp/holding_space/holding_space_model.h"
#include "ash/shell.h"
#include "ash/strings/grit/ash_strings.h"
#include "ash/system/holding_space/holding_space_item_chip_view.h"
#include "ash/system/holding_space/holding_space_item_chips_container.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_popup_item_style.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/border.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/separator.h"
#include "ui/views/layout/box_layout.h"
namespace ash {
PinnedFilesContainer::PinnedFilesContainer(
HoldingSpaceItemViewDelegate* delegate)
: delegate_(delegate) {
SetID(kHoldingSpacePinnedFilesContainerId);
SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical, kHoldingSpaceContainerPadding,
kHoldingSpaceContainerChildSpacing));
auto* title_label = AddChildView(std::make_unique<views::Label>(
l10n_util::GetStringUTF16(IDS_ASH_HOLDING_SPACE_PINNED_TITLE)));
TrayPopupItemStyle style(TrayPopupItemStyle::FontStyle::HOLDING_SPACE_TITLE,
true /* use_unified_theme */);
style.SetupLabel(title_label);
title_label->SetPaintToLayer();
title_label->layer()->SetFillsBoundsOpaquely(false);
item_chips_container_ =
AddChildView(std::make_unique<HoldingSpaceItemChipsContainer>());
if (HoldingSpaceController::Get()->model())
OnHoldingSpaceModelAttached(HoldingSpaceController::Get()->model());
}
PinnedFilesContainer::~PinnedFilesContainer() = default;
void PinnedFilesContainer::AddHoldingSpaceItemView(
const HoldingSpaceItem* item) {
DCHECK(!base::Contains(views_by_item_id_, item->id()));
if (item->type() == HoldingSpaceItem::Type::kPinnedFile) {
views_by_item_id_[item->id()] = item_chips_container_->AddChildViewAt(
std::make_unique<HoldingSpaceItemChipView>(delegate_, item),
/*index=*/0);
}
}
void PinnedFilesContainer::RemoveAllHoldingSpaceItemViews() {
views_by_item_id_.clear();
item_chips_container_->RemoveAllChildViews(true);
}
void PinnedFilesContainer::RemoveHoldingSpaceItemView(
const HoldingSpaceItem* item) {
auto it = views_by_item_id_.find(item->id());
if (it == views_by_item_id_.end())
return;
item_chips_container_->RemoveChildViewT(it->second);
views_by_item_id_.erase(it->first);
}
} // namespace ash
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
a9482c33fb8e07452e0a4797cbbf272d051e185c | a4c8d163888799dbb6efe236b4d3886114d4769b | /cie_sign_sdk/include/UUCTextFileReader.h | 012aedf29c9f61c7bb19149ae5d74c210a9a811a | [
"BSD-3-Clause"
] | permissive | bitpdg/cie-middleware-linux | 8b5ab036ebbcef29fb18c17c7d1af7421725be3d | d3a794802240a2cda55ecd1d02ff79195689e5ac | refs/heads/master | 2023-04-24T02:17:41.952027 | 2021-05-19T12:49:24 | 2021-05-19T12:49:24 | 267,796,262 | 0 | 0 | BSD-3-Clause | 2020-05-29T07:38:35 | 2020-05-29T07:38:35 | null | UTF-8 | C++ | false | false | 753 | h | // UUCTextFile.h: interface for the UUCTextFile class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_UUCTEXTFILE_H__CD3660A5_B4C5_4CD4_99AC_69AC96D1460F__INCLUDED_)
#define AFX_UUCTEXTFILE_H__CD3660A5_B4C5_4CD4_99AC_69AC96D1460F__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <stdio.h>
#include "ASN1/UUCByteArray.h"
class UUCTextFileReader
{
public:
UUCTextFileReader(const char* szFilePath);
virtual ~UUCTextFileReader();
long readLine(char* szLine, unsigned long nLen);// throw (long);
long readLine(UUCByteArray& line);
private:
FILE* m_pf;
};
#endif // !defined(AFX_UUCTEXTFILE_H__CD3660A5_B4C5_4CD4_99AC_69AC96D1460F__INCLUDED_)
| [
"pdg@bit4id.com"
] | pdg@bit4id.com |
555ed01e6d846c7b8a0bc71e879f8f0b43b908e2 | 3dfa2da447272f37da95b866aba154082b3c8ab4 | /future.h | ea66f5aaf4425af0fcf2779b96670741edec0216 | [] | no_license | cool-colo/future | 03d40673aee63b4cdd0ead0cdb88ca6b3834e005 | 8283e03d95f2cce28830bf0808995605962c76e7 | refs/heads/master | 2023-05-06T16:29:53.067160 | 2021-06-03T09:00:12 | 2021-06-03T09:00:12 | 352,545,823 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,618 | h | #pragma once
#include<cassert>
#include "future-pre.h"
class FutureException : public std::logic_error {
public:
using std::logic_error::logic_error;
};
class FutureInvalid : public FutureException {
public:
FutureInvalid() : FutureException("Future invalid") {}
};
class FutureAlreadyContinued : public FutureException {
public:
FutureAlreadyContinued() : FutureException("Future already continued") {}
};
class FutureNotReady : public FutureException {
public:
FutureNotReady() : FutureException("Future not ready") {}
};
class FutureCancellation : public FutureException {
public:
FutureCancellation() : FutureException("Future was cancelled") {}
};
class FutureTimeout : public FutureException {
public:
FutureTimeout() : FutureException("Timed out") {}
};
class FuturePredicateDoesNotObtain : public FutureException {
public:
FuturePredicateDoesNotObtain()
: FutureException("Predicate does not obtain") {}
};
class FutureNoTimekeeper : public FutureException {
public:
FutureNoTimekeeper() : FutureException("No timekeeper available") {}
};
class FutureNoExecutor : public FutureException {
public:
FutureNoExecutor() : FutureException("No executor provided to via") {}
};
template <class T>
class Future;
template<typename T>
class FutureBase {
public:
using value_type = T;
FutureBase(FutureBase<T> const&) = delete;
FutureBase(Future<T>&&) noexcept;
// not copyable
FutureBase(Future<T> const&) = delete;
virtual ~FutureBase();
T& value() &;
T const& value() const&;
T&& value() &&;
T const&& value() const&&;
bool isReady() const;
bool hasValue() const;
std::optional<T> poll();
template <class F>
void setCallback_(F&& func);
protected:
friend class Promise<T>;
template <class>
friend class Future;
Core<T>& getCore() { return getCoreImpl(*this); }
Core<T> const& getCore() const { return getCoreImpl(*this); }
template <typename Self>
static decltype(auto) getCoreImpl(Self& self) {
if (!self.core_) {
throw FutureInvalid();
}
return *self.core_;
}
T& getCoreValueChecked() { return getCoreValueChecked(*this); }
T const& getCoreValueChecked() const { return getCoreValueChecked(*this); }
template <typename Self>
static decltype(auto) getCoreValueChecked(Self& self) {
auto& core = self.getCore();
if (!core.hasResult()) {
throw FutureNotReady();
}
return core.get();
}
std::shared_ptr<Core<T>> core_;
explicit FutureBase(std::shared_ptr<Core<T>> obj) : core_(obj) {}
void throwIfInvalid() const;
void throwIfContinued() const;
void assign(FutureBase<T>&& other) noexcept;
// Variant: returns a value
// e.g. f.thenTry([](Try<T> t){ return t.value(); });
template <typename F, typename R>
typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
thenImplementation(F&& func, R);
// Variant: returns a Future
// e.g. f.thenTry([](Try<T> t){ return makeFuture<T>(t); });
template <typename F, typename R>
typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
thenImplementation(F&& func, R);
};
template <class T>
class Future : private FutureBase<T> {
private:
using Base = FutureBase<T>;
public:
/// Type of the value that the producer, when successful, produces.
using typename Base::value_type;
Future(Future<T> const&) = delete;
// movable
Future(Future<T>&&) noexcept;
using Base::isReady;
using Base::poll;
using Base::setCallback_;
using Base::value;
/// Creates/returns an invalid Future, that is, one with no shared state.
///
/// Postcondition:
///
/// - `RESULT.valid() == false`
static Future<T> makeEmpty();
// not copyable
Future& operator=(Future const&) = delete;
// movable
Future& operator=(Future&&) noexcept;
/// Unwraps the case of a Future<Future<T>> instance, and returns a simple
/// Future<T> instance.
///
/// Preconditions:
///
/// - `valid() == true` (else throws FutureInvalid)
///
/// Postconditions:
///
/// - Calling code should act as if `valid() == false`,
/// i.e., as if `*this` was moved into RESULT.
/// - `RESULT.valid() == true`
template <class F = T>
typename std::
enable_if<isFuture<F>::value, Future<typename isFuture<T>::Inner>>::type
unwrap() &&;
/// When this Future has completed, execute func which is a function that
/// can be called with `T&&` (often a lambda with parameter type
/// `auto&&` or `auto`).
///
/// Func shall return either another Future or a value.
///
/// Versions of these functions with Inline in the name will run the
/// continuation inline with the execution of the previous callback in the
/// chain if the callback attached to the previous future that triggers
/// execution of func runs on the same executor that func would be executed
/// on.
///
/// A Future for the return type of func is returned.
///
/// Future<string> f2 = f1.then([](auto&& v) {
/// ...
/// return string("foo");
/// });
///
/// Preconditions:
///
/// - `valid() == true` (else throws FutureInvalid)
///
/// Postconditions:
///
/// - `valid() == false`
/// - `RESULT.valid() == true`
template <typename F>
Future<typename valueCallableResult<T, F>::value_type>
then(F&& func) &&;
/// func is like std::function<void()> and is executed unconditionally, and
/// the value/exception is passed through to the resulting Future.
/// func shouldn't throw, but if it does it will be captured and propagated,
/// and discard any value/exception that this Future has obtained.
///
/// Preconditions:
///
/// - `valid() == true` (else throws FutureInvalid)
///
/// Postconditions:
///
/// - Calling code should act as if `valid() == false`,
/// i.e., as if `*this` was moved into RESULT.
/// - `RESULT.valid() == true`
template <class F>
Future<T> ensure(F&& func) &&;
T get() &&;
Future<T>& wait() &;
Future<T>&& wait() &&;
protected:
friend class Promise<T>;
template <class>
friend class FutureBase;
template <class T2>
friend Future<T2> makeFuture(T2&&);
template <class>
friend class Future;
template <class>
friend class FutureSplitter;
using Base::throwIfContinued;
using Base::throwIfInvalid;
explicit Future(std::shared_ptr<Core<T>> obj) : Base(obj) {}
};
template <class T>
std::pair<Promise<T>, Future<T>> makePromiseContract() {
auto p = Promise<T>();
auto f = p.getFuture();
return std::make_pair(std::move(p), std::move(f));
}
#include "future-inl.h"
| [
"fanglc@wifi.com"
] | fanglc@wifi.com |
73eb810dba6fa9feb96bd2df35538fb73ab967f7 | 81e4a14225fdef668aee4a4eb3c0e4bf4f992196 | /src/Timer.cpp | 1e477af20d33e6baa1135b39d39d52d6bd4d72fa | [] | no_license | LPPOINT/Checkers | dffdad148024e60ff0f03ea2bcfce700e9f8712a | 12d5b06d0ab70327c65186cf97d4e6fa798a91fb | refs/heads/master | 2021-01-10T19:22:24.115634 | 2012-08-11T12:37:08 | 2012-08-11T12:37:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #include "Timer.h"
void Timer::Update(float msec)
{
if((_msec+=msec)>1000)
{
_sec++;
_msec-= 1000;
}
} | [
"ostrov1762@mail.ru"
] | ostrov1762@mail.ru |
6a46c3fed10e50d21aac4071a80a618367e743f7 | 51c8fabe609cc7de64dc1aa8a0c702d1ae4f61fe | /54.ScrollView/Classes/HelloWorldScene.cpp | 118c80ca1c34cfdae7db411931b01f1ff8f84621 | [] | no_license | Gasbebe/cocos2d_source | 5f7720da904ff71a4951bee470b8744aab51c59d | 2376f6bdb93a58ae92c0e9cbd06c0d97cd241d14 | refs/heads/master | 2021-01-18T22:35:30.357253 | 2016-05-20T08:10:55 | 2016-05-20T08:10:55 | 54,854,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,595 | cpp | #include "HelloWorldScene.h"
USING_NS_CC;
using namespace cocos2d;
using namespace cocos2d::extension;
Scene* HelloWorld::createScene()
{
auto scene = Scene::create();
auto layer = HelloWorld::create();
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
if ( !LayerColor::initWithColor(Color4B(255,255,255,255)) )
{
return false;
}
/////////////////////////////
auto sprite1 = Sprite::create("Hello.png");
auto sprite2 = Sprite::create("Hello.png");
sprite1->setScale(0.4f);
sprite2->setScale(0.4f);
sprite1->setPosition(Vec2(100, 80));
sprite2->setPosition(Vec2(850, 80));
auto layer = LayerColor::create(Color4B::GREEN);
layer->setAnchorPoint(Vec2::ZERO);
layer->setPosition(Vec2::ZERO);
layer->setContentSize(Size(960, 160));
layer->addChild(sprite1);
layer->addChild(sprite2);
scrollView = ScrollView::create();
scrollView->retain();
scrollView->setDirection(ScrollView::Direction::HORIZONTAL);
scrollView->setViewSize(Size(480, 160));
scrollView->setContentSize(layer->getContentSize());
scrollView->setContentOffset(Vec2::ZERO, false);
//scrollView->setContentOffset(Vec2(300,0), true);
scrollView->setPosition(Vec2(0, 100));
scrollView->setContainer(layer);
scrollView->setDelegate(this);
this->addChild(scrollView);
return true;
}
void HelloWorld::scrollViewDidScroll(ScrollView* view) {
log("scrollViewDidScroll......");
}
void HelloWorld::scrollViewDidZoom(ScrollView* view) {
log("scrollViewDidZoom");
} | [
"gasbebe@gmail.com"
] | gasbebe@gmail.com |
0700619ec984e56ec470bdb14241a910a61d68bf | c3c6d5e826d2cd231dcab832b457f22bbaaeaaa0 | /chrome/browser/ui/web_applications/web_app_browsertest.cc | 593c444c53116cff6e3e7c637780f3944659deea | [
"BSD-3-Clause"
] | permissive | boy12371/chromium | 698c1218fb60d6cbf985932fab0a84709c0a60a1 | c19205e6abcec73ee37140b851c0bb5477998660 | refs/heads/master | 2022-11-18T17:24:27.789838 | 2020-07-28T02:01:11 | 2020-07-28T02:01:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,378 | cc | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/metrics/user_action_tester.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/sessions/tab_restore_service_factory.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_test.h"
#include "chrome/browser/ui/page_info/page_info_dialog.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/toolbar/app_menu_model.h"
#include "chrome/browser/ui/web_applications/app_browser_controller.h"
#include "chrome/browser/ui/web_applications/test/web_app_browsertest_util.h"
#include "chrome/browser/ui/web_applications/web_app_controller_browsertest.h"
#include "chrome/browser/ui/web_applications/web_app_launch_manager.h"
#include "chrome/browser/ui/web_applications/web_app_launch_utils.h"
#include "chrome/browser/ui/web_applications/web_app_menu_model.h"
#include "chrome/browser/web_applications/components/app_registrar.h"
#include "chrome/browser/web_applications/components/app_registry_controller.h"
#include "chrome/browser/web_applications/components/external_install_options.h"
#include "chrome/browser/web_applications/components/web_app_constants.h"
#include "chrome/browser/web_applications/components/web_app_helpers.h"
#include "chrome/browser/web_applications/components/web_app_provider_base.h"
#include "chrome/browser/web_applications/test/web_app_install_observer.h"
#include "chrome/browser/web_applications/test/web_app_test.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/web_application_info.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/sessions/core/tab_restore_service.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/clipboard/clipboard_buffer.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h"
#endif
#if defined(OS_MACOSX)
#include "ui/base/test/scoped_fake_nswindow_fullscreen.h"
#endif
namespace {
constexpr const char kExampleURL[] = "http://example.org/";
constexpr char kLaunchWebAppDisplayModeHistogram[] = "Launch.WebAppDisplayMode";
// Opens |url| in a new popup window with the dimensions |popup_size|.
Browser* OpenPopupAndWait(Browser* browser,
const GURL& url,
const gfx::Size& popup_size) {
content::WebContents* const web_contents =
browser->tab_strip_model()->GetActiveWebContents();
content::WebContentsAddedObserver new_contents_observer;
std::string open_window_script = base::StringPrintf(
"window.open('%s', '_blank', 'toolbar=none,width=%i,height=%i')",
url.spec().c_str(), popup_size.width(), popup_size.height());
EXPECT_TRUE(content::ExecJs(web_contents, open_window_script));
content::WebContents* popup_contents = new_contents_observer.GetWebContents();
content::WaitForLoadStop(popup_contents);
Browser* popup_browser = chrome::FindBrowserWithWebContents(popup_contents);
// The navigation should happen in a new window.
EXPECT_NE(browser, popup_browser);
return popup_browser;
}
} // namespace
namespace web_app {
class WebAppBrowserTest : public WebAppControllerBrowserTest {
public:
GURL GetSecureAppURL() {
return https_server()->GetURL("app.com", "/ssl/google.html");
}
GURL GetURLForPath(const std::string& path) {
return https_server()->GetURL("app.com", path);
}
AppId InstallPwaForCurrentUrl() {
chrome::SetAutoAcceptPWAInstallConfirmationForTesting(true);
WebAppInstallObserver observer(profile());
CHECK(chrome::ExecuteCommand(browser(), IDC_INSTALL_PWA));
AppId app_id = observer.AwaitNextInstall();
chrome::SetAutoAcceptPWAInstallConfirmationForTesting(false);
return app_id;
}
};
// A dedicated test fixture for DisplayOverride, which is supported
// only for the new web apps mode, and requires a command line switch
// to enable manifest parsing.
class WebAppBrowserTest_DisplayOverride : public WebAppBrowserTest {
public:
void SetUpCommandLine(base::CommandLine* command_line) override {
WebAppBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kEnableBlinkFeatures,
"DisplayOverride");
}
};
using WebAppTabRestoreBrowserTest = WebAppBrowserTest;
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ThemeColor) {
{
const SkColor theme_color = SkColorSetA(SK_ColorBLUE, 0xF0);
blink::Manifest manifest;
manifest.start_url = GURL(kExampleURL);
manifest.scope = GURL(kExampleURL);
manifest.theme_color = theme_color;
auto web_app_info = std::make_unique<WebApplicationInfo>();
web_app::UpdateWebAppInfoFromManifest(manifest, web_app_info.get());
AppId app_id = InstallWebApp(std::move(web_app_info));
Browser* app_browser = LaunchWebAppBrowser(app_id);
EXPECT_EQ(GetAppIdFromApplicationName(app_browser->app_name()), app_id);
EXPECT_EQ(SkColorSetA(theme_color, SK_AlphaOPAQUE),
app_browser->app_controller()->GetThemeColor());
}
{
auto web_app_info = std::make_unique<WebApplicationInfo>();
web_app_info->app_url = GURL("http://example.org/2");
web_app_info->scope = GURL("http://example.org/");
web_app_info->theme_color = base::Optional<SkColor>();
AppId app_id = InstallWebApp(std::move(web_app_info));
Browser* app_browser = LaunchWebAppBrowser(app_id);
EXPECT_EQ(GetAppIdFromApplicationName(app_browser->app_name()), app_id);
EXPECT_EQ(base::nullopt, app_browser->app_controller()->GetThemeColor());
}
}
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, BackgroundColor) {
// This feature is intentionally not implemented for the obsolete bookmark
// apps.
if (!base::FeatureList::IsEnabled(features::kDesktopPWAsWithoutExtensions))
return;
blink::Manifest manifest;
manifest.start_url = GURL(kExampleURL);
manifest.scope = GURL(kExampleURL);
manifest.background_color = SkColorSetA(SK_ColorBLUE, 0xF0);
auto web_app_info = std::make_unique<WebApplicationInfo>();
web_app::UpdateWebAppInfoFromManifest(manifest, web_app_info.get());
AppId app_id = InstallWebApp(std::move(web_app_info));
auto* provider = WebAppProviderBase::GetProviderBase(profile());
EXPECT_EQ(provider->registrar().GetAppBackgroundColor(app_id), SK_ColorBLUE);
}
// This tests that we don't crash when launching a PWA window with an
// autogenerated user theme set.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, AutoGeneratedUserThemeCrash) {
ThemeServiceFactory::GetForProfile(browser()->profile())
->BuildAutogeneratedThemeFromColor(SK_ColorBLUE);
auto web_app_info = std::make_unique<WebApplicationInfo>();
web_app_info->app_url = GURL(kExampleURL);
AppId app_id = InstallWebApp(std::move(web_app_info));
LaunchWebAppBrowser(app_id);
}
// Check the 'Open in Chrome' menu button for web app windows.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, OpenInChrome) {
const GURL app_url(kExampleURL);
const AppId app_id = InstallPWA(app_url);
{
Browser* const app_browser = LaunchWebAppBrowser(app_id);
EXPECT_EQ(1, app_browser->tab_strip_model()->count());
EXPECT_EQ(1, browser()->tab_strip_model()->count());
ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
chrome::ExecuteCommand(app_browser, IDC_OPEN_IN_CHROME);
// The browser frame is closed next event loop so it's still safe to access
// here.
EXPECT_EQ(0, app_browser->tab_strip_model()->count());
EXPECT_EQ(2, browser()->tab_strip_model()->count());
EXPECT_EQ(1, browser()->tab_strip_model()->active_index());
EXPECT_EQ(
app_url,
browser()->tab_strip_model()->GetActiveWebContents()->GetVisibleURL());
}
// Wait until the browser actually gets closed. This invalidates
// |app_browser|.
content::RunAllPendingInMessageLoop();
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
}
// Check the 'App info' menu button for web app windows.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, AppInfoOpensPageInfo) {
const GURL app_url(kExampleURL);
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowser(app_id);
bool dialog_created = false;
GetPageInfoDialogCreatedCallbackForTesting() = base::BindOnce(
[](bool* dialog_created) { *dialog_created = true; }, &dialog_created);
chrome::ExecuteCommand(app_browser, IDC_WEB_APP_MENU_APP_INFO);
EXPECT_TRUE(dialog_created);
// The test closure should have run. But clear the global in case it hasn't.
EXPECT_FALSE(GetPageInfoDialogCreatedCallbackForTesting());
GetPageInfoDialogCreatedCallbackForTesting().Reset();
}
// Check that last launch time is set after launch.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, AppLastLaunchTime) {
const GURL app_url(kExampleURL);
const AppId app_id = InstallPWA(app_url);
auto* provider = WebAppProviderBase::GetProviderBase(profile());
// last_launch_time is not set before launch
EXPECT_TRUE(provider->registrar().GetAppLastLaunchTime(app_id).is_null());
auto before_launch = base::Time::Now();
LaunchWebAppBrowser(app_id);
EXPECT_TRUE(provider->registrar().GetAppLastLaunchTime(app_id) >=
before_launch);
}
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, HasMinimalUiButtons) {
int index = 0;
auto has_buttons = [this, &index](DisplayMode display_mode,
bool open_as_window) -> bool {
base::HistogramTester tester;
const std::string base_url = "https://example.com/path";
auto web_app_info = std::make_unique<WebApplicationInfo>();
web_app_info->app_url = GURL(base_url + base::NumberToString(index++));
web_app_info->scope = web_app_info->app_url;
web_app_info->display_mode = display_mode;
web_app_info->open_as_window = open_as_window;
AppId app_id = InstallWebApp(std::move(web_app_info));
Browser* app_browser = LaunchWebAppBrowser(app_id);
DCHECK(app_browser->app_controller());
tester.ExpectUniqueSample(kLaunchWebAppDisplayModeHistogram, display_mode,
1);
return app_browser->app_controller()->HasMinimalUiButtons();
};
EXPECT_TRUE(has_buttons(DisplayMode::kBrowser,
/*open_as_window=*/true));
EXPECT_TRUE(has_buttons(DisplayMode::kMinimalUi,
/*open_as_window=*/true));
EXPECT_FALSE(has_buttons(DisplayMode::kStandalone,
/*open_as_window=*/true));
EXPECT_TRUE(has_buttons(DisplayMode::kBrowser,
/*open_as_window=*/false));
EXPECT_TRUE(has_buttons(DisplayMode::kMinimalUi,
/*open_as_window=*/false));
EXPECT_FALSE(has_buttons(DisplayMode::kStandalone,
/*open_as_window=*/false));
}
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest_DisplayOverride, DisplayOverride) {
GURL test_url = https_server()->GetURL(
"/banners/"
"manifest_test_page.html?manifest=manifest_display_override.json");
NavigateToURLAndWait(browser(), test_url);
const AppId app_id = InstallPwaForCurrentUrl();
auto* provider = WebAppProvider::Get(profile());
std::vector<DisplayMode> app_display_mode_override =
provider->registrar().GetAppDisplayModeOverride(app_id);
ASSERT_EQ(2u, app_display_mode_override.size());
EXPECT_EQ(DisplayMode::kMinimalUi, app_display_mode_override[0]);
EXPECT_EQ(DisplayMode::kStandalone, app_display_mode_override[1]);
}
// Tests that desktop PWAs open links in the browser.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, DesktopPWAsOpenLinksInApp) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id);
NavigateToURLAndWait(app_browser, app_url);
ASSERT_TRUE(app_browser->app_controller());
NavigateAndCheckForToolbar(app_browser, GURL(kExampleURL), true);
}
// Tests that desktop PWAs open links in a new tab at the end of the tabstrip of
// the last active browser.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, DesktopPWAsOpenLinksInNewTab) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id);
NavigateToURLAndWait(app_browser, app_url);
ASSERT_TRUE(app_browser->app_controller());
EXPECT_EQ(chrome::GetTotalBrowserCount(), 2u);
Browser* browser2 = CreateBrowser(app_browser->profile());
EXPECT_EQ(chrome::GetTotalBrowserCount(), 3u);
TabStripModel* model2 = browser2->tab_strip_model();
chrome::AddTabAt(browser2, GURL(), -1, true);
EXPECT_EQ(model2->count(), 2);
model2->SelectPreviousTab();
EXPECT_EQ(model2->active_index(), 0);
NavigateParams param(app_browser, GURL("http://www.google.com/"),
ui::PAGE_TRANSITION_LINK);
param.window_action = NavigateParams::SHOW_WINDOW;
param.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
ui_test_utils::NavigateToURL(¶m);
EXPECT_EQ(chrome::GetTotalBrowserCount(), 3u);
EXPECT_EQ(model2->count(), 3);
EXPECT_EQ(param.browser, browser2);
EXPECT_EQ(model2->active_index(), 2);
EXPECT_EQ(param.navigated_or_inserted_contents,
model2->GetActiveWebContents());
}
// Tests that desktop PWAs are opened at the correct size.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, PWASizeIsCorrectlyRestored) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id);
EXPECT_TRUE(AppBrowserController::IsForWebAppBrowser(app_browser));
NavigateToURLAndWait(app_browser, app_url);
const gfx::Rect bounds = gfx::Rect(50, 50, 500, 500);
app_browser->window()->SetBounds(bounds);
app_browser->window()->Close();
Browser* const new_browser = LaunchWebAppBrowser(app_id);
EXPECT_EQ(new_browser->window()->GetBounds(), bounds);
}
// Tests that desktop PWAs are reopened at the correct size.
IN_PROC_BROWSER_TEST_P(WebAppTabRestoreBrowserTest,
ReopenedPWASizeIsCorrectlyRestored) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id);
EXPECT_TRUE(AppBrowserController::IsForWebAppBrowser(app_browser));
NavigateToURLAndWait(app_browser, app_url);
const gfx::Rect bounds = gfx::Rect(50, 50, 500, 500);
app_browser->window()->SetBounds(bounds);
app_browser->window()->Close();
content::WebContentsAddedObserver new_contents_observer;
sessions::TabRestoreService* const service =
TabRestoreServiceFactory::GetForProfile(profile());
ASSERT_GT(service->entries().size(), 0U);
service->RestoreMostRecentEntry(nullptr);
content::WebContents* const restored_web_contents =
new_contents_observer.GetWebContents();
Browser* const restored_browser =
chrome::FindBrowserWithWebContents(restored_web_contents);
EXPECT_EQ(restored_browser->window()->GetBounds(), bounds);
}
// Tests that using window.open to create a popup window out of scope results in
// a correctly sized window.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, OffScopePWAPopupsHaveCorrectSize) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowser(app_id);
EXPECT_TRUE(AppBrowserController::IsForWebAppBrowser(app_browser));
const GURL offscope_url("https://example.com");
const gfx::Size size(500, 500);
Browser* const popup_browser =
OpenPopupAndWait(app_browser, offscope_url, size);
// The navigation should have happened in a new window.
EXPECT_NE(popup_browser, app_browser);
// The popup browser should be a PWA.
EXPECT_TRUE(AppBrowserController::IsForWebAppBrowser(popup_browser));
// Toolbar should be shown, as the popup is out of scope.
EXPECT_TRUE(popup_browser->app_controller()->ShouldShowCustomTabBar());
// Skip animating the toolbar visibility.
popup_browser->app_controller()->UpdateCustomTabBarVisibility(false);
// The popup window should be the size we specified.
EXPECT_EQ(size, popup_browser->window()->GetContentsSize());
}
// Tests that using window.open to create a popup window in scope results in
// a correctly sized window.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, InScopePWAPopupsHaveCorrectSize) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowser(app_id);
EXPECT_TRUE(AppBrowserController::IsForWebAppBrowser(app_browser));
const gfx::Size size(500, 500);
Browser* const popup_browser = OpenPopupAndWait(app_browser, app_url, size);
// The navigation should have happened in a new window.
EXPECT_NE(popup_browser, app_browser);
// The popup browser should be a PWA.
EXPECT_TRUE(AppBrowserController::IsForWebAppBrowser(popup_browser));
// Toolbar should not be shown, as the popup is in scope.
EXPECT_FALSE(popup_browser->app_controller()->ShouldShowCustomTabBar());
// Skip animating the toolbar visibility.
popup_browser->app_controller()->UpdateCustomTabBarVisibility(false);
// The popup window should be the size we specified.
EXPECT_EQ(size, popup_browser->window()->GetContentsSize());
}
// Tests that app windows are correctly restored.
IN_PROC_BROWSER_TEST_P(WebAppTabRestoreBrowserTest, RestoreAppWindow) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id);
ASSERT_TRUE(app_browser->is_type_app());
app_browser->window()->Close();
content::WebContentsAddedObserver new_contents_observer;
sessions::TabRestoreService* const service =
TabRestoreServiceFactory::GetForProfile(profile());
service->RestoreMostRecentEntry(nullptr);
content::WebContents* const restored_web_contents =
new_contents_observer.GetWebContents();
Browser* const restored_browser =
chrome::FindBrowserWithWebContents(restored_web_contents);
EXPECT_TRUE(restored_browser->is_type_app());
}
// Test navigating to an out of scope url on the same origin causes the url
// to be shown to the user.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest,
LocationBarIsVisibleOffScopeOnSameOrigin) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id);
// Toolbar should not be visible in the app.
ASSERT_FALSE(app_browser->app_controller()->ShouldShowCustomTabBar());
// The installed PWA's scope is app.com:{PORT}/ssl,
// so app.com:{PORT}/accessibility_fail.html is out of scope.
const GURL out_of_scope = GetURLForPath("/accessibility_fail.html");
NavigateToURLAndWait(app_browser, out_of_scope);
// Location should be visible off scope.
ASSERT_TRUE(app_browser->app_controller()->ShouldShowCustomTabBar());
}
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, UpgradeWithoutCustomTabBar) {
const GURL secure_app_url =
https_server()->GetURL("app.site.com", "/empty.html");
GURL::Replacements rep;
rep.SetSchemeStr(url::kHttpScheme);
const GURL app_url = secure_app_url.ReplaceComponents(rep);
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowser(app_id);
NavigateToURLAndWait(app_browser, secure_app_url);
EXPECT_FALSE(app_browser->app_controller()->ShouldShowCustomTabBar());
const GURL off_origin_url =
https_server()->GetURL("example.org", "/empty.html");
NavigateToURLAndWait(app_browser, off_origin_url);
EXPECT_EQ(app_browser->app_controller()->ShouldShowCustomTabBar(), true);
}
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, OverscrollEnabled) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id);
// Overscroll is only enabled on Aura platforms currently.
#if defined(USE_AURA)
EXPECT_TRUE(app_browser->CanOverscrollContent());
#else
EXPECT_FALSE(app_browser->CanOverscrollContent());
#endif
}
// Check the 'Copy URL' menu button for Web App windows.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, CopyURL) {
const GURL app_url(kExampleURL);
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id);
content::BrowserTestClipboardScope test_clipboard_scope;
chrome::ExecuteCommand(app_browser, IDC_COPY_URL);
ui::Clipboard* const clipboard = ui::Clipboard::GetForCurrentThread();
base::string16 result;
clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr,
&result);
EXPECT_EQ(result, base::UTF8ToUTF16(kExampleURL));
}
// Tests that the command for popping a tab out to a PWA window is disabled in
// incognito.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, PopOutDisabledInIncognito) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const incognito_browser = OpenURLOffTheRecord(profile(), app_url);
auto app_menu_model =
std::make_unique<AppMenuModel>(nullptr, incognito_browser);
app_menu_model->Init();
ui::MenuModel* model = app_menu_model.get();
int index = -1;
ASSERT_TRUE(app_menu_model->GetModelAndIndexForCommandId(
IDC_OPEN_IN_PWA_WINDOW, &model, &index));
EXPECT_FALSE(model->IsEnabledAt(index));
}
// Tests that web app menus don't crash when no tabs are selected.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, NoTabSelectedMenuCrash) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id);
app_browser->tab_strip_model()->CloseAllTabs();
auto app_menu_model = std::make_unique<WebAppMenuModel>(nullptr, app_browser);
app_menu_model->Init();
}
// Tests that PWA menus have an uninstall option.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, UninstallMenuOption) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id);
auto app_menu_model = std::make_unique<WebAppMenuModel>(nullptr, app_browser);
app_menu_model->Init();
ui::MenuModel* model = app_menu_model.get();
int index = -1;
const bool found = app_menu_model->GetModelAndIndexForCommandId(
WebAppMenuModel::kUninstallAppCommandId, &model, &index);
#if defined(OS_CHROMEOS)
EXPECT_FALSE(found);
#else
EXPECT_TRUE(found);
EXPECT_TRUE(model->IsEnabledAt(index));
base::HistogramTester tester;
app_menu_model->ExecuteCommand(WebAppMenuModel::kUninstallAppCommandId,
/*event_flags=*/0);
tester.ExpectUniqueSample("HostedAppFrame.WrenchMenu.MenuAction",
MENU_ACTION_UNINSTALL_APP, 1);
tester.ExpectUniqueSample("WrenchMenu.MenuAction", MENU_ACTION_UNINSTALL_APP,
1);
#endif // defined(OS_CHROMEOS)
}
// Tests that both installing a PWA and creating a shortcut app are disabled for
// incognito windows.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ShortcutMenuOptionsInIncognito) {
Browser* const incognito_browser = CreateIncognitoBrowser(profile());
EXPECT_FALSE(NavigateAndAwaitInstallabilityCheck(incognito_browser,
GetSecureAppURL()));
EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, incognito_browser),
kDisabled);
EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, incognito_browser),
kNotPresent);
}
// Tests that both installing a PWA and creating a shortcut app are disabled for
// an error page.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ShortcutMenuOptionsForErrorPage) {
EXPECT_FALSE(NavigateAndAwaitInstallabilityCheck(
browser(), https_server()->GetURL("/invalid_path.html")));
EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, browser()), kDisabled);
EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, browser()), kNotPresent);
}
// Tests that both installing a PWA and creating a shortcut app are available
// for an installable PWA.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest,
ShortcutMenuOptionsForInstallablePWA) {
EXPECT_TRUE(
NavigateAndAwaitInstallabilityCheck(browser(), GetInstallableAppURL()));
EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, browser()), kEnabled);
EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, browser()), kEnabled);
}
// Tests that both installing a PWA and creating a shortcut app are disabled
// when page crashes.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ShortcutMenuOptionsForCrashedTab) {
EXPECT_TRUE(
NavigateAndAwaitInstallabilityCheck(browser(), GetInstallableAppURL()));
content::WebContents* tab_contents =
browser()->tab_strip_model()->GetActiveWebContents();
tab_contents->SetIsCrashed(base::TERMINATION_STATUS_PROCESS_CRASHED, -1);
ASSERT_TRUE(tab_contents->IsCrashed());
EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, browser()), kDisabled);
EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, browser()), kDisabled);
}
// Tests that an installed PWA is not used when out of scope by one path level.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, MenuOptionsOutsideInstalledPwaScope) {
NavigateToURLAndWait(
browser(),
https_server()->GetURL("/banners/scope_is_start_url/index.html"));
InstallPwaForCurrentUrl();
// Open a page that is one directory up from the installed PWA.
Browser* const new_browser = NavigateInNewWindowAndAwaitInstallabilityCheck(
https_server()->GetURL("/banners/no_manifest_test_page.html"));
EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, new_browser), kEnabled);
EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, new_browser), kNotPresent);
EXPECT_EQ(GetAppMenuCommandState(IDC_OPEN_IN_PWA_WINDOW, new_browser),
kNotPresent);
}
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, InstallInstallableSite) {
base::Time before_install_time = base::Time::Now();
base::UserActionTester user_action_tester;
NavigateToURLAndWait(browser(), GetInstallableAppURL());
const AppId app_id = InstallPwaForCurrentUrl();
auto* provider = WebAppProviderBase::GetProviderBase(profile());
EXPECT_EQ(provider->registrar().GetAppShortName(app_id),
GetInstallableAppName());
// Installed PWAs should launch in their own window.
EXPECT_EQ(provider->registrar().GetAppUserDisplayMode(app_id),
blink::mojom::DisplayMode::kStandalone);
// Installed PWAs should have install time set.
EXPECT_TRUE(provider->registrar().GetAppInstallTime(app_id) >=
before_install_time);
EXPECT_EQ(1, user_action_tester.GetActionCount("InstallWebAppFromMenu"));
EXPECT_EQ(0, user_action_tester.GetActionCount("CreateShortcut"));
#if defined(OS_CHROMEOS)
// Apps on Chrome OS should not be pinned after install.
EXPECT_FALSE(ChromeLauncherController::instance()->IsAppPinned(app_id));
#endif
}
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, CanInstallOverTabPwa) {
NavigateToURLAndWait(browser(), GetInstallableAppURL());
const AppId app_id = InstallPwaForCurrentUrl();
// Change display mode to open in tab.
auto* provider = WebAppProviderBase::GetProviderBase(profile());
provider->registry_controller().SetAppUserDisplayMode(
app_id, blink::mojom::DisplayMode::kBrowser);
Browser* const new_browser =
NavigateInNewWindowAndAwaitInstallabilityCheck(GetInstallableAppURL());
EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, new_browser), kEnabled);
EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, new_browser), kEnabled);
EXPECT_EQ(GetAppMenuCommandState(IDC_OPEN_IN_PWA_WINDOW, new_browser),
kNotPresent);
}
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, CannotInstallOverWindowPwa) {
NavigateToURLAndWait(browser(), GetInstallableAppURL());
InstallPwaForCurrentUrl();
// Avoid any interference if active browser was changed by PWA install.
Browser* const new_browser =
NavigateInNewWindowAndAwaitInstallabilityCheck(GetInstallableAppURL());
EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, new_browser), kEnabled);
EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, new_browser), kNotPresent);
EXPECT_EQ(GetAppMenuCommandState(IDC_OPEN_IN_PWA_WINDOW, new_browser),
kEnabled);
}
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, CannotInstallOverPolicyPwa) {
ExternalInstallOptions options = CreateInstallOptions(GetInstallableAppURL());
options.install_source = ExternalInstallSource::kExternalPolicy;
PendingAppManagerInstall(profile(), options);
// Avoid any interference if active browser was changed by PWA install.
Browser* const new_browser =
NavigateInNewWindowAndAwaitInstallabilityCheck(GetInstallableAppURL());
EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, new_browser),
kDisabled);
EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, new_browser), kNotPresent);
EXPECT_EQ(GetAppMenuCommandState(IDC_OPEN_IN_PWA_WINDOW, new_browser),
kEnabled);
}
// Tests that the command for OpenActiveTabInPwaWindow is available for secure
// pages in an app's scope.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ReparentWebAppForSecureActiveTab) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
NavigateToURLAndWait(browser(), app_url);
content::WebContents* tab_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_EQ(tab_contents->GetLastCommittedURL(), app_url);
EXPECT_EQ(GetAppMenuCommandState(IDC_OPEN_IN_PWA_WINDOW, browser()),
kEnabled);
Browser* const app_browser = ReparentWebAppForActiveTab(browser());
ASSERT_EQ(app_browser->app_controller()->GetAppId(), app_id);
}
// Tests that reparenting the last browser tab doesn't close the browser window.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ReparentLastBrowserTab) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
NavigateToURLAndWait(browser(), app_url);
Browser* const app_browser = ReparentWebAppForActiveTab(browser());
ASSERT_EQ(app_browser->app_controller()->GetAppId(), app_id);
ASSERT_TRUE(IsBrowserOpen(browser()));
EXPECT_EQ(browser()->tab_strip_model()->count(), 1);
}
// Tests that reparenting a shortcut app tab results in a minimal-ui app window.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ReparentShortcutApp) {
const GURL app_url = GetSecureAppURL();
auto web_app_info = std::make_unique<WebApplicationInfo>();
web_app_info->app_url = app_url;
web_app_info->scope = app_url.GetWithoutFilename();
web_app_info->display_mode = DisplayMode::kBrowser;
web_app_info->open_as_window = false;
web_app_info->title = base::ASCIIToUTF16("A Shortcut App");
const AppId app_id = InstallWebApp(std::move(web_app_info));
NavigateToURLAndWait(browser(), app_url);
content::WebContents* tab_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_EQ(tab_contents->GetLastCommittedURL(), app_url);
EXPECT_EQ(GetAppMenuCommandState(IDC_OPEN_IN_PWA_WINDOW, browser()),
kEnabled);
EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_OPEN_IN_PWA_WINDOW));
Browser* const app_browser = BrowserList::GetInstance()->GetLastActive();
ASSERT_EQ(app_browser->app_controller()->GetAppId(), app_id);
EXPECT_TRUE(app_browser->app_controller()->HasMinimalUiButtons());
// User preference remains unchanged. Future instances will open in tabs.
auto* provider = WebAppProvider::Get(profile());
EXPECT_EQ(provider->registrar().GetAppUserDisplayMode(app_id),
DisplayMode::kBrowser);
EXPECT_EQ(provider->registrar().GetAppEffectiveDisplayMode(app_id),
DisplayMode::kBrowser);
}
// Tests that the manifest name of the current installable site is used in the
// installation menu text.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, InstallToShelfContainsAppName) {
EXPECT_TRUE(
NavigateAndAwaitInstallabilityCheck(browser(), GetInstallableAppURL()));
auto app_menu_model = std::make_unique<AppMenuModel>(nullptr, browser());
app_menu_model->Init();
ui::MenuModel* model = app_menu_model.get();
int index = -1;
EXPECT_TRUE(app_menu_model->GetModelAndIndexForCommandId(IDC_INSTALL_PWA,
&model, &index));
EXPECT_EQ(app_menu_model.get(), model);
EXPECT_EQ(model->GetLabelAt(index),
base::UTF8ToUTF16("Install Manifest test app\xE2\x80\xA6"));
}
// Check that no assertions are hit when showing a permission request bubble.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, PermissionBubble) {
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id);
content::RenderFrameHost* const render_frame_host =
app_browser->tab_strip_model()->GetActiveWebContents()->GetMainFrame();
EXPECT_TRUE(content::ExecuteScript(
render_frame_host,
"navigator.geolocation.getCurrentPosition(function(){});"));
}
// Ensure that web app windows with blank titles don't display the URL as a
// default window title.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, EmptyTitlesDoNotDisplayUrl) {
const GURL app_url = https_server()->GetURL("app.site.com", "/empty.html");
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowser(app_id);
content::WebContents* const web_contents =
app_browser->tab_strip_model()->GetActiveWebContents();
EXPECT_TRUE(content::WaitForLoadStop(web_contents));
EXPECT_EQ(base::string16(), app_browser->GetWindowTitleForCurrentTab(false));
NavigateToURLAndWait(app_browser,
https_server()->GetURL("app.site.com", "/simple.html"));
EXPECT_EQ(base::ASCIIToUTF16("OK"),
app_browser->GetWindowTitleForCurrentTab(false));
}
// Ensure that web app windows display the app title instead of the page
// title when off scope.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, OffScopeUrlsDisplayAppTitle) {
const GURL app_url = GetSecureAppURL();
const base::string16 app_title = base::ASCIIToUTF16("A Web App");
auto web_app_info = std::make_unique<WebApplicationInfo>();
web_app_info->app_url = app_url;
web_app_info->scope = app_url.GetWithoutFilename();
web_app_info->title = app_title;
const AppId app_id = InstallWebApp(std::move(web_app_info));
Browser* const app_browser = LaunchWebAppBrowser(app_id);
content::WebContents* const web_contents =
app_browser->tab_strip_model()->GetActiveWebContents();
EXPECT_TRUE(content::WaitForLoadStop(web_contents));
// When we are within scope, show the page title.
EXPECT_EQ(base::ASCIIToUTF16("Google"),
app_browser->GetWindowTitleForCurrentTab(false));
NavigateToURLAndWait(app_browser,
https_server()->GetURL("app.site.com", "/simple.html"));
// When we are off scope, show the app title.
EXPECT_EQ(app_title, app_browser->GetWindowTitleForCurrentTab(false));
}
// Ensure that web app windows display the app title instead of the page
// title when using http.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, InScopeHttpUrlsDisplayAppTitle) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL app_url =
embedded_test_server()->GetURL("app.site.com", "/simple.html");
const base::string16 app_title = base::ASCIIToUTF16("A Web App");
auto web_app_info = std::make_unique<WebApplicationInfo>();
web_app_info->app_url = app_url;
web_app_info->title = app_title;
const AppId app_id = InstallWebApp(std::move(web_app_info));
Browser* const app_browser = LaunchWebAppBrowser(app_id);
content::WebContents* const web_contents =
app_browser->tab_strip_model()->GetActiveWebContents();
EXPECT_TRUE(content::WaitForLoadStop(web_contents));
// The page title is "OK" but the page is being served over HTTP, so the app
// title should be used instead.
EXPECT_EQ(app_title, app_browser->GetWindowTitleForCurrentTab(false));
}
// Check that a subframe on a regular web page can navigate to a URL that
// redirects to a web app. https://crbug.com/721949.
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, SubframeRedirectsToWebApp) {
ASSERT_TRUE(embedded_test_server()->Start());
// Set up a web app which covers app.com URLs.
GURL app_url = embedded_test_server()->GetURL("app.com", "/title1.html");
const AppId app_id = InstallPWA(app_url);
// Navigate a regular tab to a page with a subframe.
const GURL url = embedded_test_server()->GetURL("foo.com", "/iframe.html");
content::WebContents* const tab =
browser()->tab_strip_model()->GetActiveWebContents();
NavigateToURLAndWait(browser(), url);
// Navigate the subframe to a URL that redirects to a URL in the web app's
// web extent.
const GURL redirect_url = embedded_test_server()->GetURL(
"bar.com", "/server-redirect?" + app_url.spec());
EXPECT_TRUE(NavigateIframeToURL(tab, "test", redirect_url));
// Ensure that the frame navigated successfully and that it has correct
// content.
content::RenderFrameHost* const subframe =
content::ChildFrameAt(tab->GetMainFrame(), 0);
EXPECT_EQ(app_url, subframe->GetLastCommittedURL());
EXPECT_EQ(
"This page has no title.",
EvalJs(subframe, "document.body.innerText.trim();").ExtractString());
}
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, NewAppWindow) {
BrowserList* const browser_list = BrowserList::GetInstance();
const GURL app_url = GetSecureAppURL();
const AppId app_id = InstallPWA(app_url);
Browser* const app_browser = LaunchWebAppBrowser(app_id);
EXPECT_EQ(browser_list->size(), 2U);
EXPECT_TRUE(chrome::ExecuteCommand(app_browser, IDC_NEW_WINDOW));
EXPECT_EQ(browser_list->size(), 3U);
Browser* const new_browser = browser_list->GetLastActive();
EXPECT_NE(new_browser, browser());
EXPECT_NE(new_browser, app_browser);
EXPECT_TRUE(new_browser->is_type_app());
EXPECT_EQ(new_browser->app_controller()->GetAppId(), app_id);
WebAppProviderBase::GetProviderBase(profile())
->registry_controller()
.SetAppUserDisplayMode(app_id, DisplayMode::kBrowser);
EXPECT_EQ(browser()->tab_strip_model()->count(), 1);
EXPECT_TRUE(chrome::ExecuteCommand(app_browser, IDC_NEW_WINDOW));
EXPECT_EQ(browser_list->GetLastActive(), browser());
EXPECT_EQ(browser()->tab_strip_model()->count(), 2);
EXPECT_EQ(
browser()->tab_strip_model()->GetActiveWebContents()->GetVisibleURL(),
app_url);
}
#endif
IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, PopupLocationBar) {
#if defined(OS_MACOSX)
ui::test::ScopedFakeNSWindowFullscreen fake_fullscreen;
#endif
const GURL app_url = GetSecureAppURL();
const GURL in_scope =
https_server()->GetURL("app.com", "/ssl/page_with_subresource.html");
const AppId app_id = InstallPWA(app_url);
Browser* const popup_browser = web_app::CreateWebApplicationWindow(
profile(), app_id, WindowOpenDisposition::NEW_POPUP);
EXPECT_TRUE(
popup_browser->CanSupportWindowFeature(Browser::FEATURE_LOCATIONBAR));
EXPECT_TRUE(
popup_browser->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR));
FullscreenNotificationObserver waiter(popup_browser);
chrome::ToggleFullscreenMode(popup_browser);
waiter.Wait();
EXPECT_TRUE(
popup_browser->CanSupportWindowFeature(Browser::FEATURE_LOCATIONBAR));
}
INSTANTIATE_TEST_SUITE_P(All,
WebAppBrowserTest,
::testing::Values(ProviderType::kBookmarkApps,
ProviderType::kWebApps),
ProviderTypeParamToString);
INSTANTIATE_TEST_SUITE_P(All,
WebAppTabRestoreBrowserTest,
::testing::Values(ProviderType::kBookmarkApps,
ProviderType::kWebApps),
ProviderTypeParamToString);
// DisplayOverride is supported only for the new web apps mode
INSTANTIATE_TEST_SUITE_P(All,
WebAppBrowserTest_DisplayOverride,
::testing::Values(ProviderType::kWebApps),
ProviderTypeParamToString);
} // namespace web_app
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
cdaf0aa25f8fe0c592f216237ff58329df4d1290 | 88ff0f4227d8f2004df52205cde54f568256597a | /task_1_8_11.cpp | cb19e3a2356604e0c4765eb88a8924d2deb89f46 | [] | no_license | AlterFritz88/intro_to_prog_c_plus_plus | 6f5322ff6d2ce17ab5252db62cb774fcfb075598 | d83b15bbfad2252a041a560487b2dcc5c6b39c16 | refs/heads/master | 2020-06-13T04:39:24.602066 | 2019-07-16T10:18:53 | 2019-07-16T10:18:53 | 194,537,678 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 557 | cpp | #include <iostream>
using namespace std;
int main() {
int r, c;
cin >> r >> c;
int arr[r][c];
int tranc_arr[c][r];
for (int i = 0; i < r; i++){
for (int j = 0; j < c; j++){
cin >> arr[i][j];
}
}
for (int i = 0; i < r; i++){
for (int j = 0; j < c; j++){
tranc_arr[j][i] = arr[r - i - 1][j];
}
}
for (int i = 0; i < c; i++){
for (int j = 0; j < r; j++) {
cout << tranc_arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
| [
"burdin009@gmail.com"
] | burdin009@gmail.com |
c20671998265105cf986067aeb34803888bf596f | e18d3ba753df23d389b6903a7e495bfaaef8b2d4 | /labs161/practicestrings.cpp | 2642148daebef8f5b8b50bad9318fd0628d892f6 | [] | no_license | ErinTanaka/IntroToCS | be4656ae915437f7bccedae2ef52735c1a171fd8 | 6efc984cee29a73ee29cd056392ff4450ed59178 | refs/heads/master | 2022-07-15T02:17:11.552524 | 2020-05-11T22:16:28 | 2020-05-11T22:16:28 | 263,171,285 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | cpp | #include <iostream>
#include <string>
using namespace std;
void dointhings(string &str);
int main(){
string mystr;
mystr="hello world";
cout << "whole string: " << mystr << endl;
cout << "3rd character in string: " << mystr[2] << endl;
dointhings(mystr);
cout << mystr << endl;
cout << "dynamic 1-d array" << endl;
int *a;
a= new int[3];
a[0]=1;
a[1]=2;
a[2]=9;
cout << "2nd element of a: " << a[1] << endl;
cout << "static 2d array" << endl;
int 2darray[4][2];
return 0;
}
void dointhings(string &str){
str[0]='s';
str[1]='t';
str[2]='a';
str[3]='r';
str[4]='t';
}
| [
"tanakae@flip3.engr.oregonstate.edu"
] | tanakae@flip3.engr.oregonstate.edu |
aebb9268c3df555dd40407d922e029f361df6a98 | 5d4da40e0b511a955b418748327ce29565d9c10c | /include/ResourceManager.h | bb2b11cfb8d52c1af59593628002a47c282517a1 | [] | no_license | danilodna/arf | eef0c22032813ddafd99d1e28c2c25964074b0b5 | 9f48264acd7a98a164d130f4c0e51d5f0b9d8f2b | refs/heads/master | 2020-03-27T04:44:07.212116 | 2018-10-31T13:58:07 | 2018-10-31T13:58:07 | 145,964,373 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,573 | h | #ifndef RESOURCE_MANAGER_H
#define RESOURCE_MANAGER_H
#include "../include/Shader.h"
#include "../include/Texture.h"
#include <glm/gtc/type_ptr.hpp>
#include <string>
#include <map>
class ResourceManager
{
private:
ResourceManager() = default;
// Loads and generates a shader from file
static Shader loadShaderFromFile(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile = NULL);
// Loads a single texture from file
static Texture loadTextureFromFile(const GLchar *file, GLboolean alpha);
public:
// Resource storage
static std::map<std::string, Shader> Shaders;
static std::map<std::string, Texture> Textures;
// Loads (and generates) a shader program from file loading vertex, fragment (and geometry) shader's source code. If gShaderFile is not NULL, it also loads a geometry shader
static Shader loadShader(const GLchar* vertexShaderFile, const GLchar* fragmentShaderFile, const GLchar* geometryShaderFile, const std::string& name, GLfloat width, GLfloat height);
// static Shader loadShader(const GLchar* vertexShaderFile, const GLchar* fragmentShaderFile, const GLchar* geometryShaderFile, const std::string& name);
// Retrieves a stored sader
static Shader getShader(const std::string& name);
// Loads (and generates) a texture from file
static Texture loadTexture(const GLchar *file, GLboolean alpha, const std::string& name);
// Retrieves a stored texture
static Texture getTexture(const std::string& name);
// Properly de-allocates all loaded resources
static void clear();
};
#endif // RESOURCE_MANAGER_H
| [
"danillodna@gmail.com"
] | danillodna@gmail.com |
784f01ddd93fef26d2e336012bc8879e097ea2bb | 777299f9f20b5c1dc930766809b336f5c1ae38e5 | /tests/framework/layer/wrap_objects.cpp | 8f617a6d330734672d723ed97e944efe96f666ed | [
"Apache-2.0"
] | permissive | chaoticbob/Vulkan-Loader | 3c3b0e0ef2c9fbd865c49abae198e4ab840a684f | d5bb7a92160cf34e81ed39d3454c65024cdf09ea | refs/heads/master | 2023-08-30T15:20:54.664460 | 2021-10-27T16:21:10 | 2021-11-04T21:01:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,692 | cpp | /*
* Copyright (c) 2015-2021 Valve Corporation
* Copyright (c) 2015-2021 LunarG, Inc.
*
* 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.
*
* Author: Jon Ashburn <jon@lunarg.com>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unordered_map>
#include <memory>
#include "vulkan/vk_layer.h"
#include "loader/generated/vk_dispatch_table_helper.h"
#include "loader/vk_loader_layer.h"
#if !defined(VK_LAYER_EXPORT)
#if defined(__GNUC__) && __GNUC__ >= 4
#define VK_LAYER_EXPORT __attribute__((visibility("default")))
#elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590)
#define VK_LAYER_EXPORT __attribute__((visibility("default")))
#else
#define VK_LAYER_EXPORT
#endif
#endif
struct wrapped_phys_dev_obj {
VkLayerInstanceDispatchTable *loader_disp;
struct wrapped_inst_obj *inst; // parent instance object
void *obj;
};
struct wrapped_inst_obj {
VkLayerInstanceDispatchTable *loader_disp;
VkLayerInstanceDispatchTable layer_disp; // this layer's dispatch table
PFN_vkSetInstanceLoaderData pfn_inst_init;
struct wrapped_phys_dev_obj *ptr_phys_devs; // any enumerated phys devs
VkInstance obj;
};
struct wrapped_dev_obj {
VkLayerDispatchTable *disp;
VkLayerInstanceDispatchTable *layer_disp; // TODO use this
PFN_vkSetDeviceLoaderData pfn_dev_init; // TODO use this
void *obj;
};
// typedef std::unordered_map<void *, VkLayerDispatchTable *> device_table_map;
// typedef std::unordered_map<void *, VkLayerInstanceDispatchTable *> instance_table_map;
typedef void *dispatch_key;
VkInstance unwrap_instance(const VkInstance instance, wrapped_inst_obj **inst) {
*inst = reinterpret_cast<wrapped_inst_obj *>(instance);
return (*inst)->obj;
}
VkPhysicalDevice unwrap_phys_dev(const VkPhysicalDevice physical_device, wrapped_phys_dev_obj **phys_dev) {
*phys_dev = reinterpret_cast<wrapped_phys_dev_obj *>(physical_device);
return reinterpret_cast<VkPhysicalDevice>((*phys_dev)->obj);
}
dispatch_key get_dispatch_key(const void *object) { return (dispatch_key) * (VkLayerDispatchTable **)object; }
template <typename T>
struct TableMap {
using map_type = std::unordered_map<void *, std::unique_ptr<T>>;
map_type map;
template <typename U>
T *get_table(U *object) {
dispatch_key key = get_dispatch_key(object);
typename map_type::const_iterator it = map.find(static_cast<void *>(key));
assert(it != map.end() && "Not able to find dispatch entry");
return it->second.get();
}
void destroy_table(dispatch_key key) {
typename map_type::const_iterator it = map.find(static_cast<void *>(key));
if (it != map.end()) {
map.erase(it);
}
}
VkLayerDispatchTable *initDeviceTable(VkDevice device, const PFN_vkGetDeviceProcAddr gpa) {
dispatch_key key = get_dispatch_key(device);
typename map_type::const_iterator it = map.find((void *)key);
if (it == map.end()) {
map[(void *)key] = std::unique_ptr<T>(new VkLayerDispatchTable);
VkLayerDispatchTable *pTable = map.at((void *)key).get();
layer_init_device_dispatch_table(device, pTable, gpa);
return pTable;
} else {
return it->second.get();
}
}
};
TableMap<VkLayerDispatchTable> device_map;
VkLayerInstanceCreateInfo *get_chain_info(const VkInstanceCreateInfo *pCreateInfo, VkLayerFunction func) {
VkLayerInstanceCreateInfo *chain_info = (VkLayerInstanceCreateInfo *)pCreateInfo->pNext;
while (chain_info && !(chain_info->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && chain_info->function == func)) {
chain_info = (VkLayerInstanceCreateInfo *)chain_info->pNext;
}
assert(chain_info != NULL);
return chain_info;
}
VkLayerDeviceCreateInfo *get_chain_info(const VkDeviceCreateInfo *pCreateInfo, VkLayerFunction func) {
VkLayerDeviceCreateInfo *chain_info = (VkLayerDeviceCreateInfo *)pCreateInfo->pNext;
while (chain_info && !(chain_info->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && chain_info->function == func)) {
chain_info = (VkLayerDeviceCreateInfo *)chain_info->pNext;
}
assert(chain_info != NULL);
return chain_info;
}
namespace wrap_objects {
static const VkLayerProperties global_layer = {
"VK_LAYER_LUNARG_wrap_objects",
VK_HEADER_VERSION_COMPLETE,
1,
"LunarG Test Layer",
};
uint32_t loader_layer_if_version = CURRENT_LOADER_LAYER_INTERFACE_VERSION;
VKAPI_ATTR VkResult VKAPI_CALL wrap_vkCreateInstance(const VkInstanceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkInstance *pInstance) {
VkLayerInstanceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
PFN_vkCreateInstance fpCreateInstance = (PFN_vkCreateInstance)fpGetInstanceProcAddr(NULL, "vkCreateInstance");
if (fpCreateInstance == NULL) {
return VK_ERROR_INITIALIZATION_FAILED;
}
// Advance the link info for the next element on the chain
chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
VkResult result = fpCreateInstance(pCreateInfo, pAllocator, pInstance);
if (result != VK_SUCCESS) {
return result;
}
auto inst = new wrapped_inst_obj;
if (!inst) return VK_ERROR_OUT_OF_HOST_MEMORY;
memset(inst, 0, sizeof(*inst));
inst->obj = (*pInstance);
*pInstance = reinterpret_cast<VkInstance>(inst);
// store the loader callback for initializing created dispatchable objects
chain_info = get_chain_info(pCreateInfo, VK_LOADER_DATA_CALLBACK);
if (chain_info) {
inst->pfn_inst_init = chain_info->u.pfnSetInstanceLoaderData;
result = inst->pfn_inst_init(inst->obj, reinterpret_cast<void *>(inst));
if (VK_SUCCESS != result) return result;
} else {
inst->pfn_inst_init = NULL;
inst->loader_disp = *(reinterpret_cast<VkLayerInstanceDispatchTable **>(*pInstance));
}
layer_init_instance_dispatch_table(*pInstance, &inst->layer_disp, fpGetInstanceProcAddr);
return result;
}
VKAPI_ATTR void VKAPI_CALL wrap_vkDestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator) {
wrapped_inst_obj *inst;
auto vk_inst = unwrap_instance(instance, &inst);
VkLayerInstanceDispatchTable *pDisp = &inst->layer_disp;
pDisp->DestroyInstance(vk_inst, pAllocator);
if (inst->ptr_phys_devs) delete[] inst->ptr_phys_devs;
delete inst;
}
VKAPI_ATTR VkResult VKAPI_CALL vkEnumeratePhysicalDevices(VkInstance instance, uint32_t *pPhysicalDeviceCount,
VkPhysicalDevice *pPhysicalDevices) {
wrapped_inst_obj *inst;
auto vk_inst = unwrap_instance(instance, &inst);
VkResult result = inst->layer_disp.EnumeratePhysicalDevices(vk_inst, pPhysicalDeviceCount, pPhysicalDevices);
if (VK_SUCCESS != result) return result;
if (pPhysicalDevices != NULL) {
assert(pPhysicalDeviceCount);
auto phys_devs = new wrapped_phys_dev_obj[*pPhysicalDeviceCount];
if (!phys_devs) return VK_ERROR_OUT_OF_HOST_MEMORY;
if (inst->ptr_phys_devs) delete[] inst->ptr_phys_devs;
inst->ptr_phys_devs = phys_devs;
for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
if (inst->pfn_inst_init == NULL) {
phys_devs[i].loader_disp = *(reinterpret_cast<VkLayerInstanceDispatchTable **>(pPhysicalDevices[i]));
} else {
result = inst->pfn_inst_init(vk_inst, reinterpret_cast<void *>(&phys_devs[i]));
if (VK_SUCCESS != result) return result;
}
phys_devs[i].obj = reinterpret_cast<void *>(pPhysicalDevices[i]);
phys_devs[i].inst = inst;
pPhysicalDevices[i] = reinterpret_cast<VkPhysicalDevice>(&phys_devs[i]);
}
}
return result;
}
VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties *pProperties) {
wrapped_phys_dev_obj *phys_dev;
auto vk_phys_dev = unwrap_phys_dev(physicalDevice, &phys_dev);
phys_dev->inst->layer_disp.GetPhysicalDeviceProperties(vk_phys_dev, pProperties);
}
VKAPI_ATTR void VKAPI_CALL wrap_vkGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
uint32_t *pQueueFamilyPropertyCount,
VkQueueFamilyProperties *pQueueFamilyProperties) {
wrapped_phys_dev_obj *phys_dev;
auto vk_phys_dev = unwrap_phys_dev(physicalDevice, &phys_dev);
phys_dev->inst->layer_disp.GetPhysicalDeviceQueueFamilyProperties(vk_phys_dev, pQueueFamilyPropertyCount,
pQueueFamilyProperties);
}
VKAPI_ATTR VkResult VKAPI_CALL wrap_vkCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) {
wrapped_phys_dev_obj *phys_dev;
auto vk_phys_dev = unwrap_phys_dev(physicalDevice, &phys_dev);
VkLayerDeviceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr = chain_info->u.pLayerInfo->pfnNextGetDeviceProcAddr;
PFN_vkCreateDevice fpCreateDevice = (PFN_vkCreateDevice)fpGetInstanceProcAddr(phys_dev->inst->obj, "vkCreateDevice");
if (fpCreateDevice == NULL) {
return VK_ERROR_INITIALIZATION_FAILED;
}
// Advance the link info for the next element on the chain
chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
VkResult result = fpCreateDevice(vk_phys_dev, pCreateInfo, pAllocator, pDevice);
if (result != VK_SUCCESS) {
return result;
}
device_map.initDeviceTable(*pDevice, fpGetDeviceProcAddr);
#if 0 // TODO add once device is wrapped
// store the loader callback for initializing created dispatchable objects
chain_info = get_chain_info(pCreateInfo, VK_LOADER_DATA_CALLBACK);
if (chain_info) {
dev->pfn_dev_init = chain_info->u.pfnSetDeviceLoaderData;
} else {
dev->pfn_dev_init = NULL;
}
#endif
return result;
}
VKAPI_ATTR void VKAPI_CALL wrap_vkDestroyDevice(VkDevice device, const VkAllocationCallbacks *pAllocator) {
dispatch_key key = get_dispatch_key(device);
VkLayerDispatchTable *pDisp = device_map.get_table(device);
pDisp->DestroyDevice(device, pAllocator);
device_map.destroy_table(key);
}
VKAPI_ATTR VkResult VKAPI_CALL wrap_vkEnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice, const char *pLayerName,
uint32_t *pPropertyCount,
VkExtensionProperties *pProperties) {
wrapped_phys_dev_obj *phys_dev;
auto vk_phys_dev = unwrap_phys_dev(physicalDevice, &phys_dev);
if (pLayerName && !strcmp(pLayerName, global_layer.layerName)) {
*pPropertyCount = 0;
return VK_SUCCESS;
}
return phys_dev->inst->layer_disp.EnumerateDeviceExtensionProperties(vk_phys_dev, pLayerName, pPropertyCount, pProperties);
}
PFN_vkVoidFunction layer_intercept_proc(const char *name) {
if (!name || name[0] != 'v' || name[1] != 'k') return NULL;
name += 2;
if (!strcmp(name, "CreateInstance")) return (PFN_vkVoidFunction)wrap_vkCreateInstance;
if (!strcmp(name, "DestroyInstance")) return (PFN_vkVoidFunction)wrap_vkDestroyInstance;
if (!strcmp(name, "EnumeratePhysicalDevices")) return (PFN_vkVoidFunction)vkEnumeratePhysicalDevices;
if (!strcmp(name, "GetPhysicalDeviceQueueFamilyProperties"))
return (PFN_vkVoidFunction)wrap_vkGetPhysicalDeviceQueueFamilyProperties;
if (!strcmp(name, "CreateDevice")) return (PFN_vkVoidFunction)wrap_vkCreateDevice;
if (!strcmp(name, "DestroyDevice")) return (PFN_vkVoidFunction)wrap_vkDestroyDevice;
return NULL;
}
PFN_vkVoidFunction layer_intercept_instance_proc(const char *name) {
if (!name || name[0] != 'v' || name[1] != 'k') return NULL;
name += 2;
if (!strcmp(name, "GetInstanceProcAddr")) return (PFN_vkVoidFunction)wrap_vkCreateInstance;
if (!strcmp(name, "DestroyInstance")) return (PFN_vkVoidFunction)wrap_vkDestroyInstance;
if (!strcmp(name, "EnumeratePhysicalDevices")) return (PFN_vkVoidFunction)vkEnumeratePhysicalDevices;
if (!strcmp(name, "GetPhysicalDeviceProperties")) return (PFN_vkVoidFunction)vkGetPhysicalDeviceProperties;
if (!strcmp(name, "GetPhysicalDeviceQueueFamilyProperties"))
return (PFN_vkVoidFunction)wrap_vkGetPhysicalDeviceQueueFamilyProperties;
if (!strcmp(name, "EnumerateDeviceExtensionProperties")) return (PFN_vkVoidFunction)wrap_vkEnumerateDeviceExtensionProperties;
return NULL;
}
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL wrap_vkGetDeviceProcAddr(VkDevice device, const char *funcName) {
PFN_vkVoidFunction addr;
if (!strcmp("vkGetDeviceProcAddr", funcName)) {
return (PFN_vkVoidFunction)wrap_vkGetDeviceProcAddr;
}
addr = layer_intercept_proc(funcName);
if (addr) return addr;
if (device == VK_NULL_HANDLE) {
return NULL;
}
VkLayerDispatchTable *pDisp = device_map.get_table(device);
if (pDisp->GetDeviceProcAddr == NULL) {
return NULL;
}
return pDisp->GetDeviceProcAddr(device, funcName);
}
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL wrap_vkGetInstanceProcAddr(VkInstance instance, const char *funcName) {
PFN_vkVoidFunction addr;
if (!strcmp(funcName, "vkCreateInstance")) return (PFN_vkVoidFunction)wrap_vkCreateInstance;
if (!strcmp(funcName, "vkCreateDevice")) return (PFN_vkVoidFunction)wrap_vkCreateDevice;
if (instance == VK_NULL_HANDLE) {
return NULL;
}
addr = layer_intercept_instance_proc(funcName);
if (addr) return addr;
wrapped_inst_obj *inst;
(void)unwrap_instance(instance, &inst);
VkLayerInstanceDispatchTable *pTable = &inst->layer_disp;
if (pTable->GetInstanceProcAddr == NULL) return NULL;
return pTable->GetInstanceProcAddr(instance, funcName);
}
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetPhysicalDeviceProcAddr(VkInstance instance, const char *funcName) {
assert(instance);
wrapped_inst_obj *inst;
(void)unwrap_instance(instance, &inst);
VkLayerInstanceDispatchTable *pTable = &inst->layer_disp;
if (pTable->GetPhysicalDeviceProcAddr == NULL) return NULL;
return pTable->GetPhysicalDeviceProcAddr(instance, funcName);
}
} // namespace wrap_objects
extern "C" {
// loader-layer interface v0, just wrappers since there is only a layer
VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance, const char *funcName) {
return wrap_objects::wrap_vkGetInstanceProcAddr(instance, funcName);
}
VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice device, const char *funcName) {
return wrap_objects::wrap_vkGetDeviceProcAddr(device, funcName);
}
VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceExtensionProperties(const char *pLayerName, uint32_t *pCount,
VkExtensionProperties *pProperties) {
assert(0); // TODO return wrap_objects::EnumerateInstanceExtensionProperties(pLayerName, pCount, pProperties);
return VK_SUCCESS;
}
VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceLayerProperties(uint32_t *pCount,
VkLayerProperties *pProperties) {
assert(0); // TODO return wrap_objects::EnumerateInstanceLayerProperties(pCount, pProperties);
return VK_SUCCESS;
}
VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice,
const char *pLayerName, uint32_t *pCount,
VkExtensionProperties *pProperties) {
// the layer command handles VK_NULL_HANDLE just fine internally
assert(physicalDevice == VK_NULL_HANDLE);
return wrap_objects::wrap_vkEnumerateDeviceExtensionProperties(VK_NULL_HANDLE, pLayerName, pCount, pProperties);
}
VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_layerGetPhysicalDeviceProcAddr(VkInstance instance,
const char *funcName) {
return wrap_objects::GetPhysicalDeviceProcAddr(instance, funcName);
}
VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkNegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface *pVersionStruct) {
assert(pVersionStruct != NULL);
assert(pVersionStruct->sType == LAYER_NEGOTIATE_INTERFACE_STRUCT);
// Fill in the function pointers if our version is at least capable of having the structure contain them.
if (pVersionStruct->loaderLayerInterfaceVersion >= 2) {
pVersionStruct->pfnGetInstanceProcAddr = wrap_objects::wrap_vkGetInstanceProcAddr;
pVersionStruct->pfnGetDeviceProcAddr = wrap_objects::wrap_vkGetDeviceProcAddr;
pVersionStruct->pfnGetPhysicalDeviceProcAddr = vk_layerGetPhysicalDeviceProcAddr;
}
if (pVersionStruct->loaderLayerInterfaceVersion < CURRENT_LOADER_LAYER_INTERFACE_VERSION) {
wrap_objects::loader_layer_if_version = pVersionStruct->loaderLayerInterfaceVersion;
} else if (pVersionStruct->loaderLayerInterfaceVersion > CURRENT_LOADER_LAYER_INTERFACE_VERSION) {
pVersionStruct->loaderLayerInterfaceVersion = CURRENT_LOADER_LAYER_INTERFACE_VERSION;
}
return VK_SUCCESS;
}
} | [
"46324611+charles-lunarg@users.noreply.github.com"
] | 46324611+charles-lunarg@users.noreply.github.com |
66e17a3aae3c0f57cafdebaacbf14867eab99e30 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /media/blink/multibuffer_data_source_unittest.cc | 02be5cee8fcc21b3d4bc016b050ca392f8d988c0 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 58,312 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <stdint.h>
#include "base/bind.h"
#include "base/run_loop.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "media/base/media_switches.h"
#include "media/base/media_util.h"
#include "media/base/mock_filters.h"
#include "media/base/test_helpers.h"
#include "media/blink/buffered_data_source_host_impl.h"
#include "media/blink/mock_resource_fetch_context.h"
#include "media/blink/mock_webassociatedurlloader.h"
#include "media/blink/multibuffer_data_source.h"
#include "media/blink/multibuffer_reader.h"
#include "media/blink/resource_multibuffer_data_provider.h"
#include "media/blink/test_response_generator.h"
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/public/platform/web_url_response.h"
using ::testing::_;
using ::testing::Assign;
using ::testing::DoAll;
using ::testing::Invoke;
using ::testing::InvokeWithoutArgs;
using ::testing::InSequence;
using ::testing::NiceMock;
using ::testing::StrictMock;
using blink::WebAssociatedURLLoader;
using blink::WebString;
using blink::WebURLResponse;
namespace media {
class TestResourceMultiBuffer;
class TestMultiBufferDataProvider;
std::set<TestMultiBufferDataProvider*> test_data_providers;
class TestMultiBufferDataProvider : public ResourceMultiBufferDataProvider {
public:
TestMultiBufferDataProvider(UrlData* url_data, MultiBuffer::BlockId pos)
: ResourceMultiBufferDataProvider(url_data,
pos,
false /* is_client_audio_element */) {
CHECK(test_data_providers.insert(this).second);
}
~TestMultiBufferDataProvider() override {
CHECK_EQ(static_cast<size_t>(1), test_data_providers.erase(this));
}
// ResourceMultiBufferDataProvider overrides.
void Start() override {
ResourceMultiBufferDataProvider::Start();
if (!on_start_.is_null())
on_start_.Run();
}
void SetDeferred(bool defer) override {
deferred_ = defer;
ResourceMultiBufferDataProvider::SetDeferred(defer);
}
bool loading() const { return !!active_loader_; }
bool deferred() const { return deferred_; }
void RunOnStart(base::Closure cb) { on_start_ = cb; }
private:
bool deferred_ = false;
base::Closure on_start_;
};
class TestUrlData;
class TestResourceMultiBuffer : public ResourceMultiBuffer {
public:
explicit TestResourceMultiBuffer(UrlData* url_data, int shift)
: ResourceMultiBuffer(url_data, shift) {}
std::unique_ptr<MultiBuffer::DataProvider> CreateWriter(const BlockId& pos,
bool) override {
auto writer = std::make_unique<TestMultiBufferDataProvider>(url_data_, pos);
writer->Start();
return writer;
}
// TODO: Make these global
TestMultiBufferDataProvider* GetProvider() {
EXPECT_EQ(test_data_providers.size(), 1U);
if (test_data_providers.size() != 1)
return nullptr;
return *test_data_providers.begin();
}
TestMultiBufferDataProvider* GetProvider_allownull() {
EXPECT_LE(test_data_providers.size(), 1U);
if (test_data_providers.size() != 1U)
return nullptr;
return *test_data_providers.begin();
}
bool HasProvider() const { return test_data_providers.size() == 1U; }
bool loading() {
if (test_data_providers.empty())
return false;
return GetProvider()->loading();
}
};
class TestUrlData : public UrlData {
public:
TestUrlData(const GURL& url, CorsMode cors_mode, UrlIndex* url_index)
: UrlData(url, cors_mode, url_index),
block_shift_(url_index->block_shift()) {}
ResourceMultiBuffer* multibuffer() override {
if (!test_multibuffer_.get()) {
test_multibuffer_.reset(new TestResourceMultiBuffer(this, block_shift_));
}
return test_multibuffer_.get();
}
TestResourceMultiBuffer* test_multibuffer() {
if (!test_multibuffer_.get()) {
test_multibuffer_.reset(new TestResourceMultiBuffer(this, block_shift_));
}
return test_multibuffer_.get();
}
protected:
~TestUrlData() override = default;
const int block_shift_;
std::unique_ptr<TestResourceMultiBuffer> test_multibuffer_;
};
class TestUrlIndex : public UrlIndex {
public:
explicit TestUrlIndex(ResourceFetchContext* fetch_context)
: UrlIndex(fetch_context) {}
scoped_refptr<UrlData> NewUrlData(const GURL& url,
UrlData::CorsMode cors_mode) override {
last_url_data_ = new TestUrlData(url, cors_mode, this);
return last_url_data_;
}
scoped_refptr<TestUrlData> last_url_data() {
EXPECT_TRUE(last_url_data_);
return last_url_data_;
}
size_t load_queue_size() { return loading_queue_.size(); }
private:
scoped_refptr<TestUrlData> last_url_data_;
};
class MockBufferedDataSourceHost : public BufferedDataSourceHost {
public:
MockBufferedDataSourceHost() = default;
~MockBufferedDataSourceHost() override = default;
MOCK_METHOD1(SetTotalBytes, void(int64_t total_bytes));
MOCK_METHOD2(AddBufferedByteRange, void(int64_t start, int64_t end));
private:
DISALLOW_COPY_AND_ASSIGN(MockBufferedDataSourceHost);
};
class MockMultibufferDataSource : public MultibufferDataSource {
public:
MockMultibufferDataSource(
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
scoped_refptr<UrlData> url_data,
BufferedDataSourceHost* host)
: MultibufferDataSource(
task_runner,
std::move(url_data),
&media_log_,
host,
base::Bind(&MockMultibufferDataSource::set_downloading,
base::Unretained(this))),
downloading_(false) {}
bool downloading() { return downloading_; }
void set_downloading(bool downloading) { downloading_ = downloading; }
bool range_supported() { return url_data_->range_supported(); }
void CallSeekTask() { SeekTask(); }
private:
// Whether the resource is downloading or deferred.
bool downloading_;
NullMediaLog media_log_;
DISALLOW_COPY_AND_ASSIGN(MockMultibufferDataSource);
};
static const int64_t kFileSize = 5000000;
static const int64_t kFarReadPosition = 3997696;
static const int kDataSize = 32 << 10;
static const char kHttpUrl[] = "http://localhost/foo.webm";
static const char kFileUrl[] = "file:///tmp/bar.webm";
static const char kHttpDifferentPathUrl[] = "http://localhost/bar.webm";
static const char kHttpDifferentOriginUrl[] = "http://127.0.0.1/foo.webm";
class MultibufferDataSourceTest : public testing::Test {
public:
MultibufferDataSourceTest() : preload_(MultibufferDataSource::AUTO) {
ON_CALL(fetch_context_, CreateUrlLoader(_))
.WillByDefault(Invoke([](const blink::WebAssociatedURLLoaderOptions&) {
return std::make_unique<NiceMock<MockWebAssociatedURLLoader>>();
}));
url_index_ = std::make_unique<TestUrlIndex>(&fetch_context_);
}
MOCK_METHOD1(OnInitialize, void(bool));
void InitializeWithCors(const char* url,
bool expected,
UrlData::CorsMode cors_mode,
size_t file_size = kFileSize) {
GURL gurl(url);
data_source_.reset(new MockMultibufferDataSource(
base::ThreadTaskRunnerHandle::Get(),
url_index_->GetByUrl(gurl, cors_mode), &host_));
data_source_->SetPreload(preload_);
response_generator_.reset(new TestResponseGenerator(gurl, file_size));
EXPECT_CALL(*this, OnInitialize(expected));
data_source_->Initialize(base::Bind(
&MultibufferDataSourceTest::OnInitialize, base::Unretained(this)));
base::RunLoop().RunUntilIdle();
// Not really loading until after OnInitialize is called.
EXPECT_EQ(data_source_->downloading(), false);
}
void Initialize(const char* url,
bool expected,
size_t file_size = kFileSize) {
InitializeWithCors(url, expected, UrlData::CORS_UNSPECIFIED, file_size);
}
// Helper to initialize tests with a valid 200 response.
void InitializeWith200Response() {
Initialize(kHttpUrl, true);
EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length()));
Respond(response_generator_->Generate200());
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
ReceiveData(kDataSize);
}
// Helper to initialize tests with a valid 206 response.
void InitializeWith206Response(size_t file_size = kFileSize) {
Initialize(kHttpUrl, true, file_size);
EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length()));
Respond(response_generator_->Generate206(0));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
ReceiveData(kDataSize);
}
// Helper to initialize tests with a valid file:// response.
void InitializeWithFileResponse() {
Initialize(kFileUrl, true);
EXPECT_CALL(host_, SetTotalBytes(kFileSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kFileSize));
Respond(response_generator_->GenerateFileResponse(0));
ReceiveData(kDataSize);
}
// Starts data source.
void Start() {
EXPECT_TRUE(data_provider());
EXPECT_FALSE(active_loader_allownull());
data_provider()->Start();
}
// Stops any active loaders and shuts down the data source.
//
// This typically happens when the page is closed and for our purposes is
// appropriate to do when tearing down a test.
void Stop() {
if (loading()) {
data_provider()->DidFail(response_generator_->GenerateError());
base::RunLoop().RunUntilIdle();
}
data_source_->Stop();
base::RunLoop().RunUntilIdle();
}
void Respond(const WebURLResponse& response) {
EXPECT_TRUE(active_loader());
data_provider()->DidReceiveResponse(response);
base::RunLoop().RunUntilIdle();
}
void ReceiveDataLow(int size) {
EXPECT_TRUE(active_loader());
std::unique_ptr<char[]> data(new char[size]);
memset(data.get(), 0xA5, size); // Arbitrary non-zero value.
data_provider()->DidReceiveData(data.get(), size);
}
void ReceiveData(int size) {
ReceiveDataLow(size);
base::RunLoop().RunUntilIdle();
}
void FinishLoading() {
EXPECT_TRUE(active_loader());
data_provider()->DidFinishLoading();
base::RunLoop().RunUntilIdle();
}
void FailLoading() {
data_provider()->DidFail(response_generator_->GenerateError());
base::RunLoop().RunUntilIdle();
}
MOCK_METHOD1(ReadCallback, void(int size));
void ReadAt(int64_t position, int64_t howmuch = kDataSize) {
data_source_->Read(position, howmuch, buffer_,
base::Bind(&MultibufferDataSourceTest::ReadCallback,
base::Unretained(this)));
base::RunLoop().RunUntilIdle();
}
void ExecuteMixedResponseSuccessTest(const WebURLResponse& response1,
const WebURLResponse& response2) {
EXPECT_CALL(host_, SetTotalBytes(kFileSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
EXPECT_CALL(*this, ReadCallback(kDataSize)).Times(2);
Respond(response1);
ReceiveData(kDataSize);
ReadAt(0);
EXPECT_TRUE(loading());
FinishLoading();
Start();
ReadAt(kDataSize);
Respond(response2);
ReceiveData(kDataSize);
FinishLoading();
Stop();
}
void ExecuteMixedResponseFailureTest(const WebURLResponse& response1,
const WebURLResponse& response2) {
EXPECT_CALL(host_, SetTotalBytes(kFileSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
EXPECT_CALL(*this, ReadCallback(kDataSize));
// Stop() will also cause the readback to be called with kReadError, but
// we want to make sure it was called before Stop().
bool failed_ = false;
EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError))
.WillOnce(Assign(&failed_, true));
Respond(response1);
ReceiveData(kDataSize);
ReadAt(0);
EXPECT_TRUE(loading());
FinishLoading();
Start();
ReadAt(kDataSize);
Respond(response2);
EXPECT_TRUE(failed_);
Stop();
}
void CheckCapacityDefer() {
EXPECT_EQ(2 << 20, preload_low());
EXPECT_EQ(3 << 20, preload_high());
}
void CheckReadThenDefer() {
EXPECT_EQ(2 << 14, preload_low());
EXPECT_EQ(3 << 14, preload_high());
}
void CheckNeverDefer() {
EXPECT_EQ(1LL << 40, preload_low());
EXPECT_EQ(1LL << 40, preload_high());
}
// Accessors for private variables on |data_source_|.
MultiBufferReader* loader() { return data_source_->reader_.get(); }
TestResourceMultiBuffer* multibuffer() {
return url_index_->last_url_data()->test_multibuffer();
}
TestMultiBufferDataProvider* data_provider() {
return multibuffer()->GetProvider();
}
blink::WebAssociatedURLLoader* active_loader() {
EXPECT_TRUE(data_provider());
if (!data_provider())
return nullptr;
return data_provider()->active_loader_.get();
}
blink::WebAssociatedURLLoader* active_loader_allownull() {
TestMultiBufferDataProvider* data_provider =
multibuffer()->GetProvider_allownull();
if (!data_provider)
return nullptr;
return data_provider->active_loader_.get();
}
bool loading() { return multibuffer()->loading(); }
MultibufferDataSource::Preload preload() { return data_source_->preload_; }
void set_preload(MultibufferDataSource::Preload preload) {
preload_ = preload;
}
int64_t preload_high() {
CHECK(loader());
return loader()->preload_high();
}
int64_t preload_low() {
CHECK(loader());
return loader()->preload_low();
}
int data_source_bitrate() { return data_source_->bitrate_; }
int64_t max_buffer_forward() { return loader()->max_buffer_forward_; }
int64_t max_buffer_backward() { return loader()->max_buffer_backward_; }
int64_t buffer_size() {
return loader()->current_buffer_size_ * 32768 /* block size */;
}
double data_source_playback_rate() { return data_source_->playback_rate_; }
bool is_local_source() { return data_source_->AssumeFullyBuffered(); }
scoped_refptr<UrlData> url_data() { return data_source_->url_data_; }
void set_might_be_reused_from_cache_in_future(bool value) {
url_data()->set_cacheable(value);
}
protected:
MultibufferDataSource::Preload preload_;
NiceMock<MockResourceFetchContext> fetch_context_;
std::unique_ptr<TestUrlIndex> url_index_;
std::unique_ptr<MockMultibufferDataSource> data_source_;
std::unique_ptr<TestResponseGenerator> response_generator_;
StrictMock<MockBufferedDataSourceHost> host_;
// Used for calling MultibufferDataSource::Read().
uint8_t buffer_[kDataSize * 2];
DISALLOW_COPY_AND_ASSIGN(MultibufferDataSourceTest);
};
TEST_F(MultibufferDataSourceTest, Range_Supported) {
InitializeWith206Response();
EXPECT_TRUE(loading());
EXPECT_FALSE(data_source_->IsStreaming());
Stop();
}
TEST_F(MultibufferDataSourceTest, Range_InstanceSizeUnknown) {
Initialize(kHttpUrl, true);
Respond(response_generator_->Generate206(
0, TestResponseGenerator::kNoContentRangeInstanceSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
ReceiveData(kDataSize);
EXPECT_TRUE(loading());
EXPECT_TRUE(data_source_->IsStreaming());
Stop();
}
TEST_F(MultibufferDataSourceTest, Range_NotFound) {
Initialize(kHttpUrl, false);
Respond(response_generator_->Generate404());
EXPECT_FALSE(loading());
Stop();
}
TEST_F(MultibufferDataSourceTest, Range_NotSupported) {
InitializeWith200Response();
EXPECT_TRUE(loading());
EXPECT_TRUE(data_source_->IsStreaming());
Stop();
}
TEST_F(MultibufferDataSourceTest, Range_NotSatisfiable) {
Initialize(kHttpUrl, true);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
Respond(response_generator_->GenerateResponse(416));
EXPECT_FALSE(loading());
Stop();
}
// Special carve-out for Apache versions that choose to return a 200 for
// Range:0- ("because it's more efficient" than a 206)
TEST_F(MultibufferDataSourceTest, Range_SupportedButReturned200) {
Initialize(kHttpUrl, true);
EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length()));
WebURLResponse response = response_generator_->Generate200();
response.SetHttpHeaderField(WebString::FromUTF8("Accept-Ranges"),
WebString::FromUTF8("bytes"));
Respond(response);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
ReceiveData(kDataSize);
EXPECT_TRUE(loading());
EXPECT_FALSE(data_source_->IsStreaming());
Stop();
}
TEST_F(MultibufferDataSourceTest, Range_MissingContentRange) {
Initialize(kHttpUrl, false);
Respond(response_generator_->Generate206(
0, TestResponseGenerator::kNoContentRange));
EXPECT_FALSE(loading());
Stop();
}
TEST_F(MultibufferDataSourceTest, Range_MissingContentLength) {
Initialize(kHttpUrl, true);
// It'll manage without a Content-Length response.
EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length()));
Respond(response_generator_->Generate206(
0, TestResponseGenerator::kNoContentLength));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
ReceiveData(kDataSize);
EXPECT_TRUE(loading());
EXPECT_FALSE(data_source_->IsStreaming());
Stop();
}
TEST_F(MultibufferDataSourceTest, Range_WrongContentRange) {
Initialize(kHttpUrl, false);
// Now it's done and will fail.
Respond(response_generator_->Generate206(1337));
EXPECT_FALSE(loading());
Stop();
}
// Test the case where the initial response from the server indicates that
// Range requests are supported, but a later request prove otherwise.
TEST_F(MultibufferDataSourceTest, Range_ServerLied) {
InitializeWith206Response();
// Read causing a new request to be made, we will discard the data that
// was already read in the first request.
ReadAt(kFarReadPosition);
// Return a 200 in response to a range request.
EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError));
Respond(response_generator_->Generate200());
EXPECT_TRUE(loading());
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_AbortWhileReading) {
InitializeWith206Response();
// Make sure there's a pending read -- we'll expect it to error.
ReadAt(kFileSize);
// Abort!!!
EXPECT_CALL(*this, ReadCallback(media::DataSource::kAborted));
data_source_->Abort();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(loading());
Stop();
}
TEST_F(MultibufferDataSourceTest, File_AbortWhileReading) {
InitializeWithFileResponse();
// Make sure there's a pending read -- we'll expect it to error.
ReadAt(kFileSize);
// Abort!!!
EXPECT_CALL(*this, ReadCallback(media::DataSource::kAborted));
data_source_->Abort();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(loading());
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_Retry) {
InitializeWith206Response();
// Read to advance our position.
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
// Issue a pending read but terminate the connection to force a retry.
ReadAt(kDataSize);
FinishLoading();
Start();
Respond(response_generator_->Generate206(kDataSize));
// Complete the read.
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
ReceiveData(kDataSize);
EXPECT_TRUE(loading());
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_RetryOnError) {
InitializeWith206Response();
// Read to advance our position.
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
// Issue a pending read but trigger an error to force a retry.
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
ReadAt(kDataSize);
base::RunLoop run_loop;
data_provider()->DidFail(response_generator_->GenerateError());
data_provider()->RunOnStart(run_loop.QuitClosure());
run_loop.Run();
Respond(response_generator_->Generate206(kDataSize));
ReceiveData(kDataSize);
FinishLoading();
EXPECT_FALSE(loading());
Stop();
}
// Make sure that we prefetch across partial responses. (crbug.com/516589)
TEST_F(MultibufferDataSourceTest, Http_PartialResponsePrefetch) {
Initialize(kHttpUrl, true);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
WebURLResponse response2 =
response_generator_->GeneratePartial206(kDataSize, kDataSize * 3 - 1);
EXPECT_CALL(host_, SetTotalBytes(kFileSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
EXPECT_CALL(*this, ReadCallback(kDataSize));
Respond(response1);
ReceiveData(kDataSize);
ReadAt(0);
EXPECT_TRUE(loading());
FinishLoading();
Start();
Respond(response2);
ReceiveData(kDataSize);
ReceiveData(kDataSize);
FinishLoading();
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_PartialResponse) {
Initialize(kHttpUrl, true);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
WebURLResponse response2 =
response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1);
// The origin URL of response1 and response2 are same. So no error should
// occur.
ExecuteMixedResponseSuccessTest(response1, response2);
}
TEST_F(MultibufferDataSourceTest,
Http_MixedResponse_RedirectedToDifferentPathResponse) {
Initialize(kHttpUrl, true);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
WebURLResponse response2 =
response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1);
response2.SetCurrentRequestUrl(GURL(kHttpDifferentPathUrl));
// The origin URL of response1 and response2 are same. So no error should
// occur.
ExecuteMixedResponseSuccessTest(response1, response2);
}
TEST_F(MultibufferDataSourceTest,
Http_MixedResponse_RedirectedToDifferentOriginResponse) {
Initialize(kHttpUrl, true);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
WebURLResponse response2 =
response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1);
response2.SetCurrentRequestUrl(GURL(kHttpDifferentOriginUrl));
// The origin URL of response1 and response2 are different. So an error should
// occur.
ExecuteMixedResponseFailureTest(response1, response2);
}
TEST_F(MultibufferDataSourceTest,
Http_MixedResponse_ServiceWorkerGeneratedResponseAndNormalResponse) {
Initialize(kHttpUrl, true);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
response1.SetWasFetchedViaServiceWorker(true);
WebURLResponse response2 =
response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1);
// response1 is generated in a Service Worker but response2 is from a native
// server. So an error should occur.
ExecuteMixedResponseFailureTest(response1, response2);
}
TEST_F(MultibufferDataSourceTest,
Http_MixedResponse_ServiceWorkerProxiedAndSameURLResponse) {
Initialize(kHttpUrl, true);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
response1.SetWasFetchedViaServiceWorker(true);
std::vector<blink::WebURL> url_list = {GURL(kHttpUrl)};
response1.SetUrlListViaServiceWorker(url_list);
WebURLResponse response2 =
response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1);
// The origin URL of response1 and response2 are same. So no error should
// occur.
ExecuteMixedResponseSuccessTest(response1, response2);
}
TEST_F(MultibufferDataSourceTest,
Http_MixedResponse_ServiceWorkerProxiedAndDifferentPathResponse) {
Initialize(kHttpUrl, true);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
response1.SetWasFetchedViaServiceWorker(true);
std::vector<blink::WebURL> url_list = {GURL(kHttpDifferentPathUrl)};
response1.SetUrlListViaServiceWorker(url_list);
WebURLResponse response2 =
response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1);
// The origin URL of response1 and response2 are same. So no error should
// occur.
ExecuteMixedResponseSuccessTest(response1, response2);
}
TEST_F(MultibufferDataSourceTest,
Http_MixedResponse_ServiceWorkerProxiedAndDifferentOriginResponse) {
Initialize(kHttpUrl, true);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
response1.SetWasFetchedViaServiceWorker(true);
std::vector<blink::WebURL> url_list = {GURL(kHttpDifferentOriginUrl)};
response1.SetUrlListViaServiceWorker(url_list);
WebURLResponse response2 =
response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1);
// The origin URL of response1 and response2 are different. So an error should
// occur.
ExecuteMixedResponseFailureTest(response1, response2);
}
TEST_F(MultibufferDataSourceTest,
Http_MixedResponse_ServiceWorkerProxiedAndDifferentOriginResponseCors) {
InitializeWithCors(kHttpUrl, true, UrlData::CORS_ANONYMOUS);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
response1.SetWasFetchedViaServiceWorker(true);
std::vector<blink::WebURL> url_list = {GURL(kHttpDifferentOriginUrl)};
response1.SetUrlListViaServiceWorker(url_list);
WebURLResponse response2 =
response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1);
// The origin URL of response1 and response2 are different, but a CORS check
// has been passed for each request, so expect success.
ExecuteMixedResponseSuccessTest(response1, response2);
}
TEST_F(MultibufferDataSourceTest, File_Retry) {
InitializeWithFileResponse();
// Read to advance our position.
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
// Issue a pending read but terminate the connection to force a retry.
ReadAt(kDataSize);
FinishLoading();
Start();
Respond(response_generator_->GenerateFileResponse(kDataSize));
// Complete the read.
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReceiveData(kDataSize);
EXPECT_TRUE(loading());
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_TooManyRetries) {
InitializeWith206Response();
// Make sure there's a pending read -- we'll expect it to error.
ReadAt(kDataSize);
for (int i = 0; i < ResourceMultiBufferDataProvider::kMaxRetries; i++) {
FailLoading();
Start();
Respond(response_generator_->Generate206(kDataSize));
}
// Stop() will also cause the readback to be called with kReadError, but
// we want to make sure it was called during FailLoading().
bool failed_ = false;
EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError))
.WillOnce(Assign(&failed_, true));
FailLoading();
EXPECT_TRUE(failed_);
EXPECT_FALSE(loading());
Stop();
}
TEST_F(MultibufferDataSourceTest, File_TooManyRetries) {
InitializeWithFileResponse();
// Make sure there's a pending read -- we'll expect it to error.
ReadAt(kDataSize);
for (int i = 0; i < ResourceMultiBufferDataProvider::kMaxRetries; i++) {
FailLoading();
Start();
Respond(response_generator_->Generate206(kDataSize));
}
// Stop() will also cause the readback to be called with kReadError, but
// we want to make sure it was called during FailLoading().
bool failed_ = false;
EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError))
.WillOnce(Assign(&failed_, true));
FailLoading();
EXPECT_TRUE(failed_);
EXPECT_FALSE(loading());
Stop();
}
TEST_F(MultibufferDataSourceTest, File_InstanceSizeUnknown) {
Initialize(kFileUrl, false);
Respond(
response_generator_->GenerateFileResponse(media::DataSource::kReadError));
ReceiveData(kDataSize);
EXPECT_FALSE(data_source_->downloading());
EXPECT_FALSE(loading());
Stop();
}
TEST_F(MultibufferDataSourceTest, File_Successful) {
InitializeWithFileResponse();
EXPECT_TRUE(loading());
EXPECT_FALSE(data_source_->IsStreaming());
Stop();
}
TEST_F(MultibufferDataSourceTest, StopDuringRead) {
InitializeWith206Response();
uint8_t buffer[256];
data_source_->Read(kDataSize, base::size(buffer), buffer,
base::Bind(&MultibufferDataSourceTest::ReadCallback,
base::Unretained(this)));
// The outstanding read should fail before the stop callback runs.
{
InSequence s;
EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError));
data_source_->Stop();
}
base::RunLoop().RunUntilIdle();
}
TEST_F(MultibufferDataSourceTest, DefaultValues) {
InitializeWith206Response();
// Ensure we have sane values for default loading scenario.
EXPECT_EQ(MultibufferDataSource::AUTO, preload());
EXPECT_EQ(2 << 20, preload_low());
EXPECT_EQ(3 << 20, preload_high());
EXPECT_EQ(0, data_source_bitrate());
EXPECT_EQ(0.0, data_source_playback_rate());
EXPECT_TRUE(loading());
Stop();
}
TEST_F(MultibufferDataSourceTest, SetBitrate) {
InitializeWith206Response();
data_source_->SetBitrate(1234);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1234, data_source_bitrate());
// Read so far ahead to cause the loader to get recreated.
TestMultiBufferDataProvider* old_loader = data_provider();
ReadAt(kFarReadPosition);
Respond(response_generator_->Generate206(kFarReadPosition));
// Verify loader changed but still has same bitrate.
EXPECT_NE(old_loader, data_provider());
EXPECT_TRUE(loading());
EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError));
Stop();
}
TEST_F(MultibufferDataSourceTest, MediaPlaybackRateChanged) {
InitializeWith206Response();
data_source_->MediaPlaybackRateChanged(2.0);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(2.0, data_source_playback_rate());
// Read so far ahead to cause the loader to get recreated.
TestMultiBufferDataProvider* old_loader = data_provider();
ReadAt(kFarReadPosition);
Respond(response_generator_->Generate206(kFarReadPosition));
// Verify loader changed but still has same playback rate.
EXPECT_NE(old_loader, data_provider());
EXPECT_TRUE(loading());
EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError));
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_Read) {
InitializeWith206Response();
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0, kDataSize * 2);
ReadAt(kDataSize, kDataSize);
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_,
AddBufferedByteRange(kDataSize, kDataSize + kDataSize / 2));
ReceiveData(kDataSize / 2);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
ReceiveData(kDataSize / 2);
EXPECT_TRUE(data_source_->downloading());
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_ShareData) {
InitializeWith206Response();
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0, kDataSize * 2);
ReadAt(kDataSize, kDataSize);
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_,
AddBufferedByteRange(kDataSize, kDataSize + kDataSize / 2));
ReceiveData(kDataSize / 2);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
ReceiveData(kDataSize / 2);
EXPECT_TRUE(data_source_->downloading());
StrictMock<MockBufferedDataSourceHost> host2;
MockMultibufferDataSource source2(
base::ThreadTaskRunnerHandle::Get(),
url_index_->GetByUrl(GURL(kHttpUrl), UrlData::CORS_UNSPECIFIED), &host2);
source2.SetPreload(preload_);
EXPECT_CALL(*this, OnInitialize(true));
// This call would not be expected if we were not sharing data.
EXPECT_CALL(host2, SetTotalBytes(response_generator_->content_length()));
EXPECT_CALL(host2, AddBufferedByteRange(0, kDataSize * 2));
source2.Initialize(base::Bind(&MultibufferDataSourceTest::OnInitialize,
base::Unretained(this)));
base::RunLoop().RunUntilIdle();
// Always loading after initialize.
EXPECT_EQ(source2.downloading(), true);
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_Read_Seek) {
InitializeWith206Response();
// Read a bit from the beginning.
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
// Simulate a seek by reading a bit beyond kDataSize.
ReadAt(kDataSize * 2);
// We receive data leading up to but not including our read.
// No notification will happen, since it's progress outside
// of our current range.
ReceiveData(kDataSize);
// We now receive the rest of the data for our read.
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3));
ReceiveData(kDataSize);
EXPECT_TRUE(data_source_->downloading());
Stop();
}
TEST_F(MultibufferDataSourceTest, File_Read) {
InitializeWithFileResponse();
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0, kDataSize * 2);
ReadAt(kDataSize, kDataSize);
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReceiveData(kDataSize);
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_FinishLoading) {
InitializeWith206Response();
EXPECT_TRUE(data_source_->downloading());
// premature didFinishLoading() will cause a retry.
FinishLoading();
EXPECT_TRUE(data_source_->downloading());
Stop();
}
TEST_F(MultibufferDataSourceTest, File_FinishLoading) {
InitializeWithFileResponse();
ReceiveData(kDataSize);
EXPECT_FALSE(data_source_->downloading());
// premature didFinishLoading() will cause a retry.
FinishLoading();
EXPECT_FALSE(data_source_->downloading());
Stop();
}
TEST_F(MultibufferDataSourceTest, LocalResource_DeferStrategy) {
InitializeWithFileResponse();
EXPECT_EQ(MultibufferDataSource::AUTO, preload());
EXPECT_TRUE(is_local_source());
CheckCapacityDefer();
data_source_->MediaIsPlaying();
CheckCapacityDefer();
Stop();
}
TEST_F(MultibufferDataSourceTest, LocalResource_PreloadMetadata_DeferStrategy) {
set_preload(MultibufferDataSource::METADATA);
InitializeWithFileResponse();
EXPECT_EQ(MultibufferDataSource::METADATA, preload());
EXPECT_TRUE(is_local_source());
CheckReadThenDefer();
data_source_->MediaIsPlaying();
CheckCapacityDefer();
Stop();
}
TEST_F(MultibufferDataSourceTest, ExternalResource_Reponse200_DeferStrategy) {
InitializeWith200Response();
EXPECT_EQ(MultibufferDataSource::AUTO, preload());
EXPECT_FALSE(is_local_source());
EXPECT_FALSE(data_source_->range_supported());
CheckCapacityDefer();
data_source_->MediaIsPlaying();
CheckCapacityDefer();
Stop();
}
TEST_F(MultibufferDataSourceTest,
ExternalResource_Response200_PreloadMetadata_DeferStrategy) {
set_preload(MultibufferDataSource::METADATA);
InitializeWith200Response();
EXPECT_EQ(MultibufferDataSource::METADATA, preload());
EXPECT_FALSE(is_local_source());
EXPECT_FALSE(data_source_->range_supported());
CheckReadThenDefer();
data_source_->MediaIsPlaying();
CheckCapacityDefer();
Stop();
}
TEST_F(MultibufferDataSourceTest, ExternalResource_Reponse206_DeferStrategy) {
InitializeWith206Response();
EXPECT_EQ(MultibufferDataSource::AUTO, preload());
EXPECT_FALSE(is_local_source());
EXPECT_TRUE(data_source_->range_supported());
CheckCapacityDefer();
data_source_->MediaIsPlaying();
CheckCapacityDefer();
set_might_be_reused_from_cache_in_future(true);
data_source_->MediaIsPlaying();
CheckCapacityDefer();
Stop();
}
TEST_F(MultibufferDataSourceTest,
ExternalResource_Response206_PreloadMetadata_DeferStrategy) {
set_preload(MultibufferDataSource::METADATA);
InitializeWith206Response();
EXPECT_EQ(MultibufferDataSource::METADATA, preload());
EXPECT_FALSE(is_local_source());
EXPECT_TRUE(data_source_->range_supported());
CheckReadThenDefer();
data_source_->MediaIsPlaying();
CheckCapacityDefer();
set_might_be_reused_from_cache_in_future(true);
data_source_->MediaIsPlaying();
CheckCapacityDefer();
set_might_be_reused_from_cache_in_future(false);
CheckCapacityDefer();
Stop();
}
TEST_F(MultibufferDataSourceTest, ExternalResource_Response206_VerifyDefer) {
set_preload(MultibufferDataSource::METADATA);
InitializeWith206Response();
EXPECT_EQ(MultibufferDataSource::METADATA, preload());
EXPECT_FALSE(is_local_source());
EXPECT_TRUE(data_source_->range_supported());
CheckReadThenDefer();
// Read a bit from the beginning.
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
ReceiveData(kDataSize);
ASSERT_TRUE(active_loader());
EXPECT_TRUE(data_provider()->deferred());
}
TEST_F(MultibufferDataSourceTest,
ExternalResource_Response206_CancelAfterDefer) {
set_preload(MultibufferDataSource::METADATA);
InitializeWith206Response();
EXPECT_EQ(MultibufferDataSource::METADATA, preload());
EXPECT_FALSE(is_local_source());
EXPECT_TRUE(data_source_->range_supported());
CheckReadThenDefer();
ReadAt(kDataSize);
data_source_->OnBufferingHaveEnough(false);
ASSERT_TRUE(active_loader());
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
ReceiveData(kDataSize);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3));
ReceiveData(kDataSize);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 4));
ReceiveData(kDataSize);
EXPECT_FALSE(active_loader_allownull());
}
// This test tries to trigger an edge case where the read callback
// never happens because the reader is deleted before that happens.
TEST_F(MultibufferDataSourceTest,
ExternalResource_Response206_CancelAfterDefer2) {
set_preload(MultibufferDataSource::METADATA);
InitializeWith206Response();
EXPECT_EQ(MultibufferDataSource::METADATA, preload());
EXPECT_FALSE(is_local_source());
EXPECT_TRUE(data_source_->range_supported());
CheckReadThenDefer();
ReadAt(kDataSize);
data_source_->OnBufferingHaveEnough(false);
ASSERT_TRUE(active_loader());
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_, AddBufferedByteRange(kDataSize, kDataSize + 2000));
ReceiveDataLow(2000);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2 + 2000));
EXPECT_CALL(host_, AddBufferedByteRange(kDataSize * 2, kDataSize * 2 + 2000));
ReceiveDataLow(kDataSize);
base::RunLoop().RunUntilIdle();
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3 + 2000));
ReceiveData(kDataSize);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 4 + 2000));
ReceiveData(kDataSize);
EXPECT_FALSE(active_loader_allownull());
}
// This test tries to trigger an edge case where the read callback
// never happens because the reader is deleted before that happens.
TEST_F(MultibufferDataSourceTest,
ExternalResource_Response206_CancelAfterDefer3) {
set_preload(MultibufferDataSource::METADATA);
InitializeWith206Response();
EXPECT_EQ(MultibufferDataSource::METADATA, preload());
EXPECT_FALSE(is_local_source());
EXPECT_TRUE(data_source_->range_supported());
CheckReadThenDefer();
ReadAt(kDataSize);
ASSERT_TRUE(active_loader());
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
ReceiveData(kDataSize);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3));
ReceiveData(kDataSize);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 4));
ReceiveData(kDataSize);
EXPECT_EQ(data_source_->downloading(), false);
data_source_->Read(kDataSize * 10, kDataSize, buffer_,
base::Bind(&MultibufferDataSourceTest::ReadCallback,
base::Unretained(this)));
data_source_->OnBufferingHaveEnough(false);
EXPECT_TRUE(active_loader_allownull());
EXPECT_CALL(*this, ReadCallback(-1));
Stop();
}
TEST_F(MultibufferDataSourceTest,
ExternalResource_Response206_CancelAfterPlay) {
set_preload(MultibufferDataSource::METADATA);
InitializeWith206Response();
EXPECT_EQ(MultibufferDataSource::METADATA, preload());
EXPECT_FALSE(is_local_source());
EXPECT_TRUE(data_source_->range_supported());
CheckReadThenDefer();
ReadAt(kDataSize);
// Marking the media as playing should prevent deferral. It also tells the
// data source to start buffering beyond the initial load.
data_source_->MediaIsPlaying();
data_source_->OnBufferingHaveEnough(false);
CheckCapacityDefer();
ASSERT_TRUE(active_loader());
// Read a bit from the beginning and ensure deferral hasn't happened yet.
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
ReceiveData(kDataSize);
ASSERT_TRUE(active_loader());
data_source_->OnBufferingHaveEnough(true);
ASSERT_TRUE(active_loader());
ASSERT_FALSE(data_provider()->deferred());
// Deliver data until capacity is reached and verify deferral.
int bytes_received = 0;
EXPECT_CALL(host_, AddBufferedByteRange(_, _)).Times(testing::AtLeast(1));
while (active_loader_allownull() && !data_provider()->deferred()) {
ReceiveData(kDataSize);
bytes_received += kDataSize;
}
EXPECT_GT(bytes_received, 0);
EXPECT_LT(bytes_received + kDataSize, kFileSize);
EXPECT_FALSE(active_loader_allownull());
}
TEST_F(MultibufferDataSourceTest, SeekPastEOF) {
GURL gurl(kHttpUrl);
data_source_.reset(new MockMultibufferDataSource(
base::ThreadTaskRunnerHandle::Get(),
url_index_->GetByUrl(gurl, UrlData::CORS_UNSPECIFIED), &host_));
data_source_->SetPreload(preload_);
response_generator_.reset(new TestResponseGenerator(gurl, kDataSize + 1));
EXPECT_CALL(*this, OnInitialize(true));
data_source_->Initialize(base::Bind(&MultibufferDataSourceTest::OnInitialize,
base::Unretained(this)));
base::RunLoop().RunUntilIdle();
// Not really loading until after OnInitialize is called.
EXPECT_EQ(data_source_->downloading(), false);
EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length()));
Respond(response_generator_->Generate206(0));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
ReceiveData(kDataSize);
// Read a bit from the beginning.
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
EXPECT_CALL(host_, AddBufferedByteRange(kDataSize, kDataSize + 1));
ReceiveData(1);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3));
FinishLoading();
EXPECT_CALL(*this, ReadCallback(0));
ReadAt(kDataSize + 5, kDataSize * 2);
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_RetryThenRedirect) {
InitializeWith206Response();
// Read to advance our position.
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
// Issue a pending read but trigger an error to force a retry.
EXPECT_CALL(*this, ReadCallback(kDataSize - 10));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
ReadAt(kDataSize + 10, kDataSize - 10);
base::RunLoop run_loop;
data_provider()->DidFail(response_generator_->GenerateError());
data_provider()->RunOnStart(run_loop.QuitClosure());
run_loop.Run();
// Server responds with a redirect.
blink::WebURL url{GURL(kHttpDifferentPathUrl)};
blink::WebURLResponse response((GURL(kHttpUrl)));
response.SetHttpStatusCode(307);
data_provider()->WillFollowRedirect(url, response);
Respond(response_generator_->Generate206(kDataSize));
ReceiveData(kDataSize);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3));
FinishLoading();
EXPECT_FALSE(loading());
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_NotStreamingAfterRedirect) {
Initialize(kHttpUrl, true);
// Server responds with a redirect.
blink::WebURL url{GURL(kHttpDifferentPathUrl)};
blink::WebURLResponse response((GURL(kHttpUrl)));
response.SetHttpStatusCode(307);
data_provider()->WillFollowRedirect(url, response);
EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length()));
Respond(response_generator_->Generate206(0));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
ReceiveData(kDataSize);
EXPECT_FALSE(data_source_->IsStreaming());
FinishLoading();
EXPECT_FALSE(loading());
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_RangeNotSatisfiableAfterRedirect) {
Initialize(kHttpUrl, true);
// Server responds with a redirect.
blink::WebURL url{GURL(kHttpDifferentPathUrl)};
blink::WebURLResponse response((GURL(kHttpUrl)));
response.SetHttpStatusCode(307);
data_provider()->WillFollowRedirect(url, response);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
Respond(response_generator_->GenerateResponse(416));
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_404AfterRedirect) {
Initialize(kHttpUrl, false);
// Server responds with a redirect.
blink::WebURL url{GURL(kHttpDifferentPathUrl)};
blink::WebURLResponse response((GURL(kHttpUrl)));
response.SetHttpStatusCode(307);
data_provider()->WillFollowRedirect(url, response);
Respond(response_generator_->Generate404());
Stop();
}
TEST_F(MultibufferDataSourceTest, LengthKnownAtEOF) {
Initialize(kHttpUrl, true);
// Server responds without content-length.
WebURLResponse response = response_generator_->Generate200();
response.ClearHttpHeaderField(WebString::FromUTF8("Content-Length"));
response.SetExpectedContentLength(kPositionNotSpecified);
Respond(response);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
ReceiveData(kDataSize);
int64_t len;
EXPECT_FALSE(data_source_->GetSize(&len));
EXPECT_TRUE(data_source_->IsStreaming());
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
ReadAt(kDataSize);
EXPECT_CALL(host_, SetTotalBytes(kDataSize));
EXPECT_CALL(*this, ReadCallback(0));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
FinishLoading();
// Done loading, now we should know the length.
EXPECT_TRUE(data_source_->GetSize(&len));
EXPECT_EQ(kDataSize, len);
Stop();
}
TEST_F(MultibufferDataSourceTest, FileSizeLessThanBlockSize) {
Initialize(kHttpUrl, true);
GURL gurl(kHttpUrl);
blink::WebURLResponse response(gurl);
response.SetHttpStatusCode(200);
response.SetHttpHeaderField(
WebString::FromUTF8("Content-Length"),
WebString::FromUTF8(base::NumberToString(kDataSize / 2)));
response.SetExpectedContentLength(kDataSize / 2);
Respond(response);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize / 2));
EXPECT_CALL(host_, SetTotalBytes(kDataSize / 2));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
ReceiveData(kDataSize / 2);
FinishLoading();
int64_t len = 0;
EXPECT_TRUE(data_source_->GetSize(&len));
EXPECT_EQ(kDataSize / 2, len);
Stop();
}
TEST_F(MultibufferDataSourceTest, ResponseTypeBasic) {
InitializeWithCors(kHttpUrl, true, UrlData::CORS_ANONYMOUS);
set_preload(MultibufferDataSource::NONE);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
response1.SetType(network::mojom::FetchResponseType::kBasic);
EXPECT_CALL(host_, SetTotalBytes(kFileSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
EXPECT_CALL(*this, ReadCallback(kDataSize));
Respond(response1);
ReceiveData(kDataSize);
ReadAt(0);
EXPECT_TRUE(loading());
EXPECT_FALSE(data_source_->IsCorsCrossOrigin());
FinishLoading();
}
TEST_F(MultibufferDataSourceTest, ResponseTypeCors) {
InitializeWithCors(kHttpUrl, true, UrlData::CORS_ANONYMOUS);
set_preload(MultibufferDataSource::NONE);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
response1.SetType(network::mojom::FetchResponseType::kCors);
EXPECT_CALL(host_, SetTotalBytes(kFileSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
EXPECT_CALL(*this, ReadCallback(kDataSize));
Respond(response1);
ReceiveData(kDataSize);
ReadAt(0);
EXPECT_TRUE(loading());
EXPECT_FALSE(data_source_->IsCorsCrossOrigin());
FinishLoading();
}
TEST_F(MultibufferDataSourceTest, ResponseTypeDefault) {
InitializeWithCors(kHttpUrl, true, UrlData::CORS_ANONYMOUS);
set_preload(MultibufferDataSource::NONE);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
response1.SetType(network::mojom::FetchResponseType::kDefault);
EXPECT_CALL(host_, SetTotalBytes(kFileSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
EXPECT_CALL(*this, ReadCallback(kDataSize));
Respond(response1);
ReceiveData(kDataSize);
ReadAt(0);
EXPECT_TRUE(loading());
EXPECT_FALSE(data_source_->IsCorsCrossOrigin());
FinishLoading();
}
TEST_F(MultibufferDataSourceTest, ResponseTypeOpaque) {
InitializeWithCors(kHttpUrl, true, UrlData::CORS_ANONYMOUS);
set_preload(MultibufferDataSource::NONE);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
response1.SetType(network::mojom::FetchResponseType::kOpaque);
EXPECT_CALL(host_, SetTotalBytes(kFileSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
EXPECT_CALL(*this, ReadCallback(kDataSize));
Respond(response1);
ReceiveData(kDataSize);
ReadAt(0);
EXPECT_TRUE(loading());
EXPECT_TRUE(data_source_->IsCorsCrossOrigin());
FinishLoading();
}
TEST_F(MultibufferDataSourceTest, ResponseTypeOpaqueRedirect) {
InitializeWithCors(kHttpUrl, true, UrlData::CORS_ANONYMOUS);
set_preload(MultibufferDataSource::NONE);
WebURLResponse response1 =
response_generator_->GeneratePartial206(0, kDataSize - 1);
response1.SetType(network::mojom::FetchResponseType::kOpaqueRedirect);
EXPECT_CALL(host_, SetTotalBytes(kFileSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
EXPECT_CALL(*this, ReadCallback(kDataSize));
Respond(response1);
ReceiveData(kDataSize);
ReadAt(0);
EXPECT_TRUE(loading());
EXPECT_TRUE(data_source_->IsCorsCrossOrigin());
FinishLoading();
}
TEST_F(MultibufferDataSourceTest, EtagTest) {
Initialize(kHttpUrl, true);
EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length()));
WebURLResponse response = response_generator_->Generate206(0);
const std::string etag("\"arglebargle glop-glyf?\"");
response.SetHttpHeaderField(WebString::FromUTF8("Etag"),
WebString::FromUTF8(etag));
Respond(response);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
ReceiveData(kDataSize);
EXPECT_EQ(url_data()->etag(), etag);
}
TEST_F(MultibufferDataSourceTest, CheckBufferSizes) {
InitializeWith206Response(1 << 30); // 1 gb
data_source_->SetBitrate(1 << 20); // 1 mbit / s
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1 << 20, data_source_bitrate());
EXPECT_EQ(2 << 20, preload_low());
EXPECT_EQ(3 << 20, preload_high());
EXPECT_EQ(25 << 20, max_buffer_forward());
EXPECT_EQ(2 << 20, max_buffer_backward());
EXPECT_EQ(1572864 /* 1.5Mb */, buffer_size());
data_source_->SetBitrate(8 << 20); // 8 mbit / s
base::RunLoop().RunUntilIdle();
EXPECT_EQ(8 << 20, data_source_bitrate());
EXPECT_EQ(10 << 20, preload_low());
EXPECT_EQ(11 << 20, preload_high());
EXPECT_EQ(25 << 20, max_buffer_forward());
EXPECT_EQ(2 << 20, max_buffer_backward());
EXPECT_EQ(12 << 20, buffer_size());
data_source_->SetBitrate(16 << 20); // 16 mbit / s
base::RunLoop().RunUntilIdle();
EXPECT_EQ(16 << 20, data_source_bitrate());
EXPECT_EQ(20 << 20, preload_low());
EXPECT_EQ(21 << 20, preload_high());
EXPECT_EQ(25 << 20, max_buffer_forward());
EXPECT_EQ(4 << 20, max_buffer_backward());
EXPECT_EQ(24 << 20, buffer_size());
data_source_->SetBitrate(32 << 20); // 32 mbit / s
base::RunLoop().RunUntilIdle();
EXPECT_EQ(32 << 20, data_source_bitrate());
EXPECT_EQ(40 << 20, preload_low());
EXPECT_EQ(41 << 20, preload_high());
EXPECT_EQ(41 << 20, max_buffer_forward());
EXPECT_EQ(8 << 20, max_buffer_backward());
EXPECT_EQ(48 << 20, buffer_size());
data_source_->SetBitrate(80 << 20); // 80 mbit / s
base::RunLoop().RunUntilIdle();
EXPECT_EQ(80 << 20, data_source_bitrate());
EXPECT_EQ(50 << 20, preload_low());
EXPECT_EQ(51 << 20, preload_high());
EXPECT_EQ(51 << 20, max_buffer_forward());
EXPECT_EQ(20 << 20, max_buffer_backward());
EXPECT_EQ(71 << 20, buffer_size());
}
TEST_F(MultibufferDataSourceTest, CheckBufferSizeForSmallFiles) {
InitializeWith206Response();
data_source_->SetBitrate(1 << 20); // 1 mbit / s
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1 << 20, data_source_bitrate());
EXPECT_EQ(2 << 20, preload_low());
EXPECT_EQ(3 << 20, preload_high());
EXPECT_EQ(25 << 20, max_buffer_forward());
EXPECT_EQ(kFileSize * 2, max_buffer_backward());
EXPECT_EQ(5013504 /* file size rounded up to blocks size */, buffer_size());
data_source_->SetBitrate(80 << 20); // 80 mbit / s
base::RunLoop().RunUntilIdle();
EXPECT_EQ(80 << 20, data_source_bitrate());
EXPECT_EQ(50 << 20, preload_low());
EXPECT_EQ(51 << 20, preload_high());
EXPECT_EQ(51 << 20, max_buffer_forward());
EXPECT_EQ(20 << 20, max_buffer_backward());
EXPECT_EQ(5013504 /* file size rounded up to blocks size */, buffer_size());
}
TEST_F(MultibufferDataSourceTest, CheckBufferSizeAfterReadingALot) {
InitializeWith206Response();
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
const int to_read = 40;
for (int i = 1; i < to_read; i++) {
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * (i + 1)));
ReadAt(i * kDataSize);
ReceiveData(kDataSize);
}
data_source_->SetBitrate(1 << 20); // 1 mbit / s
base::RunLoop().RunUntilIdle();
int64_t extra_buffer = to_read / 10 * kDataSize;
EXPECT_EQ(1 << 20, data_source_bitrate());
EXPECT_EQ((2 << 20) + extra_buffer, preload_low());
EXPECT_EQ((3 << 20) + extra_buffer, preload_high());
EXPECT_EQ(25 << 20, max_buffer_forward());
EXPECT_EQ(kFileSize * 2, max_buffer_backward());
EXPECT_EQ(5013504 /* file size rounded up to blocks size */, buffer_size());
}
// Provoke an edge case where the loading state may not end up transitioning
// back to "idle" when we're done loading.
TEST_F(MultibufferDataSourceTest, Http_CheckLoadingTransition) {
GURL gurl(kHttpUrl);
data_source_.reset(new MockMultibufferDataSource(
base::ThreadTaskRunnerHandle::Get(),
url_index_->GetByUrl(gurl, UrlData::CORS_UNSPECIFIED), &host_));
data_source_->SetPreload(preload_);
response_generator_.reset(new TestResponseGenerator(gurl, kDataSize * 1));
EXPECT_CALL(*this, OnInitialize(true));
data_source_->Initialize(base::Bind(&MultibufferDataSourceTest::OnInitialize,
base::Unretained(this)));
base::RunLoop().RunUntilIdle();
// Not really loading until after OnInitialize is called.
EXPECT_EQ(data_source_->downloading(), false);
EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length()));
Respond(response_generator_->Generate206(0));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize));
ReceiveData(kDataSize);
EXPECT_EQ(data_source_->downloading(), true);
EXPECT_CALL(host_, AddBufferedByteRange(kDataSize, kDataSize + 1));
ReceiveDataLow(1);
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3));
data_provider()->DidFinishLoading();
EXPECT_CALL(*this, ReadCallback(1));
data_source_->Read(kDataSize, 2, buffer_,
base::Bind(&MultibufferDataSourceTest::ReadCallback,
base::Unretained(this)));
base::RunLoop().RunUntilIdle();
// Make sure we're not downloading anymore.
EXPECT_EQ(data_source_->downloading(), false);
Stop();
}
TEST_F(MultibufferDataSourceTest, Http_Seek_Back) {
InitializeWith206Response();
// Read a bit from the beginning.
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
ReadAt(kDataSize);
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2));
ReceiveData(kDataSize);
ReadAt(kDataSize * 2);
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3));
ReceiveData(kDataSize);
// Read some data from far ahead.
ReadAt(kFarReadPosition);
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_, AddBufferedByteRange(kFarReadPosition,
kFarReadPosition + kDataSize));
Respond(response_generator_->Generate206(kFarReadPosition));
ReceiveData(kDataSize);
// This should not close the current connection, because we have
// more data buffered at this location than at kFarReadPosition.
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
data_source_->CallSeekTask();
EXPECT_EQ(kFarReadPosition + kDataSize, loader()->Tell());
// Again, no seek.
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(kDataSize);
data_source_->CallSeekTask();
EXPECT_EQ(kFarReadPosition + kDataSize, loader()->Tell());
// Still no seek
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(kFarReadPosition);
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(kDataSize);
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(kDataSize * 2);
data_source_->CallSeekTask();
EXPECT_EQ(kFarReadPosition + kDataSize, loader()->Tell());
// Read some data from far ahead, but right before where we read before.
// This time we'll have one block buffered.
ReadAt(kFarReadPosition - kDataSize);
EXPECT_CALL(*this, ReadCallback(kDataSize));
EXPECT_CALL(host_, AddBufferedByteRange(kFarReadPosition - kDataSize,
kFarReadPosition + kDataSize));
Respond(response_generator_->Generate206(kFarReadPosition - kDataSize));
ReceiveData(kDataSize);
// No Seek
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(0);
data_source_->CallSeekTask();
EXPECT_EQ(kFarReadPosition, loader()->Tell());
// Seek
EXPECT_CALL(*this, ReadCallback(kDataSize));
ReadAt(kDataSize * 2);
data_source_->CallSeekTask();
EXPECT_EQ(kDataSize * 3, loader()->Tell());
Stop();
}
} // namespace media
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
365bf36fb132af686524b42aa362972d8aa2f096 | face0d0277b84d67deac5acf9a7a4abe7991762b | /L6/Q1/q1.cpp | 368c065885f84703cb3208506da20d315fddc9bb | [] | no_license | anon766/DSL | 48b53fd41bd57442181cbb8389c63a0f514a45df | 0ee86275dbe5f6e51efd8b3a59a7ac3075356059 | refs/heads/master | 2022-12-28T15:38:05.764683 | 2020-02-08T14:03:16 | 2020-02-08T14:03:16 | 200,645,625 | 0 | 0 | null | 2020-10-13T19:22:29 | 2019-08-05T11:50:07 | C++ | UTF-8 | C++ | false | false | 3,319 | cpp | #include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
Node* next;
Node(int a)
{
val=a;
next=NULL;
}
};
Node* adjacencyList[100];
int dp[100][100];
bool used[100];
Node* resultStore;
int src;
bool isCycle;
void insertResult(int );
void searchDFS(int ,int );
void insert(int ,int );
int main()
{
char v1,v2;
string temp;
int ch;
src=-1;
fstream file;
file.open("L6_Q1_sample_input.txt");
if(!file.is_open())
cout<<"Unable to open input file."<<endl;
do
{
cout<<"\t\t\tMENU\n\n";
cout<<"1. Insert Edges"<<endl;
cout<<"2. BFS traversal"<<endl;
cout<<"3. DFS traversal"<<endl;
cout<<"4. Cycle finding in the graph"<<endl;
cout<<"5. Calculate dmt of the graph"<<endl;
cout<<"6. Exit"<<endl;
cout<<"Enter choice: ";
cin>>ch;
switch(ch)
{
case 1:
while(getline(file,temp))
{
v1=temp[0];
v2=temp[2];
insert((int)v1-(int)'A',(int)v2-(int)'A');
insert((int)v2-(int)'A',(int)v1-(int)'A');
if(src==-1)
src=(int)v1-(int)'A';
}
break;
case 2:
{
if(src==-1)
break;
resultStore=NULL;
memset(used,false,sizeof(used));
insertResult(src);
used[src]=true;
while(resultStore!=NULL)
{
int v=resultStore->val;
cout<<(char)(v+(int)'A')<<" ";
Node* x=adjacencyList[v];
while(x!=NULL)
{
if(!used[x->val])
{
insertResult(x->val);
used[x->val]=true;
}
x=x->next;
}
resultStore=resultStore->next;
}
cout<<endl;
break;
}
case 3:
{
if(src==-1)
break;
resultStore=NULL;
memset(used,false,sizeof(used));
searchDFS(src,-1);
Node* x=resultStore;
while(x!=NULL)
{
cout<<(char)(x->val+(int)'A')<<" ";
x=x->next;
}
cout<<endl;
break;
}
case 4:
{
if(src==-1)
break;
resultStore=NULL;
memset(used,false,sizeof(used));
isCycle=false;
searchDFS(src,-1);
if(isCycle)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
break;
}
case 5:
{
if(src==-1)
break;
for(int i=0;i<100;i++)
for(int j=0;j<100;j++)
dp[i][j]=1000;
for(int i=0;i<100;i++)
{
Node* x=adjacencyList[i];
while(x!=NULL)
{
dp[i][x->val]=1;
dp[x->val][i]=1;
x=x->next;
}
dp[i][i]=0;
}
for(int i=0;i<100;i++)
for(int j=0;j<100;j++)
for(int k=0;k<100;k++)
if(dp[j][i]+dp[i][k]<dp[j][k])
dp[j][k]=dp[j][i]+dp[i][k];
int dmt=0;
for(int i=0;i<100;i++)
for(int j=0;j<100;j++)
if(dp[i][j]!=1000 && dp[i][j]>dmt)
dmt=dp[i][j];
cout<<"Diameter: "<<dmt<<endl;
break;
}
default:
break;
}
}
while(ch!=6);
file.close();
return 0;
}
void insert(int a,int b)
{
Node* x=adjacencyList[a];
if(x==NULL)
adjacencyList[a]=new Node(b);
else
{
while(x->next!=NULL)
x=x->next;
x->next=new Node(b);
}
return;
}
void insertResult(int a)
{
Node* x=resultStore;
if(x==NULL)
resultStore=new Node(a);
else
{
while(x->next!=NULL)
x=x->next;
x->next=new Node(a);
}
return;
}
void searchDFS(int v,int p)
{
used[v]=true;
insertResult(v);
Node* x=adjacencyList[v];
while(x!=NULL)
{
if(!used[x->val])
searchDFS(x->val,v);
else if(x->val!=p)
isCycle=true;
x=x->next;
}
return;
}
| [
"masih@omen"
] | masih@omen |
e688bf2595ac96c24261d24c192088650a07ca62 | 84f7b0f26c5ee871eb83322c2fac9f0de94eb98b | /src/splitting/breadth_first_splitter.cpp | ae14355ebe4ac406b05946f4dfbd53f93b775ebc | [
"BSD-3-Clause"
] | permissive | mfkiwl/srrg2-hipe | 8b048729046ff1c3798a440555f4d77fec9d7071 | d02bf13f63ffb7a4e35a77c595c921663e962750 | refs/heads/main | 2023-08-17T18:04:23.302808 | 2021-10-25T13:44:59 | 2021-10-25T13:44:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,456 | cpp | #include "breadth_first_splitter.h"
namespace srrg2_hipe {
using namespace srrg2_core;
using namespace srrg2_solver;
BreadthFirstSplitter::BreadthFirstSplitter() : _init_action(new OdometryPropagation){
}
const VariableBase* BreadthFirstSplitter::_computeOuterDegreeMap() {
const auto& variables = _graph->variables();
int max_degree_pose = -1;
const VariableBase* conditioner = nullptr;
for (const auto& id_variable : variables) {
VariableBase::Id id = id_variable.first;
const VariableBase* v = id_variable.second;
auto lower = _graph->lowerFactor(v);
auto upper = _graph->upperFactor(v);
int degree = std::distance(lower, upper);
_variable_outer_degree_map[id] = degree;
const VariableSE3Base* anchor_type_3d = dynamic_cast<const VariableSE3Base*>(v);
if (!anchor_type_3d) {
continue;
}
if (v->status() == VariableBase::Status::Fixed) {
conditioner = v;
max_degree_pose = std::numeric_limits<int>::max();
continue;
}
if (degree > max_degree_pose) {
max_degree_pose = degree;
conditioner = v;
}
}
return conditioner;
}
void BreadthFirstSplitter::_determineAnchorAndCreatePartition(
const VariablePtrVector& variables_,
const FactorPtrVector& factors_,
const VariableIdSet& boundary_variables_) {
if (variables_.empty() || factors_.empty() || variables_.size() <= boundary_variables_.size()) {
return;
}
int max_degree = -1;
VariableBase::Id anchor_id = -1;
for (const VariableBase* v : variables_) {
if (boundary_variables_.count(v->graphId())) {
continue;
}
auto lower = _graph->lowerFactor(v);
auto upper = _graph->upperFactor(v);
int degree = std::distance(lower, upper);
const VariableSE3Base* anchor_type_3d = dynamic_cast<const VariableSE3Base*>(v);
if (!anchor_type_3d) {
continue;
}
if (v->status() == VariableBase::Status::Fixed) {
anchor_id = v->graphId();
break;
}
if (degree > max_degree) {
max_degree = degree;
anchor_id = v->graphId();
}
}
if (anchor_id < 0) {
return;
}
_manager->createPartition(variables_, factors_, anchor_id, boundary_variables_);
}
void BreadthFirstSplitter::_constructPartition(const VariableBase* root_, bool root_is_boundary) {
// tg add root to variable deque
std::deque<const VariableBase*> variable_deque;
variable_deque.push_back(root_);
// tg initialize quantity for partition creation
VariablePtrVector variables;
FactorPtrVector factors;
VariableIdSet boundary_variables;
if (root_is_boundary) {
boundary_variables.insert(root_->graphId());
}
// tg extract break conditions
const int& min_variables = param_min_partition_variables.value();
const int& min_num_levels = param_min_partition_diameter.value();
int num_levels = 0;
// tg while deque is not empty
while (!variable_deque.empty()) {
// tg take front of the deque and extract all the factors
// where the variable is involved
const VariableBase* top = variable_deque.front();
VariableBase* v = const_cast<VariableBase*>(top);
VariableBase::Id v_id = v->graphId();
auto lower = _graph->lowerFactor(top);
auto upper = _graph->upperFactor(top);
// add variable to partition and initialize degree
variables.push_back(v);
// tg add a new level in the diameter counter
++num_levels;
// tg for all the factors
for (auto it = lower; it != upper; ++it) {
auto it_var = _variable_outer_degree_map.find(v_id);
assert(it_var != _variable_outer_degree_map.end() &&
"BreadthFirstSplitter::_constructPartition| bookeeping variables is broken");
it_var->second--;
// if its already processed skip
const FactorBase* f = it->second;
if (_processed_factors.count(f->graphId())) {
continue;
}
// tg add factor to partition and to processed factors
FactorBase* factor = const_cast<FactorBase*>(f);
factors.push_back(factor);
_processed_factors.insert(f->graphId());
if (f->numVariables() < 2) {
continue;
}
// tg determine id of the other pose variable
VariableBase::Id other_id =
f->variableId(0) == v->graphId() ? f->variableId(1) : f->variableId(0);
auto it_other = _variable_outer_degree_map.find(other_id);
assert(it_other != _variable_outer_degree_map.end() &&
"BreadthFirstSplitter::_constructPartition| bookeeping variables is broken");
it_other->second--;
// tg check if the variable is an open variable in the graph (variable to be expanded)
auto is_open = std::find(_open_variables.begin(), _open_variables.end(), other_id);
if (is_open != _open_variables.end()) {
boundary_variables.insert(*is_open);
variable_deque.push_back(_graph->variable(other_id));
_open_variables.erase(is_open);
continue;
}
// tg initialize other variable from current vertex and factor
if (_init_action->compute(v, f, _visited_variables)) {
variable_deque.push_back(_graph->variable(other_id));
_visited_variables.insert(other_id);
}
}
variable_deque.pop_front();
// tg check current size and diameter, if sufficient create a partition
int current_variables_size = variables.size() + variable_deque.size();
if (current_variables_size > min_variables && num_levels > min_num_levels) {
break;
}
}
// tg check which non-expanded variables are eligible to be boundary variables
for (const VariableBase* vs : variable_deque) {
VariableBase::Id vs_id = vs->graphId();
VariableBase* v = const_cast<VariableBase*>(vs);
variables.push_back(v);
if (_variable_outer_degree_map.at(vs_id) > 0) {
_open_variables.push_back(vs_id);
boundary_variables.insert(vs_id);
}
}
this->_determineAnchorAndCreatePartition(variables, factors, boundary_variables);
}
void BreadthFirstSplitter::compute() {
assert(_graph && "BreadthFirstSplitter::compute| no graph, call setPartitionManager");
assert(_manager && "BreadthFirstSplitter::compute| no manager, call setPartitionManager");
// tg connect factors and variables
_graph->bindFactors();
// tg determine root of the expansion as the maximum degree variable in the graph
const VariableBase* root = _computeOuterDegreeMap();
// tg compute first partition
_constructPartition(root, false);
_conditioner = root->graphId();
_visited_variables.insert(root->graphId());
// tg while there are variables to be expanded
while (!_open_variables.empty()) {
// tg extract front variable
VariableBase::Id id = _open_variables.front();
const VariableBase* v = _graph->variable(id);
_open_variables.pop_front();
// tg expand next partition
_constructPartition(v, true);
}
}
} // namespace srrg2_hipe
| [
"frevo93@gmail.com"
] | frevo93@gmail.com |
f6cd487cb63d36d26a4ed4ade00fbac6f44ad2a5 | 862a88b144cb7fca22a84d43b65a91f85027cbf0 | /extensions/GUI/cocos2dx-better/src/CBGridView.cpp | 4415b7b6af4aaf55bdd97da3a5130688aac0e040 | [
"MIT"
] | permissive | live106/cocos2d-x-AoB | 6edbb263bff9ab023da80f92fd68df49272d2851 | 11dfdf54d904bb25c963cf0846fdd3d224f07ba3 | refs/heads/master | 2020-12-25T02:20:43.013687 | 2014-11-06T08:17:16 | 2014-11-06T08:17:16 | 9,067,964 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,702 | cpp | /****************************************************************************
Author: Luma (stubma@gmail.com)
https://github.com/stubma/cocos2dx-better
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CBGridView.h"
#include "CCTableViewCell.h"
USING_NS_CC_EXT;
NS_CC_BEGIN
CBGridView::CBGridView() :
m_colCount(1) {
}
CBGridView* CBGridView::create(CBTableViewDataSource* dataSource, CCSize size) {
return CBGridView::create(dataSource, size, NULL);
}
CBGridView* CBGridView::create(CBTableViewDataSource* dataSource, CCSize size, CCNode* container) {
CBGridView* table = new CBGridView();
if(table->initWithViewSize(size, container)) {
table->autorelease();
table->setDataSource(dataSource);
table->_updateContentSize();
return table;
}
CC_SAFE_RELEASE(table);
return NULL;
}
void CBGridView::setColCount(unsigned int cols) {
m_colCount = cols;
_updateContentSize();
}
int CBGridView::__indexFromOffset(CCPoint offset) {
int index = 0;
CCSize cellSize;
int col, row;
float spaceWidth;
cellSize = m_pDataSource->cellSizeForTable(this);
switch(getDirection()) {
case kCCScrollViewDirectionHorizontal:
spaceWidth = getContainer()->getContentSize().height / m_colCount;
col = (offset.y - (spaceWidth - cellSize.height) * 0.5) / spaceWidth;
row = offset.x / cellSize.width;
break;
default:
spaceWidth = getContainer()->getContentSize().width / m_colCount;
col = (offset.x - (spaceWidth - cellSize.width) * 0.5) / spaceWidth;
row = MAX(0, offset.y / cellSize.height);
break;
}
index = col + row * m_colCount;
return index;
}
CCPoint CBGridView::__offsetFromIndex(unsigned int index) {
CCPoint offset;
CCSize cellSize;
float spaceWidth;
int col, row;
cellSize = m_pDataSource->cellSizeForTable(this);
switch(getDirection()) {
case kCCScrollViewDirectionHorizontal:
row = index / m_colCount;
col = index % m_colCount;
spaceWidth = this->getContainer()->getContentSize().height / m_colCount;
offset = ccp(row * cellSize.height,
col * spaceWidth + (spaceWidth - cellSize.width) * 0.5);
break;
default:
row = index / m_colCount;
col = index % m_colCount;
spaceWidth = this->getContainer()->getContentSize().width / m_colCount;
offset = ccp(col * spaceWidth + (spaceWidth - cellSize.width) * 0.5,
row * cellSize.height);
break;
}
return offset;
}
void CBGridView::_updateCellPositions() {
int cellsCount = m_pDataSource->numberOfCellsInTableView(this);
m_vCellsPositions.resize(cellsCount + 1, 0.0);
if(cellsCount > 0) {
float currentPos = 0;
CCSize cellSize;
for(int i = 0; i < cellsCount; i++) {
if(i > 0 && i % m_colCount == 0) {
cellSize = m_pDataSource->tableCellSizeForIndex(this, i);
switch(getDirection()) {
case kCCScrollViewDirectionHorizontal:
currentPos += cellSize.width;
break;
default:
currentPos += cellSize.height;
break;
}
}
m_vCellsPositions[i] = currentPos;
}
// 1 extra value allows us to get right/bottom of the last cell
m_vCellsPositions[cellsCount] = currentPos;
}
}
void CBGridView::_updateContentSize() {
CCSize size, cellSize, viewSize;
unsigned int cellCount, rows;
cellSize = m_pDataSource->cellSizeForTable(this);
cellCount = m_pDataSource->numberOfCellsInTableView(this);
viewSize = CCSizeMake(getViewSize().width/getContainer()->getScaleX(),
getViewSize().height / getContainer()->getScaleY());
switch(getDirection()) {
case kCCScrollViewDirectionHorizontal:
rows = ceilf(cellCount / (float)m_colCount);
size = CCSizeMake(MAX(rows * cellSize.width, viewSize.width),
m_colCount * cellSize.height);
break;
default:
rows = ceilf(cellCount/((float)m_colCount));
size = CCSizeMake(MAX(cellSize.width * m_colCount, viewSize.width),
MAX(rows * cellSize.height, viewSize.height));
break;
}
setContentSize(size);
}
NS_CC_END
| [
"wangyanan@gpp.com"
] | wangyanan@gpp.com |
a95e2caada960ccd1c4730e1d9f4c378aa55da6b | acb84fb8d54724fac008a75711f926126e9a7dcd | /poj/poj2663.cpp | 773ae3c7b0aa3e82132b9b6c6a8a03669f6c897e | [] | no_license | zrt/algorithm | ceb48825094642d9704c98a7817aa60c2f3ccdeb | dd56a1ba86270060791deb91532ab12f5028c7c2 | refs/heads/master | 2020-05-04T23:44:25.347482 | 2019-04-04T19:48:58 | 2019-04-04T19:48:58 | 179,553,878 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,095 | cpp | #include<cstdio>
using namespace std;
int H[9],P[100],X[100],tot;
inline void add(int x,int y){
P[++tot]=y;X[tot]=H[x];H[x]=tot;
}
//0 有挡板
void find(int p,int x,int now,int t){
if(x==4) add(p,t);
if(x>3) return;
if((now&1)==0) find(p,x+1,now>>1,t+(1<<(x-1)));// 没挡板
if((now&3)==0) find(p,x+2,now>>2,t);
if((now&1)!=0) find(p,x+1,now>>1,t);
}
int n,m;
inline void mul(int a[][8],int b[][8]){
int c[8][8]={0};
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
for(int k=0;k<8;k++){
c[i][j]+=a[i][k]*b[k][j];
// if(c[i][j]>=m) c[i][j]%=m;
}
}
}
for(int i=0;i<8;i++) for(int j=0;j<8;j++) a[i][j]=c[i][j];
}
int f[8][8];
int p[8][8];
int main(){
for(int i=0;i<1<<4;i++)
find(i,1,i,0);
for(int i=0;i<1<<4;i++){
for(int j=H[i];j;j=X[j]){
f[i][P[j]]=1;
}
}
while(scanf("%d",&n)&&(~n)){
int t[8][8]={0};
t[0][0]=1;
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
p[i][j]=f[i][j];
}
}
while(n){
if(n&1) mul(t,p);
mul(p,p);
n>>=1;
}
printf("%d\n",t[0][0]);
}
return 0;
} | [
"zhangruotian@foxmail.com"
] | zhangruotian@foxmail.com |
03091b2dcc93df77ae435c10e9b1298e4ee20b88 | e0f129d30ae2611fe1b78f11573a51df5af0945f | /rt-compact/src/light/distant.cpp | be799a6726211eec3f3b9535eecf469a1e2e08dc | [] | no_license | TianhuaTao/computer-graphics-assignment | 1b8034fe72cf481bb352053842d3ef9116786176 | 4f1bddac59f0ecb6be2a82bd86b709f57a69195f | refs/heads/master | 2022-11-10T02:03:55.090071 | 2020-06-21T06:39:29 | 2020-06-21T06:39:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,447 | cpp | //
// Created by Sam on 2020/6/16.
//
#include <core/prob.h>
#include "distant.h"
DistantLight::DistantLight(const Transform &LightToWorld, const Color &L,
const Vector3f &wLight)
: Light((int)LightFlags::DeltaDirection, LightToWorld, MediumInterface()),
L(L),
wLight(Normalize(LightToWorld(wLight))) {}
Color DistantLight::Sample_Li(const Interaction &ref, const Point2f &u,
Vector3f *wi, Float *pdf,
VisibilityTester *vis) const {
*wi = wLight;
*pdf = 1;
Point3f pOutside = ref.p + wLight * (2 * worldRadius);
*vis =
VisibilityTester(ref, Interaction(pOutside, ref.time, mediumInterface));
return L;
}
Color DistantLight::Power() const {
return L * Pi * worldRadius * worldRadius;
}
Float DistantLight::Pdf_Li(const Interaction &, const Vector3f &) const {
return 0.f;
}
std::shared_ptr<DistantLight> CreateDistantLight(const Transform &light2world,
const ParamSet ¶mSet) {
Color L = paramSet.FindOneSpectrum("L", Color(1.0));
Color sc = paramSet.FindOneSpectrum("scale", Color(1.0));
Point3f from = paramSet.FindOnePoint3f("from", Point3f(0, 0, 0));
Point3f to = paramSet.FindOnePoint3f("to", Point3f(0, 0, 1));
Vector3f dir = from - to;
return std::make_shared<DistantLight>(light2world, L * sc, dir);
}
| [
"tth135@126.com"
] | tth135@126.com |
112f02a6693a53d79db13a46ce5d512af1dcf862 | 8dba4d5f1d91e777e23df52babfd8d942de9591d | /sys/opt/terminal/terminal.h | 13fdb1c3935d566ca571d9ecd9c56ec82a67094f | [
"MIT"
] | permissive | scientiist/BellOS | 42c484d51511f5aef667552f3d502a38f640f6ea | 1a74bf445f2cd6bb704de7ca173bd87b7d1a23ed | refs/heads/master | 2021-06-16T17:15:20.647516 | 2017-05-13T21:06:15 | 2017-05-13T21:06:15 | 76,580,271 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 254 | h | #ifndef __TERMINAL_INCLUDED__
#define __TERMINAL_INCLUDED__
#include "../../kernel/video/videobuffer.h"
class Terminal {
VideoBuffer termVB;
String lastInp;
public:
void Initialize();
bool Run();
void Prompt();
String GetInput();
};
#endif | [
"j0sh.oleary11@gmail.com"
] | j0sh.oleary11@gmail.com |
5f88846079f0df6e0c7be4a78cae069a59f8505a | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_new_log_6099.cpp | aa0b20086616fe7b8500998968195160da6ce3ce | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 195 | cpp | ap_log_cerror(APLOG_MARK, APLOG_ERR, APR_EGENERAL, c,
APLOGNO(03080)
"h2_session(%ld): unknown state %d", session->id, session->state); | [
"993273596@qq.com"
] | 993273596@qq.com |
8140b9b18a091df34781050d65bf594b7dddb076 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_new_log_3389.cpp | 3680e9c5201d2c703bce1a244710d8b004317184 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 238 | cpp | ap_log_rerror(APLOG_MARK, APLOG_WARNING, apr_get_os_error(), r, APLOGNO(02116)
"unrecognized result code %d "
"from HttpExtensionProc(): %s ",
rv, r->filename); | [
"993273596@qq.com"
] | 993273596@qq.com |
d3e4eeb65b43aa862c38bc92bb620bb95d94cfc8 | c7c6b0a5cdaa59fe515f4e1c767746a2c9fd4c5f | /apps/qdemo/MotionModel.hpp | 14ec9c8c6cd5a0d9cd99e2865cfa96b4d34ae67c | [] | no_license | peter-popov/cppslam | bfb9236f590d887b077dc16eaedf31371968732c | 8ef7abc7989fee833b55cd7cbcd433de7f4dd0df | refs/heads/master | 2016-09-10T21:18:46.064541 | 2015-02-12T20:53:10 | 2015-02-12T20:53:10 | 26,655,903 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,212 | hpp | #pragma once
#include <QtWidgets>
#include <QtQml>
#include "SimulationModel.hpp"
class MotionSample : public QObject {
Q_OBJECT
Q_PROPERTY(Pose *startPose READ startPose)
Q_PROPERTY(QQmlListProperty<Pose> samples READ samples)
Q_PROPERTY(QQmlListProperty<Pose> moves READ moves)
public:
MotionSample();
MotionSample(QPointF pos, double dir);
Pose *startPose() const { return m_startPose.get(); }
QQmlListProperty<Pose> samples();
QQmlListProperty<Pose> moves();
void recalculate(Pose end_pose, std::array<double, 4> params);
private:
std::unique_ptr<Pose> m_startPose;
QList<std::shared_ptr<Pose> > m_samples;
QList<std::shared_ptr<Pose> > m_moves;
};
class MotionModel : public QObject {
Q_OBJECT
Q_PROPERTY(MotionSample *straightMotion READ straightMotion)
Q_PROPERTY(MotionSample *rotationMotion READ rotationMotion)
Q_PROPERTY(double a0 READ a0 WRITE setA0 NOTIFY modelChanged)
Q_PROPERTY(double a1 READ a1 WRITE setA1 NOTIFY modelChanged)
Q_PROPERTY(double a2 READ a2 WRITE setA2 NOTIFY modelChanged)
Q_PROPERTY(double a3 READ a3 WRITE setA3 NOTIFY modelChanged)
signals:
void modelChanged();
public:
MotionModel();
MotionSample *straightMotion() { return &m_straightMotion; }
MotionSample *rotationMotion() { return &m_rotationMotion; }
std::array<double, 4> params();
double a0() const { return m_a0; }
double a1() const { return m_a1; }
double a2() const { return m_a2; }
double a3() const { return m_a3; }
void setA0(double v) {
if (m_a0 == v)
return;
m_a0 = v;
recalculate();
}
void setA1(double v) {
if (m_a1 == v)
return;
m_a1 = v;
recalculate();
}
void setA2(double v) {
if (m_a2 == v)
return;
m_a2 = v;
recalculate();
}
void setA3(double v) {
if (m_a3 == v)
return;
m_a3 = v;
recalculate();
}
private:
void recalculate();
private:
double m_a0;
double m_a1;
double m_a2;
double m_a3;
MotionSample m_straightMotion;
MotionSample m_rotationMotion;
}; | [
"petro.popov@gmail.com"
] | petro.popov@gmail.com |
d89953d4b4c438b19a38f385b0aef2151e63283c | 79c2d89bbfb0fcea09358e8fbee9187c40443b9b | /source/TonyHawksProSkater3.WidescreenFix/dllmain.cpp | eb0da877e62cf04e267b4060d87d0f0a536985fc | [
"MIT"
] | permissive | Sergeanur/WidescreenFixesPack | 0d230f6ca733ac6e73a3e322f07db5b303c04fdf | 7e159be860a870476a97c322a0c4dd244e50cee7 | refs/heads/master | 2020-04-01T04:49:49.295083 | 2018-10-13T15:54:55 | 2018-10-13T15:58:33 | 152,878,656 | 0 | 0 | MIT | 2018-10-13T14:12:39 | 2018-10-13T14:12:39 | null | UTF-8 | C++ | false | false | 5,501 | cpp | #include "stdafx.h"
#include <random>
struct Screen
{
int32_t Width;
int32_t Height;
float fWidth;
float fHeight;
int32_t Width43;
float fAspectRatio;
float fAspectRatioDiff;
int32_t FOV;
float fHUDScaleX;
float fHudOffset;
float fHudOffsetReal;
} Screen;
void Init()
{
CIniReader iniReader("");
Screen.Width = iniReader.ReadInteger("MAIN", "ResX", 0);
Screen.Height = iniReader.ReadInteger("MAIN", "ResY", 0);
bool bFixHUD = iniReader.ReadInteger("MAIN", "FixHUD", 1) != 0;
bool bRandomSongOrderFix = iniReader.ReadInteger("MAIN", "RandomSongOrderFix", 1) != 0;
if (!Screen.Width || !Screen.Height)
std::tie(Screen.Width, Screen.Height) = GetDesktopRes();
Screen.fWidth = static_cast<float>(Screen.Width);
Screen.fHeight = static_cast<float>(Screen.Height);
Screen.Width43 = static_cast<int32_t>(Screen.fHeight * (4.0f / 3.0f));
Screen.fAspectRatio = (Screen.fWidth / Screen.fHeight);
Screen.fAspectRatioDiff = 1.0f / (Screen.fAspectRatio / (4.0f / 3.0f));
Screen.fHUDScaleX = 1.0f / Screen.fWidth * (Screen.fHeight / 480.0f);
Screen.fHudOffset = ((480.0f * Screen.fAspectRatio) - 640.0f) / 2.0f;
Screen.fHudOffsetReal = (Screen.fWidth - Screen.fHeight * (4.0f / 3.0f)) / 2.0f;
//Resolution
auto pattern = hook::pattern("C7 05 ? ? ? ? ? ? ? ? C7 05 ? ? ? ? ? ? ? ? B0 01 5F 5E"); //40B349
static int32_t* dword_851084 = *pattern.get_first<int32_t*>(2);
static int32_t* dword_851088 = *pattern.get_first<int32_t*>(12);
injector::MakeNOP(pattern.get_first(-12), 2, true);
struct SetResHook
{
void operator()(injector::reg_pack& regs)
{
*dword_851084 = Screen.Width;
*dword_851088 = Screen.Height;
}
};
injector::MakeInline<SetResHook>(pattern.get_first(0), pattern.get_first(20));
pattern = hook::pattern("C7 05 ? ? ? ? ? ? ? ? C7 05 ? ? ? ? ? ? ? ? C7 05 ? ? ? ? ? ? ? ? 89 2D"); //40B5B8
injector::MakeInline<SetResHook>(pattern.get_first(0), pattern.get_first(20));
pattern = hook::pattern("A3 ? ? ? ? 8B 04 AE 85 C0"); //40B835 40B84B
injector::MakeInline<SetResHook>(pattern.count(2).get(0).get<void*>(0));
injector::MakeInline<SetResHook>(pattern.count(2).get(1).get<void*>(0));
//Aspect Ratio
pattern = hook::pattern("89 4E 68 8B 50 04 89 56 6C 8B 46 04"); //0x5591B1
struct AspectRatioHook
{
void operator()(injector::reg_pack& regs)
{
*(float*)(regs.esi + 0x68) = *(float*)®s.ecx / Screen.fAspectRatioDiff;
*(float*)®s.edx = *(float*)(regs.eax + 0x04);
}
}; injector::MakeInline<AspectRatioHook>(pattern.get_first(0), pattern.get_first(6));
//HUD
if (bFixHUD)
{
pattern = hook::pattern("D8 0D ? ? ? ? 8B CF 89 5C 24 50 D8"); //0x58DDC8
injector::WriteMemory(*pattern.get_first<float*>(2), Screen.fHUDScaleX, true);
pattern = hook::pattern("C1 E6 08 0B F2 89 70 64 A1"); //0x4F65AE
struct HUDHook //sub_4F62A0
{
void operator()(injector::reg_pack& regs)
{
if (*(float*)(regs.eax + 0x00) == 0.0f && *(float*)(regs.eax + 0x1C) == 0.0f
&& (int32_t)(*(float*)(regs.eax + 0x38)) == Screen.Width43
&& (int32_t)(*(float*)(regs.eax + 0x54)) == Screen.Width43)
{
//blood overlay, maybe more
//*(float*)(regs.eax + 0x00) += Screen.fHudOffsetReal;
//*(float*)(regs.eax + 0x1C) += Screen.fHudOffsetReal;
*(float*)(regs.eax + 0x38) += Screen.fHudOffsetReal * 2.0f;
*(float*)(regs.eax + 0x54) += Screen.fHudOffsetReal * 2.0f;
}
else
{
*(float*)(regs.eax + 0x00) += Screen.fHudOffsetReal;
*(float*)(regs.eax + 0x1C) += Screen.fHudOffsetReal;
*(float*)(regs.eax + 0x38) += Screen.fHudOffsetReal;
*(float*)(regs.eax + 0x54) += Screen.fHudOffsetReal;
}
regs.esi |= regs.edx;
*(uint32_t*)(regs.eax + 0x64) = regs.esi;
}
}; injector::MakeInline<HUDHook>(pattern.get_first(0));
pattern = hook::pattern("8B 81 A4 00 00 00 89 46"); //0x4F66F0
struct HUDHook2 //sub_4F65E0
{
void operator()(injector::reg_pack& regs)
{
*(float*)(regs.esi - 0x04) += Screen.fHudOffsetReal;
regs.eax = *(uint32_t*)(regs.ecx + 0xA4);
}
}; injector::MakeInline<HUDHook2>(pattern.get_first(0), pattern.get_first(6));
}
if (bRandomSongOrderFix)
{
pattern = hook::pattern("E8 ? ? ? ? 8B 96 E8");
struct RandomHook
{
void operator()(injector::reg_pack& regs)
{
std::mt19937 r{ std::random_device{}() };
std::uniform_int_distribution<uint32_t> uid(0, regs.eax);
regs.eax = uid(r);
}
}; injector::MakeInline<RandomHook>(pattern.get_first(0));
}
}
CEXP void InitializeASI()
{
std::call_once(CallbackHandler::flag, []()
{
CallbackHandler::RegisterCallback(Init, hook::pattern("53 55 56 57 52 6A 00"));
});
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved)
{
if (reason == DLL_PROCESS_ATTACH)
{
}
return TRUE;
} | [
"thirteenag@gmail.com"
] | thirteenag@gmail.com |
888ca9f0d4a48b0fd5b9fc6fd03a72dae4559ecf | 7d8d3acacb099341f49bd740c1dc2637a0a7413d | /Code Chef/The Leaking Robot.cpp | bd9431f172dff8d158159dc664347304f1a6fd76 | [] | no_license | himanshushukla254/BugFreeCodes | 71c57023bac39dc9363321a063e0b398f8e23ae8 | cf5bd96d8f67a99f107824a20afb54e0ad85e0b3 | refs/heads/master | 2020-12-03T10:25:52.635565 | 2016-05-14T11:53:50 | 2016-05-14T11:53:50 | 58,805,309 | 1 | 1 | null | 2016-05-14T11:52:15 | 2016-05-14T11:52:14 | null | UTF-8 | C++ | false | false | 674 | cpp | //http://www.codechef.com/AUG14/problems/CRAWA
//Ashish Kedia, NITK Surathkal
//@ashish1294
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include<utility>
using namespace std;
int main()
{
int t,x,y,f;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&x,&y);
f=0;
if(y>=0 && y%2==0 && x>=-y && x<=(y-1)) printf("YES\n");
else if(y<0 && y%2==0 && x>=y && x<=(1-y)) printf("YES\n");
else if(x>0 && x%2==1 && y>=(1-x) && y<=(x+1)) printf("YES\n");
else if(x<=0 && x%2==0 && y>=x && y<=(-x)) printf("YES\n");
else printf("NO\n");
}
return 0;
}
| [
"ashish1294@gmail.com"
] | ashish1294@gmail.com |
7ede46d46b1b8e6bf9b755e5e2f09fd0424c22f2 | 2b62400eb58ca6a93c66c0025a4c440496698f89 | /SDPSeminarHomework(GraphAndTree)/SeminatTreeAndGraphTash/SeminatTreeAndGraphTash/Node.h | 2a44e8e51b5d15cb2d6be42d7f0ac368fd0612de | [] | no_license | MPTGits/SDP_Tasks | 040bccb2444e00a2d44d8640ce236943ad545944 | f3eccdce298934e5414b67026bce7c482d054b3a | refs/heads/master | 2020-05-25T19:20:58.269353 | 2019-05-22T02:33:46 | 2019-05-22T02:33:46 | 187,948,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 159 | h | #pragma once
template <typename T>
struct Node {
T data;
Node<T> *next;
Node(T const& _data, Node<T>* _next = nullptr) : data(_data), next(_next){};
};
| [
"mr.greend@abv.bg"
] | mr.greend@abv.bg |
4ea7e418ebc21075e8753e710d576a7c1a4ca2a6 | 666e70c36b92a97a87de07ddc5c9f9ab1587de66 | /str concat functin.cpp | c534ad16d3e161c33f944bd98d90e3c0d5370db6 | [] | no_license | Manash-git/C-Programming-Study | f3a4e56a8fa09c974f5a11ac9f64141eeeb9a3cb | 26562ab58c08d637cfbf5eeebb1690e2d16d6830 | refs/heads/master | 2021-07-16T03:25:45.497664 | 2017-10-23T19:54:45 | 2017-10-23T19:54:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 195 | cpp | //#include<stdio.h>
#include<bits/stdc++.h>
int main(){
char name[]={"People's republic of "};
strcat(name,"Bangladesh");
puts(name);
printf("\nLenght is : %d",strlen(name));
return 0;
}
| [
"manashmondalcse@gmail.com"
] | manashmondalcse@gmail.com |
320ea568caa1e69f1d20a299d8ab390a17846772 | bbb240f6737d04fddb785b271c3a0852e0dd9c08 | /Battle/Mine.h | ff50c58594332f76102062844802b491ff19810b | [] | no_license | pascaldevink/smashbattle | 72e3fd34f43e077fd9dba41e0f470144583282b2 | 994e021b824a06dda405709ed3a9594dd5cedb5d | refs/heads/master | 2021-01-15T13:19:45.562883 | 2013-12-16T01:46:22 | 2013-12-16T01:46:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 313 | h | #ifndef _MINE_H
#define _MINE_H
#include "Bomb.h"
#include "Player.h"
#define MINE_W 6
#define MINE_H 4
class Mine : public Bomb {
public:
Mine(SDL_Surface * surface);
int flash_interval;
int flash_length;
int flash_start;
void process();
protected:
void set_clips();
};
#endif
| [
"bert@demontpx.com"
] | bert@demontpx.com |
6e2de082929ed74593cdf69c8c135780a158ad2b | e1a24c5c0d710a20b2575f4ee6bc29ffd2321a82 | /CodeChef-Programs/MARCHA1.cpp | 5e0791a301156090f34bcd18c80743232f9d0e0e | [] | no_license | Anshu-ros/Cool-Practice-Programs | fc14a4703ea3e0da1b9033fef36f32657aa219fa | e0607d70e99e20359f713d10129ffc36a78460ad | refs/heads/master | 2021-01-11T17:10:15.938767 | 2016-12-17T12:46:38 | 2016-12-17T12:46:38 | 79,729,412 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 441 | cpp | #include<stdio.h>
int cc_payup(int *A,int m){
for(;*A!=0;A++){
if(*A==m){
return 1;
}
else if(*A<m){
return cc_payup(A+1,m-*A)||cc_payup(A+1,m);
}
}
return 0;
}
int main(){
int A[1000],i,j,t,n,m;
scanf("%d",&t);
for(i=0;i<t;i++){
scanf("%d %d",&n,&m);
for(j=0;j<n;j++){
scanf("%d",&A[j]);
}
A[n]=0;
if(cc_payup(A,m)==1){
printf("Yes\n");
}
else{
printf("No\n");
}
}
return 0;
}
| [
"faheemzunjani@gmail.com"
] | faheemzunjani@gmail.com |
334b648ecf34d61c1a1b7e28a88d3da82affe3a8 | 00948a19e63549ddfdea1f6e5ac55ffcfeb7c1b3 | /utils/NN.h | 031b2b12eb8695044b7b523e3c2ffc85c2972759 | [
"MIT"
] | permissive | Voleco/bdexplain | 6aa310cc9f4c11025d967e4c89aa9673053a708c | 5e610155ad4cc0e9024d73497a8c88e33801e833 | refs/heads/master | 2021-07-04T09:06:10.217994 | 2019-04-04T13:04:53 | 2019-04-04T13:04:53 | 147,047,793 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,710 | h | #ifndef NN_H
#define NN_H
#include "FunctionApproximator.h"
#include <vector>
class NN : public FunctionApproximator {
public:
NN(int inputs, int hiddens, int outputs, double learnrate);
NN(NN *);
NN(FunctionApproximator *);
NN(char *);
~NN();
void load(const char *);
void load(FILE *);
void load(const NN *);
void load(const FunctionApproximator *fa) { load((NN*)fa); }
static bool validSaveFile(char *fname);
void save(const char *);
void save(FILE *);
double train(std::vector<double> &input, std::vector<double> &target);
double *test(const std::vector<double> &input);
double GetInput(std::vector<double> &input, const std::vector<double> &target);
double train(std::vector<unsigned int> &input, std::vector<double> &target);
double *test(const std::vector<unsigned int> &input);
int getNumInputs() { return inputs; }
double getInputWeight(int inp, int outp=0) { return weights[0][outp][inp]; }
void Print();
private:
void allocateMemory(const NN *nn = 0);
void freeMemory();
std::vector< std::vector< std::vector<double> > > weights;
std::vector< std::vector< std::vector<double> > > updatedweights;
std::vector< std::vector< std::vector<double> > > errors;
std::vector<double> hidden;
std::vector<double> output;
int inputs, hiddens, outputs;
double g(double a);
double dg(double a);
double outputerr(const std::vector<double> &output, const std::vector<double> &expected, int which);
double internalerr(const std::vector<double> &output, const std::vector<double> &expected, int which);
double internalinputerr(const std::vector<double> &output, const std::vector<double> &expected, int which);
double error(const std::vector<double> &outputs);
};
#endif
| [
"chenjingwei1991@gmail.com"
] | chenjingwei1991@gmail.com |
ec84e4ae78fa7470f55e43f5f3c7a7cbd787ea9c | 28ef30faa8122b3b68da10f79b047a6e2be32de0 | /Modelos/Motor Diesel/simulation_model_motor_diesel_bueno/simulation_model_motor_diesel_bueno.ino | b3c57a381c11a3665712e8285eeae8b93961de55 | [] | no_license | carmar14/Simulacion_ugrid | 05f0c87248e0616a80571bfa3cc5f2c80b60b3a2 | 80529f394e1f5bf1a10de1ab0e3a75cd0a201846 | refs/heads/master | 2021-07-05T11:25:09.124412 | 2020-11-03T00:16:22 | 2020-11-03T00:16:22 | 197,256,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,259 | ino |
#include <FreeRTOS_ARM.h>
double TenK, VelK, KGen;
double VelK1, TNK, TNK1;
double PLK, PLK1, U[51];
double KGen = 1/2;
bool r=false;
void setup() {
pinMode(52,OUTPUT);
analogWriteResolution(12);
analogReadResolution(12);
Serial.begin(115200);
xTaskCreate(motor, NULL,configMINIMAL_STACK_SIZE , NULL, 1, NULL);
vTaskStartScheduler();
}
static void motor(void* arg){
portTickType xLastWakeTime;
xLastWakeTime = xTaskGetTickCount();
while(1){
r=true;
digitalWrite(52,r);
for (int j=50;j>0;j--) U[j] = U[j-1];
TNK1=TNK;
VelK1 = VelK;
PLK1=PLK;
U[0]=analogRead(A0)*1/4095; // Acción al actuador
PLK=analogRead(A1)*1/4095; // Par de carga
Serial.print("Acción al Actuador = ");
Serial.println(U[0]);
Serial.print("Par de carga = ");
Serial.println(PLK);
TNK = (0.9231*TNK1) + (0.04423*(U[49]+U[50])) - PLK + (0.9231 * PLK1);
VelK = (0.9997*VelK1) + (0.00015+(TNK+TNK1));
TenK = VelK * KGen;
float Vel=VelK*4095/3.3;
float Ten=TenK*4095/3.3;
Serial.println("Velocidad = ");
Serial.println(Vel);
Serial.println("Tensión = ");
Serial.println(Ten);
r=!r;
digitalWrite(52,r);
vTaskDelayUntil(&xLastWakeTime, (10/portTICK_RATE_MS));
}
}
void loop() {}
| [
"carmar141414@hotmail.com"
] | carmar141414@hotmail.com |
18073528c7c6e9612caa5418379206e78db4085b | b7dd7ddf80a2468244bf9479ee0916d3298629ed | /course_work/me537/project/simulation/ros_packages/unsuper_nn/src/evo_unsupervised_learner.h | 740ccbe81007b3cb42fb6f404278b3a6e708a1a9 | [] | no_license | kckemper/kemper | 5550e3a0ce1814bd8963ca97cb4d7bacbb3fdbe8 | a1c33d19363fa2a60f61a69d21b3dec6a2bddbad | refs/heads/master | 2021-01-10T08:49:26.918463 | 2012-09-21T18:30:50 | 2012-09-21T18:30:50 | 52,307,308 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,033 | h | #include <stdio.h>
#include <cv.h>
#include <highgui.h>
#include <math.h>
#include <iostream>
#include <fstream>
#include "evo.h"
#define NF 6
#define N_SLICES 8 // number of slices to make of the image
#define N_STEPS 855 // number of images
#define SIZE 16 // scaled image size
#define N_LEARN 200 // number of images per learing episode
#define N_EPISODES 50 // number of learning episodes
#define N_TRIALS 10 // number of times to repeat the learning
#define N_NETS 20
#define N_HIDDEN 16
#define PIX(img,x,y) ((uchar*)((img)->imageData + (img)->widthStep*(y)))[(x)]
static void allocateOnDemand( IplImage **, CvSize, int, int);
class EvoUnsupervisedLearner {
private:
CvPoint p,q;
CvScalar line_color;
CvScalar out_color;
const char* name_orig;
const char* name_ave;
const char* name_weights;
const char* inputCmdFile_name;
const char* outputFile_name;
FILE* outputFile;
FILE* inputCmdFile;
char inputName[128];
char outputName[128];
// Picture filenames.
char sliced_filename[128];
char weight_filename[128];
CvCapture* capture;
CvSize frame_size;
CvScalar ave;
CvRect slice_rect;
CvSize slice_size;
IplImage* frame;
IplImage* frame_g;
IplImage* frame_small;
IplImage* frame_weights;
IplImage* frame_w_big;
IplImage* frame_w_final;
IplImage* frame_final;
IplImage* ave_image;
// static IplImage *scale;
IplImage* frame_slices[N_SLICES];
float inputs[(SIZE/N_SLICES)*SIZE];
float outputs[N_SLICES];
int choices[N_SLICES];
// float desired[N_SLICES];
// float desired[] = {0,0,0,1,1,0,0,0}; //XXX dummy test...
//Evo (int nNets, int nInputs, int nHidden, int nOuts)
Evo* evoSlice;
int ep;
int trial;
int stepCnt;
int flag;
char c;
int i,j,k,s;
float tmp;
public:
EvoUnsupervisedLearner();
EvoUnsupervisedLearner(IplImage*);
void initialize(int);
char takeImage(IplImage*, int);
void penalize(float);
void decayPenalties(float);
};
| [
"kkemper@f5c5be9c-040c-f34b-f993-a0493b5d6c12"
] | kkemper@f5c5be9c-040c-f34b-f993-a0493b5d6c12 |
238fbf64b556953aa6aeca52a4c7fe8ffc573a4c | 66634a99cf626b05174e583e92704903a9e006db | /include/cub/sched/Executor.h | 7782a5df8e92d50bf5530ed675789b1046b3f17b | [
"Apache-2.0"
] | permissive | ccup/cub | 069ce1f3a3d9ddf66c177e0cb6d29b1ec69cd9cf | 41e1c1b44252f00021aa61f5f305488abad7b289 | refs/heads/master | 2022-06-19T08:12:42.286109 | 2022-05-20T16:31:36 | 2022-05-20T16:31:36 | 298,842,727 | 14 | 12 | null | null | null | null | UTF-8 | C++ | false | false | 1,237 | h | #ifndef H441EB5A0_2E97_4187_AA21_FAB5C70470C0
#define H441EB5A0_2E97_4187_AA21_FAB5C70470C0
#include <cub/base/BaseTypes.h>
#include <cub/sched/Synchronization.h>
#include <condition_variable>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <future>
#include <functional>
#include <memory>
CUB_NS_BEGIN
struct Executor
{
Executor(size_t);
~Executor();
template<class F, class... Args>
auto execute(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
using ReturnType = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared< std::packaged_task<ReturnType()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<ReturnType> res = task->get_future();
SYNCHRONIZED(tasksMutex)
{
tasks.emplace([task](){ (*task)(); });
}
condition.notify_one();
return res;
}
private:
void threadRun();
private:
std::vector< std::thread > workers;
std::queue< std::function<void()> > tasks;
std::mutex tasksMutex;
std::condition_variable condition;
bool stop;
};
CUB_NS_END
#endif
| [
"e.bowen.wang@icloud.com"
] | e.bowen.wang@icloud.com |
aebd755a9eeb9561ecb1b795045c9432cb58b451 | 84464965f202caa72fa395ddf997f026096524f7 | /extra/server.cpp | f07fb29eb5fb1c02f70690bcfb3015f5390c2bb8 | [] | no_license | dartuso/VeryStrangeWebProxy | fc9ae32b83018008d24d55fcf01c67fe366d8376 | c44046b1b8a0538add9abc6e5e7badee504c1db3 | refs/heads/master | 2022-12-21T06:59:41.074151 | 2020-10-01T18:19:02 | 2020-10-01T18:19:02 | 238,564,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,371 | cpp | /*
* A simple TCP server that echos messages back to the client.
* This server works with only a single client. With a simple modification, it can take more clients.
*/
#include <iostream>
#include <sys/socket.h> // for socket(), connect(), send(), and recv()
#include <arpa/inet.h> // for sockaddr_in and inet_addr()
#include <stdlib.h> // for atoi() and exit()
#include <string.h> // for memset()
#include <unistd.h> // for close()
using namespace std;
const int BUFFERSIZE = 32; // Size the message buffers
const int MAXPENDING = 1; // Maximum pending connections
int main(int argc, char *argv[])
{
int serverSock; // server socket descriptor
int clientSock; // client socket descriptor
struct sockaddr_in serverAddr; // address of the server
struct sockaddr_in clientAddr; // address of the client
char inBuffer[BUFFERSIZE]; // Buffer for the message from the server
int bytesRecv, bytes; // Number of bytes received
int bytesSent; // Number of bytes sent
// Check for input errors
if (argc != 2)
{
cout << "Usage: " << argv[0] << " <Listening Port>" << endl;
exit(1);
}
// Create a TCP socket
// * AF_INET: using address family "Internet Protocol address"
// * SOCK_STREAM: Provides sequenced, reliable, bidirectional, connection-mode byte streams.
// * IPPROTO_TCP: TCP protocol
if ((serverSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
cout << "socket() failed" << endl;
exit(1);
}
// Free up the port before binding
// * sock: the socket just created
// * SOL_SOCKET: set the protocol level at the socket level
// * SO_REUSEADDR: allow reuse of local addresses
// * &yes: set SO_REUSEADDR on a socket to true (1)
// * sizeof(int): size of the value pointed by "yes"
int yes = 1;
if (setsockopt(serverSock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0)
{
cout << "setsockopt() failed" << endl;
exit(1);
}
// Initialize the server information
// Note that we can't choose a port less than 1023 if we are not privileged users (root)
memset(&serverAddr, 0, sizeof(serverAddr)); // Zero out the structure
serverAddr.sin_family = AF_INET; // Use Internet address family
serverAddr.sin_port = htons(atoi(argv[1])); // Server port number
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Any incoming interface
// Bind to the local address
if (bind(serverSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) < 0)
{
cout << "bind() failed" << endl;
exit(1);
}
// Listen for connection requests
if (listen(serverSock, MAXPENDING) < 0)
{
cout << "listen() failed" << endl;
exit(1);
}
// set the size of the client address structure
unsigned int size = sizeof(clientAddr);
// Waiting for connection requests
if ((clientSock = accept(serverSock, (struct sockaddr *) &clientAddr, &size)) < 0)
{
cout << "accept() failed" << endl;
exit(1);
}
// The server will be blocked until a client is connected to it.
cout << "Accepted a connection from " << inet_ntoa(clientAddr.sin_addr) << endl;
// Start communication with the client (terminate when receive a "terminate" command)
while (strncmp(inBuffer, "terminate", 9) != 0)
{
// Clear the buffers
memset(&inBuffer, 0, BUFFERSIZE);
// Receive the message from client
bytesRecv = recv(clientSock, (char *) &inBuffer, BUFFERSIZE, 0);
// Check for connection close (0) or errors (< 0)
if (bytesRecv <= 0)
{
cout << "recv() failed, or the connection is closed. " << endl;
exit(1);
}
cout << "Client: " << inBuffer;
// Echo the message back to the client
bytesSent = send(clientSock, (char *) &inBuffer, bytesRecv, 0);
if (bytesSent < 0 || bytesSent != bytesRecv)
{
cout << "error in sending" << endl;
exit(1);
}
}
// Close the connection with the client
close(clientSock);
// Close the server socket
close(serverSock);
}
| [
"daniel.artuso1@gmail.com"
] | daniel.artuso1@gmail.com |
b7aa01fed16438a76afe431923688efdf0176652 | 3701e5410478b44109411f72f522f91493d4525d | /factorial.cpp | d26f44ed50176dc177704d90e267e62407ef1273 | [] | no_license | Alam11/metaprogramowanie | 3cde320f436209ba6fb272455a54f58f8a893024 | 37438bd75b47bee365cb3f8b06422c6a74577b6c | refs/heads/master | 2016-09-01T14:59:37.976477 | 2016-01-17T21:21:58 | 2016-01-17T21:21:58 | 49,573,945 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 239 | cpp | template<int N>
struct factorial {
enum {
val = factorial<N - 1>::val * N
};
};
template<>
struct factorial<0> {
enum {
val = 1
};
};
template<>
struct factorial<1> {
enum {
val = 1
};
};
| [
"morzydusza@gmail.com"
] | morzydusza@gmail.com |
0ee6f8c1718f44606d2b48f8d3037073ee88f84f | 4e971bd8f059f3fdb1cf29ec2f870cfb4e38021e | /Uppgift 3 - QuadTree/Projekt/Source/CommonUtilities/Line/Line.hpp | e864c75328f8aad0c827caca0961c3e2c7ce42a5 | [] | no_license | godofnanners/Spelorienterade-datastrukturer-och-algoritmer | b0a810ba4009049705bd4cca740943b6bb7558e2 | 618054d8a301c82896c364f720403cc84f91aa1b | refs/heads/master | 2022-12-29T03:04:15.430220 | 2020-10-21T00:05:53 | 2020-10-21T00:05:53 | 287,136,220 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,744 | hpp | #pragma once
#include "Vector/Vector2.h"
namespace CommonUtilities
{
template <class T>
class Line
{
public:
// Default constructor: there is no line, the normal is the zero vector.
Line();
// Copy constructor.
Line(const Line <T>& aLine);
// Constructor that takes two points that define the line, the direction is aPoint1 -aPoint0.
Line(const Vector2<T>& aPoint0, const Vector2<T>& aPoint1);
// Init the line with two points, the same as the constructor above.
void InitWith2Points(const Vector2<T>& aPoint0, const Vector2<T>& aPoint1);
// Init the line with a point and a direction.
void InitWithPointAndDirection(const Vector2<T>& aPoint, const Vector2<T>&
aDirection);
// Returns whether a point is inside the line: it is inside when the point is on the line or on the side the normal is pointing away from.
bool IsInside(const Vector2<T>& aPosition) const;
// Returns the direction of the line.
const Vector2<T>& GetDirection() const;
// Returns the normal of the line, which is (-direction.y, direction.x).
const Vector2<T>& GetNormal() const;
private:
Vector2<T> myDirection;
Vector2<T> myPoint;
Vector2<T> myNormal;
};
template<class T>
inline Line<T>::Line()
{
myDirection = { 0,0 };
myPoint = { 0,0 };
}
template<class T>
inline Line<T>::Line(const Line<T>& aLine)
{
myDirection = aLine.myDirection;
myPoint = aLine.myPoint;
myNormal = aLine.myNormal;
}
template<class T>
inline Line<T>::Line(const Vector2<T>& aPoint0, const Vector2<T>& aPoint1)
{
Vector2<T>unNormalizedDir = (aPoint1 - aPoint0);
myDirection = unNormalizedDir.GetNormalized();
myPoint = aPoint0;
myNormal = { -myDirection.y,myDirection.x };
}
template<class T>
inline void Line<T>::InitWith2Points(const Vector2<T>& aPoint0, const Vector2<T>& aPoint1)
{
Vector2<T>unNormalizedDir = (aPoint1 - aPoint0);
myDirection = unNormalizedDir.GetNormalized();
myPoint = aPoint0;
myNormal = { -myDirection.y,myDirection.x };
}
template<class T>
inline void Line<T>::InitWithPointAndDirection(const Vector2<T>& aPoint, const Vector2<T>& aDirection)
{
myPoint = aPoint;
myDirection = aDirection.GetNormalized();
myNormal = { -myDirection.y,myDirection.x };
}
template<class T>
inline bool Line<T>::IsInside(const Vector2<T>& aPosition) const
{
Vector2<T> differenceVector = aPosition - myPoint;
if (( differenceVector.Dot(myNormal)) <= 0)
{
return true;
}
return false;
}
template<class T>
inline const Vector2<T>& Line<T>::GetDirection() const
{
return myDirection;
// TODO: insert return statement here
}
template<class T>
inline const Vector2<T>& Line<T>::GetNormal() const
{
return myNormal;
// TODO: insert return statement here
}
}
| [
"casper.martensson@telia.com"
] | casper.martensson@telia.com |
7c772ad1efd1c6508cc0d06561d44a9e3b246ed8 | 6009e3237259cd78970abb6cc9c5654553a8d625 | /jwspubctrl/sub_client.cpp | 22ecb89f43e68b0b7bfd437c14bbacb1b29e31e8 | [] | no_license | jmuncaster/jwspubctrl | 70c05afa5c1b25540d132daf28f3ec14abadb158 | c1abee0ec72d5618047f41a5ef429ffe6b4ca442 | refs/heads/main | 2023-05-10T16:42:04.854880 | 2023-04-27T19:01:11 | 2023-04-27T19:01:11 | 127,324,796 | 0 | 0 | null | 2023-04-27T19:01:13 | 2018-03-29T17:26:10 | C++ | UTF-8 | C++ | false | false | 1,598 | cpp | #include "sub_client.hpp"
#include <jws/json_with_schema.hpp>
#include <wspubctrl/sub_client.hpp>
#include <functional>
#include <memory>
#include <string>
namespace jwspubctrl {
struct SubClient::Detail {
Detail(
const std::string& pub_uri,
const jws::json& pub_schema)
: _client(pub_uri) {
_pub_validator = jws::load_validator(pub_schema);
}
wspubctrl::SubClient _client;
jws::json_validator _pub_validator;
};
SubClient::SubClient(const std::string& pub_uri, const jws::json& pub_schema)
: _detail(new Detail(pub_uri, pub_schema)) {
}
SubClient::~SubClient() {
}
void SubClient::connect() {
_detail->_client.connect();
}
void SubClient::disconnect() {
_detail->_client.disconnect();
}
jws::json SubClient::poll_json(int timeout_ms) {
auto data = _detail->_client.poll(timeout_ms);
auto data_json = jws::json::parse(data);
_detail->_pub_validator.validate(data_json);
return data_json;
}
bool SubClient::poll_json(jws::json& data_json, int timeout_ms) {
// Grab data, return if timeout
std::string data;
auto success = _detail->_client.poll(data, timeout_ms);
if (!success) {
return false;
}
// Validate json and return
data_json = jws::json::parse(data);
_detail->_pub_validator.validate(data_json);
return true;
}
std::string SubClient::poll_string(int timeout_ms) {
return _detail->_client.poll(timeout_ms);
}
bool SubClient::poll_string(std::string& data, int timeout_ms) {
return _detail->_client.poll(data, timeout_ms);
}
}
| [
"justin@muncaster.io"
] | justin@muncaster.io |
09e432d03bb9691e45548ddec07c2917a50344f9 | 5d2177228b61c95e334491010611797b86552ec5 | /psmg-oops/src/context/PValueSym.h | e1de0b3bd8e2537cf32542a974f343420dbf05ca | [] | no_license | fqiang/psmg | 02d762cda9c03251d1d0878648e90a99aed0f271 | 474cd07a3e857e3880aec08dde77dca4830801dd | refs/heads/master | 2021-01-10T19:02:59.059533 | 2015-07-17T02:58:03 | 2015-07-17T02:58:03 | 41,818,377 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 883 | h | /*
* SymValue.h
*
* Created on: 22 Mar 2014
* Author: s0965328
*/
#ifndef PVALUESYM_H_
#define PVALUESYM_H_
#include "PValue.h"
class PValueSym : public PValue {
public:
string value;
PValueSym(const string&);
PValueSym(const PValueSym& other);
virtual ~PValueSym();
virtual PValueSym* clone();
virtual PValueSym* plus(PValue* other);
virtual PValueSym* accumulate(PValue* other);
virtual PValueSym* minus(PValue* other);
virtual PValueSym* neg();
virtual PValueSym* times(PValue* other);
virtual PValueSym* divid(PValue* other);
virtual PValueSym* power(PValue* other);
virtual PValueSym* power(double&);
virtual bool isGT(PValue* other);
virtual bool isEQ(PValue* other);
virtual bool isNE(PValue* other);
virtual string toString();
virtual void calculateMemoryUsage(unsigned long&);
private:
PValueSym* error();
};
#endif /* PVALUESYM_H_ */
| [
"f.qiang@gmail.com"
] | f.qiang@gmail.com |
5f1d6668a8655ce3a7ddafd9d2e18e7f5e9ecd9f | c2d320626432c783b5f5090bfcc0ad56eb8d814c | /Backend/Parser/submissions/Assignment 12/68.cpp | dc16ceab9e4075481e66fe29eee1feb337c58c39 | [] | no_license | shreysingla11/ssl-project | dbc5569ac2d83b359daa3eda67ab1083949ea160 | 1a6e7494074f74a61100c1d8d09e7709f7f4931c | refs/heads/master | 2023-01-29T07:57:20.968588 | 2020-12-08T15:34:37 | 2020-12-08T15:34:37 | 304,885,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,372 | cpp | #include <iostream>
#include <vector>
#include <stack>
using namespace std;
struct node
{
int index;
vector<int> successors;
vector<int> predecessors;
char going;
bool visited;
int t_i;
int n_i;
int friendsGoing;
int friendsNotGoing;
node ()
{
going = '0';
friendsGoing = 0;
friendsNotGoing = 0;
visited = false;
}
};
struct graph
{
vector<node> vertices;
};
int main()
{
graph g;
stack <int > definitelyGoing;
stack <int > definitelyNotGoing;
int num;
cin>>num;
g.vertices.resize(num);
for (int i = 0; i < num; ++i)
{
g.vertices[i].index=i;
int T_i;
int N_i;
int Friend;
cin>>T_i>>N_i;
g.vertices[i].t_i=T_i;
g.vertices[i].n_i=N_i;
if (T_i == 0)
{
definitelyGoing.push(i);
g.vertices[i].visited = true;
}
else if (T_i > N_i)
{
definitelyNotGoing.push(i);
g.vertices[i].visited = true;
}
for (int j = 0; j < N_i; ++j)
{
cin>>Friend;
g.vertices[i].successors.push_back(Friend);
g.vertices[Friend].index=Friend;
g.vertices[Friend].predecessors.push_back(i);
}
}
int min = 0;
int max = num;
while (!definitelyGoing.empty())
{
int temp = definitelyGoing.top();
min++;
definitelyGoing.pop();
int size = g.vertices[temp].predecessors.size();
for (int i = 0; i < size; ++i)
{
g.vertices[g.vertices[temp].predecessors[i]]. friendsGoing++;
if (g.vertices[g.vertices[temp].predecessors[i]].visited == false && g.vertices[g.vertices[temp].predecessors[i]].friendsGoing >= g.vertices[g.vertices[temp].predecessors[i]].t_i)
{
definitelyGoing.push(g.vertices[temp].predecessors[i]);
g.vertices[g.vertices[temp].predecessors[i]].visited = true;
}
}
}
while (!definitelyNotGoing.empty())
{
int temp = definitelyNotGoing.top();
max--;
definitelyNotGoing.pop();
int size = g.vertices[temp].predecessors.size();
for (int i = 0; i < size; ++i)
{
g.vertices[g.vertices[temp].predecessors[i]]. friendsNotGoing++;
if (g.vertices[g.vertices[temp].predecessors[i]].visited == false && g.vertices[g.vertices[temp].predecessors[i]].friendsNotGoing > g.vertices[g.vertices[temp].predecessors[i]].n_i - g.vertices[g.vertices[temp].predecessors[i]].t_i)
{
definitelyNotGoing.push(g.vertices[temp].predecessors[i]);
g.vertices[g.vertices[temp].predecessors[i]].visited = true;
}
}
}
cout<<min<<" "<<max<<endl;
return 0;
}
| [
"shreysingla2@gmail.com"
] | shreysingla2@gmail.com |
0766fa1050c80d364934f905f7932d4947368c85 | 3a65ed8a0635c498feb66c571daba4448352a8ed | /modules/rt/include/motis/rt/update_constant_graph.h | 1c8606c9e5ca1c776e4496acdb149f173861e214 | [
"Apache-2.0",
"MIT"
] | permissive | julianharbarth/motis | e83e8bccd6b8c2025613d91dea715c0ec3055d5d | d5ded8b519a85809949f084ca7983a22180deb1a | refs/heads/master | 2022-07-29T04:40:42.429723 | 2020-05-17T11:49:15 | 2020-05-17T11:49:15 | 264,986,758 | 0 | 0 | MIT | 2020-05-18T16:06:00 | 2020-05-18T15:47:50 | null | UTF-8 | C++ | false | false | 2,333 | h | #pragma once
#include "motis/core/schedule/schedule.h"
namespace motis::rt {
inline void constant_graph_add_route_node(schedule& sched, int route_index,
station_node const* sn,
bool in_allowed, bool out_allowed) {
auto const route_offset = static_cast<uint32_t>(sched.station_nodes_.size());
auto const route_lb_node_id =
route_offset + static_cast<uint32_t>(route_index);
auto const cg_size = route_offset + sched.route_count_;
auto const add_edge = [&](uint32_t const from, uint32_t const to,
bool const is_exit) {
auto& fwd_edges = sched.transfers_lower_bounds_fwd_[to];
if (std::find_if(begin(fwd_edges), end(fwd_edges), [&](auto const& se) {
return se.to_ == from;
}) == end(fwd_edges)) {
fwd_edges.emplace_back(from, is_exit);
}
auto& bwd_edges = sched.transfers_lower_bounds_bwd_[from];
if (std::find_if(begin(bwd_edges), end(bwd_edges), [&](auto const& se) {
return se.to_ == to;
}) == end(bwd_edges)) {
bwd_edges.emplace_back(to, !is_exit);
}
};
sched.transfers_lower_bounds_fwd_.resize(cg_size);
sched.transfers_lower_bounds_bwd_.resize(cg_size);
if (in_allowed) {
add_edge(sn->id_, route_lb_node_id, false);
}
if (out_allowed) {
add_edge(route_lb_node_id, sn->id_, true);
}
}
inline void constant_graph_add_route_edge(schedule& sched,
trip::route_edge const& route_edge) {
auto const min_cost = route_edge->get_minimum_cost();
if (!min_cost.is_valid()) {
return;
}
auto const update_min = [&](constant_graph& cg, uint32_t const from,
uint32_t const to) {
for (auto& se : cg[from]) {
if (se.to_ == to) {
se.cost_ = std::min(se.cost_, min_cost.time_);
return;
}
}
cg[from].emplace_back(to, min_cost.time_);
};
auto const from_station_id = route_edge->from_->get_station()->id_;
auto const to_station_id = route_edge->to_->get_station()->id_;
update_min(sched.travel_time_lower_bounds_fwd_, to_station_id,
from_station_id);
update_min(sched.travel_time_lower_bounds_bwd_, from_station_id,
to_station_id);
}
} // namespace motis::rt
| [
"felix.guendling@gmail.com"
] | felix.guendling@gmail.com |
f37fe918a5e5f9f8e63d18b002682a43b851b309 | 27e8b7337fa04d4e814b4cf162a561dac9c8b4f9 | /linked_list.h | 2c21ae9c8429d066bca49e19d5654a646ceea26b | [] | no_license | matt1moore/2020-DataStructures-PA5 | 9404487a8b97012081883ae1389bb131b6a8f17e | 008c8a88499385fcac41e8867f427701619f1f14 | refs/heads/main | 2023-02-16T12:21:41.476872 | 2020-12-23T16:39:18 | 2020-12-23T16:39:18 | 328,014,668 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,748 | h | //----------------------------------------------------------------------
// FILE: linked_list.h
// NAME: Matthew Moore
// DATE: September, 2020
// DESC: Implements a linked list version of the list class. Elements
// are added by default to the end of the list via a tail pointer.
// Implemented sorting algorithms that sort lists in ascending order.
//----------------------------------------------------------------------
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include "list.h"
#include <iostream>
using namespace std;
template<typename T>
class LinkedList : public List<T>
{
public:
LinkedList();
LinkedList(const List<T>& rhs);
~LinkedList();
LinkedList& operator=(const List<T>& rhs);
void add(const T& item);
bool add(size_t index, const T& item);
bool get(size_t index, T& return_item) const;
bool set(size_t index, const T& new_item);
bool remove(size_t index);
size_t size() const;
void selection_sort();
void insertion_sort();
void merge_sort();
void quick_sort();
void sort();
private:
struct Node {
T value;
Node* next;
};
Node* head;
Node* tail;
size_t length;
// helper to delete linked list
void make_empty();
// helper functions for merge and quick sort
Node * merge_sort(Node* left, int len);
Node * quick_sort(Node* start, int len);
};
template<typename T>
LinkedList<T>::LinkedList()
: head(nullptr), tail(nullptr), length(0)
{
}
template<typename T>
LinkedList<T>::LinkedList(const List<T>& rhs)
: head(nullptr), tail(nullptr), length(0)
{
// defer to assignment operator
*this = rhs;
}
// TODO: Finish the remaining functions below
template<typename T>
LinkedList<T>::~LinkedList() {
Node * currNode = NULL;
Node * nextNode = head;
while (currNode != NULL) {
// Traversal of Nodes in the list
nextNode = currNode->next;
// Deletes the current Node
delete currNode;
currNode = nextNode;
}
// Good practice to set head to NULL when list is empty
head = NULL;
}
template<typename T>
LinkedList<T>& LinkedList<T>::operator=(const List<T>& rhs)
{
int i = 1;
if (this != &rhs) { // protects against self-assignment chance
if (head != nullptr) { // Clears the lhs if not already clear
~LinkedList();
}
Node * copyPtr = nullptr;
Node * currPtr = rhs.head;
while (currPtr != nullptr) {
if (head == NULL) {
// Sets the head to point to initial element
copyPtr = new Node(currPtr->get(length,0));
head = copyPtr;
}
else {
// Sets all next pointers to point new elements
copyPtr->add(new Node(currPtr->get(length,i)));
copyPtr = copyPtr->next;
++i;
}
currPtr = currPtr->next;;
}
}
return *this;
}
template<typename T>
void LinkedList<T>::add(const T& item) {
// Assigns value to new node
Node * newNode = new Node;
newNode->value = item;
if (head == NULL) { // List is empty if true
head = newNode;
tail = newNode;
}
else { // List contains elements
tail->next = newNode;
tail = newNode;
}
newNode->next = NULL;
length = length + 1;
}
template<typename T>
bool LinkedList<T>:: add(size_t index, const T& item) {
if (index > length || index < 0) { // Invalid index
return false;
}
Node * newNode = new Node;
newNode->value = item;
if (head == NULL) { // For an empty list
head = newNode;
tail = newNode;
newNode->next = NULL;
}
else { // New node will be inserted at the index
Node * currPtr = head;
Node * prevPtr = NULL;
size_t i = 0;
while (i < index) {
// Traverse list to the correct index
prevPtr = currPtr;
currPtr = currPtr->next;
++i;
}
if (i == 0) { // The element will be at head of the list
head = newNode;
newNode->next = currPtr;
}
else if (index == length) {
// Case of adding element to the end
newNode->next = NULL;
prevPtr->next = newNode;
tail = newNode;
}
else {
// Regular case
prevPtr->next = newNode;
newNode->next = currPtr;
}
}
length = length + 1;
return true;
}
template<typename T>
bool LinkedList<T>::get(size_t index, T& return_item) const {
if (index >= length || index < 0) { // Invalid index
return false;
}
else if (head == tail) { // One element in the list
Node * currPtr = head;
return_item = currPtr->value;
return true;
}
else {
Node * currPtr = head;
for (size_t i = 0; i < index; ++i) {
// Traverses until index number is hit
currPtr = currPtr->next;
}
return_item = currPtr->value;
return true;
}
}
template<typename T>
bool LinkedList<T>::set(size_t index, const T& new_item) {
if (index >= length || index < 0) {
return false;
}
else if (head == tail) { // One element in the list
head->value = new_item;
return true;
}
else {
Node * currPtr = head;
for (size_t i = 0; i < index; i++) {
//Traversal of list until index is reached
currPtr = currPtr->next;
}
// Set new value to the index value
currPtr->value = new_item;
return true;
}
}
template<typename T>
bool LinkedList<T>::remove(size_t index) {
size_t i = 0;
if (index >= length || index < 0) {
return false;
}
else if (head == tail) {
// Singular element in the list
Node * currPtr = head;
delete currPtr;
head = nullptr;
tail = nullptr;
length = length - 1;
return true;
}
else {
Node * currPtr = head;
Node * prevPtr = nullptr;
while (i < index) {
// Traversal of list until index is reached
prevPtr = currPtr;
currPtr = currPtr->next;
++i;
}
// Remove the value at this index and fix the pointers
if (index == 0) { // Front of the list
head = currPtr->next;
}
else if (index == length - 1) { // Element is at the end of the list
tail = prevPtr;
prevPtr->next = nullptr;
}
else {
prevPtr->next = currPtr->next;
}
delete currPtr;
length = length - 1;
return true;
}
}
template<typename T>
size_t LinkedList<T>::size() const {
return length;
}
template<typename T>
void LinkedList<T>::selection_sort() {
Node * outerNode = head;
Node * innerNode = nullptr;
Node * minNode = nullptr;
Node * tmpNode = nullptr;
Node * prevNode = nullptr;
Node * prevMin = nullptr;
Node * outerPrev = nullptr;
if (head == NULL) {
// No elements to sort !!!
}
else if (head == tail) {
// There is only one element, so already sorted !!!
}
else {
while (outerNode->next != NULL) {
// Runs through list, finding the minimum in the unsorted section
minNode = outerNode;
innerNode = outerNode;
prevMin = outerPrev;
while (innerNode != NULL) {
// Searches through unsorted region for smallest element
if (innerNode->value < minNode->value) {
// New minimum has been found
minNode = innerNode;
prevMin = prevNode;
}
prevNode = innerNode;
innerNode = innerNode->next;
}
// Now swap the new min value into the first element of the unsorted portion
if (outerNode == minNode) { // Case of equivalence,
// Thus nothing happens
}
else if (outerNode == head) { // Case of outer node equalling head, swap occurs
head = minNode;
tmpNode = minNode->next;
if (outerNode->next == minNode) { // Case of first and second element swapping
minNode->next = outerNode;
outerNode->next = tmpNode->next;
}
else { // Normal case
minNode->next = outerNode->next;
prevMin->next = outerNode;
outerNode->next = tmpNode;
}
}
else if (outerNode->next == minNode) { // Case of the outerNode and minimum Node being next to each other
tmpNode = minNode->next;
minNode->next = outerNode;
outerPrev->next = minNode;
outerNode->next = tmpNode;
}
else { // Regular swapping of nodes
tmpNode = minNode->next;
minNode->next = outerNode->next;
outerPrev->next = minNode;
prevMin->next = outerNode;
outerNode->next = tmpNode;
}
if (minNode == tail) { // Used only in the first swap of a list of numbers
tail = outerNode;
outerNode->next = nullptr;
}
// Resets the outer node to the first element in the unsorted array
outerNode = minNode->next;
// A prev node must be set to the last element of the sorted region, for swapping
outerPrev = minNode;
}
}
length = size();
}
template<typename T>
void LinkedList<T>::insertion_sort() {
Node * outerNode = head;
Node * innerNode = nullptr;
Node * innerPrev = head;
Node * finalSorted = nullptr; // Generally the first sorted element
Node * tmpNode = nullptr;
Node * outerPrev = nullptr;
if (head == NULL) {
// No elements in the list
}
else if (head == tail) {
// List is one element long and already sorted
}
else {
// List has at least two elements
while (outerNode->next != NULL) {
finalSorted = outerNode;
outerNode = outerNode->next;
innerNode = head;
if (outerNode == tail) { // Final element is being sorted
tail = finalSorted;
}
// First element of unsorted portion initially set to head
head = outerNode;
if (innerNode->next == outerNode) { // Case 1: Inner node and outer node are adjacent
tmpNode = outerNode->next;
outerNode->next = innerNode;
innerNode->next = tmpNode;
}
else { // Case 2: Normal case
finalSorted->next = outerNode->next;
outerNode->next = innerNode;
if (finalSorted == tail) { // Last element to sort
finalSorted->next = nullptr;
}
}
while (outerNode != finalSorted && outerNode->value > innerNode->value) { // Outer prev is the final element in the sorted region here
// Swapping of items next to each other
if (outerNode == head) {
head = innerNode;
tmpNode = innerNode;
innerNode->next = outerNode;
outerNode->next = tmpNode->next;
}
else {
// Normal swapping case
tmpNode = innerNode;
outerPrev->next = innerNode;
innerNode->next = outerNode;
outerNode->next = tmpNode->next;
}
// Shifting inner node to be the element to the right of the outer pointer
outerPrev = innerNode;
innerNode = outerNode->next;
}
// Reset the Nodes to their correct possitions
outerNode = finalSorted;
}
}
}
template<typename T>
void LinkedList<T>::merge_sort() {
Node * i = head;
int k = length - 1; // Value based upon index
if (head == NULL) {
// Case already sorted, 1 element
}
else if (head->next == NULL) {
// Case already sorted, 1 element
}
else {
// Normal case
// head = merge_sort(i, k);
}
}
template<typename T>
void LinkedList<T>::quick_sort() {
if (length <= 1) {
return;
}
head = quick_sort(head, length);
// Traverse list to set tail
tail = head;
while (tail->next != NULL) {
tail = tail->next;
}
}
/*
CODE ERROR : SEG fault occurs upon the iteration where the list merges to reach a length of 4
Time Spent: Over 6 hours, unable to decipher how to initialize mergeHead pointer
*/
template<typename T>
typename LinkedList<T>::Node *
LinkedList<T>::merge_sort(Node * left, int len) {
Node * right = left;
size_t mid = 0;
Node * mergeHead = left;
Node * mergeTail = left;
if (len > 1) { // As long as there are two or more elements
while ((mid + 1) < (len / 2)) { // Traverses list to set the right Node to the start of right partition
right = right->next;
++mid;
}
Node * leftTail = right;
right = right->next;
leftTail->next = NULL;
++mid;
Node * leftPos = merge_sort(left, mid);
Node * rightPos = merge_sort(right, len - mid);
// Add smallest element first to the tmp linked list
while (leftPos != NULL && rightPos != NULL) {
if (leftPos->value <= rightPos->value) {
// The value from the left partition is greater, so transfer the right value
mergeTail->next = leftPos;
mergeTail = leftPos;
leftPos = leftPos->next;
}
else {
// The value from the left partition is greater, so transfer the right value
mergeTail->next = rightPos;
mergeTail = rightPos;
rightPos = rightPos->next;
}
}
// Attatch the remaining elements in the partition if the end is not reached
if (left != NULL) {
mergeTail->next = left;
}
if (right != NULL) {
mergeTail->next = right;
}
}
return mergeHead;
}
template<typename T>
typename LinkedList<T>::Node *
LinkedList<T>::quick_sort(Node * left, int len) {
Node * pivot = left;
Node * smaller = NULL;
Node * larger = NULL;
Node * tmp = NULL;
Node * tmpPivot = NULL;
size_t smaller_len = 0;
size_t larger_len = 0;
// BEST CASE : List is either 1 or no elements
if (len <= 1) {
return left;
}
while (pivot->next != NULL) {
// Partition elements until pivot is only element
tmpPivot = pivot->next->next;
if (pivot->next->value > pivot->value) {
// Partition to front of larger list if true
pivot->next->next = larger;
larger = pivot->next;
pivot->next = tmpPivot;
++larger_len;
}
else {
// Partition to front of smaller list
pivot->next->next = smaller;
smaller = pivot->next;
pivot->next = tmpPivot;
++smaller_len;
}
// Adjust remaining element in the pivot list
pivot->next = tmpPivot;
}
smaller = quick_sort(smaller,smaller_len);
larger = quick_sort(larger,larger_len);
if (smaller == NULL) {
// Pivot is the first element
left = pivot;
}
else {
// Reattatch all elements to the original list
left = smaller;
Node * theGluer = smaller;
for (int i = 1; i < smaller_len; ++i) {
// Traverse smaller list to final element
theGluer = theGluer->next;
}
theGluer->next = pivot;
}
pivot->next = larger;
return left;
}
template <typename T>
void LinkedList<T>::sort() {
quick_sort();
}
#endif | [
"mmoore11@zagmail.gonzaga.edu"
] | mmoore11@zagmail.gonzaga.edu |
bdc25bff4912ccea8ccba1cadcd78b4c9e7b2de2 | fe22a9e12dd6bf68e5f133f083dd32e6ae989597 | /SDL Animation/Event.cpp | 6e8d917e7882254705b52d5144b38445123beb5f | [
"MIT"
] | permissive | akshay-vv/SDL-Tutorials | de6c3269d983f69685e3012edf0e5f196b04b74f | 0768ef3c9104a7bc2905a79120b103caa72f86bf | refs/heads/master | 2022-12-30T14:14:31.403496 | 2020-09-23T17:30:11 | 2020-09-23T17:30:11 | 289,952,906 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,347 | cpp | #include "Event.h"
Event::Event() {
keyStates.insert({SDLK_UP, false});
keyStates.insert({SDLK_DOWN, false});
keyStates.insert({SDLK_LEFT, false});
keyStates.insert({SDLK_RIGHT, false});
}
Event::~Event() {
//Do nothing
}
void Event::OnEvent(SDL_Event* Event) {
switch (Event->type) {
// case SDL_ACTIVEEVENT: {
// switch (Event->active.state) {
// case SDL_APPMOUSEFOCUS: {
// if (Event->active.gain)
// OnMouseFocus();
// else
// OnMouseBlur();
// break;
// }
// case SDL_APPINPUTFOCUS: {
// if (Event->active.gain)
// OnInputFocus();
// else
// OnInputBlur();
// break;
// }
// case SDL_APPACTIVE: {
// if (Event->active.gain)
// OnRestore();
// else
// OnMinimize();
// break;
// }
// }
// break;
// }
case SDL_KEYDOWN: {
OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod);
break;
}
case SDL_KEYUP: {
OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod);
break;
}
case SDL_MOUSEMOTION: {
OnMouseMove(Event->motion.x, Event->motion.y, Event->motion.xrel, Event->motion.yrel, (Event->motion.state & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0, (Event->motion.state & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0, (Event->motion.state & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0);
break;
}
case SDL_MOUSEBUTTONDOWN: {
switch (Event->button.button) {
case SDL_BUTTON_LEFT: {
OnLButtonDown(Event->button.x, Event->button.y);
break;
}
case SDL_BUTTON_RIGHT: {
OnRButtonDown(Event->button.x, Event->button.y);
break;
}
case SDL_BUTTON_MIDDLE: {
OnMButtonDown(Event->button.x, Event->button.y);
break;
}
}
break;
}
case SDL_MOUSEBUTTONUP: {
switch (Event->button.button) {
case SDL_BUTTON_LEFT: {
OnLButtonUp(Event->button.x, Event->button.y);
break;
}
case SDL_BUTTON_RIGHT: {
OnRButtonUp(Event->button.x, Event->button.y);
break;
}
case SDL_BUTTON_MIDDLE: {
OnMButtonUp(Event->button.x, Event->button.y);
break;
}
}
break;
}
case SDL_JOYAXISMOTION: {
OnJoyAxis(Event->jaxis.which, Event->jaxis.axis, Event->jaxis.value);
break;
}
case SDL_JOYBALLMOTION: {
OnJoyBall(Event->jball.which, Event->jball.ball, Event->jball.xrel, Event->jball.yrel);
break;
}
case SDL_JOYHATMOTION: {
OnJoyHat(Event->jhat.which, Event->jhat.hat, Event->jhat.value);
break;
}
case SDL_JOYBUTTONDOWN: {
OnJoyButtonDown(Event->jbutton.which, Event->jbutton.button);
break;
}
case SDL_JOYBUTTONUP: {
OnJoyButtonUp(Event->jbutton.which, Event->jbutton.button);
break;
}
case SDL_QUIT: {
OnExit();
break;
}
case SDL_SYSWMEVENT: {
//Ignore
break;
}
// case SDL_VIDEORESIZE: {
// OnResize(Event->resize.w,Event->resize.h);
// break;
// }
// case SDL_VIDEOEXPOSE: {
// OnExpose();
// break;
// }
default: {
OnUser(Event->user.type, Event->user.code, Event->user.data1, Event->user.data2);
break;
}
}
}
void Event::OnInputFocus() {
//Pure virtual, do nothing
}
void Event::OnInputBlur() {
//Pure virtual, do nothing
}
void Event::OnKeyDown(SDL_Keycode sym, Uint16 mod) {
//Pure virtual, do nothing
}
void Event::OnKeyUp(SDL_Keycode sym, Uint16 mod) {
//Pure virtual, do nothing
}
void Event::OnMouseFocus() {
//Pure virtual, do nothing
}
void Event::OnMouseBlur() {
//Pure virtual, do nothing
}
void Event::OnMouseMove(int mX, int mY, int relX, int relY, bool Left, bool Right, bool Middle) {
//Pure virtual, do nothing
}
void Event::OnMouseWheel(bool Up, bool Down) {
//Pure virtual, do nothing
}
void Event::OnLButtonDown(int mX, int mY) {
//Pure virtual, do nothing
}
void Event::OnLButtonUp(int mX, int mY) {
//Pure virtual, do nothing
}
void Event::OnRButtonDown(int mX, int mY) {
//Pure virtual, do nothing
}
void Event::OnRButtonUp(int mX, int mY) {
//Pure virtual, do nothing
}
void Event::OnMButtonDown(int mX, int mY) {
//Pure virtual, do nothing
}
void Event::OnMButtonUp(int mX, int mY) {
//Pure virtual, do nothing
}
void Event::OnJoyAxis(Uint8 which, Uint8 axis, Sint16 value) {
//Pure virtual, do nothing
}
void Event::OnJoyButtonDown(Uint8 which, Uint8 button) {
//Pure virtual, do nothing
}
void Event::OnJoyButtonUp(Uint8 which, Uint8 button) {
//Pure virtual, do nothing
}
void Event::OnJoyHat(Uint8 which, Uint8 hat, Uint8 value) {
//Pure virtual, do nothing
}
void Event::OnJoyBall(Uint8 which, Uint8 ball, Sint16 xrel, Sint16 yrel) {
//Pure virtual, do nothing
}
void Event::OnMinimize() {
//Pure virtual, do nothing
}
void Event::OnRestore() {
//Pure virtual, do nothing
}
void Event::OnResize(int w, int h) {
//Pure virtual, do nothing
}
void Event::OnExpose() {
//Pure virtual, do nothing
}
void Event::OnExit() {
//Pure virtual, do nothing
}
void Event::OnUser(Uint8 type, int code, void* data1, void* data2) {
//Pure virtual, do nothing
} | [
"akshayvivekverma@gmail.com"
] | akshayvivekverma@gmail.com |
04b0871df3de974c8fcc4a7074f8ab3b99d24582 | 3d72414df47fe6572b166af5c10b8f4c8f9d35d4 | /Minigin/FPSComponent.h | e1dfeeb516503ab48b436fce569b811aa39ae995 | [] | no_license | Shadania/Minigin-DigDug | cdf3d11dfcca417a75e118c1c0cc4fb040e15cf4 | 25e5ee8c72e5da14c8b6012579b343b1447a8e16 | refs/heads/master | 2020-04-28T01:47:21.718367 | 2019-06-13T14:24:17 | 2019-06-13T14:24:17 | 174,872,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 508 | h | #pragma once
#include "BaseComponent.h"
#include "TextureComponents.h"
namespace dae
{
class FPSComponent final : public BaseComponent
{
public:
FPSComponent(const std::shared_ptr<Font> font, const Float4& color);
virtual void Initialize() override;
virtual void Update() override;
void SetColor(const Float4& newColor);
void SetFont(const std::shared_ptr<Font>& newFont);
private:
std::shared_ptr<TextComponent> m_spText;
const std::shared_ptr<Font> m_spFont;
Float4 m_Color;
};
} | [
"sarah.druyts@gmail.com"
] | sarah.druyts@gmail.com |
da2e51cbed7582161cd0b1c2850e644d3725ae0a | d4388e906098bb45885ad218f655c4c80a40ec21 | /src/toolkit/net/BaseSocket.cpp | b29deb3dca93e7b459c2842f3833848a3bb21375 | [
"MIT"
] | permissive | jbinkleyj/toolkit | 911ca3b10a1047da8ffde52904c39971e282e3b5 | 8d58e968047538ce83a7fe95fb3f0414875d2796 | refs/heads/master | 2020-05-16T12:01:57.540743 | 2019-04-14T21:34:48 | 2019-04-14T21:34:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 304 | cpp | #include <toolkit/net/ipv4/TCPSocket.h>
#include <toolkit/net/ipv4/Endpoint.h>
namespace TOOLKIT_NS { namespace net
{
BaseSocket::~BaseSocket()
{
bsd::Socket::Shutdown(SHUT_RDWR);
}
ssize_t BaseSocket::Write(ConstBuffer data)
{
return bsd::Socket::Send(data.data(), data.size(), 0);
}
}}
| [
"vladimir.menshakov@gmail.com"
] | vladimir.menshakov@gmail.com |
f6cb00583613ba59ca273fc04efbcd344c107043 | 1e2908e99ff62132291883e07f55ba41813236cd | /DP_Frog.cpp | 5d5f211d3cf73554d661342afdf1b8ea6b1078ae | [] | no_license | dev625/dsacpp | f68b0850a7c22dc51c58512ecbb54df272f8bfa9 | 1de18d761a6a68eb5b9e8aa19b1a6659a6648ed6 | refs/heads/master | 2023-09-04T01:00:52.085101 | 2021-11-07T17:13:47 | 2021-11-07T17:13:47 | 281,089,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 753 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long int;
constexpr long long int MOD = 1e9 + 7;
#define pb push_back
#define ppb pob_back
#define pf push_front
#define ppf pop_front
#define fr first
#define sc second
#define vi vector<int>
#define pii pair<int, int>
void solve()
{
int n;
cin >> n;
vi V(n);
for (int i = 0; i < n; i++)
cin >> V[i];
vi dp(n);
dp[0] = 0;
dp[1] = abs(V[1] - V[0]);
for (int i = 2; i < n; i++)
{
dp[i] = min(dp[i - 1] + abs(V[i] - V[i - 1]), dp[i - 2] + abs(V[i] - V[i - 2]));
}
cout << dp[n - 1];
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
while (t--)
{
solve();
}
}
| [
"witdx514@gmail.com"
] | witdx514@gmail.com |
add9d8623ba8a67850102008796590e09e58cb79 | b81c57e5fc621d425d0f34e685b6d566f1b908a9 | /include/feedForwardFunctions.hpp | 6f784176a9230e0087e06903254c2b2ea34dbf33 | [] | no_license | AaronMathankeri/project-basicNN | 69acf94d08475ce267cbf7ac44078a65020dda5d | 157ff5556a3c98950bd40fed83de8eca3b1a53c0 | refs/heads/master | 2021-06-15T18:03:45.440804 | 2017-03-21T13:07:05 | 2017-03-21T13:07:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 775 | hpp | /**
* \file feedForwardFunctions.hpp
* \brief declare feed forward network functions
*
* Detailed description
*
*/
#ifndef FEEDFORWARDFUNCTIONS_H
#define FEEDFORWARDFUNCTIONS_H
#include <iostream>
#include "mkl.h"
#include "mlpParameters.hpp"
#include "networkAgnosticFunctions.hpp"
using namespace std;
//-----------------------------------------------------
// Feed-forward Functions
void computeActivations( float* x, float* firstLayerWeightMatrix, float* a);
void computeHiddenUnits( float* a, float* z, int length);
void computeOutputActivations( float* z, float* secondLayerWeightVector, float* v);
//-----------------------------------------------------
//void logisticSigmoid( float * a , float *sigma, int length);
#endif /* FEEDFORWARDFUNCTIONS_H */
| [
"aaron@quantifiedag.com"
] | aaron@quantifiedag.com |
125aa9580c6b91baccdf14cb9b939630a1c5c6e9 | 5499e8b91353ef910d2514c8a57a80565ba6f05b | /sdk/lib/sys/cpp/file_descriptor.cc | 715c88a78f1d915c74873fd36f9d60ab580f5bdf | [
"BSD-3-Clause"
] | permissive | winksaville/fuchsia | 410f451b8dfc671f6372cb3de6ff0165a2ef30ec | a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f | refs/heads/master | 2022-11-01T11:57:38.343655 | 2019-11-01T17:06:19 | 2019-11-01T17:06:19 | 223,695,500 | 3 | 2 | BSD-3-Clause | 2022-10-13T13:47:02 | 2019-11-24T05:08:59 | C++ | UTF-8 | C++ | false | false | 704 | cc | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/fdio/fd.h>
#include <lib/sys/cpp/file_descriptor.h>
#include <lib/zx/handle.h>
#include <zircon/processargs.h>
namespace sys {
fuchsia::sys::FileDescriptorPtr CloneFileDescriptor(int fd) {
zx::handle handle;
zx_status_t status = fdio_fd_clone(fd, handle.reset_and_get_address());
if (status != ZX_OK)
return nullptr;
fuchsia::sys::FileDescriptorPtr result = fuchsia::sys::FileDescriptor::New();
result->type0 = PA_HND(PA_FD, fd);
result->handle0 = std::move(handle);
return result;
}
} // namespace sys
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
c20bb8110790048f082bcbdbe67a7a5fc7793fba | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /avatar/src/model/QueryTimedResetOperateStatusResult.cc | d6026373b4746e8d520f52c27c19319bf505177e | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 2,311 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* 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.
*/
#include <alibabacloud/avatar/model/QueryTimedResetOperateStatusResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Avatar;
using namespace AlibabaCloud::Avatar::Model;
QueryTimedResetOperateStatusResult::QueryTimedResetOperateStatusResult() :
ServiceResult()
{}
QueryTimedResetOperateStatusResult::QueryTimedResetOperateStatusResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
QueryTimedResetOperateStatusResult::~QueryTimedResetOperateStatusResult()
{}
void QueryTimedResetOperateStatusResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["InstanceId"].isNull())
data_.instanceId = dataNode["InstanceId"].asString();
if(!dataNode["StatusStr"].isNull())
data_.statusStr = dataNode["StatusStr"].asString();
if(!dataNode["TenantId"].isNull())
data_.tenantId = dataNode["TenantId"].asString();
if(!dataNode["Status"].isNull())
data_.status = std::stol(dataNode["Status"].asString());
if(!value["Code"].isNull())
code_ = value["Code"].asString();
if(!value["Message"].isNull())
message_ = value["Message"].asString();
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
}
std::string QueryTimedResetOperateStatusResult::getMessage()const
{
return message_;
}
QueryTimedResetOperateStatusResult::Data QueryTimedResetOperateStatusResult::getData()const
{
return data_;
}
std::string QueryTimedResetOperateStatusResult::getCode()const
{
return code_;
}
bool QueryTimedResetOperateStatusResult::getSuccess()const
{
return success_;
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
0ba2250ec26863b26b081691e156d8bb0c18fd17 | bdda98f269400b13dfb277d52da4cb234fd4305c | /CVGCom_async/forms/Unit_Result_1.h | 4c19fb8c44e83d28d5dcb4a5e35e7b618c7e6e28 | [] | no_license | fangxuetian/sources_old | 75883b556c2428142e3323e676bea46a1191c775 | 7b1b0f585c688cb89bd4a23d46067f1dca2a17b2 | refs/heads/master | 2021-05-11T01:26:02.180353 | 2012-09-05T20:20:16 | 2012-09-05T20:20:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,439 | h | //===========================================================================-
#ifndef Unit_Result_1H
#define Unit_Result_1H
//===========================================================================-
#include <Classes.hpp>
#include <Controls.hpp>
#include <Grids.hpp>
#include <ComCtrls.hpp>
#include <ExtCtrls.hpp>
#include <StdCtrls.hpp>
#include <Dialogs.hpp>
#include <Buttons.hpp>
//===========================================================================-
class Tform_Result_1 : public TForm
{
__published:
TTabControl *TabControl1;
TStringGrid *StringGrid1;
TPanel *Panel1;
TButton *Button1;
TSaveDialog *SaveDialog1;
TPanel *Panel2;
TLabel *Label2;
TEdit *Edit1;
TLabel *Label4;
TLabel *Label3;
TComboBox *ComboBox1;
TLabel *Label1;
TComboBox *ComboBox2;
TButton *Button4;
TEdit *Edit3;
TLabel *Label5;
TLabel *Label6;
TLabel *Label7;
TEdit *Edit2;
TSpeedButton *SpeedButton1;
TSpeedButton *SpeedButton2;
TSpeedButton *speedbutton_ConvertToFreq;
TButton *Button2;
void __fastcall FormShow(TObject *Sender);
void __fastcall TabControl1Change(TObject *Sender);
void __fastcall Button1Click(TObject *Sender);
void __fastcall Button2Click(TObject *Sender);
void __fastcall SpeedButton1Click(TObject *Sender);
void __fastcall FormActivate(TObject *Sender);
void __fastcall Button4Click(TObject *Sender);
void __fastcall SpeedButton2Click(TObject *Sender);
void __fastcall speedbutton_ConvertToFreqClick(TObject *Sender);
void __fastcall Panel1DblClick(TObject *Sender);
private:
CCollectionStorage<float> *pStorage;
TSelectPart *pSelecetStorageParts;
bool *pisSelecetStorageParts;
int *pCountSelectedStorageParts;
double SKOCoef;
bool isConvertToFreq;
public:
void SetupTableValues(int aIndex);
void SetupForms( CCollectionStorage<float> *apStorage, TSelectPart *apSelecetStorageParts, bool *apisSelecetStorageParts, int *apCountSelectedStorageParts );
virtual __fastcall Tform_Result_1(TComponent* AOwner);
};
//===========================================================================-
extern PACKAGE Tform_Result_1 *form_Result_1;
//===========================================================================-
#endif
| [
"pm@pm.(none)"
] | pm@pm.(none) |
e0a85653a9a10f8f9d689f8a04ebfc1ae1c3a4a1 | fb188ae45fe8945ba757599b71e2e34c5d095d8c | /Trash/prueba_abstracta001/src/Proceso.cpp | e0525348acecf32a944cdccdafa49b1dfce3cc31 | [] | no_license | patrick03524/Algebra-Abstracta | f8726085ddcb4316d77bc1ac2ecd9c2f5c45de1c | bd92d3bf20234b87daa5c0c8fe808eed0673e1a7 | refs/heads/master | 2021-04-18T20:22:19.305662 | 2018-06-02T11:25:07 | 2018-06-02T11:25:07 | 126,630,623 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 670 | cpp | #include "Proceso.h"
Proceso::Proceso(unsigned int n_cuadrados, unsigned int n_len_cuadrado, string mensaje1)
{
n=n_cuadrados;
n_len=n_len_cuadrado;
mensaje=mensaje1;
}
string Proceso::encriptacion()
{
string mensaje_encriptado1;
unsigned int cont=0;
for(int i = 0; i<n_len; i++){
for(int j = 0; j<n_len; j++){
///mensaje_encriptado.insert(mensaje_encriptado.begin()+i+n_len-i, mensaje[j*n_len+n_len-i]);
mensaje_encriptado1.insert(mensaje_encriptado1.begin()+j*n_len+n_len-i, mensaje[cont]);
cont++;
}
}
cout << mensaje_encriptado1<<endl;
}
void Proceso::desencriptacion(string)
{
}
| [
"patrick03524@hotmail.com"
] | patrick03524@hotmail.com |
06af317d1e026577fa116d9ea88b332fdf437016 | 12e7bd84511b61bbde2288ae695ee64746d337a7 | /Stronger/746.使用最小花费爬楼梯.cpp | e71778f845c2241fb7d1b09aded2d5cc7fcb9d53 | [] | no_license | hellozmz/LeetCode | 97ec70e9c80e601a7cb8ed0efea9ceca30e6843f | 05295f388d5952a408d62ba34f6d4fde177f31c4 | refs/heads/master | 2023-05-11T10:47:26.792395 | 2023-04-29T05:27:55 | 2023-04-29T05:27:55 | 235,086,823 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,931 | cpp | /*
* @lc app=leetcode.cn id=746 lang=cpp
*
* [746] 使用最小花费爬楼梯
*
* https://leetcode.cn/problems/min-cost-climbing-stairs/description/
*
* algorithms
* Easy (63.24%)
* Likes: 1025
* Dislikes: 0
* Total Accepted: 254.3K
* Total Submissions: 401.8K
* Testcase Example: '[10,15,20]'
*
* 给你一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。
*
* 你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。
*
* 请你计算并返回达到楼梯顶部的最低花费。
*
*
*
* 示例 1:
*
*
* 输入:cost = [10,15,20]
* 输出:15
* 解释:你将从下标为 1 的台阶开始。
* - 支付 15 ,向上爬两个台阶,到达楼梯顶部。
* 总花费为 15 。
*
*
* 示例 2:
*
*
* 输入:cost = [1,100,1,1,1,100,1,1,100,1]
* 输出:6
* 解释:你将从下标为 0 的台阶开始。
* - 支付 1 ,向上爬两个台阶,到达下标为 2 的台阶。
* - 支付 1 ,向上爬两个台阶,到达下标为 4 的台阶。
* - 支付 1 ,向上爬两个台阶,到达下标为 6 的台阶。
* - 支付 1 ,向上爬一个台阶,到达下标为 7 的台阶。
* - 支付 1 ,向上爬两个台阶,到达下标为 9 的台阶。
* - 支付 1 ,向上爬一个台阶,到达楼梯顶部。
* 总花费为 6 。
*
*
*
*
* 提示:
*
*
* 2 <= cost.length <= 1000
* 0 <= cost[i] <= 999
*
*
*/
// @lc code=start
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int len = cost.size();
vector<int> dp(len + 1);
dp[0] = 0;
dp[1] = 0;
for (int i = 2; i <= len; ++i) {
dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
}
return dp[len];
}
};
// @lc code=end
| [
"407190054@qq.com"
] | 407190054@qq.com |
ca96460389522ecf52ca4bc58ac7882383d37e46 | 94dbfcf94dd0a61d7cd197cf996602d5a2acdda7 | /weekly_contest/231/leetcode_1785_minimum-elements-to-add-to-form-a-given-sum.cpp | 618d2cc0914dc8757ba38c327a25e6c2f688f404 | [] | no_license | PengJi/Algorithms | 46ac90691cc20b0f769374ac3d848a26766965b1 | 6aa26240679bc209a6fd69580b9c7994cef51b54 | refs/heads/master | 2023-07-21T05:57:50.637703 | 2023-07-07T10:16:48 | 2023-07-09T10:17:10 | 243,935,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 531 | cpp | /**
* 1785. 构成特定和需要添加的最少元素
* https://leetcode-cn.com/problems/minimum-elements-to-add-to-form-a-given-sum/
*/
class Solution {
public:
int minElements(vector<int>& nums, int limit, int goal) {
long cur_sum=0;
for(int i = 0; i < nums.size(); i++) {
cur_sum += nums[i];
}
long goal_sum = abs(goal - cur_sum);
if(goal_sum % limit == 0) {
return goal_sum/limit;
} else {
return goal_sum/limit+1;
}
}
};
| [
"jipengpro@gmail.com"
] | jipengpro@gmail.com |
f765701410bf67d0526b1f077fba5865683e4af9 | 4e51cfcb0621b88ea8620f05f49bedae2a2c9978 | /Algorithms/0. temp.cpp | 5157cca3c7056cd38da454ecf3ffe2a6205b775e | [] | no_license | KaiqiaoTian/LeetCode_practice | d5d43525269a05a0fc9a367bc4dcd3d15dcf3c74 | a300d0380a01d0b48c4074718d30056e2b2a6c20 | refs/heads/master | 2023-05-28T11:17:18.473716 | 2021-06-11T19:55:52 | 2021-06-11T19:55:52 | 375,115,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | cpp | /*Description
*/
class Solution {
public:
vector<int> runningSum(vector<int>& nums) {
vector<int> result = {nums[0]};
for(int i = 1; i < nums.size(); i++){
result.push_back(result.back()+nums[i]);
}
return result;
}
};
| [
"kaiqiaotian@gmail.com"
] | kaiqiaotian@gmail.com |
3a033a48cb739021bd94f037f7bc1f84dc61d8cd | 0949d5f41fa9c9eb50610fb424ce9a165a9bee88 | /Data Structure/twoStack.cpp | add451dbbfb6bf91f9d1469696aa0c2658b3f4d0 | [] | no_license | mdsagor07/Programming-Tools | f560120ffa6f57f4290803da1912a414af89da7d | 2a6f34072ec289aad7a1c08f9c1cd5f5066f23b1 | refs/heads/main | 2023-04-14T03:43:52.925464 | 2021-04-23T04:43:36 | 2021-04-23T04:43:36 | 321,398,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,383 | cpp | #include <iostream>
#include <stdlib.h>
using namespace std;
class twoStacks {
int* arr;
int size;
int top1, top2;
public:
twoStacks(int n) // constructor
{
size = n;
arr = new int[n];
top1 = -1;
top2 = size;
}
// Method to push an element x to stack1
void push1(int x)
{
// There is at least one empty space for new element
if (top1 < top2 - 1) {
top1++;
arr[top1] = x;
}
else {
cout << "Stack Overflow";
exit(1);
}
}
// Method to push an element x to stack2
void push2(int x)
{
// There is at least one empty
// space for new element
if (top1 < top2 - 1) {
top2--;
arr[top2] = x;
}
else {
cout << "Stack Overflow";
exit(1);
}
}
// Method to pop an element from first stack
int pop1()
{
if (top1 >= 0) {
int x = arr[top1];
top1--;
return x;
}
else {
cout << "Stack UnderFlow";
exit(1);
}
}
// Method to pop an element from second stack
int pop2()
{
if (top2 < size) {
int x = arr[top2];
top2++;
return x;
}
else {
cout << "Stack UnderFlow";
exit(1);
}
}
};
/* Driver program to test twStacks class */
int main()
{
twoStacks ts(5);
ts.push1(5);
ts.push2(10);
ts.push2(15);
ts.push1(11);
ts.push2(7);
cout << "Popped element from stack1 is "
<< ts.pop1();
ts.push2(40);
cout << "\nPopped element from stack2 is "
<< ts.pop2();
return 0;
}
| [
"sagor.cse.just@gmail.com"
] | sagor.cse.just@gmail.com |
dd9669aab3af03f19e09e042e3501313488d2640 | f6814ecdd2f2ecd2dd1d08bf33ec86f50ace4c77 | /多线程顺序打印ABC.cpp | 980b8beb3e2a3635035ab8e9afecec09e23076a4 | [] | no_license | hp2362/multi-thread- | ea4bf320aad195b4c0d857b491e23bd0ceeb382e | 15fab89ffaf55c65eed878efa75a255a3b2f6664 | refs/heads/master | 2021-01-16T21:11:58.722779 | 2017-08-14T10:18:45 | 2017-08-14T10:18:45 | 100,220,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,430 | cpp |
#include<stdio.h>
#include<pthread.h>
void *secondFunc(void *);
void *thirdFunc(void *);
void *firstFunc(void *args)
{
pthread_t id2;
pthread_create(&id2, NULL, &secondFunc, NULL);
pthread_join(id2, NULL);
printf("C\n");
}
void *secondFunc(void *args)
{
pthread_t id3;
pthread_create(&id3, NULL, &thirdFunc, NULL);
pthread_join(id3, NULL);
printf("B\n");
}
void *thirdFunc(void *args)
{
printf("A\n");
}
int main()
{
pthread_t id1;
pthread_create(&id1, NULL, &firstFunc, NULL);
pthread_join(id1, NULL);
return 0;
}
/*
#include<stdio.h>
#include<sys/types.h>
#include<semaphore.h>
#include<pthread.h>
sem_t sem_id1, sem_id2, sem_id3;
void* func1(void*); //声明
void* func2(void*);
void* func3(void*);
int main(void) {
sem_init(&sem_id1, 0, 1); //活动
sem_init(&sem_id2, 0, 0);
sem_init(&sem_id3, 0, 0);
pthread_t pthread_id1, pthread_id2, pthread_id3;
pthread_create(&pthread_id1, NULL, func1, NULL);
pthread_create(&pthread_id2, NULL, func2, NULL);
pthread_create(&pthread_id3, NULL, func3, NULL);
pthread_join(phread_id1, NULL);
pthread_join(phread_id1, NULL);
pthread_join(phread_id1, NULL);
return 0;
}
void *func1(void*) {
sem_wait(sem_id1);
printf("A\n");
sem_post(sem_id2);
}
void *func2(void*) {
sem_wait(sem_id2);
printf("B\n");
sem_post(sem_id3);
}
void *func3(void*) {
sem_wait(sem_id3);
printf("C\n");
sem_post(sem_id1);
}
*/ | [
"964358093@qq.com"
] | 964358093@qq.com |
8eb91ab194dcab357a9a76b41776e37e377fa042 | 0e0a887164b1e5478261faf0ddd33c694f20bdde | /src/caffe/CTPN/ctpn_layers.hpp | 9c6684b89ae8faf1797d21c08774edb6ca034e08 | [
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | xyt2008/frcnn | 86882aa0ffa376fa527006bdd32dc311161eeab8 | 32a559e881cceeba09a90ff45ad4aae1dabf92a1 | refs/heads/master | 2020-03-14T20:56:21.930791 | 2019-09-22T11:16:32 | 2019-09-22T11:16:32 | 131,785,765 | 0 | 0 | NOASSERTION | 2019-09-22T11:16:33 | 2018-05-02T02:10:55 | C++ | UTF-8 | C++ | false | false | 4,808 | hpp | #ifndef CAFFE_CTPN_LAYERS_HPP_
#define CAFFE_CTPN_LAYERS_HPP_
#include <string>
#include <utility>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/layers/base_data_layer.hpp"
#include "caffe/layer.hpp"
#include "caffe/layers/loss_layer.hpp"
//#include "caffe/neuron_layers.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/**
* @brief Long-short term memory layer.
* fyk: the implementation is from https://github.com/junhyukoh/caffe-lstm
* this code is a little quicker than the master branch of Caffe's implementation
* TODO(dox): thorough documentation for Forward, Backward, and proto params.
*/
template <typename Dtype>
class LstmLayer : public Layer<Dtype> {
public:
explicit LstmLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "Lstm"; }
virtual bool IsRecurrent() const { return true; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
int I_; // input dimension
int H_; // num of hidden units
int T_; // length of sequence
int N_; // batch size
Dtype clipping_threshold_; // threshold for clipped gradient
Blob<Dtype> bias_multiplier_;
Blob<Dtype> top_; // output values
Blob<Dtype> cell_; // memory cell
Blob<Dtype> pre_gate_; // gate values before nonlinearity
Blob<Dtype> gate_; // gate values after nonlinearity
Blob<Dtype> c_0_; // previous cell state value
Blob<Dtype> h_0_; // previous hidden activation value
Blob<Dtype> c_T_; // next cell state value
Blob<Dtype> h_T_; // next hidden activation value
// intermediate values
Blob<Dtype> h_to_gate_;
Blob<Dtype> h_to_h_;
};
template <typename Dtype>
class TransposeLayer : public Layer<Dtype> {
public:
explicit TransposeLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "Transpose"; }
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
private:
TransposeParameter transpose_param_;
vector<int> permute(const vector<int>& vec);
Blob<int> bottom_counts_;
Blob<int> top_counts_;
Blob<int> forward_map_;
Blob<int> backward_map_;
Blob<int> buf_;
};
template <typename Dtype>
class ReverseLayer : public Layer<Dtype> {
public:
explicit ReverseLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "Reverse"; }
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
private:
ReverseParameter reverse_param_;
Blob<int> bottom_counts_;
int axis_;
};
} // namespace caffe
#endif // CAFFE_CTPN_LAYERS_HPP_
| [
"fymkang@gmail.com"
] | fymkang@gmail.com |
be2e71aef83b88e6334f47429be746ed6c49fa60 | c32ee8ade268240a8064e9b8efdbebfbaa46ddfa | /Libraries/m2sdk/game/ai/C_AIMessage_Death.h | a4564c27ee9e426b94c945866dc7266e8e7dcab3 | [] | no_license | hopk1nz/maf2mp | 6f65bd4f8114fdeb42f9407a4d158ad97f8d1789 | 814cab57dc713d9ff791dfb2a2abeb6af0e2f5a8 | refs/heads/master | 2021-03-12T23:56:24.336057 | 2015-08-22T13:53:10 | 2015-08-22T13:53:10 | 41,209,355 | 19 | 21 | null | 2015-08-31T05:28:13 | 2015-08-22T13:56:04 | C++ | UTF-8 | C++ | false | false | 407 | h | // auto-generated file (rttidump-exporter by h0pk1nz)
#pragma once
#include <game/ai/C_AIMessage.h>
namespace game
{
namespace ai
{
/** game::ai::C_AIMessage_Death (VTable=0x01E4D720) */
class C_AIMessage_Death : public C_AIMessage
{
public:
virtual void vfn_0001_1A4039D8() = 0;
virtual void vfn_0002_1A4039D8() = 0;
virtual void vfn_0003_1A4039D8() = 0;
};
} // namespace ai
} // namespace game
| [
"hopk1nz@gmail.com"
] | hopk1nz@gmail.com |
ca5c2f8f7ffa780bcd14fc65f524a8c046eb14c4 | ab0d9add78242021c278d3cf891ef7098daf7659 | /V1.0/code/Server/common/OnvifSDK/OnvifAPIAll/soapAnalyticsEngineBindingProxy.h | e9a7a7a3b9f96d72cf1a42c91a67c665908cab28 | [] | no_license | qcamei/Project_njlw | fe6f80dd42cf7c6bb0abd448eff76c56dade1440 | e56b42800042062f6b18d2023d73afbdf1668ab0 | refs/heads/master | 2020-04-17T11:02:41.014763 | 2017-11-13T11:09:52 | 2017-11-13T11:09:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,397 | h | /* soapAnalyticsEngineBindingProxy.h
Generated by gSOAP 2.8.0 from Onvif.h
Copyright(C) 2000-2010, Robert van Engelen, Genivia Inc. All Rights Reserved.
The generated code is released under one of the following licenses:
GPL, the gSOAP public license, or Genivia's license for commercial use.
*/
#ifndef soapAnalyticsEngineBindingProxy_H
#define soapAnalyticsEngineBindingProxy_H
#include "soapH.h"
class AnalyticsEngineBinding
{ public:
/// Runtime engine context allocated in constructor
struct soap *soap;
/// Endpoint URL of service 'AnalyticsEngineBinding' (change as needed)
const char *endpoint;
/// Constructor allocates soap engine context, sets default endpoint URL, and sets namespace mapping table
AnalyticsEngineBinding()
{ soap = soap_new(); endpoint = "http://localhost:80"; if (soap && !soap->namespaces) { static const struct Namespace namespaces[] =
{
{"SOAP-ENV", "http://www.w3.org/2003/05/soap-envelope", "http://schemas.xmlsoap.org/soap/envelope/", NULL},
{"SOAP-ENC", "http://www.w3.org/2003/05/soap-encoding", "http://schemas.xmlsoap.org/soap/encoding/", NULL},
{"xsi", "http://www.w3.org/2001/XMLSchema-instance", "http://www.w3.org/*/XMLSchema-instance", NULL},
{"xsd", "http://www.w3.org/2001/XMLSchema", "http://www.w3.org/*/XMLSchema", NULL},
{"wsa5", "http://www.w3.org/2005/08/addressing", "http://schemas.xmlsoap.org/ws/2004/08/addressing", NULL},
{"c14n", "http://www.w3.org/2001/10/xml-exc-c14n#", NULL, NULL},
{"wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", NULL, NULL},
{"ds", "http://www.w3.org/2000/09/xmldsig#", NULL, NULL},
{"wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd", NULL},
{"ns5", "http://docs.oasis-open.org/wsrf/r-2", NULL, NULL},
{"ns6", "http://schemas.xmlsoap.org/ws/2005/04/discovery", NULL, NULL},
{"xmime", "http://tempuri.org/xmime.xsd", NULL, NULL},
{"xop", "http://www.w3.org/2004/08/xop/include", NULL, NULL},
{"tt", "http://www.onvif.org/ver10/schema", NULL, NULL},
{"ns2", "http://docs.oasis-open.org/wsrf/bf-2", NULL, NULL},
{"wsa", "http://schemas.xmlsoap.org/ws/2004/08/addressing", NULL, NULL},
{"ns3", "http://docs.oasis-open.org/wsn/t-1", NULL, NULL},
{"ns10", "http://www.onvif.org/ver10/events/wsdl/PullPointSubscriptionBinding", NULL, NULL},
{"ns11", "http://www.onvif.org/ver10/events/wsdl/EventBinding", NULL, NULL},
{"tev", "http://www.onvif.org/ver10/events/wsdl", NULL, NULL},
{"ns12", "http://www.onvif.org/ver10/events/wsdl/SubscriptionManagerBinding", NULL, NULL},
{"ns13", "http://www.onvif.org/ver10/events/wsdl/NotificationProducerBinding", NULL, NULL},
{"ns14", "http://www.onvif.org/ver10/events/wsdl/NotificationConsumerBinding", NULL, NULL},
{"ns15", "http://www.onvif.org/ver10/events/wsdl/PullPointBinding", NULL, NULL},
{"ns16", "http://www.onvif.org/ver10/events/wsdl/CreatePullPointBinding", NULL, NULL},
{"ns17", "http://www.onvif.org/ver10/events/wsdl/PausableSubscriptionManagerBinding", NULL, NULL},
{"ns1", "http://docs.oasis-open.org/wsn/b-2", NULL, NULL},
{"ns18", "http://www.onvif.org/ver10/network/wsdl/RemoteDiscoveryBinding", NULL, NULL},
{"ns19", "http://www.onvif.org/ver10/network/wsdl/DiscoveryLookupBinding", NULL, NULL},
{"dn", "http://www.onvif.org/ver10/network/wsdl", NULL, NULL},
{"ns8", "http://www.onvif.org/ver20/analytics/wsdl/RuleEngineBinding", NULL, NULL},
{"ns9", "http://www.onvif.org/ver20/analytics/wsdl/AnalyticsEngineBinding", NULL, NULL},
{"tan", "http://www.onvif.org/ver20/analytics/wsdl", NULL, NULL},
{"tds", "http://www.onvif.org/ver10/device/wsdl", NULL, NULL},
{"timg", "http://www.onvif.org/ver20/imaging/wsdl", NULL, NULL},
{"tptz", "http://www.onvif.org/ver20/ptz/wsdl", NULL, NULL},
{"trt", "http://www.onvif.org/ver10/media/wsdl", NULL, NULL},
{NULL, NULL, NULL, NULL}
};
soap->namespaces = namespaces; } };
/// Destructor frees deserialized data and soap engine context
virtual ~AnalyticsEngineBinding() { if (soap) { soap_destroy(soap); soap_end(soap); soap_free(soap); } };
/// Invoke 'GetSupportedAnalyticsModules' of service 'AnalyticsEngineBinding' and return error code (or SOAP_OK)
virtual int __ns9__GetSupportedAnalyticsModules(_tan__GetSupportedAnalyticsModules *tan__GetSupportedAnalyticsModules, _tan__GetSupportedAnalyticsModulesResponse *tan__GetSupportedAnalyticsModulesResponse) { return soap ? soap_call___ns9__GetSupportedAnalyticsModules(soap, endpoint, NULL, tan__GetSupportedAnalyticsModules, tan__GetSupportedAnalyticsModulesResponse) : SOAP_EOM; };
/// Invoke 'CreateAnalyticsModules' of service 'AnalyticsEngineBinding' and return error code (or SOAP_OK)
virtual int __ns9__CreateAnalyticsModules(_tan__CreateAnalyticsModules *tan__CreateAnalyticsModules, _tan__CreateAnalyticsModulesResponse *tan__CreateAnalyticsModulesResponse) { return soap ? soap_call___ns9__CreateAnalyticsModules(soap, endpoint, NULL, tan__CreateAnalyticsModules, tan__CreateAnalyticsModulesResponse) : SOAP_EOM; };
/// Invoke 'DeleteAnalyticsModules' of service 'AnalyticsEngineBinding' and return error code (or SOAP_OK)
virtual int __ns9__DeleteAnalyticsModules(_tan__DeleteAnalyticsModules *tan__DeleteAnalyticsModules, _tan__DeleteAnalyticsModulesResponse *tan__DeleteAnalyticsModulesResponse) { return soap ? soap_call___ns9__DeleteAnalyticsModules(soap, endpoint, NULL, tan__DeleteAnalyticsModules, tan__DeleteAnalyticsModulesResponse) : SOAP_EOM; };
/// Invoke 'GetAnalyticsModules' of service 'AnalyticsEngineBinding' and return error code (or SOAP_OK)
virtual int __ns9__GetAnalyticsModules(_tan__GetAnalyticsModules *tan__GetAnalyticsModules, _tan__GetAnalyticsModulesResponse *tan__GetAnalyticsModulesResponse) { return soap ? soap_call___ns9__GetAnalyticsModules(soap, endpoint, NULL, tan__GetAnalyticsModules, tan__GetAnalyticsModulesResponse) : SOAP_EOM; };
/// Invoke 'ModifyAnalyticsModules' of service 'AnalyticsEngineBinding' and return error code (or SOAP_OK)
virtual int __ns9__ModifyAnalyticsModules(_tan__ModifyAnalyticsModules *tan__ModifyAnalyticsModules, _tan__ModifyAnalyticsModulesResponse *tan__ModifyAnalyticsModulesResponse) { return soap ? soap_call___ns9__ModifyAnalyticsModules(soap, endpoint, NULL, tan__ModifyAnalyticsModules, tan__ModifyAnalyticsModulesResponse) : SOAP_EOM; };
};
#endif
| [
"yang.haifeng@zbitcloud.com"
] | yang.haifeng@zbitcloud.com |
de08a559cfda9b5c00b94c083c258fb8f2ed5f21 | 1bd8d99894ba1d789031cd75cdfea81b5d59e1f6 | /src/general/tick.h | 2252e0153ec30ac3a0697af0ac19605133679cb7 | [
"MIT"
] | permissive | RJJain/VANS | ab7ef169680685a9d32f3f6c682c7dea0f6415d9 | 1eb6f3873125e0b24aa66d3634ade350c4f5f13f | refs/heads/master | 2023-02-09T03:12:04.429169 | 2020-12-31T06:31:06 | 2020-12-31T06:31:06 | 321,661,640 | 0 | 0 | MIT | 2020-12-31T06:31:07 | 2020-12-15T12:30:14 | null | UTF-8 | C++ | false | false | 246 | h |
#ifndef VANS_TICK_H
#define VANS_TICK_H
#include "utils.h"
namespace vans
{
class tick_able
{
public:
/* Use a global clock signal from outside */
virtual void tick(clk_t curr_clk) = 0;
};
} // namespace vans
#endif // VANS_TICK_H
| [
"zxwang42@gmail.com"
] | zxwang42@gmail.com |
a5f13b7b55a3e5fd367e7582f3424ebfd543dd93 | 4d108f357f7c3da833911293a5bcda4ebba66526 | /chrome/browser/ui/ash/fake_tablet_mode_controller.cc | 61a34145538abbc9343891b3d3dc5980ad226d58 | [
"BSD-3-Clause"
] | permissive | ycbxklk/chromium | 1b57c52a441d38814feb2b5b040d7058b51db974 | dbeb94d7208e902c90291ee27e07a636f9d72865 | refs/heads/master | 2023-02-28T05:04:33.740036 | 2019-07-10T10:44:35 | 2019-07-10T10:44:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 680 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/ash/fake_tablet_mode_controller.h"
#include <utility>
FakeTabletModeController::FakeTabletModeController() = default;
FakeTabletModeController::~FakeTabletModeController() = default;
void FakeTabletModeController::SetTabletModeToggleObserver(
ash::TabletModeToggleObserver* observer) {
observer_ = observer;
}
bool FakeTabletModeController::InTabletMode() const {
return enabled_;
}
void FakeTabletModeController::SetEnabledForTest(bool enabled) {
enabled_ = enabled;
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
c0210268585f22b512d48b7f1ff6a502407367f6 | 60a532f91b8e51b7e504c0422f47708772b5c205 | /algorithm/demo/object_server.cpp | e4ec64ba2e425cce4f9a2b87a84b521f6537f890 | [] | no_license | wujcheng/solrex | eca0e62b8d476e01b98d97ac312a0704e2566800 | 1260039d373dab2147dd27ac74ca49fd534f83e5 | refs/heads/master | 2021-01-18T16:00:33.803400 | 2012-01-18T07:21:26 | 2012-01-18T07:21:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,468 | cpp | /* COMPILE: g++ objserver.cpp -o objserver -lpthread */
#include <queue>
#include <pthread.h>
#include <unistd.h>
using namespace std;
#define MAX_OBJECTS 5 /* number of objects */
#define MAX_THREADS 10 /* number of threads */
#define TID0_TID 0 /* thread_per_obj thread id */
#define CALL_OID (MAX_OBJECTS) /* pseudo object id of call() thread */
#define TID0_OID 0 /* thread_per_obj thread object id */
typedef int THREAD_POLICY; /* thread usage policy */
#define THREAD_PER_OBJ 0 /* 0: 1 thread per 1 object */
#define THREAD_PER_REQ 1 /* 1: 1 thread per 1 request */
/* Message format, we simplified it in our case. */
struct MESSAGE {
int source;
int object_id;
int thread_id;
int data;
};
/* Thread information structure. */
struct THREAD {
int tid; /* Thread id in our case */
int oid; /* Object id for the thread */
pthread_t posix_tid; /* POSIX thread id(the real Linux thread id) */
};
/* Object structure in our object server. */
class object {
public:
int oid;
void stub(MESSAGE req, MESSAGE &res) {
res = req;
}
};
object objects[MAX_OBJECTS]; /* objects in object server */
THREAD threads[MAX_THREADS]; /* threads for object adapter */
MESSAGE mes_pool[MAX_OBJECTS]; /* message buffers for communication */
queue<int> object_queue; /* object index queue for object assignment */
queue<int> thread_queue; /* thread index queue for thread assignment */
int pipe_call[2], pipe_tid0[2]; /* pipe for communication */
/* Get message function */
void get_msg (THREAD_POLICY policy, int oid, MESSAGE &data) {
if (policy == THREAD_PER_OBJ) {
if (oid == TID0_OID) {
read(pipe_tid0[0], &data, sizeof(data));
} else {
read(pipe_call[0], &data, sizeof(data));
}
} else {
data = mes_pool[oid];
}
}
/* Put message function */
void put_msg (THREAD_POLICY policy, int oid, MESSAGE &data) {
if (policy == THREAD_PER_OBJ) {
if (oid == TID0_OID) {
write(pipe_tid0[1], &data, sizeof(data));
} else {
write(pipe_call[1], &data, sizeof(data));
}
} else {
mes_pool[oid] = data;
}
}
/* Exit thread, */
void thread_exit(THREAD *thread) {
thread_queue.push(thread->tid);
object_queue.push(thread->oid);
pthread_exit(NULL);
}
/* Object adapter implemented ONE THREAD PER OBJECT policy. */
void * thread_per_object (void *arg) {
THREAD *thread = (THREAD *)arg;
MESSAGE req, res;
while (true) {
get_msg (THREAD_PER_OBJ, TID0_OID, req);
req.object_id = thread->oid;
req.thread_id = thread->tid;
objects[thread->oid].stub(req, res);
put_msg (THREAD_PER_OBJ, CALL_OID, res);
}
thread_exit(thread);
}
/* Object adapter implemented ONE THREAD PER REQUEST policy. */
void * thread_per_request (void *arg) {
THREAD *thread = (THREAD *)arg;
MESSAGE req, res;
get_msg (THREAD_PER_REQ, thread->oid, req);
req.object_id = thread->oid;
req.thread_id = thread->tid;
objects[thread->oid].stub(req, res);
put_msg (THREAD_PER_REQ, thread->oid, res);
thread_exit(thread);
}
/* Helper function to create a thread. */
THREAD * create_thread(THREAD_POLICY policy, MESSAGE *request) {
if(policy == THREAD_PER_OBJ) {
threads[TID0_TID].oid = TID0_OID;
pthread_create(&threads[TID0_TID].posix_tid, NULL, &thread_per_object,
&threads[TID0_TID]);
return &threads[TID0_TID];
} else {
int i, j;
i = thread_queue.front();
thread_queue.pop();
j = object_queue.front();
object_queue.pop();
threads[i].oid = j;
put_msg(THREAD_PER_REQ, threads[i].oid, *request);
pthread_create(&threads[i].posix_tid, NULL, &thread_per_request,
&threads[i]);
return &threads[i];
}
}
/* Request demultiplexer: If the source of request is an even number, we use
* the ONE THREAD PER OBJECT object adapter; else, we use the ONE THREAD PER
* REQUEST object adapter. */
MESSAGE call(MESSAGE &request) {
THREAD *thread;
MESSAGE result;
if (request.source%2 == 0) {
put_msg(THREAD_PER_OBJ, TID0_OID, request);
get_msg(THREAD_PER_OBJ, CALL_OID, result);
} else {
thread = create_thread(THREAD_PER_REQ, &request);
pthread_join(thread->posix_tid, NULL);
get_msg(THREAD_PER_REQ, thread->oid, result);
}
return result;
}
/* Initialize object server. */
void init_objserver() {
int i;
if (pipe(pipe_call) < 0 || pipe(pipe_tid0) < 0)
perror("pipe() error");
for (i=1; i<MAX_THREADS; i++)
threads[i].tid = i;
for (i=1; i<MAX_THREADS; i++)
thread_queue.push(i);
for (i=1; i<MAX_OBJECTS; i++)
objects[i].oid = i;
for (i=1; i<MAX_OBJECTS; i++)
object_queue.push(i);
create_thread(THREAD_PER_OBJ, NULL);
}
int main()
{
/* Test object server. */
MESSAGE request, result;
init_objserver();
printf("### Our object server has 5 objects, and maximum 10 threads. ###\n");
printf("Request demultiplexing policy is:\n");
printf(" Request from even source will be served by THREAD PER OBJECT.\n");
printf(" Request from odd source will be served by THREAD PER REQUEST.\n");
printf("============= TEST START =============\n");
for (int i=0; i<30; i++) {
request.source = i;
result = call(request);
printf("Request from %2d was served by thread %d and object %d\n",
result.source, result.thread_id, result.object_id);
}
return 0;
}
| [
"solrex@b8839100-cf4c-0410-a34d-a92c6c0b7f09"
] | solrex@b8839100-cf4c-0410-a34d-a92c6c0b7f09 |
28be2175b62194b9395bcea3047f812193a89011 | e778be8ebc60a2ec915698280f17fafffe55c5fb | /platforms/imx8mm/include/nav_os/transport/shm/segment_factory.h | f8da18e9e424eeaa57fef59e3289ac7037482970 | [] | no_license | 3JLinux/xag_xhome | 30b933e11b40ff3c72c810e49a857caaf49a7247 | c2b00f449354cf12b72c8c87246a3b4493b751d8 | refs/heads/master | 2023-06-14T08:05:29.771649 | 2021-07-02T02:00:42 | 2021-07-02T02:00:42 | 382,225,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,252 | h | /******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* 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.
*****************************************************************************/
#ifndef CYBER_TRANSPORT_SHM_SEGMENT_FACTORY_H_
#define CYBER_TRANSPORT_SHM_SEGMENT_FACTORY_H_
#include <memory>
#include <string>
#include "spdlog/spdlog.h"
#include "transport/shm/segment.h"
#include "transport/shm/posix_segment.h"
#include "transport/shm/xsi_segment.h"
namespace xag_nav {
namespace os {
namespace transport{
class SegmentFactory {
public:
static SegmentPtr CreateSegment(uint64_t channel_id);
};
}
}
}
#endif // CYBER_TRANSPORT_SHM_SEGMENT_FACTORY_H_
| [
"421721486@qq.com"
] | 421721486@qq.com |
0f84f9736f88cc537f01cec5cdd1f7a86626a55a | be12bbdc92825830005f7806c67de7a99175cc1c | /src/core/SkArenaAlloc.h | 04f929181ca65e132bc6bbadd25d6b597d77d9e9 | [
"BSD-3-Clause"
] | permissive | chagge/skia | 03b93885199ae859c36a8dcaa1ce4f6636473e6e | 3012d187a487ad82c172790bef14c6333fac6e03 | refs/heads/master | 2021-01-18T16:00:22.544069 | 2017-03-08T15:22:41 | 2017-03-08T15:53:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,593 | h | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkFixedAlloc_DEFINED
#define SkFixedAlloc_DEFINED
#include "SkRefCnt.h"
#include "SkTFitsIn.h"
#include "SkTypes.h"
#include <cstddef>
#include <new>
#include <type_traits>
#include <utility>
#include <vector>
// SkArenaAlloc allocates object and destroys the allocated objects when destroyed. It's designed
// to minimize the number of underlying block allocations. SkArenaAlloc allocates first out of an
// (optional) user-provided block of memory, and when that's exhausted it allocates on the heap,
// starting with an allocation of extraSize bytes. If your data (plus a small overhead) fits in
// the user-provided block, SkArenaAlloc never uses the heap, and if it fits in extraSize bytes,
// it'll use the heap only once. If you pass extraSize = 0, it allocates blocks for each call to
// make<T>.
//
// Examples:
//
// char block[mostCasesSize];
// SkArenaAlloc arena(block, almostAllCasesSize);
//
// If mostCasesSize is too large for the stack, you can use the following pattern.
//
// std::unique_ptr<char[]> block{new char[mostCasesSize]};
// SkArenaAlloc arena(block.get(), mostCasesSize, almostAllCasesSize);
//
// If the program only sometimes allocates memory, use the following.
//
// SkArenaAlloc arena(nullptr, 0, almostAllCasesSize);
//
// The storage does not necessarily need to be on the stack. Embedding the storage in a class also
// works.
//
// class Foo {
// char storage[mostCasesSize];
// SkArenaAlloc arena (storage, almostAllCasesSize);
// };
//
// In addition, the system is optimized to handle POD data including arrays of PODs (where
// POD is really data with no destructors). For POD data it has zero overhead per item, and a
// typical block overhead of 8 bytes. For non-POD objects there is a per item overhead of 4 bytes.
// For arrays of non-POD objects there is a per array overhead of typically 8 bytes. There is an
// addition overhead when switching from POD data to non-POD data of typically 8 bytes.
//
// If additional blocks are needed they are increased exponentially. This strategy bounds the
// recursion of the RunDtorsOnBlock to be limited to O(ln size-of-memory). In practical terms, this
// is a maximum recursion depth of 33 for an 8GB machine but usually much less.
class SkArenaAlloc {
public:
SkArenaAlloc(char* block, size_t size, size_t extraSize = 0);
template <size_t kSize>
SkArenaAlloc(char (&block)[kSize], size_t extraSize = kSize)
: SkArenaAlloc(block, kSize, extraSize)
{}
SkArenaAlloc(size_t extraSize)
: SkArenaAlloc(nullptr, 0, extraSize)
{}
~SkArenaAlloc();
template <typename T, typename... Args>
T* make(Args&&... args) {
uint32_t size = SkTo<uint32_t>(sizeof(T));
uint32_t alignment = SkTo<uint32_t>(alignof(T));
char* objStart;
if (skstd::is_trivially_destructible<T>::value) {
objStart = this->allocObject(size, alignment);
fCursor = objStart + size;
} else {
objStart = this->allocObjectWithFooter(size + sizeof(Footer), alignment);
// Can never be UB because max value is alignof(T).
uint32_t padding = SkTo<uint32_t>(objStart - fCursor);
// Advance to end of object to install footer.
fCursor = objStart + size;
FooterAction* releaser = [](char* objEnd) {
char* objStart = objEnd - (sizeof(T) + sizeof(Footer));
((T*)objStart)->~T();
return objStart;
};
this->installFooter(releaser, padding);
}
// This must be last to make objects with nested use of this allocator work.
return new(objStart) T(std::forward<Args>(args)...);
}
template <typename T, typename... Args>
sk_sp<T> makeSkSp(Args&&... args) {
SkASSERT(SkTFitsIn<uint32_t>(sizeof(T)));
// The arena takes a ref for itself to account for the destructor. The sk_sp count can't
// become zero or the sk_sp will try to call free on the pointer.
return sk_sp<T>(SkRef(this->make<T>(std::forward<Args>(args)...)));
}
template <typename T>
T* makeArrayDefault(size_t count) {
uint32_t safeCount = SkTo<uint32_t>(count);
T* array = (T*)this->commonArrayAlloc<T>(safeCount);
// If T is primitive then no initialization takes place.
for (size_t i = 0; i < safeCount; i++) {
new (&array[i]) T;
}
return array;
}
template <typename T>
T* makeArray(size_t count) {
uint32_t safeCount = SkTo<uint32_t>(count);
T* array = (T*)this->commonArrayAlloc<T>(safeCount);
// If T is primitive then the memory is initialized. For example, an array of chars will
// be zeroed.
for (size_t i = 0; i < safeCount; i++) {
new (&array[i]) T();
}
return array;
}
// Destroy all allocated objects, free any heap allocations.
void reset();
private:
using Footer = int64_t;
using FooterAction = char* (char*);
static char* SkipPod(char* footerEnd);
static void RunDtorsOnBlock(char* footerEnd);
static char* NextBlock(char* footerEnd);
void installFooter(FooterAction* releaser, uint32_t padding);
void installUint32Footer(FooterAction* action, uint32_t value, uint32_t padding);
void installPtrFooter(FooterAction* action, char* ptr, uint32_t padding);
void ensureSpace(uint32_t size, uint32_t alignment);
char* allocObject(uint32_t size, uint32_t alignment);
char* allocObjectWithFooter(uint32_t sizeIncludingFooter, uint32_t alignment);
template <typename T>
char* commonArrayAlloc(uint32_t count) {
char* objStart;
uint32_t arraySize = SkTo<uint32_t>(count * sizeof(T));
uint32_t alignment = SkTo<uint32_t>(alignof(T));
if (skstd::is_trivially_destructible<T>::value) {
objStart = this->allocObject(arraySize, alignment);
fCursor = objStart + arraySize;
} else {
uint32_t totalSize = arraySize + sizeof(Footer) + sizeof(uint32_t);
objStart = this->allocObjectWithFooter(totalSize, alignment);
// Can never be UB because max value is alignof(T).
uint32_t padding = SkTo<uint32_t>(objStart - fCursor);
// Advance to end of array to install footer.?
fCursor = objStart + arraySize;
this->installUint32Footer(
[](char* footerEnd) {
char* objEnd = footerEnd - (sizeof(Footer) + sizeof(uint32_t));
uint32_t count;
memmove(&count, objEnd, sizeof(uint32_t));
char* objStart = objEnd - count * sizeof(T);
T* array = (T*) objStart;
for (uint32_t i = 0; i < count; i++) {
array[i].~T();
}
return objStart;
},
SkTo<uint32_t>(count),
padding);
}
return objStart;
}
char* fDtorCursor;
char* fCursor;
char* fEnd;
char* const fFirstBlock;
const uint32_t fFirstSize;
const uint32_t fExtraSize;
// The extra size allocations grow exponentially:
// size-allocated = extraSize * 2 ^ fLogGrowth.
uint8_t fLogGrowth {0};
};
#endif//SkFixedAlloc_DEFINED
| [
"skia-commit-bot@chromium.org"
] | skia-commit-bot@chromium.org |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.