blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
f11d3b8843c29ffe6e0b186c89dda5cd8636eb0f | C++ | NITISH26ISM/C_DS_ALGO | /priority Queue/minBinaryHeap.cpp | UTF-8 | 4,820 | 3.40625 | 3 | [] | no_license | # include <iostream>
# include <vector>
# include <unordered_map>
# include <cstring>
# include <list>
# include <climits>
using namespace std;
struct node{
int vertice;
int priority;
node() { }
node(int v, int p){
vertice = v;
priority = p;
}
};
struct edge{
int v;
int wt;
edge( ) { }
edge( int vr, int w ){
v = vr;
wt = w;
}
};
void addEdge( list<edge> adj[], int u, int v, int w){
adj[u].push_back(edge(v,w));
adj[v].push_back(edge(u,w));
}
class binaryMinHeap{
private:
vector<node> heap;
unordered_map< int, int > pos;
int size;
int capacity;
public:
binaryMinHeap(int n){
heap.resize(n);
size = 0;
capacity = n;
}
~binaryMinHeap(){
heap.clear();
pos.clear();
}
node min(){
return heap[0];
}
void heapify( int i ){
int min, c1, c2;
c1 = 2*i+1;
c2 = 2*i+2;
if( c1 < size && c2 < size ){
min = (heap[c1].priority < heap[c2].priority)? c1: c2;
}
else if( c1 < size ){
min = c1;
}
else
return;
while( heap[i].priority > heap[min].priority ){
node temp = heap[min];
heap[min] = heap[i];
heap[i] = temp;
pos[heap[i].vertice] = i;
pos[heap[min].vertice] = min;
i = min;
c1 = 2*i+1;
c2 = 2*i+2;
if( c1 < size && c2 < size ){
min = (heap[c1].priority < heap[c2].priority)? c1: c2;
}
else if( c1 < size ){
min = c1;
}
else
return;
}
}
void insert(node n){
int t = size;
heap[t] = n;
pos[heap[t].vertice] = t;
size++;
node temp;
while( t != 0 && heap[t].priority < heap[(t-1)/2].priority ){
temp = heap[(t-1)/2];
heap[(t-1)/2] = heap[t];
heap[t] = temp;
pos[heap[t].vertice] = t;
pos[heap[(t-1)/2].vertice] = (t-1)/2;
t = (t-1)/2;
}
}
bool contain( int vertex ){
if(pos.count(vertex) > 0 )
return true;
else
return false;
}
node extract_min(){
node temp = heap[0];
heap[0] = heap[size-1];
pos[heap[0].vertice] = 0;
size--;
heapify(0);
pos.erase(temp.vertice);
return temp;
}
bool isEmpty(){
return size==0;
}
void decrease_key( int vertex, int m ){
int p = pos[vertex];
heap[p].priority = m;
node temp;
while( p != 0 && heap[p].priority < heap[(p-1)/2].priority ){
temp = heap[(p-1)/2];
heap[(p-1)/2] = heap[p];
heap[p] = temp;
pos[heap[p].vertice] = p;
pos[heap[(p-1)/2].vertice] = (p-1)/2;
p = (p-1)/2;
}
}
void increase_key( int vertex, int m){
int p = pos[vertex];
heap[p].priority = m;
heapify(p);
}
void print(){
cout<<"Size: "<<size<<endl;
for(int i = 0; i < size; i++)
cout<<heap[i].vertice<<" ";
cout<<endl;
}
int key(int vertex){
int p = pos[vertex];
return heap[p].priority;
}
};
void primMST(list<edge> adj[], int v ){
binaryMinHeap Q(v);
vector<int> parent(v, -1);
Q.insert(node(0,0));
for( int i = 1; i < v; i++ ){
Q.insert(node(i,INT_MAX));
}
while( !Q.isEmpty() ){
node n_u = Q.extract_min();
int u = n_u.vertice;
for( auto itr = adj[u].begin(); itr != adj[u].end(); itr++ ){
int v = (*itr).v;
int wt = (*itr).wt;
if( Q.contain(v) ){
if( Q.key(v) > wt ){
Q.decrease_key(v, wt );
parent[v] = u;
}
}
}
}
cout<<"Edges in MST:"<<endl;
for( int i = 1; i < v ; i++ ){
cout<<i<<"---"<<parent[i]<<endl;
}
}
int main(){
int v = 9;
list<edge> adj[v];
addEdge(adj, 0, 1, 4);
addEdge(adj,0, 7, 8);
addEdge(adj,1, 2, 8);
addEdge(adj,1, 7, 11);
addEdge(adj,2, 3, 7);
addEdge(adj,2, 8, 2);
addEdge(adj,2, 5, 4);
addEdge(adj,3, 4, 9);
addEdge(adj,3, 5, 14);
addEdge(adj,4, 5, 10);
addEdge(adj,5, 6, 2);
addEdge(adj,6, 7, 1);
addEdge(adj,6, 8, 6);
addEdge(adj,7, 8, 7);
primMST(adj, v);
return 0;
}
| true |
d490a7ce18a4e7c53256c7241a37d2ae6c54ae2c | C++ | LiYouCheng2014/leetCode | /leetCode-c/leetCode-c/LeetCode/leetCode-0050/leetCode-0050.cpp | UTF-8 | 1,340 | 2.96875 | 3 | [] | no_license | //
// leetCode-0050.cpp
// leetCode-c
//
// Created by liyoucheng on 2019/1/27.
// Copyright © 2019年 Giga. All rights reserved.
//
#include "leetCode-0050.hpp"
//class Solution {
//public:
// double myPow(double x, int n) {
//
// if (n < 0) {
//
// return 1 / power(x, -n);
// }
// return power(x, n);
// }
//
// double power(double x, int n) {
//
// if (n == 0) {
//
// return 1;
// }
//
// double half = power(x, n / 2);
// if (n % 2 == 0) {
//
// return half * half;
// }
//
// return x * half *half;
// }
//};
//class Solution {
//public:
// double myPow(double x, int n) {
//
// if (n == 0) {
//
// return 1;
// }
//
// double half = myPow(x, n / 2);
// if (n % 2 == 0) {
//
// return half * half;
// }
//
// if (n > 0) {
//
// return half * half * x;
// }
//
// return half * half / x;
// }
//};
class Solution {
public:
double myPow(double x, int n) {
double res = 1.0;
for (int i = n; i != 0; i /= 2) {
if (i % 2 != 0) {
res *= x;
}
x *= x;
}
return n < 0 ? 1 / res : res;
}
};
| true |
c6f9d1ef61d93bad091d96bc9046172115ead76e | C++ | IgorRas/studia_przed_spec | /Add.cpp | UTF-8 | 1,767 | 3.875 | 4 | [] | no_license | /*
Zaimplementuj:
•Operator+, po którego obu stronach stoją niemodyfikujące referencje wektorów liczb rzeczywistych,
zaś wynikiem jest nowy wektor zawierający wszystkie elementy wektora po lewej,
a po nich wszystkie elementy wektora po prawej.
•Operator+=, po którego lewej i prawej stronie stoi odpowiednio modyfikująca i niemodyfikująca referencja wektora liczb rzeczywistych,
a wynikiem jest modyfikująca referencja wektora po lewej.
Operator dopisuje na jego koniec wszystkie elementy wektora po prawej.
Operatory powinny być przystosowane do użycia w przykładowym programie poniżej. Operatory korzystają tylko z pliku nagłówkowego vector.
Przykładowy program
int main() {
std::vector<double> vector = std::vector<double> {6.7, -12.3} + std::vector<double> {-2.7, 19};
(vector += std::vector<double> {0.5, -2.7}) += std::vector<double> {19};
for (double element: vector) {
std::cout << element << " "; }
std::cout << std::endl; }
Wykonanie
Out: 6.7 -12.3 -2.7 19 0.5 -2.7 19
*/
#include <iostream>
#include <vector>
std::vector<double> operator +(const std::vector<double> &v1, const std::vector<double> &v2) {
std::vector<double> vc;
vc.insert(vc.begin(), v1.begin(), v1.end());
vc.insert(vc.end(), v2.begin(), v2.end());
return vc;
}
std::vector<double> &operator += (std::vector<double> &v1, const std::vector<double> &v2) {
v1.insert(v1.end(), v2.begin(), v2.end());
return v1;
}
int main() {
std::vector<double> vector = std::vector<double> {6.7, -12.3} + std::vector<double> {-2.7, 19};
(vector += std::vector<double> {0.5, -2.7}) += std::vector<double> {19};
for (double element: vector) {
std::cout << element << " ";
}
std::cout << std::endl;
}
| true |
c3d4c8f882b16533be85e7dc46bf4299def100e1 | C++ | eckertalex/musicplayer372 | /src/textureManager.cpp | UTF-8 | 625 | 2.515625 | 3 | [
"Unlicense"
] | permissive | // textureManager.cpp
// 26. April 2017
// Created by:
// Bryan Burkhardt (bmburkhardt@alaska.edu)
// Alexander Eckert (aeckert@alaska.edu)
// Jeremiah Jacobson (jjjacobson2@alaska.edu)
// Jarye Murphy (jmurphy11@alaska.edu)
// Cameron Showalter (@alaska.edu)
//
// Source file for textureManager
#include <SFML/Graphics.hpp>
#include "../include/textureManager.hpp"
void TextureManager::loadTexture(const std::string &name, const std::string &filename) {
// Load the texture
sf::Texture tex;
tex.loadFromFile(filename);
// Add it to the list of textures
this->textures[name] = tex;
return;
}
sf::Texture & TextureManager::getRef(const std::string &texture) {
return this->textures.at(texture);
} | true |
ea8f3956d362af86d086ae049ea904244ed72642 | C++ | Bablu-Mehta/GymTraine-cpp | /GymTraine.cpp | UTF-8 | 11,793 | 2.640625 | 3 | [] | no_license | #include<conio.h>
#include<iostream>
#include<string.h> //string header file
using namespace std;
class man
{
public:
void monday()
{
cout<<"\t\tChest day"<<endl;
cout<<"\t\tFirst of all Stretch your body"<<endl;
cout<<"\t\t1. Barbell Bench Press"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t2. Inclined Dumbbell Press"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t3. Dips"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t4. Pullups"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
}
void tuesday()
{ cout<<"\t\tShoulders and Arms day"<<endl;
cout<<"\t\tFirst of all Stretch your body"<<endl;
cout<<"\t\t1. Military Press or Dumbbell Press"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t2. Lateral Raises"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t3. Barbell Curls"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t4. Dumbell Curls"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
}
void wednesday()
{ cout<<"\t\tBiceps day"<<endl;
cout<<"\t\tFirst of all Stretch your body"<<endl;
cout<<"\t\t1. Incline Dumbell Hammer curl"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t2. Incline Inner-Biceps curl "<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t3. Zottman Curl"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t4. EZ-Bar curl"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
}
void thursday()
{
cout<<"\t\tTriceps day"<<endl;
cout<<"\t\tFirst of all Stretch your body"<<endl;
cout<<"\t\t1. Close-Grip Barbell Bench Press"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t2. Dip Machine"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t3. Seated Dumbell Press"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t4. V-Bar Pulldown"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
}
void friday()
{
cout<<"\t\tBack day"<<endl;
cout<<"\t\tFirst of all Stretch your body"<<endl;
cout<<"\t\t1. Band Bent-over Row"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t2. Renegade Row"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t3. Dumbbell Single Arm Row"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t4. Inverted Row"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
}
void saturday()
{
cout<<"\t\tLeg Day"<<endl;
cout<<"\t\tFirst of all Stretch your body"<<endl;
cout<<"\t\t1. Barbell Squat"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t2. Dumbell Lunges"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t3. Leg Press"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t4. Standing Calf Raises"<<endl;
cout<<"\t\t\t * 3-4 sets of 6-8 reps or 10-12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
}
};
class woman
{ public:
void wmonday()
{
cout<<"\t\tChest day"<<endl;
cout<<"\t\tFirst of all Stretch your body"<<endl;
cout<<"\t\t1. Standing Chest Stretch"<<endl;
cout<<"\t\t\t * Hold the position for 2o-3o seconds"<<endl;
cout<<"\t\t\t * 2 sets of 5 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t2. Camel Pose"<<endl;
cout<<"\t\t\t * Hold the position for 3o seconds"<<endl;
cout<<"\t\t\t * 2 sets of 5 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t3. Seated Dumbell Fly"<<endl;
cout<<"\t\t\t * 2 sets of 12 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t4. Lying Chest Fly"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
}
void wtuesday()
{
cout<<"\t\tBiceps day"<<endl;
cout<<"\t\tFirst of all Stretch your body"<<endl;
cout<<"\t\t1. Biceps Curl"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t2. Hammer Curl"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t3. Curtsy Lunge With Biceps Curl"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t4. Squat With Biceps Curl"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
}
void wwednesday()
{
cout<<"\t\tTriceps Day"<<endl;
cout<<"\t\tFirst of All Stretch your body a little bit"<<endl;
cout<<"\t\t1. Triceps Extension"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t2. Skull Crusher or Lying Triceps Extension"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t3. Triceps Dips"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t4. Triceps Push-ups"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
}
void wthursday()
{
cout<<"\t\tBack and Wings day"<<endl;
cout<<"\t\tFirst of all Stretch your body"<<endl;
cout<<"\t\t1. Spreading Wings Lift"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t2. one Arm Rowing Dumbbell"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t3. Bow And Arrow"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t4. Back Arm Walk"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
}
void wfriday()
{
cout<<"\t\tShoulders Day"<<endl;
cout<<"\t\tFirst of All stretch your body a little bit"<<endl;
cout<<"\t\t1. Dumbbell Front Raises"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t2. Standing Shoulder Press"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t3. Lateral Raises"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t4. Bent Arm Lateral Raises"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
}
void wsaturday()
{
cout<<"\t\tLeg day"<<endl;
cout<<"\t\tFirst of all Stretch your body"<<endl;
cout<<"\t\t1. Goblet Squat"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t2. Banded Lateral Walk"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t3. Single Leg Deadlift"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
cout<<"\t\t4. Lateral Lunge"<<endl;
cout<<"\t\t\t * 3 sets of 10 reps"<<endl;
cout<<"\t\t\t Rest a little bit after the sets"<<endl;
}
};
class details:public man, public woman
{
public:
void detail1()
{
int ch;
do
{
cout<<"\t\t|=====================================|"<<endl;
cout<<"\t\t| Welcome to my gym Exercises |"<<endl;
cout<<"\t\t| Exercises for Male |"<<endl;
cout<<"\t\t| Press [0] for exit the page |"<<endl;
cout<<"\t\t| Press [1] for the day 1 routine |"<<endl;
cout<<"\t\t| Press [2] for the day 2 routine |"<<endl;
cout<<"\t\t| Press [3] for the day 3 routine |"<<endl;
cout<<"\t\t| Press [4] for the day 4 routine |"<<endl;
cout<<"\t\t| Press [5] for the day 5 routine |"<<endl;
cout<<"\t\t| Press [6] for the day 6 routine |"<<endl;
cout<<"\t\t|=====================================|"<<endl;
cin>>ch;
switch(ch)
{
case 1:
{
monday();
break;
}
case 2:
{
tuesday();
break;
}
case 3:
{
wednesday();
break;
}
case 4:
{
thursday();
break;
}
case 5:
{
friday();
break;
}
case 6:
{
saturday();
break;
}
default:
{
cout<<"Thank you for your valuable time"<<endl;
}
}
}
while(ch!=0);
}
void detail2()
{
int ch;
do
{
cout<<"\t\t|=====================================|"<<endl;
cout<<"\t\t| Welcome to my gym Exercises |"<<endl;
cout<<"\t\t| Exercises for Female |"<<endl;
cout<<"\t\t| Press [0] for exit the page |"<<endl;
cout<<"\t\t| Press [1] for the day 1 routine |"<<endl;
cout<<"\t\t| Press [2] for the day 2 routine |"<<endl;
cout<<"\t\t| Press [3] for the day 3 routine |"<<endl;
cout<<"\t\t| Press [4] for the day 4 routine |"<<endl;
cout<<"\t\t| Press [5] for the day 5 routine |"<<endl;
cout<<"\t\t| Press [6] for the day 6 routine |"<<endl;
cout<<"\t\t|=====================================|"<<endl;
cin>>ch;
switch(ch)
{
case 1:
{
wmonday();
break;
}
case 2:
{
wtuesday();
break;
}
case 3:
{
wwednesday();
break;
}
case 4:
{
wthursday();
break;
}
case 5:
{
wfriday();
break;
}
case 6:
{
wsaturday();
break;
}
default:
{
cout<<"Thank you for your valuable time"<<endl;
}
}
}
while(ch!=0);
}
};
int main()
{
char name[50], age[10], gender;
details d;
cout<<"\t\t\t----------------------------"<<endl;
cout<<"\t\t\t Enter Your Name:-";
cin.getline(name,100);
cout<<endl;
cout<<"\t\t\t Enter Your Age:-";
cin.getline(age,10);
cout<<endl;
cout<<"\t\t\t Enter Your Gender(m/f):-";
cin>>gender;
cout<<"\t\t\t----------------------------"<<endl;
switch(gender)
{
case 'm':
{
d.detail1();
break;
}
case 'f':
{
d.detail2();
break;
}
default:
{
cout<<"This is unspecified Gender";
}
}
return 0;
}
| true |
ed1cf63ce9fabf9a7e8acca74004c464d2bb7c30 | C++ | hyunstory/CodingTestPractice | /Baekjoon/CPP/17090.cpp | UTF-8 | 1,540 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <deque>
using namespace std;
#define input_max 500 + 1
int n, m;
char map_c[input_max][input_max];
int map_status[input_max][input_max]; // 0은 모름 unkown, 1은 가능, 2는 불가능, 3은 갔던 길
int dx[] = { -1, 0, 1, 0 }; // 상우하좌
int dy[] = { 0, 1, 0, -1 };
int result;
void solution() {
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
cin >> map_c[i][j];
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
int x = i;
int y = j;
deque<pair<int, int>> dq;
bool impos_FLAG = false;
while (0 <= x && x < n && 0 <= y && y < m) {
if (map_status[x][y] == 1) break;
else if (map_status[x][y] == 2 || map_status[x][y] == 3) {
impos_FLAG = true;
break;
}
char temp = map_c[x][y];
dq.push_back(make_pair(x, y));
map_status[x][y] = 3;
if (temp == 'U') {
x = x + dx[0];
y = y + dy[0];
}
else if (temp == 'R') {
x = x + dx[1];
y = y + dy[1];
}
else if (temp == 'D') {
x = x + dx[2];
y = y + dy[2];
}
else if (temp == 'L') {
x = x + dx[3];
y = y + dy[3];
}
}
if (!impos_FLAG) {
while (!dq.empty()) {
int dq_x = dq.back().first;
int dq_y = dq.back().second;
map_status[dq_x][dq_y] = 1;
dq.pop_back();
}
result++;
}
}
cout << result << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solution();
return 0;
} | true |
8396d65c8b05257acc70b5a730b56950aa2d93a1 | C++ | skyformat99/lftpd | /src/config.cc | UTF-8 | 2,607 | 3.171875 | 3 | [] | no_license | #include "config.h"
#include <boost/regex.hpp>
#include <iostream>
#include <fstream>
Config * Config::instance = NULL;
Config::Config(){
}
Config * Config::get_instance(){
if(!instance){
instance = new Config();
}
return instance;
}
CFG_CODES Config::parse_config(std::string file_name){
std::string line;
if(this->config_name.empty() ){
this->config_name = file_name;
}else{
return CFG_ALREADY_READ;
}
std::ifstream f(file_name.c_str(), std::ifstream::in);
if(!f.is_open() ){
return CFG_FILE_NOT_AVAILABLE;
}
std::string section("default") ;
std::string key;
std::string value;
while ( getline (f,line) ){
line = clear_comment(line);
section = get_section(line, section);
section = trim(section);
if(parse_line(line,&key, &value) == CFG_OK){
key_value[section + trim(key)] = trim(value);
}
}
f.close();
return CFG_OK;
}
CFG_CODES Config::clear(){
key_value.clear();
config_name = "";
return CFG_OK;
}
CFG_CODES Config::parse_line(std::string line, std::string * key, std::string * value){
boost::regex rgx("([^=]+)\\s*=\\s*(.+)");
boost::smatch match;
if (boost::regex_search(line, match, rgx)){
*key = match[1];
*value = match[2];
}else{
return CFG_WRONG_LINE;
}
return CFG_OK;
}
std::string Config::get_section(std::string line, std::string current_section){
boost::regex rgx("\\[(\\w+)\\]");
boost::smatch match;
if (boost::regex_search(line, match, rgx)){
std::string str = match[1];
return str;
}else{
return current_section;
}
}
std::string Config::clear_comment(std::string line){
boost::regex rgx("(^[^#]+)#?");
boost::smatch match;
std::string str;
if(boost::regex_search(line, match, rgx)){
str = std::string(match[1]);
}
return str;
}
std::string Config::get_value(std::string key){
return get_value("default", key);
}
std::string Config::get_value(std::string section, std::string key){
std::map<std::string,std::string>::iterator it = key_value.find(section + key);
std::string str;
if(it != key_value.end()){
str = it->second;
}
return str;
}
std::string Config::get_config_name(){
return config_name;
}
std::string Config::trim(std::string str){
size_t first = str.find_first_not_of(' ');
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last-first+1));
} | true |
ff03bd58cbb9d710283396c42255f73df0187db2 | C++ | tangzhenyu/Distributed_Machine_Learning | /mpi_based/src/io/io.h | UTF-8 | 900 | 2.59375 | 3 | [] | no_license | #pragma once
#include <fstream>
#include <iostream>
namespace dml{
struct kv{
int fgid;
long int fid;
float val;
};
class IO{
public:
IO(const char *file_path) : file_path(file_path){
Init();
};
~IO(){};
void Init(){
fin_.open(file_path, std::ios::in);
if(!fin_.is_open()){
std::cout<<"open file "<<file_path<<" error!"<<std::endl;
exit(1);
}else{
std::cout<<"open file "<<file_path<<" sucess!"<<std::endl;
}
}
virtual void load_all_data() = 0;
virtual void load_batch_data(int num) = 0;
public:
std::ifstream fin_;
std::string line;
typedef kv key_val;
const char *file_path;
int fgid;
long int fid;
float val;
int nchar;
int y;
};
}
| true |
8c41696ce68ed5a7f2efe2dc64ce233eb6b10dc9 | C++ | lucaschf/OnlineJudge | /Beginner/Problem1478.cpp | UTF-8 | 933 | 3.1875 | 3 | [] | no_license | //
// Created by lucas on 01/18/2021.
//
#include <iostream>
using namespace std;
int main() {
int size;
while ((cin >> size) && (size != 0)) {
int arr[size][size];
for (int line = 0; line < size; line++) {
arr[line][0] = line + 1;
for (int column = line; column >= 0; column--) {
arr[line][column] = line - (column - 1);
}
arr[line][line] = 1;
int value = 1;
for (int column = line + 1; column < size; column++) {
arr[line][column] = ++value;
}
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (j == 0)
printf("%3d", arr[i][j]);
else
printf("%4d", arr[i][j]);
}
cout << endl;
}
cout << endl;
}
return 0;
}
| true |
267948eccf8735a571b3e7abe28a05c1f60a9706 | C++ | Jim-CodeHub/libmime | /libmime/rfc822/field_name.cpp | UTF-8 | 2,952 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | /**-----------------------------------------------------------------------------------------------------------------
* @file field_name.cpp
* @brief Standrad for ARPA Ineternet text messages
* @ref IETF-rfc822
*
* Copyright (c) 2019-2019 Jim Zhang 303683086@qq.com
*------------------------------------------------------------------------------------------------------------------
*/
#include <libmime/rfc822/field_name.hpp>
using namespace NS_LIBMIME;
/*
--------------------------------------------------------------------------------------------------------------------
*
* FUNCTIONS IMPLEMENT
*
--------------------------------------------------------------------------------------------------------------------
*/
/**
* @brief Set field name
* @param[in] name - field name
* @param[out] None
* @return None
* @exception "const char *", rfc822 field name error
**/
void field_name::set(const string &name)
{
string::const_iterator _index = name.begin(), _end = name.end();
while (_index != _end)
{
if ((*_index < FIELD_NAME_ASCII_SCOPE_MIN) || (*_index > FIELD_NAME_ASCII_SCOPE_MAX)
|| (*_index == FIELD_NAME_ASCII_EXCLUDECH))
{
throw("Exception : 'field_name.cpp' - Character out of range!");
}
_index++;
}
this->name = name;
return;
}
field_name::field_name(const string &name) { this->set(name); }
/**
* @brief Set field name
* @param[in] name - field name
* @param[in] _size - size of field name
* @param[out] None
* @return None
* @exception "const char *", rfc822 field name error
**/
void field_name::set(const char *name, size_t _size)
{
const char *_index = name;
this->name.clear();
while ((*_index != '\0') && (_size-- != 0))
{
if ((*_index < FIELD_NAME_ASCII_SCOPE_MIN) || (*_index > FIELD_NAME_ASCII_SCOPE_MAX)
|| (*_index == FIELD_NAME_ASCII_EXCLUDECH))
{
this->name.clear();
throw("Exception : 'field_name.cpp' - Character out of range!");
}
this->name.append(1, *_index);
_index++;
}
if (*_index != '\0') {this->name.append(1, '\0');}
return;
}
field_name::field_name(const char *name, size_t _size) { this->set(name, _size); }
/**
* @brief Operator '=' overloading
* @param[in] rname_t - class field_name reference
* @param[out] None
* @return class field_name reference
**/
const class field_name &field_name::operator=(const class field_name &rname_t)
{
this->name = rname_t.name;
return rname_t;
}
/**
* @brief Operator '==' overloading
* @param[in] rname_t - class field_name reference
* @param[out] None
* @return true/false
**/
bool field_name::operator==(const class field_name &rname_t)
{
return (this->name == rname_t.name);
}
/**
* @brief Get field name
* @param[in] None
* @param[out] None
* @return None
* @exception "const char *", rfc822 field name error
**/
const string &field_name::get(void) const noexcept
{
return name;
}
| true |
b57ad07a8bbf6667d778732a7e4e801b8489bcc8 | C++ | frc4646/frc4646-2015-competition-code | /src/Commands/TotesMaGoats.cpp | UTF-8 | 2,345 | 2.765625 | 3 | [] | no_license | #include "TotesMaGoats.h"
#include "GrabberCloseCommand.h"
#include "LiftToLevelCommand.h"
#include "DriveForDistance.h"
#include "../RobotMap.h"
#include "SlideForDistance.h"
#include "DriveUntilClose.h"
#include "DriveUntilCloseWithIntake.h"
#include "GrabberOpenCommand.h"
#include "LiftToBottomCommand.h"
TotesMaGoats::TotesMaGoats()
{
// Add Commands here:
// e.g. AddSequential(new Command1());
// AddSequential(new Command2());
// these will run in order.
// To run multiple commands at the same time,
// use AddParallel()
// e.g. AddParallel(new Command1());
// AddSequential(new Command2());
// Command1 and Command2 will run in parallel.
// A command group will require all of the subsystems that each member
// would require.
// e.g. if Command1 requires chassis, and Command2 requires arm,
// a CommandGroup containing them would require both the chassis and the
// arm.
AddSequential(new LiftToBottomCommand());
AddSequential(new GrabberCloseCommand(), 0.01);
AddSequential(new LiftToLevelCommand(LIFT_LEVEL_TWO));
AddSequential(new SlideForDistance(38.5, 0.3));
AddSequential(new DriveForDistance(40.5, -0.3));
AddSequential(new SlideForDistance(38.5, -0.6));
AddSequential(new DriveUntilCloseWithIntake(), 3);
//Lower the tote onto the other tote
AddSequential(new LiftToLevelCommand((LIFT_LEVEL_ONE + LIFT_LEVEL_TWO)/2.0));
AddSequential(new GrabberOpenCommand(), 0.01);
AddSequential(new LiftToBottomCommand());
//Repeat all previous commands
AddSequential(new GrabberCloseCommand(), 0.01);
AddSequential(new LiftToLevelCommand(LIFT_LEVEL_TWO));
AddSequential(new SlideForDistance(38.5, 0.3));
AddSequential(new DriveForDistance(40.5, -0.3));
AddSequential(new SlideForDistance(38.5, -0.6));
AddSequential(new DriveUntilCloseWithIntake(), 3);
AddSequential(new LiftToLevelCommand((LIFT_LEVEL_ONE + LIFT_LEVEL_TWO)/2.0));
AddSequential(new GrabberOpenCommand(), 0.01);
AddSequential(new LiftToBottomCommand());
//Pick up the final stack of totes
AddSequential(new GrabberCloseCommand(), 0.01);
//Slide into the autonomous zone
AddSequential(new SlideForDistance(107, 0.3));
//TODO: Add timeouts to all autonomous commands. This is to prevent the
// robot from potentially never meeting the finished requirements
// for the commands and driving off haywire!!!
}
| true |
e78e685ffbb3f99fe6981faecb535059a236e74e | C++ | querrec/Mascaret | /Dev/C++/Mascaret/include/VEHA/Entity/AnimationSpecification.h | UTF-8 | 3,237 | 2.796875 | 3 | [] | no_license | #ifndef _v2_VEHA_Entity_Animation_H
#define _v2_VEHA_Entity_Animation_H
#include <boost/signal.hpp>
#include <boost/bind.hpp>
#include "Tools/veha_plateform.h"
#include "VEHA/Entity/VirtualRealitySpecification.h"
namespace VEHA
{
class ShapeSpecification;
class VEHA_API AnimationSpecification : public VirtualRealitySpecification
{
public :
AnimationSpecification(const std::string & name, const std::string & url);
virtual ~AnimationSpecification();
inline std::string getName() { return _name;}
inline std::string getUrl() { return _url;}
virtual void setShape(shared_ptr<ShapeSpecification> shape)=0;
virtual shared_ptr<ShapeSpecification> getShape() const=0;
virtual bool play(double speed=1.0, int sens=1, bool cycle=false)=0;
virtual bool stop()=0;
virtual shared_ptr<ValueSpecification> clone() const;
template <class T1,class T2>
inline boost::signals::connection addCallbackOnPlayStarted(shared_ptr<T1> instance,void (T2::*method)(shared_ptr<AnimationSpecification>));
template <class T1,class T2>
inline boost::signals::connection addCallbackOnPlayFinished(shared_ptr<T1> instance,void (T2::*method)(shared_ptr<AnimationSpecification>));
template <class T1,class T2>
inline boost::signals::connection addCallbackOnAnimationPosition(shared_ptr<T1> instance,void (T2::*method)(shared_ptr<AnimationSpecification>, double));
protected:
inline void firePlayStarted();
inline void firePlayFinished();
inline void fireAnimationPosition(double position);
private :
std::string _name;
std::string _url;
boost::signal<void (shared_ptr<AnimationSpecification>)> _cbOnPlayStarted;
boost::signal<void (shared_ptr<AnimationSpecification>)> _cbOnPlayFinished;
boost::signal<void (shared_ptr<AnimationSpecification>, double)> _cbOnAnimationPosition;
};
template <class T1,class T2>
boost::signals::connection AnimationSpecification::addCallbackOnPlayStarted(shared_ptr<T1> instance,void (T2::*method)(shared_ptr<AnimationSpecification>))
{
T2 * dummy1=(T1 *)0; // ensure T1 inherits from T2
(void)dummy1;
return _cbOnPlayStarted.connect(bind(method,instance,_1));
}
void AnimationSpecification::firePlayStarted()
{
_cbOnPlayStarted(shared_dynamic_cast<AnimationSpecification>(shared_from_this()));
}
template <class T1,class T2>
boost::signals::connection AnimationSpecification::addCallbackOnPlayFinished(shared_ptr<T1> instance,void (T2::*method)(shared_ptr<AnimationSpecification>))
{
T2 * dummy1=(T1 *)0; // ensure T1 inherits from T2
(void)dummy1;
return _cbOnPlayFinished.connect(bind(method,instance,_1));
}
void AnimationSpecification::firePlayFinished()
{
_cbOnPlayFinished(shared_dynamic_cast<AnimationSpecification>(shared_from_this()));
}
template <class T1,class T2>
boost::signals::connection AnimationSpecification::addCallbackOnAnimationPosition(shared_ptr<T1> instance,void (T2::*method)(shared_ptr<AnimationSpecification>,double))
{
T2 * dummy1=(T1 *)0; // ensure T1 inherits from T2
(void)dummy1;
return _cbOnAnimationPosition.connect(bind(method,instance,_1, _2));
}
void AnimationSpecification::fireAnimationPosition(double position)
{
_cbOnAnimationPosition(shared_dynamic_cast<AnimationSpecification>(shared_from_this()), position);
}
}
#endif
| true |
b7518ec06910fb9093bffd61b9d8054f8c44aaac | C++ | dcesini/Darwin | /Chromo.cpp | UTF-8 | 3,403 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | #include "include/Constants.h"
#include "include/Constants_wrapper.h"
#include "include/Chromo.h"
#include <iostream>
#include <string>
#include <sstream>
std::string chromo::REPRODUCTION_METHOD = "";
chromo::chromo(){
for(int i = 0; i < DIM ; ++i) ch_[i] = 0;
REPRODUCTION_METHOD = "SEGMENTS_EXCHANGE";
};
chromo::chromo(const short int ch_ii[DIM]) {
for(int i = 0; i < DIM ; i++) ch_[i] = ch_ii[i];
REPRODUCTION_METHOD = "SEGMENTS_EXCHANGE";
};
chromo::chromo(const chromo& c1) {
for(int i = 0; i < DIM ; i++) ch_[i] = c1.get_base(i);
REPRODUCTION_METHOD = "SEGMENTS_EXCHANGE";
};
void chromo::set_base(int pos, short int val) {
if((pos >= 0) && (pos < DIM))
{
ch_[pos] = val;
}
else
{
std::cout << "Error(chromo::set_base): pos outside limits";
}
};
short int chromo::get_base(int pos) const {
if((pos >= 0) && (pos < DIM))
{
return ch_[pos];
}
else
{
std::cout << "Error(chromo::get_pos): pos outside limits";
return -1;
}
};
chromo& chromo::operator=(const chromo &rhs) {
for(int i = 0; i < DIM ; i++) ch_[i] = rhs.ch_[i];
return *this;
};
bool operator== (chromo const& lhs , chromo const& rhs){
for (int ii = 0; ii < DIM; ++ii) {
if (!(lhs.get_base(ii) == rhs.get_base(ii))) return false;
};
return true;
}
void chromo::show_chromo() const {
std::string s;
std::string Result;
s = "";
for(int ii = 0; ii < CHROMO_SEGMENTS; ii++) {
s = s + "[";
for(int jj = 0; jj < SEGMENTS_LENGHT; jj++) {
std::ostringstream convert; // stream used for the conversion
convert << ch_[ ii*SEGMENTS_LENGHT + jj]; // insert the textual representation of 'Number' in the characters in the stream
Result = convert.str(); // set 'Result' to the contents of the stream
if(jj == SEGMENTS_LENGHT - 1) s = s + Result ;
else s = s + Result + ",";
}
if(ii == CHROMO_SEGMENTS - 1) s = s + "]";
else s = s + "] + ";
}
std::cout << s << std::endl;
};
std::ostream& operator<<(std::ostream& os, const chromo& obj) {
for(int ii = 0; ii < CHROMO_SEGMENTS; ++ii) {
os << "[";
std::string Result;
for(int jj = 0; jj < SEGMENTS_LENGHT; jj++) {
std::ostringstream convert; // stream used for the conversion
convert << obj.get_base(ii*SEGMENTS_LENGHT + jj); // insert the textual representation of 'Number' in the characters in the stream
Result = convert.str(); // set 'Result' to the contents of the stream
if(jj == SEGMENTS_LENGHT - 1) os << Result ;
else os << Result << ",";
}
if(ii == CHROMO_SEGMENTS - 1) os << "]";
else os << "] + ";
}
return os;
};
chromo chromo_mix(chromo const& lhs, chromo const& rhs) {
chromo new_chromo;
std::string REPRODUCTION_METHOD(lhs.repr_method());
if (REPRODUCTION_METHOD == "SEGMENTS_EXCHANGE") {
for(int jj = 0; jj < (CHROMO_SEGMENTS * SEGMENTS_LENGHT) / 2; ++jj) {
new_chromo.set_base(jj,rhs.get_base(jj));
}
for(int jj = (CHROMO_SEGMENTS * SEGMENTS_LENGHT) / 2; jj < DIM; ++jj) {
new_chromo.set_base(jj,lhs.get_base(jj));
}
}
return new_chromo;
};
chromo operator+(chromo const& lhs, chromo const& rhs) {
return chromo_mix(lhs, rhs);
};
int chromo::sum_chromo() const {
int sum(0);
for (int ii = 0; ii < DIM; ++ii) sum = sum + ch_[ii];
return sum;
};
| true |
50512e1eb82fc087535d566887c89b33675dc356 | C++ | tjfr8s/GameOfLife | /cell.cpp | UTF-8 | 653 | 3.59375 | 4 | [] | no_license | #include "cell.h"
// populated cell status denoted by 'o' character. unpopulated cell status
// denoted by 'x' character.
Cell::Cell(char status = 'o'): m_status(status)
{
}
void Cell::toggleStatus()
{
if(m_status == 'o')
{
m_status = 'x';
}
else if(m_status == 'x')
{
m_status = 'o';
}
}
bool Cell::isAlive() const
{
if(m_status == 'o')
{
return true;
}
else if(m_status == 'x')
{
return false;
}
}
char Cell::getStatus() const
{
return m_status;
}
std::ostream& operator<<(std::ostream &out, const Cell &cell)
{
out << cell.getStatus();
return out;
}
| true |
3635f122d3ff09fcfd0f162b374d3c83315c30b0 | C++ | qulacs/qulacs | /src/csim/update_ops.hpp | UTF-8 | 60,932 | 2.703125 | 3 | [
"MIT"
] | permissive | /*
rules for arguments of update functions:
The order of arguments must be
information_about_applying_qubits -> Pauli_operator ->
information_about_applying_gate_matrix_elements -> a_kind_of_rotation_angle ->
state_vector -> dimension If there is control-qubit and target-qubit,
control-qubit is the first argument. If an array of which the size is not known
comes, the size of that array follows.
Definition of update function is divided to named_gates,
single_target_qubit_gates, multiple_target_qubit_gates, QFT_gates
*/
#pragma once
#include "type.hpp"
#ifdef _OPENMP
#include <omp.h>
#endif
/** X gate **/
/**
* \~english
* Apply the Pauli X gate to the quantum state.
*
* Apply the Pauli X gate to the quantum state.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* パウリX演算を作用させて状態を更新。
*
* パウリX演算を作用させて状態を更新。
* @param[in] target_qubit_index 作用する量子ビットのインデックス。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void X_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void X_gate_parallel_unroll(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void X_gate_parallel_simd(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void X_gate_parallel_sve(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void X_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply the Pauli Y gate to the quantum state.
*
* Apply the Pauli Y gate to the quantum state.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* パウリY演算を作用させて状態を更新。
*
* パウリY演算を作用させて状態を更新。
* @param[in] target_qubit_index 作用する量子ビットのインデックス。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void Y_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void Y_gate_parallel_unroll(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void Y_gate_parallel_simd(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void Y_gate_parallel_sve(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void Y_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply the Pauli Z gate to the quantum state.
*
* Apply the Pauli Z gate to the quantum state.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* パウリZ演算を作用させて状態を更新。
*
* パウリZ演算を作用させて状態を更新。
* @param[in] target_qubit_index 作用する量子ビットのインデックス。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void Z_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void Z_gate_parallel_unroll(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void Z_gate_parallel_simd(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void Z_gate_parallel_sve(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void Z_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply S gate to the quantum state.
*
* Apply S gate to the quantum state.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 位相演算 S を作用させて状態を更新。
*
* 位相演算 S = diag(1,i) を作用させて状態を更新。
* @param[in] target_qubit_index 作用する量子ビットのインデックス。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void S_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void S_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT outer_qb);
/**
* \~english
* Apply S gate to the quantum state.
*
* Apply S gate to the quantum state.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 位相演算 S^dag を作用させて状態を更新。
*
* 位相演算 S^dag = diag(1,-i) を作用させて状態を更新。
* @param[in] target_qubit_index 作用する量子ビットのインデックス。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void Sdag_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void Sdag_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT outer_qb);
/**
* \~english
* Apply T gate to the quantum state.
*
* Apply T gate to the quantum state.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* T 演算を作用させて状態を更新。
*
* T 演算(pi/8演算)、 T = diag(1,exp(i pi/4))
* を作用させて状態を更新。非クリフォード演算。
* @param[in] target_qubit_index 作用する量子ビットのインデックス。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void T_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void T_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT outer_qb);
/**
* \~english
* Apply T^dag gate to the quantum state.
*
* Apply T^dag gate to the quantum state.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* T^dag 演算を作用させて状態を更新。
*
* T 演算のエルミート共役、 T^dag = diag(1,exp(-i pi/4))
* を作用させて状態を更新。非クリフォード演算。
* @param[in] target_qubit_index 作用する量子ビットのインデックス。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void Tdag_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void Tdag_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT outer_qb);
/**
* \~english
* Apply the square root of the X gate to the quantum state.
*
* Apply the square root of the X gate to the quantum state.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* パウリ X 演算子の平方根の演算子を作用させて状態を更新。
*
* パウリ X 演算子の平方根の演算子を作用させて状態を更新。非クリフォード演算。
* @param[in] target_qubit_index 作用する量子ビットのインデックス。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void sqrtX_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void sqrtX_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply hermitian conjugate of the square root of the X gate to the quantum
* state.
*
* Apply hermitian conjugate of the square root of the X gate to the quantum
* state.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* パウリ X 演算子の平方根に対してエルミート共役な演算子を作用させて状態を更新。
*
* パウリ X
* 演算子の平方根に対してエルミート共役な演算子を作用させて状態を更新。非クリフォード演算。
* @param[in] target_qubit_index 作用する量子ビットのインデックス。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void sqrtXdag_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void sqrtXdag_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply the square root of the Y gate to the quantum state.
*
* Apply the square root of the Y gate to the quantum state.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* パウリ Y 演算子の平方根の演算子を作用させて状態を更新。
*
* パウリ Y 演算子の平方根の演算子を作用させて状態を更新。非クリフォード演算。
* @param[in] target_qubit_index 作用する量子ビットのインデックス。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void sqrtY_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void sqrtY_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply hermitian conjugate of the square root of the Y gate to the quantum
* state.
*
* Apply hermitian conjugate of the square root of the Y gate to the quantum
* state.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* パウリ Y 演算子の平方根に対してエルミート共役な演算子を作用させて状態を更新。
*
* パウリ Y
* 演算子の平方根に対してエルミート共役な演算子を作用させて状態を更新。非クリフォード演算。
* @param[in] target_qubit_index 作用する量子ビットのインデックス。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void sqrtYdag_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void sqrtYdag_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply the Hadamard gate to the quantum state.
*
* Apply the Hadamard gate to the quantum state.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* アダマール演算子を作用させて状態を更新。
*
* アダマール演算子を作用させて状態を更新。
* @param[in] target_qubit_index 作用する量子ビットのインデックス。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void H_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void H_gate_parallel_unroll(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void H_gate_parallel_simd(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void H_gate_parallel_sve(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void H_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT inner_qc);
void _H_gate_mpi(CTYPE* t, CTYPE* si, ITYPE dim, int flag);
/** Hadamard gate multiplied sqrt(2) **/
// DllExport void H_gate_unnormalized(UINT target_qubit_index, CTYPE *state,
// ITYPE dim);
/**
* \~english
* Apply the CNOT gate to the quantum state.
*
* Apply the CNOT gate to the quantum state.
* @param[in] control_qubit_index index of control qubit
* @param[in] target_qubit_index index of target qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
* \~japanese-en
* CNOT演算を作用させて状態を更新。
*
* 2量子ビット演算、CNOT演算を作用させて状態を更新。
* @param[in] control_qubit_index 制御量子ビットのインデックス
* @param[in] target_qubit_index ターゲット量子ビットのインデックス
* @param[in,out] state 量子状態
* @param[in] dim 次元
*/
DllExport void CNOT_gate(
UINT control_qubit_index, UINT target_qubit_index, CTYPE* state, ITYPE dim);
void CNOT_gate_parallel_unroll(
UINT control_qubit_index, UINT target_qubit_index, CTYPE* state, ITYPE dim);
void CNOT_gate_parallel_simd(
UINT control_qubit_index, UINT target_qubit_index, CTYPE* state, ITYPE dim);
void CNOT_gate_parallel_sve(
UINT control_qubit_index, UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void CNOT_gate_mpi(UINT control_qubit_index, UINT target_qubit_index,
CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply the CZ gate to the quantum state.
*
* Apply the CZ gate to the quantum state.
* @param[in] control_qubit_index index of control qubit
* @param[in] target_qubit_index index of target qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
* \~japanese-en
* CZ演算を作用させて状態を更新。
*
* 2量子ビット演算、CZ演算を作用させて状態を更新。制御量子ビットとターゲット量子ビットに対して対称に作用(インデックスを入れ替えても同じ作用)。
* @param[in] control_qubit_index 制御量子ビットのインデックス
* @param[in] target_qubit_index ターゲット量子ビットのインデックス
* @param[in,out] state 量子状態
* @param[in] dim 次元
*/
DllExport void CZ_gate(
UINT control_qubit_index, UINT target_qubit_index, CTYPE* state, ITYPE dim);
void CZ_gate_parallel_unroll(
UINT control_qubit_index, UINT target_qubit_index, CTYPE* state, ITYPE dim);
void CZ_gate_parallel_simd(
UINT control_qubit_index, UINT target_qubit_index, CTYPE* state, ITYPE dim);
void CZ_gate_parallel_sve(
UINT control_qubit_index, UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void CZ_gate_mpi(UINT control_qubit_index, UINT target_qubit_index,
CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply the SWAP to the quantum state.
*
* Apply the SWAP to the quantum state.
* @param[in] control_qubit_index index of control qubit
* @param[in] target_qubit_index index of target qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
* \~japanese-en
* SWAP演算を作用させて状態を更新。
*
* 2量子ビット演算、SWAP演算を作用させて状態を更新。2つの量子ビットに対して対称に作用する(インデックスを入れ替えても同じ作用)。
* @param[in] target_qubit_index_0 作用する量子ビットのインデックス
* @param[in] target_qubit_index_1 作用する量子ビットのインデックス
* @param[in,out] state 量子状態
* @param[in] dim 次元
*/
DllExport void SWAP_gate(UINT target_qubit_index_0, UINT target_qubit_index_1,
CTYPE* state, ITYPE dim);
void SWAP_gate_parallel_unroll(UINT target_qubit_index_0,
UINT target_qubit_index_1, CTYPE* state, ITYPE dim);
void SWAP_gate_parallel_simd(UINT target_qubit_index_0,
UINT target_qubit_index_1, CTYPE* state, ITYPE dim);
void SWAP_gate_parallel_sve(UINT target_qubit_index_0,
UINT target_qubit_index_1, CTYPE* state, ITYPE dim);
DllExport void SWAP_gate_mpi(UINT target_qubit_index_0,
UINT target_qubit_index_1, CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply the FusedSWAP to the quantum state.
*
* Apply the FusedSWAP to the quantum state.
* @param[in] control_qubit_index index of start target-0 qubit
* @param[in] target_qubit_index index of start target-1 qubit
* @param[in] number_qubits number of target qubits
* @param[in,out] state quantum state
* @param[in] dim dimension
*
* \~japanese-en
* FusedSWAP演算を作用させて状態を更新。
*
* (2n)量子ビット演算、FusedSWAP演算を作用させて状態を更新。block_size個の2つの量子ビットに対して対称に作用する(インデックスを入れ替えても同じ作用)。
* @param[in] target_qubit_index_0 作用する量子ビットの最初のインデックス
* @param[in] target_qubit_index_1 作用する量子ビットの最初のインデックス
* @param[in] block_size 作用する量子ビット数
* @param[in,out] state 量子状態
* @param[in] dim 次元
*/
DllExport void FusedSWAP_gate(UINT target_qubit_index_0,
UINT target_qubit_index_1, UINT block_size, CTYPE* state, ITYPE dim);
void FusedSWAP_gate_global(UINT target_qubit_index_0, UINT target_qubit_index_1,
UINT block_size, CTYPE* state, ITYPE dim);
DllExport void FusedSWAP_gate_mpi(UINT target_qubit_index_0,
UINT target_qubit_index_1, UINT block_size, CTYPE* state, ITYPE dim,
UINT inner_qc);
/**
* \~english
* Project the quantum state to the 0 state.
*
* Project the quantum state to the 0 state. The output state is not normalized.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
* \~japanese-en
* 0状態への射影
*
* 0状態への射影演算子 |0><0|
* を作用させて状態を更新する。ノルムは規格化されない。
* @param[in] target_qubit_index 作用する量子ビットのインデックス
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void P0_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void P0_gate_parallel(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void P0_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Project the quantum state to the 1 state.
*
* Project the quantum state to the 1 state. The output state is not normalized.
* @param[in] target_qubit_index index of the qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*
* \~japanese-en
* 1状態への射影
*
* 1状態への射影演算子 |1><1|
* を作用させて状態を更新する。ノルムは規格化されない。
* @param[in] target_qubit_index 作用する量子ビットのインデックス
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void P1_gate(UINT target_qubit_index, CTYPE* state, ITYPE dim);
void P1_gate_parallel(UINT target_qubit_index, CTYPE* state, ITYPE dim);
DllExport void P1_gate_mpi(
UINT target_qubit_index, CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Normalize the quantum state.
*
* Normalize the quantum state by multiplying the normalization factor
* 1/sqrt(norm).
* @param[in] norm norm of the state
* @param[in,out] state quantum state
* @param[in] dim dimension
*
* \~japanese-en
* 状態を規格化
*
* 状態に対して 1/sqrt(norm) 倍をする。norm
* が量子状態のノルムである場合にはノルムが1になるように規格化される。
* @param[in] norm ノルム
* @param[in,out] state 量子状態
* @param[in] dim 次元
*/
DllExport void normalize(double squared_norm, CTYPE* state, ITYPE dim);
/**
* \~english
* Normalize the quantum state.
*
* Normalize the quantum state by multiplying the normalization factor
* 1/sqrt(norm).
* @param[in] norm norm of the state
* @param[in,out] state quantum state
* @param[in] dim dimension
*
* \~japanese-en
* 状態を規格化
*
* 状態に対して 1/sqrt(norm) 倍をする。norm
* が量子状態のノルムである場合にはノルムが1になるように規格化される。
* @param[in] norm ノルム
* @param[in,out] state 量子状態
* @param[in] dim 次元
*/
DllExport void normalize_single_thread(
double squared_norm, CTYPE* state, ITYPE dim);
/**
* \~english
* Apply a X rotation gate by angle to the quantum state.
*
* Apply a X rotation gate by angle to the quantum state.
* @param[in] target_qubit_index index of the qubit
* @param[in] angle angle of the rotation
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* X軸の回転演算を作用させて状態を更新
*
* X軸の回転演算
*
* cos (angle/2) I + i sin (angle/2) X
*
* を作用させて状態を更新。angleは回転角。
* @param[in] target_qubit_index 量子ビットのインデックス
* @param[in] angle 回転角
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void RX_gate(
UINT target_qubit_index, double angle, CTYPE* state, ITYPE dim);
DllExport void RX_gate_mpi(UINT target_qubit_index, double angle, CTYPE* state,
ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply a Y rotation gate by angle to the quantum state.
*
* Apply a Y rotation gate by angle to the quantum state.
* @param[in] target_qubit_index index of the qubit
* @param[in] angle angle of the rotation
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* Y軸の回転演算を作用させて状態を更新
*
* Y軸の回転演算
*
* cos (angle/2) I + i sin (angle/2) Y
*
* を作用させて状態を更新。angleは回転角。
* @param[in] target_qubit_index 量子ビットのインデックス
* @param[in] angle 回転角
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void RY_gate(
UINT target_qubit_index, double angle, CTYPE* state, ITYPE dim);
DllExport void RY_gate_mpi(UINT target_qubit_index, double angle, CTYPE* state,
ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply a Z rotation gate by angle to the quantum state.
*
* Apply a Z rotation gate by angle to the quantum state.
* @param[in] target_qubit_index index of the qubit
* @param[in] angle angle of the rotation
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* Z軸の回転演算を作用させて状態を更新
*
* Z軸の回転演算
*
* cos (angle/2) I + i sin (angle/2) Z
*
* を作用させて状態を更新。angleは回転角。
* @param[in] target_qubit_index 量子ビットのインデックス
* @param[in] angle 回転角
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void RZ_gate(
UINT target_qubit_index, double angle, CTYPE* state, ITYPE dim);
DllExport void RZ_gate_mpi(UINT target_qubit_index, double angle, CTYPE* state,
ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply a single-qubit Pauli operator to the quantum state.
*
* Apply a single-qubit Pauli operator to the quantum state. Pauli_operator_type
* must be 0,1,2,3 corresponding to the Pauli I, X, Y, Z operators respectively.
*
*
* @param[in] target_qubit_index index of the qubit
* @param[in] Pauli_operator_type type of the Pauli operator 0,1,2,3
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* パウリ演算子を作用させて状態を更新
*
* パウリ演算子を作用させて状態を更新。Pauli_operator_type はパウリ演算子 I, X,
* Y, Z に対応して 0,1,2,3 を指定。
* @param[in] target_qubit_index 量子ビットのインデックス
* @param[in] Pauli_operator_type
* 作用するパウリ演算子のタイプ、0,1,2,3。それぞれI, X, Y, Zに対応。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*
*/
DllExport void single_qubit_Pauli_gate(
UINT target_qubit_index, UINT Pauli_operator_type, CTYPE* state, ITYPE dim);
// Not implemented for multi-cpu
/**
* \~english
* Apply a single-qubit Pauli rotation operator to the quantum state.
*
* Apply a single-qubit Pauli rotation operator to the quantum state.
* Pauli_operator_type must be 0,1,2,3 corresponding to the Pauli I, X, Y, Z
* operators respectively.
*
*
* @param[in] target_qubit_index index of the qubit
* @param[in] Pauli_operator_type type of the Pauli operator 0,1,2,3
* @param[in] angle rotation angle
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* パウリ演算子の回転演算を作用させて状態を更新
*
* パウリ演算子 A = I, X, Y, Zに対する回転角 angle の回転演算
*
* cos (angle/2) I + i sin (angle/2) A
*
* を作用させて状態を更新。Pauli_operator_type はパウリ演算子 I, X, Y, Z
* に対応して 0,1,2,3 を指定。
* @param[in] target_qubit_index 量子ビットのインデックス
* @param[in] Pauli_operator_type
* 作用するパウリ演算子のタイプ、0,1,2,3。それぞれI, X, Y, Zに対応。
* @param[in] angle 回転角
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*
*/
DllExport void single_qubit_Pauli_rotation_gate(UINT target_qubit_index,
UINT Pauli_operator_index, double angle, CTYPE* state, ITYPE dim);
// Not implemented for multi-cpu
/**
* \~english
* Apply a single-qubit dense operator to the quantum state.
*
* Apply a single-qubit dense operator to the quantum state.
*
* @param[in] target_qubit_index index of the qubit
* @param[in] matrix[4] description of the dense matrix as one-dimensional array
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 任意の1量子ビット演算を作用させて状態を更新
*
* 任意の1量子ビット演算を作用させて状態を更新。1量子ビット演算は、4つの要素をもつ1次元配列
* matrix[4] によって指定される。
*
* 例)パウリX演算子:{0, 1, 1,
* 0}、アダマール演算子:{1/sqrt(2),1/sqrt(2),1/sqrt(2),-1/sqrt(2)}。
*
* @param[in] target_qubit_index 量子ビットのインデックス
* @param[in] matrix[4] 1量子ビット演算を指定する4次元配列
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void single_qubit_dense_matrix_gate(
UINT target_qubit_index, const CTYPE matrix[4], CTYPE* state, ITYPE dim);
void single_qubit_dense_matrix_gate_parallel_unroll(
UINT target_qubit_index, const CTYPE matrix[4], CTYPE* state, ITYPE dim);
void single_qubit_dense_matrix_gate_parallel(
UINT target_qubit_index, const CTYPE matrix[4], CTYPE* state, ITYPE dim);
void single_qubit_dense_matrix_gate_parallel_simd(
UINT target_qubit_index, const CTYPE matrix[4], CTYPE* state, ITYPE dim);
void single_qubit_dense_matrix_gate_parallel_sve(
UINT target_qubit_index, const CTYPE matrix[4], CTYPE* state, ITYPE dim);
DllExport void single_qubit_dense_matrix_gate_mpi(UINT target_qubit_index,
const CTYPE matrix[4], CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply a single-qubit diagonal operator to the quantum state.
*
* Apply a single-qubit diagonal operator to the quantum state.
*
* @param[in] target_qubit_index index of the qubit
* @param[in] diagonal_matrix[2] description of the single-qubit diagonal
* elements
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 1量子ビットの対角演算を作用させて状態を更新
*
* 1量子ビットの対角演算を作用させて状態を更新。1量子ビットの対角演算は、その対角成分を定義する2つの要素から成る1次元配列
* diagonal_matrix[2] によって指定される。
*
* @param[in] target_qubit_index 量子ビットのインデックス
* @param[in] diagonal_matrix[2] 2つの対角成分を定義する1次元配列
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void single_qubit_diagonal_matrix_gate(UINT target_qubit_index,
const CTYPE diagonal_matrix[2], CTYPE* state, ITYPE dim);
void single_qubit_diagonal_matrix_gate_parallel_unroll(UINT target_qubit_index,
const CTYPE diagonal_matrix[2], CTYPE* state, ITYPE dim);
void single_qubit_diagonal_matrix_gate_parallel_simd(UINT target_qubit_index,
const CTYPE diagonal_matrix[2], CTYPE* state, ITYPE dim);
void single_qubit_diagonal_matrix_gate_parallel_sve(UINT target_qubit_index,
const CTYPE diagonal_matrix[2], CTYPE* state, ITYPE dim);
DllExport void single_qubit_diagonal_matrix_gate_mpi(UINT target_qubit_index,
const CTYPE diagonal_matrix[2], CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply a single-qubit phase operator to the quantum state.
*
* Apply a single-qubit phase operator, diag(1,phsae), to the quantum state.
*
* @param[in] target_qubit_index index of the qubit
* @param[in] phase phase factor
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 1量子ビットの一般位相演算を作用させて状態を更新
*
* 1量子ビットの一般位相演算 diag(1,phase) を作用させて状態を更新。|1>状態が
* phase 倍される。
*
* @param[in] target_qubit_index 量子ビットのインデックス
* @param[in] phase 位相因子
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void single_qubit_phase_gate(
UINT target_qubit_index, CTYPE phase, CTYPE* state, ITYPE dim);
void single_qubit_phase_gate_parallel_unroll(
UINT target_qubit_index, CTYPE phase, CTYPE* state, ITYPE dim);
void single_qubit_phase_gate_parallel_simd(
UINT target_qubit_index, CTYPE phase, CTYPE* state, ITYPE dim);
DllExport void single_qubit_phase_gate_mpi(UINT target_qubit_index, CTYPE phase,
CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply a single-qubit controlled single-qubit gate.
*
* Apply a single-qubit controlled single-qubit gate.
*
* @param[in] control_qubit_index index of the control qubit
* @param[in] control_value value of the control qubit
* @param[in] target_qubit_index index of the target qubit
* @param[in] matrix[4] description of the single-qubit dense matrix
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 単一量子ビットを制御量子ビットとする単一量子ビット演算
*
* 単一量子ビットを制御量子ビットとする単一量子ビット演算。制御量子ビット |0>
* もしくは |1>のどちらの場合に作用するかは control_value = 0,1
* によって指定。作用する単一量子ビット演算は matrix[4]
* によって1次元配列として定義。
*
* @param[in] control_qubit_index 制御量子ビットのインデックス
* @param[in] control_value 制御量子ビットの値
* @param[in] target_qubit_index ターゲット量子ビットのインデックス
* @param[in] matrix[4] 単一量子ビットの記述を与える1次元配列
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void single_qubit_control_single_qubit_dense_matrix_gate(
UINT control_qubit_index, UINT control_value, UINT target_qubit_index,
const CTYPE matrix[4], CTYPE* state, ITYPE dim);
void single_qubit_control_single_qubit_dense_matrix_gate_unroll(
UINT control_qubit_index, UINT control_value, UINT target_qubit_index,
const CTYPE matrix[4], CTYPE* state, ITYPE dim);
void single_qubit_control_single_qubit_dense_matrix_gate_simd(
UINT control_qubit_index, UINT control_value, UINT target_qubit_index,
const CTYPE matrix[4], CTYPE* state, ITYPE dim);
void single_qubit_control_single_qubit_dense_matrix_gate_sve512(
UINT control_qubit_index, UINT control_value, UINT target_qubit_index,
const CTYPE matrix[4], CTYPE* state, ITYPE dim);
DllExport void single_qubit_control_single_qubit_dense_matrix_gate_mpi(
UINT control_qubit_index, UINT control_value, UINT target_qubit_index,
const CTYPE matrix[4], CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply a multi-qubit controlled single-qubit gate.
*
* Apply a multi-qubit controlled single-qubit gate.
*
* @param[in] control_qubit_index_list list of the indexes of the control qubits
* @param[in] control_value_list list of the vlues of the control qubits
* @param[in] control_qubit_index_count the number of the control qubits
* @param[in] target_qubit_index index of the target qubit
* @param[in] matrix[4] description of the single-qubit dense matrix
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 複数量子ビットを制御量子ビットとする単一量子ビット演算
*
* 複数量子ビットを制御量子ビットとする単一量子ビット演算。control_qubit_index_count
* 個の制御量子ビットについて、どの状態の場合に制御演算が作用するかは
* control_value_list によって指定。作用する単一量子ビット演算は matrix[4]
* によって1次元配列として定義。
*
* @param[in] control_qubit_index_list 制御量子ビットのインデックスのリスト
* @param[in] control_value_list 制御演算が作用する制御量子ビットの値のリスト
* @param[in] control_qubit_index_count 制御量子ビットの数
* @param[in] target_qubit_index ターゲット量子ビットのインデックス
* @param[in] matrix[4] 単一量子ビットの記述を与える1次元配列
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void multi_qubit_control_single_qubit_dense_matrix_gate(
const UINT* control_qubit_index_list, const UINT* control_value_list,
UINT control_qubit_index_count, UINT target_qubit_index,
const CTYPE matrix[4], CTYPE* state, ITYPE dim);
void multi_qubit_control_single_qubit_dense_matrix_gate_unroll(
const UINT* control_qubit_index_list, const UINT* control_value_list,
UINT control_qubit_index_count, UINT target_qubit_index,
const CTYPE matrix[4], CTYPE* state, ITYPE dim);
void multi_qubit_control_single_qubit_dense_matrix_gate_simd(
const UINT* control_qubit_index_list, const UINT* control_value_list,
UINT control_qubit_index_count, UINT target_qubit_index,
const CTYPE matrix[4], CTYPE* state, ITYPE dim);
DllExport void multi_qubit_control_single_qubit_dense_matrix_gate_mpi(
const UINT* control_qubit_index_list, const UINT* control_value_list,
UINT control_qubit_index_count, UINT target_qubit_index,
const CTYPE matrix[4], CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply multi-qubit Pauli operator to the quantum state with a whole list.
*
* Apply multi-qubit Pauli operator to the quantum state with a whole list of
* the Pauli operators. Pauli_operator_type_list must be a list of n single
* Pauli operators.
*
* @param[in] Pauli_operator_type_list list of {0,1,2,3} corresponding to I, X,
* Y, Z for all qubits
* @param[in] qubit_count the number of the qubits
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* すべての量子ビットに多体のパウリ演算子を作用させて状態を更新
*
* 全ての量子ビットに対するパウリ演算子を与えて、多体のパウリ演算子を作用させて状態を更新。Pauli_operator_type_list
* には全ての量子ビットに対するパウリ演算子を指定。
*
* 例)5量子ビット系の3つめの量子ビットへのX演算、4つめの量子ビットへのZ演算、IZXII:{0,0,1,3,0}(量子ビットの順番は右から数えている)
*
* @param[in] Pauli_operator_type_list 長さ qubit_count の {0,1,2,3} のリスト。
* 0,1,2,3 はそれぞれパウリ演算子 I, X, Y, Z に対応。
* @param[in] qubit_count 量子ビットの数
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void multi_qubit_Pauli_gate_whole_list(
const UINT* Pauli_operator_type_list, UINT qubit_count, CTYPE* state,
ITYPE dim_);
// Not implemented for multi-cpu
/**
* \~english
* Apply multi-qubit Pauli operator to the quantum state with a whole list.
*
* Apply multi-qubit Pauli operator to the quantum state with a whole list of
* the Pauli operators. Pauli_operator_type_list must be a list of n single
* Pauli operators.
*
* @param[in] Pauli_operator_type_list list of {0,1,2,3} corresponding to I, X,
* Y, Z for all qubits
* @param[in] qubit_count the number of the qubits
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* すべての量子ビットに多体のパウリ演算子を作用させて状態を更新
*
* 全ての量子ビットに対するパウリ演算子を与えて、多体のパウリ演算子を作用させて状態を更新。Pauli_operator_type_list
* には全ての量子ビットに対するパウリ演算子を指定。
*
* 例)5量子ビット系の3つめの量子ビットへのX演算、4つめの量子ビットへのZ演算、IZXII:{0,0,1,3,0}(量子ビットの順番は右から数えている)
*
* @param[in] Pauli_operator_type_list 長さ qubit_count の {0,1,2,3} のリスト。
* 0,1,2,3 はそれぞれパウリ演算子 I, X, Y, Z に対応。
* @param[in] qubit_count 量子ビットの数
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void multi_qubit_Pauli_gate_whole_list_single_thread(
const UINT* Pauli_operator_type_list, UINT qubit_count, CTYPE* state,
ITYPE dim_);
// Not implemented for multi-cpu
/**
* \~english
* Apply multi-qubit Pauli operator to the quantum state with a partial list.
*
* Apply multi-qubit Pauli operator to the quantum state with a partial list of
* the Pauli operators. Pauli_operator_type_list must be a list of n single
* Pauli operators.
*
* @param[in] target_qubit_index_list list of the target qubits
* @param[in] Pauli_operator_type_list list of {0,1,2,3} corresponding to I, X,
* Y, Z for the target qubits
* @param[in] target_qubit_index_count the number of the target qubits
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* すべての量子ビットに多体のパウリ演算子を作用させて状態を更新
*
* 全ての量子ビットに対するパウリ演算子を与えて、多体のパウリ演算子を作用させて状態を更新。Pauli_operator_type_list
* には全ての量子ビットに対するパウリ演算子を指定。
*
* 例)5量子ビット系の3つめの量子ビットへのX演算、4つめの量子ビットへのZ演算、IZXII:Pauli_operator_type_list
* ={2,3}, Pauli_operator_type_list
* ={1,3}(量子ビットの順番は右から数えている).
*
* @param[in] target_qubit_index_list 作用する量子ビットのインデックスのリスト。
* @param[in] Pauli_operator_type_list
* 作用する量子ビットのみに対するパウリ演算子を指定する、長さ
* target_qubit_index_count の{0,1,2,3}のリスト。0,1,2,3 はそれぞれパウリ演算子
* I, X, Y, Z に対応。
* @param[in] target_qubit_index_count 作用する量子ビットの数
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void multi_qubit_Pauli_gate_partial_list(
const UINT* target_qubit_index_list, const UINT* Pauli_operator_type_list,
UINT target_qubit_index_count, CTYPE* state, ITYPE dim);
// This function is used in apply_to_state and gate_noisy_evolution
// TODO: multi_qubit_Pauli_gate_partial_list is not implemented for multi-cpu
// yet
/**
* \~english
* Apply multi-qubit Pauli operator to the quantum state with a partial list.
*
* Apply multi-qubit Pauli operator to the quantum state with a partial list of
* the Pauli operators. Pauli_operator_type_list must be a list of n single
* Pauli operators.
*
* @param[in] target_qubit_index_list list of the target qubits
* @param[in] Pauli_operator_type_list list of {0,1,2,3} corresponding to I, X,
* Y, Z for the target qubits
* @param[in] target_qubit_index_count the number of the target qubits
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* すべての量子ビットに多体のパウリ演算子を作用させて状態を更新
*
* 全ての量子ビットに対するパウリ演算子を与えて、多体のパウリ演算子を作用させて状態を更新。Pauli_operator_type_list
* には全ての量子ビットに対するパウリ演算子を指定。
*
* 例)5量子ビット系の3つめの量子ビットへのX演算、4つめの量子ビットへのZ演算、IZXII:Pauli_operator_type_list
* ={2,3}, Pauli_operator_type_list
* ={1,3}(量子ビットの順番は右から数えている).
*
* @param[in] target_qubit_index_list 作用する量子ビットのインデックスのリスト。
* @param[in] Pauli_operator_type_list
* 作用する量子ビットのみに対するパウリ演算子を指定する、長さ
* target_qubit_index_count の{0,1,2,3}のリスト。0,1,2,3 はそれぞれパウリ演算子
* I, X, Y, Z に対応。
* @param[in] target_qubit_index_count 作用する量子ビットの数
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void multi_qubit_Pauli_gate_partial_list_single_thread(
const UINT* target_qubit_index_list, const UINT* Pauli_operator_type_list,
UINT target_qubit_index_count, CTYPE* state, ITYPE dim);
// This function is used in gate_noisy_evolution
// TODO: multi_qubit_Pauli_gate_partial_list_single_thread is not implemented
// for multi-cpu yet
/**
* \~english
* Apply multi-qubit Pauli rotation operator to the quantum state with a whole
* list.
*
* Apply multi-qubit Pauli rotation operator to state with a whole list of the
* Pauli operators. Pauli_operator_type_list must be a list of n single Pauli
* operators. Update a quantum state with a mutliple qubits Pauli rotation, cos
* (angle/2 ) I + i sin ( angle/2 ) A, where A is the Pauli operator specified
* by Pauli_operator.
*
* @param[in] Pauli_operator_type_list array of {0,1,2,3} of the length
* n_qubits. 0,1,2,3 corresponds to i,x,y,z
* @param[in] qubit_count number of the qubits
* @param[in] angle rotation angle
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 複数量子ビット(全て指定)のパウリ演算子による回転演算を用いて状態を更新。
*
* 複数量子ビット(全て指定)のパウリ演算子 A による回転演算
*
* cos ( angle/2 ) I + i sin ( angle/2 ) A
*
* を用いて状態を更新。Pauli_operator_type_list
* は全ての量子ビットに対するパウリ演算子のリスト。パウリ演算子はI, X, Y,
* Zがそれぞれ 0,1,2,3 に対応。
*
* 例) 5量子ビットに対する YIZXI
* の場合は、{0,1,3,0,2}(量子ビットの順番は右から数えている)。
*
* @param[in] Pauli_operator_type_list 長さ qubit_count の {0,1,2,3} のリスト。
* 0,1,2,3 はそれぞれパウリ演算子 I, X, Y, Z に対応。
* @param[in] qubit_count 量子ビットの数
* @param[in] angle 回転角度
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void multi_qubit_Pauli_rotation_gate_whole_list(
const UINT* Pauli_operator_type_list, UINT qubit_count, double angle,
CTYPE* state, ITYPE dim_);
// Not implemented for multi-cpu
/**
* \~english
* Apply multi-qubit Pauli rotation operator to the quantum state with a whole
* list.
*
* Apply multi-qubit Pauli rotation operator to state with a whole list of the
* Pauli operators. Pauli_operator_type_list must be a list of n single Pauli
* operators. Update a quantum state with a mutliple qubits Pauli rotation, cos
* (angle/2 ) I + i sin ( angle/2 ) A, where A is the Pauli operator specified
* by Pauli_operator.
*
* @param[in] Pauli_operator_type_list array of {0,1,2,3} of the length
* n_qubits. 0,1,2,3 corresponds to i,x,y,z
* @param[in] qubit_count number of the qubits
* @param[in] angle rotation angle
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 複数量子ビット(全て指定)のパウリ演算子による回転演算を用いて状態を更新。
*
* 複数量子ビット(全て指定)のパウリ演算子 A による回転演算
*
* cos ( angle/2 ) I + i sin ( angle/2 ) A
*
* を用いて状態を更新。Pauli_operator_type_list
* は全ての量子ビットに対するパウリ演算子のリスト。パウリ演算子はI, X, Y,
* Zがそれぞれ 0,1,2,3 に対応。
*
* 例) 5量子ビットに対する YIZXI
* の場合は、{0,1,3,0,2}(量子ビットの順番は右から数えている)。
*
* @param[in] Pauli_operator_type_list 長さ qubit_count の {0,1,2,3} のリスト。
* 0,1,2,3 はそれぞれパウリ演算子 I, X, Y, Z に対応。
* @param[in] qubit_count 量子ビットの数
* @param[in] angle 回転角度
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void multi_qubit_Pauli_rotation_gate_whole_list_single_thread(
const UINT* Pauli_operator_type_list, UINT qubit_count, double angle,
CTYPE* state, ITYPE dim_);
// Not implemented for multi-cpu
/**
* \~english
* Apply multi-qubit Pauli rotation operator to the quantum state with a partial
* list.
*
* Apply multi-qubit Pauli rotation operator to state with a partial list of the
* Pauli operators.
*
* @param[in] target_qubit_index_list list of the target qubits
* @param[in] Pauli_operator_type_list list of {0,1,2,3} of length
* target_qubit_index_count. {0,1,2,3} corresponds to I, X, Y, Z for the target
* qubits.
* @param[in] target_qubit_index_count the number of the target qubits
* @param[in] angle rotation angle
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 複数量子ビット(部分的に指定)のパウリ演算子による回転演算を用いて状態を更新。
*
* 複数量子ビット(部分的に指定)のパウリ演算子 A による回転演算
*
* cos ( angle/2 ) I + i sin ( angle/2 ) A
*
* を用いて状態を更新。パウリ演算子Aは、target_qubit_index_list
* で指定される一部の量子ビットに対するパウリ演算子のリスト
* Pauli_operator_type_list
* によって定義。回転角には(1/2)の因子はついていない。パウリ演算子はI, X, Y,
* Zがそれぞれ 0,1,2,3 に対応。
*
* 例) 5量子ビットに対する YIZXI の場合は、target_qubit_index_list = {1,2,4},
* Pauli_operator_type_list = {1,3,2}(量子ビットの順番は右から数えている)。
*
* @param[in] target_qubit_index_list 作用する量子ビットのインデックス
* @param[in] Pauli_operator_type_list 長さ target_qubit_index_countの {0,1,2,3}
* のリスト。0,1,2,3は、それぞれパウリ演算子 I, X, Y, Z 対応。
* @param[in] target_qubit_index_count 作用する量子ビットの数
* @param[in] angle 回転角
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void multi_qubit_Pauli_rotation_gate_partial_list(
const UINT* target_qubit_index_list, const UINT* Pauli_operator_type_list,
UINT target_qubit_index_count, double angle, CTYPE* state, ITYPE dim);
// This function is used in ClsPauliRotationGate
// TODO: multi_qubit_Pauli_rotation_gate_partial_list is not implemented for
// multi-cpu yet
/**
* \~english
* Apply multi-qubit Pauli rotation operator to the quantum state with a partial
* list.
*
* Apply multi-qubit Pauli rotation operator to state with a partial list of the
* Pauli operators.
*
* @param[in] target_qubit_index_list list of the target qubits
* @param[in] Pauli_operator_type_list list of {0,1,2,3} of length
* target_qubit_index_count. {0,1,2,3} corresponds to I, X, Y, Z for the target
* qubits.
* @param[in] target_qubit_index_count the number of the target qubits
* @param[in] angle rotation angle
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 複数量子ビット(部分的に指定)のパウリ演算子による回転演算を用いて状態を更新。
*
* 複数量子ビット(部分的に指定)のパウリ演算子 A による回転演算
*
* cos ( angle/2 ) I + i sin ( angle/2 ) A
*
* を用いて状態を更新。パウリ演算子Aは、target_qubit_index_list
* で指定される一部の量子ビットに対するパウリ演算子のリスト
* Pauli_operator_type_list
* によって定義。回転角には(1/2)の因子はついていない。パウリ演算子はI, X, Y,
* Zがそれぞれ 0,1,2,3 に対応。
*
* 例) 5量子ビットに対する YIZXI の場合は、target_qubit_index_list = {1,2,4},
* Pauli_operator_type_list = {1,3,2}(量子ビットの順番は右から数えている)。
*
* @param[in] target_qubit_index_list 作用する量子ビットのインデックス
* @param[in] Pauli_operator_type_list 長さ target_qubit_index_countの {0,1,2,3}
* のリスト。0,1,2,3は、それぞれパウリ演算子 I, X, Y, Z 対応。
* @param[in] target_qubit_index_count 作用する量子ビットの数
* @param[in] angle 回転角
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void multi_qubit_Pauli_rotation_gate_partial_list_single_thread(
const UINT* target_qubit_index_list, const UINT* Pauli_operator_type_list,
UINT target_qubit_index_count, double angle, CTYPE* state, ITYPE dim);
// Not implemented for multi-cpu
/**
* \~english
* Apply a two-qubit arbitrary gate.
*
* Apply a two-qubit arbitrary gate defined by a dense matrix as a
* one-dimentional array matrix[].
* @param[in] target_qubit_index1 index of the first target qubit
* @param[in] target_qubit_index2 index of the second target qubit
* @param[in] matrix description of a multi-qubit gate as a one-dimensional
* array with length 16
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 任意の2量子ビット演算を作用させて状態を更新。
*
* 任意の2量子ビット演算を作用させて状態を更新。演算は、その行列成分を1次元配列として
* matrix[] で与える。(j,k)成分は、matrix[dim*j+k]に対応。
*
* @param[in] target_qubit_index1 作用する量子ビットの一つ目の添え字
* @param[in] target_qubit_index2 作用する量子ビットの二つ目の添え字
* @param[in] matrix 複数量子ビット演算を定義する長さ 16 の一次元配列。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void double_qubit_dense_matrix_gate_c(UINT target_qubit_index1,
UINT target_qubit_index2, const CTYPE matrix[16], CTYPE* state, ITYPE dim);
void double_qubit_dense_matrix_gate_nosimd(UINT target_qubit_index1,
UINT target_qubit_index2, const CTYPE matrix[16], CTYPE* state, ITYPE dim);
void double_qubit_dense_matrix_gate_simd(UINT target_qubit_index1,
UINT target_qubit_index2, const CTYPE matrix[16], CTYPE* state, ITYPE dim);
void double_qubit_dense_matrix_gate_sve(UINT target_qubit_index1,
UINT target_qubit_index2, const CTYPE matrix[16], CTYPE* state, ITYPE dim);
DllExport void double_qubit_dense_matrix_gate_mpi(UINT target_qubit_index1,
UINT target_qubit_index2, const CTYPE matrix[16], CTYPE* state, ITYPE dim,
UINT inner_qc);
/**
* \~english
* Apply a multi-qubit arbitrary gate.
*
* Apply a multi-qubit arbitrary gate defined by a dense matrix as a
* one-dimentional array matrix[].
* @param[in] target_qubit_index_list list of the target qubits
* @param[in] target_qubit_index_count the number of the target qubits
* @param[in] matrix description of a multi-qubit gate as a one-dimensional
* array
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 任意の複数量子ビット演算を作用させて状態を更新。
*
* 任意の複数量子ビット演算を作用させて状態を更新。演算は、その行列成分を1次元配列として
* matrix[] で与える。(j,k)成分は、matrix[dim*j+k]に対応。
*
* 例)パウリX演算子:{0, 1, 1,
* 0}、アダマール演算子:{1/sqrt(2),1/sqrt(2),1/sqrt(2),-1/sqrt(2)}、
*
* CNOT演算:
*
* {1,0,0,0,
*
* 0,1,0,0,
*
* 0,0,0,1,
*
* 0,0,1,0}
*
* @param[in] target_qubit_index_list 作用する量子ビットのリスト
* @param[in] target_qubit_index_count 作用する量子ビットの数
* @param[in] matrix 複数量子ビット演算を定義する長さ 2^(2*
* target_qubit_index_count) の一次元配列。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void multi_qubit_dense_matrix_gate(
const UINT* target_qubit_index_list, UINT target_qubit_index_count,
const CTYPE* matrix, CTYPE* state, ITYPE dim);
void multi_qubit_dense_matrix_gate_parallel(const UINT* target_qubit_index_list,
UINT target_qubit_index_count, const CTYPE* matrix, CTYPE* state,
ITYPE dim);
DllExport void multi_qubit_dense_matrix_gate_mpi(
const UINT* target_qubit_index_list, UINT target_qubit_index_count,
const CTYPE* matrix, CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply a single-qubit controlled multi-qubit gate.
*
* Apply a single-qubit controlled multi-qubit gate. The multi-qubit gate is by
* a dense matrix as a one-dimentional array matrix[].
* @param[in] control_qubit_index index of the control qubit
* @param[in] control_value value of the control qubit
* @param[in] target_qubit_index_list list of the target qubits
* @param[in] target_qubit_index_count the number of the target qubits
* @param[in] matrix description of a multi-qubit gate as a one-dimensional
* array
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 1つの制御量子ビットによる任意の複数量子ビット演算の制御演算を作用させて状態を更新。
*
* 1つの制御量子ビットによる任意の複数量子ビット演算の制御演算を作用させて状態を更新。制御量子ビットが
* 0 もしくは 1 のどちらの場合に作用するかは control_value
* によって指定。複数量子ビット演算は、その行列成分を1次元配列として matrix[]
* で与える。(j,k)成分は、matrix[dim*j+k]に対応。
*
* 例)パウリX演算子:{0, 1, 1,
* 0}、アダマール演算子:{1/sqrt(2),1/sqrt(2),1/sqrt(2),-1/sqrt(2)}、
*
* CNOT演算:
*
* {1,0,0,0,
*
* 0,1,0,0,
*
* 0,0,0,1,
*
* 0,0,1,0}
*
* @param[in] control_qubit_index 制御量子ビットのインデックス
* @param[in] control_value 制御量子ビットの値
* @param[in] target_qubit_index_list 作用する量子ビットのリスト
* @param[in] target_qubit_index_count 作用する量子ビットの数
* @param[in] matrix 複数量子ビット演算を定義する長さ 2^(2*
* target_qubit_index_count) の一次元配列。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void single_qubit_control_multi_qubit_dense_matrix_gate(
UINT control_qubit_index, UINT control_value,
const UINT* target_qubit_index_list, UINT target_qubit_index_count,
const CTYPE* matrix, CTYPE* state, ITYPE dim);
DllExport void single_qubit_control_multi_qubit_dense_matrix_gate_mpi(
UINT control_qubit_index, UINT control_value,
const UINT* target_qubit_index_list, UINT target_qubit_index_count,
const CTYPE* matrix, CTYPE* state, ITYPE dim, UINT inner_qc);
/**
* \~english
* Apply a multi-qubit controlled multi-qubit gate.
*
* Apply a multi-qubit controlled multi-qubit gate. The multi-qubit gate is by a
* dense matrix as a one-dimentional array matrix[].
*
* @param[in] control_qubit_index_list list of the indexes of the control qubits
* @param[in] control_value_list list of the vlues of the control qubits
* @param[in] target_qubit_index_list list of the target qubits
* @param[in] target_qubit_index_count the number of the target qubits
* @param[in] matrix description of a multi-qubit gate as a one-dimensional
* array
* @param[in,out] state quantum state
* @param[in] dim dimension
*
*
* \~japanese-en
* 複数の制御量子ビットによる任意の複数量子ビット演算の制御演算を作用させて状態を更新。
*
* 複数の制御量子ビットによる任意の複数量子ビット演算の制御演算を作用させて状態を更新。制御量子ビットは、control_qubit_index_listで指定され、制御演算が作用する
* control_qubit_index_count 個の制御量子ビットの値は、 control_value_list
* によって指定。複数量子ビット演算は、その行列成分を1次元配列として matrix[]
* で与える。(j,k)成分は、matrix[dim*j+k]に対応。
*
* 例)パウリX演算子:{0, 1, 1,
* 0}、アダマール演算子:{1/sqrt(2),1/sqrt(2),1/sqrt(2),-1/sqrt(2)}、
*
* CNOT演算:
*
* {1,0,0,0,
*
* 0,1,0,0,
*
* 0,0,0,1,
*
* 0,0,1,0}
*
* @param[in] control_qubit_index_list 制御量子ビットのインデックスのリスト
* @param[in] control_value_list 制御演算が作用する制御量子ビットの値のリスト
* @param[in] control_qubit_index_count 制御量子ビットの数
* @param[in] target_qubit_index_list ターゲット量子ビットのリスト
* @param[in] target_qubit_index_count ターゲット量子ビットの数
* @param[in] matrix 複数量子ビット演算を定義する長さ
* 2^(2*target_qubit_index_count) の一次元配列。
* @param[in,out] state 量子状態
* @param[in] dim 次元
*
*/
DllExport void multi_qubit_control_multi_qubit_dense_matrix_gate(
const UINT* control_qubit_index_list, const UINT* control_value_list,
UINT control_qubit_index_count, const UINT* target_qubit_index_list,
UINT target_qubit_index_count, const CTYPE* matrix, CTYPE* state,
ITYPE dim);
void multi_qubit_control_multi_qubit_dense_matrix_gate_mpi(
const UINT* control_qubit_index_list, const UINT* control_value_list,
UINT control_qubit_index_count, const UINT* target_qubit_index_list,
UINT target_qubit_index_count, const CTYPE* matrix, CTYPE* state, ITYPE dim,
UINT inner_qc);
/**
* Diagonal gate
**/
DllExport void multi_qubit_diagonal_matrix_gate(
const UINT* target_qubit_index_list, UINT target_qubit_index_count,
const CTYPE* diagonal_element, CTYPE* state, ITYPE dim);
// Not implemented for multi-cpu
DllExport void multi_qubit_control_multi_qubit_diagonal_matrix_gate(
const UINT* control_qubit_index_list, const UINT* control_value_list,
UINT control_qubit_index_count, const UINT* target_qubit_index_list,
UINT target_qubit_index_count, const CTYPE* diagonal_element, CTYPE* state,
ITYPE dim);
// Not implemented for multi-cpu
/**
* \~english
* Reflect state according to another given state.
*
* Reflect state according to another given state. When reflect quantum state
* |a> to state |s>, unitary operator give by 2|s><s|-I is applied to |a>.
*
* @param[in] reflection_state quantum state to characterize reflection unitary
* operator
* @param[in,out] state quantum state to update
* @param[in] dim dimension
*
*
* \~japanese-en
* reflection gateを作用する。
*
* 与えられた状態にreflection
* gateを作用する。量子状態|a>を量子状態|s>に関してreflectするとは、量子状態|a>に対して2|s><s|-Iというユニタリ操作をすることに対応する。
*
* @param[in] reflection_state reflection gateのユニタリを特徴づける量子状態
* @param[in,out] state quantum 更新する量子状態
* @param[in] dim 次元
*
*/
DllExport void reflection_gate(
const CTYPE* reflection_state, CTYPE* state, ITYPE dim);
// This function is used in ClsStateReflectionGate
// TODO: reflection_gate is not implemented for multi-cpu yet
DllExport void state_add(const CTYPE* state_added, CTYPE* state, ITYPE dim);
DllExport void state_add_with_coef(
CTYPE coef, const CTYPE* state_added, CTYPE* state, ITYPE dim);
DllExport void state_add_with_coef_single_thread(
CTYPE coef, const CTYPE* state_added, CTYPE* state, ITYPE dim);
DllExport void state_multiply(CTYPE coef, CTYPE* state, ITYPE dim);
////////////////////////////////
/// QFT
/**
* update quantum state with one-qubit controlled dense matrix gate
*
* update quantum state with one-qubit controlled dense matrix gate
* @param[in] angle rotation angle
* @param[in] c_bit index of control qubit
* @param[in] t_bit index of target qubit
* @param[in,out] state quantum state
* @param[in] dim dimension
*/
DllExport void CUz_gate(
double angle, UINT c_bit, UINT t_bit, CTYPE* state, ITYPE dim);
// TODO: CUz_gate is not implemented for multi-cpu yet
/**
* update quantum state with large dense matrix
*
* update quantum state with large dense matrix
* @param[in] k ???
* @param[in] Nbits the number of qubits
* @param[in] doSWAP ???
* @param[in,out] state quantum state
* @param[in] dim dimension
*/
DllExport void qft(UINT k, UINT Nbits, int doSWAP, CTYPE* state, ITYPE dim);
// TODO: qft is not implemented for multi-cpu yet
/**
* update quantum state with large dense matrix
*
* update quantum state with large dense matrix
* @param[in] k ???
* @param[in] Nbits the number of qubits
* @param[in] doSWAP ???
* @param[in,out] state quantum state
* @param[in] dim dimension
*/
DllExport void inverse_qft(
UINT k, UINT Nbits, int doSWAP, CTYPE* state, ITYPE dim);
// TODO: inverse_qft is not implemented for multi-cpu yet
| true |
07c4102b3494b1eff3f4570911650d47281ba0ee | C++ | bmihaljevic/bnclassify | /inst/include/infer.h | UTF-8 | 5,457 | 2.921875 | 3 | [] | no_license | #ifndef bnclassify_infer_H
#define bnclassify_infer_H
#include <Rcpp.h>
#include <cmath>
#include <basic-misc.h>
#include <multidim-array.h>
/**
* All CPT internal logics and rules here.
* Users of this class should not need to think of dimnames and similar, just of variables, features, etc.
* It hold the log of original CPT entries.
* TODO: rather than giving access to entries, I should let them index thrugh the CPT, but not get to the underlying storage.
*/
class CPT {
private:
Rcpp::CharacterVector variables;
Rcpp::CharacterVector features;
std::vector<double> entries;
std::vector<int> dimprod;
public:
// Do not store the class, though. Just the features.
CPT(const Rcpp::NumericVector & cpt, const std::string & class_var);
const std::vector<double> & get_entries() const {
return entries;
}
// TODO: maybe remove this one
const Rcpp::CharacterVector & get_variables() const {
return variables;
}
const Rcpp::CharacterVector & get_features() const {
return features;
}
// Returns the cumulative product of the dimensions
const std::vector<int> & get_dimprod() const {
return dimprod;
}
};
/**
* Wraps a bnc fit model.
* Provide features, class name.
* makes a copy of cpts and logs entires after the copies. Keeps only these copies.
* Call R functions to extract those data from the CPT, to avoid re-implementing things.
*/
class Model {
private:
Rcpp::CharacterVector features;
Rcpp::CharacterVector class_var;
Rcpp::CharacterVector classes;
std::vector<CPT> cpts;
// int nclass = -1;
// int ind_class = -1;
int nclass;
int ind_class;
public:
Model(Rcpp::List model);
const CPT & get_cpt(int i) const {
return this->cpts.at(i);
}
// TODO: const return and reference!
Rcpp::CharacterVector getFeatures() const {
return this->features;
}
Rcpp::CharacterVector getClassVar() const {
return this->class_var;
}
const Rcpp::CharacterVector & get_classes() const {
return this->classes;
}
const CPT & getClassCPT() const {
return this->cpts.at(ind_class);
}
//n excludes the class
std::size_t get_n() const {
return features.size();
}
int get_nclass() const {
return nclass;
}
};
/**
* Holds the data with evidence for inference.
* Current implementation holds a copy of the underlying data and thus only a single instance should exist per call to predict (no copies).
* If the data are factors, then the values returned will correspond to 0-based indices for the MappedCPTs
*
* The indices for rows and columns are 0-based.
*/
class Evidence {
Rcpp::CharacterVector columns;
// Currently, int allows only for factors, yet it could be generic.
std::vector<Rcpp::IntegerVector> data_columns;
int N;
public:
inline int get(int column, int row) const {
return data_columns.at(column)(row) - 1;
}
inline Rcpp::CharacterVector getColumns() const {
return columns;
}
inline int getN() const {
return N;
}
Evidence(Rcpp::DataFrame & test, const Rcpp::CharacterVector & features);
};
/**
* Obtains the CPT indices corresponding to a data instance.
* An option is to use it as a proxy for CPT, in order to subset it, but
* CPT currently does not provide subsetting.
*/
class MappedCPT {
// It was faster using c++ storage than Rcpp
// Are the indices 1-based or one based? I think 0 based because they are in Rcpp.
std::vector<int> db_indices;
const CPT & cpt;
// A reference to a unique instance of Evidence
const Evidence & test;
public:
MappedCPT(const CPT & cpt, const Evidence & test);
/**
* Fills in the instance's entries into the sequence. Returns iterator to one after last added.
* The number of elements added is that of the dimensions of the CPT. It adds them into the output sequence whose start is begin.
*/
inline std::vector<int>::iterator fill_instance_indices(int row, std::vector<int>::iterator output_begin) const {
// could store ndb_inds as member. But maybe not much speed up.
int ndb_inds = db_indices.size();
for (int k = 0; k < ndb_inds ; k++) {
*output_begin= test.get(db_indices.at(k), row);
output_begin++;
}
return output_begin;
}
};
/**
* Currently keep reference to both CPT and MappedCPT; i.e, the latter is not a proxy for the former.
* Maps feature CPTs to the evidence.
*/
class MappedModel {
const Model & model;
const std::vector<double> & class_cpt;
int nclass;
int n;
const Evidence & evidence;
std::vector<MappedCPT> cpts;
// Buffer for a row of per-class probabilities
std::vector<double> output_buffer;
// Buffer for an instance
std::vector<int> instance_buffer;
public:
MappedModel(const Model & x, const Evidence & test);
inline void fill_class_entries(int row, int feature) {
const MappedCPT & mcpt = this->cpts.at(feature);
mcpt.fill_instance_indices(row, instance_buffer.begin());
const CPT & cpt = model.get_cpt(feature);
const std::vector<int> & dimprod = cpt.get_dimprod();
const std::vector<double> & cpt_entries = cpt.get_entries();
// roughly half the time is spent here:
subset_free_last_dim(cpt_entries, dimprod, instance_buffer.begin(), output_buffer);
}
NumericMatrix predict();
};
#endif | true |
99064870e7d2c97f982cd1489ec7403e5a56b4e7 | C++ | Eric-Ma-C/PAT-Advanced | /Advanced/AA1104/AA1104/main.cpp | GB18030 | 321 | 2.734375 | 3 | [
"MIT"
] | permissive | #include<stdio.h>
double a[100005];
double time[100005]={0};//int
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%lf",a+i);
time[i]=(n-i)*1.0*(i+1);
}
double sum=0.0;
for(int i=0;i<n;i++){
sum+=a[i]*time[i];
}
printf("%.2f",sum);
getchar();
getchar();
return 0;
} | true |
40fdd74c3ace354cc6dd55aabb939984fc8d2bce | C++ | WhiZTiM/coliru | /Archive2/3f/4eb8f5da9ca075/main.cpp | UTF-8 | 2,095 | 3.390625 | 3 | [] | no_license | #include <vector>
#include <map>
#include <algorithm>
#include <iostream>
template<typename T>
static
std::pair< std::vector<T>, std::vector<T> >
compare(std::vector<T>& old_user_devices,
std::vector<T>& new_user_devices)
{
std::sort(std::begin(old_user_devices), std::end(old_user_devices));
std::sort(std::begin(new_user_devices), std::end(new_user_devices));
std::vector<T> plus(new_user_devices.size());
std::vector<T> minus(old_user_devices.size());
{
auto it = std::set_difference(
std::begin(old_user_devices),
std::end(old_user_devices),
std::begin(new_user_devices),
std::end(new_user_devices),
std::begin(minus));
minus.resize(it - minus.begin());
}
{
auto it = std::set_difference(
std::begin(new_user_devices),
std::end(new_user_devices),
std::begin(old_user_devices),
std::end(old_user_devices),
std::begin(plus));
plus.resize(it - plus.begin());
}
return {std::move(plus), std::move(minus)};
}
template <typename T>
void
display(std::string const& name, std::vector<T> const& to_display)
{
std::cerr << name << "(" << to_display.size() << "):" << std::endl;
std::for_each(to_display.begin(), to_display.end(), [] (T const& i)
{ std::cerr << "- " << i << std::endl; });
}
int main()
{
{
std::vector<int> old_{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::vector<int> new_{2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16};
auto ret = compare(old_, new_);
display("Removed", ret.second);
display("Added", ret.first);
}
std::cerr << std::string(30, '-') << std::endl;
{
std::vector<int> old_{};
std::vector<int> new_{2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16};
auto ret = compare(old_, new_);
display("Removed", ret.second);
display("Added", ret.first);
}
std::cerr << std::string(30, '-') << std::endl;
{
std::vector<int> old_{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::vector<int> new_{};
auto ret = compare(old_, new_);
display("Removed", ret.second);
display("Added", ret.first);
}
} | true |
057dc0c2d57805cfd36e6c7e0a12c0dbc43b5191 | C++ | ul5/VoxelGame | /src/world/Chunk.h | UTF-8 | 979 | 2.828125 | 3 | [] | no_license | #pragma once
#include "Block.h"
#include "../graphics/BlockMesh.h"
namespace world {
class Chunk {
private:
world::Block **blocks = new world::Block*[16 * 16 * 256];
graphics::BlockMesh *blockMesh = nullptr;
void createMesh();
int chunk_x, chunk_z;
public:
Chunk(int x, int y);
~Chunk();
inline bool isInside(int x, int z) { return x >= chunk_x * 16 && x < (chunk_x + 1) * 16 && z >= chunk_z * 16 && z < (chunk_z + 1) * 16; }
inline bool isNotAir(int x, int y, int z) { return isInside(x, z) && blocks[(x & 0xF) + (y & 0xFF) * 16 + (z & 0xF) * 16 * 256]->blockid; }
inline void breakBlock(int x, int y, int z) { blocks[(x & 0xF) + (y & 0xFF) * 16 + (z & 0xF) * 16 * 256]->blockid = 0; createMesh(); }
inline void placeBlock(int x, int y, int z, int bid) { blocks[(x & 0xF) + (y & 0xFF) * 16 + (z & 0xF) * 16 * 256]->blockid = bid; createMesh(); }
void render();
};
} | true |
80ad358ca1210a1a54c4f7b3b194367b53acd77f | C++ | Huppdo/ECCS1611 | /Labs/LabThree/src/Hupp_Lab3_Part2.cpp | UTF-8 | 1,081 | 3.65625 | 4 | [] | no_license | //Dominic Hupp - ECCS1611 - Lab 3 Part 2 - 8/26/20
/*
Determine the cost of owning a car with the provided inputs
*/
#include <iostream>
using namespace std;
int main() {
//Establish user input variables
int costOfCar = 0;
double milesPerGallon = 0;
int milesPerYear = 0;
double gasPrice = 0;
double yearsOfUse = 0;
int resaleAmnt = 0;
//Establish temporary/behind the scenes variables
double netCost = 0;
//Get user input data
cout << "Enter cost of car: $";
cin >> costOfCar;
cout << "Enter MPG: ";
cin >> milesPerGallon;
cout << "Enter miles driven per year: ";
cin >> milesPerYear;
cout << "Enter gas price: $";
cin >> gasPrice;
cout << "Enter years of use: ";
cin >> yearsOfUse;
cout << "Enter car resale amount: $";
cin >> resaleAmnt;
//Calculate net cost
netCost = costOfCar; //Start by using the initial price of the car
netCost += (milesPerYear / milesPerGallon * gasPrice * yearsOfUse); //Get the total cost in gas spent
netCost -= resaleAmnt;
//Print out net cost
cout << endl << "Net cost of car ownership: $" << netCost << endl << endl;
} | true |
da96ef06eef139f28cb2e9a400cea7b99cf444ec | C++ | ratulSharker/Java_like_thread_in_c_plus_plus | /Example_6_get_status.cpp | UTF-8 | 2,120 | 3.3125 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include "Thread.h"
class GetStatusDemo implements Thread
{
public:
void run()
{
for(int i = 0 ; i < 10 ; i++)
{
//this enable wait checking will make the thread to be in te wait checking state
ENABLE_WAIT_CHECKING;
sleep(1000);
cout<<"running loops "<<i<<endl;
DISABLE_WAIT_CHECKING;
}
}
};
void statePrinter(THREAD_STATUS status)
{
switch(status)
{
case THREAD_CHECKING_FOR_WAIT:
cout<<"THREAD STATE : CHECKING FOR WAIT"<<endl;
break;
case THREAD_RUNNING:
cout<<"THREAD STATE : THREAD RUNNING"<<endl;
break;
case THREAD_NOT_YET_STARTED:
cout<<"THREAD STATE : THREAD NOT YET STARTED"<<endl;
break;
case THREAD_RUN_METHOD_RUNNING_COMPLETED:
cout<<"THREAD STATE : THREAD RUN METHOD RUNNING COMPLETED"<<endl;
break;
case THREAD_STOPPED:
cout<<"THREAD STATE : THREAD STOPPED"<<endl;
break;
}
}
int main(int argc, char **argv)
{
GetStatusDemo demo;
//before start the demo thread check the thread status
statePrinter(demo.getStatus());
demo.start();
statePrinter(demo.getStatus());
Thread::sleep(1800);
cout<<"after initial sleep"<<endl;
statePrinter(demo.getStatus());
for(int i=0 ;i<5;i++)
{
demo.wait(NO, 10);
//check for a luck so that we found the thread on "checking_for_wait" state
statePrinter(demo.getStatus());
Thread::sleep(2000);
demo.notify();
}
Thread::sleep(1500);
cout<<"out of the waiting loop"<<endl;
statePrinter(demo.getStatus());
//if you wanna see the whole portion of run method running just comment out the following 3 line of code then compile & run see what happen.
demo.stop();
cout<<"after stop"<<endl;
statePrinter(demo.getStatus());
demo.join();
cout<<"after join"<<endl;
statePrinter(demo.getStatus());
}
| true |
b6ca7ba0e8b127a7434dfca1e702c325da5ccc2d | C++ | idaholab/raven | /src/utilities/microSphere.cxx | UTF-8 | 3,322 | 2.640625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | /* Copyright 2017 Battelle Energy Alliance, LLC
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 "ND_Interpolation_Functions.h"
#include <vector>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <iso646.h>
#include "MDreader.h"
MicroSphere::MicroSphere(std::string filename, double p, int precision){
_data_filename = filename;
_p = p;
_precision = precision;
readScatteredNDArray(_data_filename, _dimensions, _number_of_points, _point_coordinates, _values);
msInitialization();
_completed_init = true;
}
MicroSphere::MicroSphere(double p, int precision)
{
_p = p;
_precision = precision;
_completed_init = false;
_number_of_points = 0;
_dimensions=0;
}
void MicroSphere::msInitialization(){
std::srand (time(NULL));
for (int j=0; j<_precision; j++){
double sum = 0;
do{
for (int i=0; i<_dimensions; i++){
// x,y,z are uniformly-distributed random numbers in the range (-1,1)
_unit_vector[j][i] = -1+2*std::rand();
sum += _unit_vector[j][i];
}
sum = std::sqrt(sum);
}while (sum > 1);
for (int i=0; i<_dimensions; i++)
_unit_vector[j][i] /= sum;
}
}
void
MicroSphere::fit(std::vector< std::vector<double> > coordinates, std::vector<double> values){
_dimensions=coordinates[0].size();
_number_of_points = coordinates.size();
_point_coordinates = coordinates;
_values = values;
msInitialization();
_completed_init = true;
}
double MicroSphere::interpolateAt(std::vector<double> point_coordinate){
double value = 0;
double weight = 0;
double cosValue = 0;
if (not _completed_init)
{
throw ("Error in interpolateAt: the class has not been completely initialized... you can not interpolate!!!!");
}
std::vector<double> weights (_values.size());
for (unsigned int n=0; n<_values.size(); n++){
weight = minkowskiDistance(point_coordinate,_point_coordinates[n],_p);
for (int j=0; j<_precision; j++){
cosValue = cosValueBetweenVectors(_unit_vector[j],point_coordinate);
if (cosValue*weight>0){
// Do something
}
}
}
return value;
}
double MicroSphere::cosValueBetweenVectors(std::vector<double> point1, std::vector<double> point2){
double cosAngle = 0;
double point1point2 = 0;
if (point1.size() == point2.size()){
for (unsigned int nDim=0; nDim<point1.size(); nDim++){
point1point2 += point1[nDim] * point2[nDim];
}
cosAngle = point1point2/(vectorNorm(point1, _p)*vectorNorm(point2, _p));
}else
throw ("Error in cosValueBetweenVectors: points having different dimensions");
return cosAngle;
}
double MicroSphere::getGradientAt(std::vector<double> /* point_coordinate */){
if (not _completed_init)
{
throw ("Error in getGradientAt: the class has not been completely initialized... you can not interpolate!!!!");
}
return -1.0;
}
| true |
53e0b1df126ed95da03cbd5bf1c49550cc502caa | C++ | CoderHermano/Data-Structures-CPP | /Leetcode/Array/Remove Duplicates/Duplicates.cpp | UTF-8 | 872 | 3.90625 | 4 | [
"MIT"
] | permissive | // Remove Duplicates from Sorted Array
// Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
// Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
// when the number of duplicates is large enough,
// it's actually faster to convert to a set and then dump the data back into a vector.
set<int> s;
unsigned size = nums.size();
for ( unsigned i = 0; i < size; ++i )
s.insert( nums[i] );
// Assign back to vector
nums.assign( s.begin(), s.end() );
return nums.size();
}
};
int main() {
vector<int> v = {1, 1, 2};
int output = Solution().removeDuplicates(v);
cout << output;
return 0;
} | true |
28e02600ef9d0d9d5d120510508b4f99bdf1003b | C++ | strengthen/LeetCode | /C++/621.cpp | UTF-8 | 2,163 | 2.609375 | 3 | [
"MIT"
] | permissive | __________________________________________________________________________________________________
sample 12 ms submission
int any = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
class Solution {
public:
int leastInterval(vector<char> &tasks, int n) {
if (tasks.empty())
return 0;
int count[26] = { 0 };
for (char l : tasks)
++count[l - 'A'];
sort(count, count + 26, greater<int>());
int interval = (count[0] - 1) * (n + 1) + 1, index = 0;
for (int i = 1; i < 26; ++i) {
if (count[i] == 0)
break;
if (count[i] == count[0]) {
++interval;
--count[i];
}
if (n == 0)
interval += count[i];
else {
index += count[i];
if (index >= count[0] - 1) {
if (n > 1)
index -= count[0] - 1;
else
interval += index - count[0] + 1;
--n;
}
}
}
return interval;
}
};
__________________________________________________________________________________________________
sample 9636 kb submission
typedef long long int64;
const int INF = 0x3f3f3f3f;
template <class T> inline int len (const T &a) { return a.size (); }
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
vector <int> dat(26, 0);
for (char task: tasks) dat [task - 'A']++;
sort(dat.begin(), dat.end(), greater<int>());
int ret = 0;
while (true) {
bool ok = true;
int knt = 0;
for (int i = 0; i < 26; i++)
if (dat[i]) {
dat[i]--;
knt++;
if (knt == n + 1) break;
}
for (int i = 0; i < 26; i++) ok &= (dat[i] == 0);
if (ok) {
ret += knt;
break;
}
else ret += max(knt, n + 1);
sort(dat.begin(), dat.end(), greater<int>());
}
return ret;
}
};
static int fastio = []() {
#define endl '\n'
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(0);
return 0;
}();
__________________________________________________________________________________________________
| true |
0a5d55524c818867e2f45087c192947c6e96417f | C++ | jeffreyooi/SP4 | /DM2240_Lab/IntroState.cpp | UTF-8 | 7,250 | 2.765625 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include "GameStateManager.h"
#include "gamestate.h"
#include "menustate.h"
#include "introstate.h"
#include "playstate.h"
CIntroState CIntroState::theIntroState;
void CIntroState::Init()
{
w = glutGet(GLUT_SCREEN_WIDTH);
h = glutGet(GLUT_SCREEN_HEIGHT);
if (!LoadTGA(&intro[0], "intro.tga")) // Load The Font Texture
return; //false;
for (int i = 0; i < 255; i++){
myKeys[i] = false;
}
Timer = 1000.0f;
}
void CIntroState::Cleanup()
{
if (theCam != NULL)
{
delete theCam;
theCam = NULL;
free(theCam);
}
}
void CIntroState::Pause()
{
}
void CIntroState::Resume()
{
}
void CIntroState::HandleEvents(CGameStateManager* theGSM)
{
/*int m_iUserChoice = -1;
do {
cout << "CIntroState: Choose one <0> Go to Menu State, <1> Go to Play State : ";
cin >> m_iUserChoice;
cin.get();
switch (m_iUserChoice) {
case 0:
theGSM->ChangeState(CMenuState::Instance());
break;
case 1:
theGSM->ChangeState(CPlayState::Instance());
break;
default:
cout << "Invalid choice!\n";
m_iUserChoice = -1;
break;
}
} while (m_iUserChoice == -1);*/
}
void CIntroState::Update(CGameStateManager* theGSM)
{
w = glutGet(GLUT_SCREEN_WIDTH);
h = glutGet(GLUT_SCREEN_HEIGHT);
static int lastTime = GetTickCount();
int time = GetTickCount();
float deltaTime = (time - lastTime) / 1000.f;
Timer -= deltaTime;
for (int i = 0; i < 255; i++)
{
if (myKeys[i] == true)
CGameStateManager::getInstance()->ChangeState(CMenuState::Instance());
}
if (Timer <= 0)
{
CGameStateManager::getInstance()->ChangeState(CMenuState::Instance());
}
if (myKeys[VK_ESCAPE] == true)
exit(0);
}
void CIntroState::Draw(CGameStateManager* theGSM)
{
// Clear the buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glEnable(GL_DEPTH_TEST);
Update(theGSM);
theCam->SetHUD(true);
RenderIntro();
theCam->SetHUD(false);
// Flush off any entity which is not drawn yet, so that we maintain the frame rate.
glFlush();
// swapping the buffers causes the rendering above to be shown
glutSwapBuffers();
glutPostRedisplay();
}
bool CIntroState::LoadTGA(TextureImage *texture, char *filename) // Loads A TGA File Into Memory
{
GLubyte TGAheader[12] = { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Uncompressed TGA Header
GLubyte TGAcompare[12]; // Used To Compare TGA Header
GLubyte header[6]; // First 6 Useful Bytes From The Header
GLuint bytesPerPixel; // Holds Number Of Bytes Per Pixel Used In The TGA File
GLuint imageSize; // Used To Store The Image Size When Setting Aside Ram
GLuint temp; // Temporary Variable
GLuint type = GL_RGBA; // Set The Default GL Mode To RBGA (32 BPP)
FILE *file = fopen(filename, "rb"); // Open The TGA File
if (file == NULL || // Does File Even Exist?
fread(TGAcompare, 1, sizeof(TGAcompare), file) != sizeof(TGAcompare) || // Are There 12 Bytes To Read?
memcmp(TGAheader, TGAcompare, sizeof(TGAheader)) != 0 || // Does The Header Match What We Want?
fread(header, 1, sizeof(header), file) != sizeof(header)) // If So Read Next 6 Header Bytes
{
if (file == NULL) // Did The File Even Exist? *Added Jim Strong*
return false; // Return False
else
{
fclose(file); // If Anything Failed, Close The File
return false; // Return False
}
}
texture->width = header[1] * 256 + header[0]; // Determine The TGA Width (highbyte*256+lowbyte)
texture->height = header[3] * 256 + header[2]; // Determine The TGA Height (highbyte*256+lowbyte)
if (texture->width <= 0 || // Is The Width Less Than Or Equal To Zero
texture->height <= 0 || // Is The Height Less Than Or Equal To Zero
(header[4] != 24 && header[4] != 32)) // Is The TGA 24 or 32 Bit?
{
fclose(file); // If Anything Failed, Close The File
return false; // Return False
}
texture->bpp = header[4]; // Grab The TGA's Bits Per Pixel (24 or 32)
bytesPerPixel = texture->bpp / 8; // Divide By 8 To Get The Bytes Per Pixel
imageSize = texture->width*texture->height*bytesPerPixel; // Calculate The Memory Required For The TGA Data
texture->imageData = (GLubyte *)malloc(imageSize); // Reserve Memory To Hold The TGA Data
if (texture->imageData == NULL || // Does The Storage Memory Exist?
fread(texture->imageData, 1, imageSize, file) != imageSize) // Does The Image Size Match The Memory Reserved?
{
if (texture->imageData != NULL) // Was Image Data Loaded
free(texture->imageData); // If So, Release The Image Data
fclose(file); // Close The File
return false; // Return False
}
for (GLuint i = 0; i<int(imageSize); i += bytesPerPixel) // Loop Through The Image Data
{ // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
temp = texture->imageData[i]; // Temporarily Store The Value At Image Data 'i'
texture->imageData[i] = texture->imageData[i + 2]; // Set The 1st Byte To The Value Of The 3rd Byte
texture->imageData[i + 2] = temp; // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
}
fclose(file); // Close The File
// Build A Texture From The Data
glGenTextures(1, &texture[0].texID); // Generate OpenGL texture IDs
glBindTexture(GL_TEXTURE_2D, texture[0].texID); // Bind Our Texture
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Linear Filtered
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtered
if (texture[0].bpp == 24) // Was The TGA 24 Bits
{
type = GL_RGB; // If So Set The 'type' To GL_RGB
}
glTexImage2D(GL_TEXTURE_2D, 0, type, texture[0].width, texture[0].height, 0, type, GL_UNSIGNED_BYTE, texture[0].imageData);
return true; // Texture Building Went Ok, Return True
}
void CIntroState::changeSize(int w, int h)
{
// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if (h == 0)
h = 1;
float ratio = (float)(1.0f* w / h);
// Reset the coordinate system before modifying
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Set the viewport to be the entire window
glViewport(0, 0, w, h);
// Set the correct perspective.
gluPerspective(45, ratio, 1, 1000);
glMatrixMode(GL_MODELVIEW);
}
void CIntroState::inputKey(int key, int x, int y){}
void CIntroState::KeyboardDown(unsigned char key, int x, int y){ myKeys[key] = true; }
void CIntroState::KeyboardUp(unsigned char key, int x, int y){ myKeys[key] = false; }
void CIntroState::MouseMove(int x, int y){}
void CIntroState::MouseClick(int button, int state, int x, int y){
if (state == 0)
{
CGameStateManager::getInstance()->ChangeState(CMenuState::Instance());
}
}
void CIntroState::RenderIntro(void)
{
glPushMatrix();
glColor3f(1.0f, 1.0f, 1.0f);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, intro[0].texID);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f); glVertex2f(0.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex2f(960.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex2f(960.0f, 672.0f);
glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f, 672.0f);
glEnd();
glDisable(GL_TEXTURE_2D);
glPopMatrix();
} | true |
eeb22106270f41a3f451f664f16e9afd3b9e8c0f | C++ | fltester/boost_tutorial | /src/test_class_inherit.cpp | UTF-8 | 1,052 | 2.875 | 3 | [] | no_license | #include<string>
#include<iostream>
#include<boost/python.hpp>
using namespace std;
using namespace boost::python;
struct Base{
virtual ~Base() {};
virtual string getName() {return "Base";}
string str;
};
struct Derived : Base{
string getName() {return "Derived";}
};
void b(Base *base) {cout << base->getName()<< endl;};
void d(Derived *derived) {cout << derived->getName() << endl;};
Base *factory() {return new Derived;}
// namespace boose
// {
// template <>
// Base const volatile *get_pointer<class Base const volatile>(
// class Base const volatile *c)
// {
// return c;
// }
// }
BOOST_PYTHON_MODULE(preprocessor)
{
class_<Base>("Base")
.def("getName", &Base::getName)
.def_readwrite("str", &Base::str);
class_<Derived, bases<Base> > ("Derived")
.def("getName", &Derived::getName)
.def_readwrite("str", &Derived::str);
def("b", b);
def("d", d);
def("factory", factory, return_value_policy<manage_new_object>());
} | true |
e34f0639bda991b4ab503eac48af1ffad9b7340d | C++ | lee658/lee | /clang/004/day004_001/day4_004.cpp | UTF-8 | 157 | 2.515625 | 3 | [] | no_license | #include <stdio.h>
int main() {
int x = 10;
int y = 010;
int z = 0x10;
printf(" x %d\n", x);
printf("y %d\n", y);
printf("z %d\n", z);
return 0;
} | true |
f83318a3cae02339c49cf0bb88c7390aa2523830 | C++ | JHW0900/Problem_Sloving | /BOJ/1018.cpp | UTF-8 | 1,196 | 2.609375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int WB_change(int x, int y);
int BW_change(int x, int y);
const string WB[8] = {
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW"
};
const string BW[8] = {
"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB"
};
string board[100];
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n, m;
int cnt = 8 * 8;
cin >> n >> m;
for(int i = 0; i < n; i++)
cin >> board[i];
for(int i = 0; i + 7 < n; i++){
for(int j = 0; j + 7 < m; j++){
cnt = min(cnt, min(WB_change(i, j), BW_change(i, j)));
}
}
cout << cnt;
return 0;
}
int WB_change(int x, int y){
int cnt = 0;
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
if(board[x + i][y + j] != WB[i][j]) cnt++;
}
}
return cnt;
}
int BW_change(int x, int y){
int cnt = 0;
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
if(board[x + i][y + j] != BW[i][j]) cnt++;
}
}
return cnt;
} | true |
6812f5de9db0eacaac3910d51f22afea1c2ed796 | C++ | GammaG/C-- | /testRN.cpp | UTF-8 | 1,955 | 2.9375 | 3 | [] | no_license | /*
Simple Unit Test for type RationalNumber
*/
#include <stdio.h>
#include <assert.h>
#include "rationalnumber.h"
#include "rationalnumbercollection.h"
using namespace std;
int main()
{
printf("Performing unit tests for RationalNumber...\n");
/* Part 1 - RationalNumber data type */
RationalNumber n1 = { 3, 4 },
n2 = { 6, 4 },
n3 = { 3, 2 },
n4 = { -9, -6 },
n5 = { 9, -6 },
n6 = { 9, 4 },
n0 = { 0, 4 },
nn = { 4, 0 };
assert( rnIsValid(n0) );
assert( !rnIsValid(nn) );
assert( rnEqual( n2, n3) );
assert( rnEqual( rnAdd(n1,n1), n2) );
assert( rnEqual( n2,n4) );
assert( !rnEqual( n4,n5) );
assert( rnLessThan( n5,n3) );
RationalNumber t1 = rnAdd(n1,n2);
RationalNumber t2 = rnDivide(n3,n3);
RationalNumber t3 = rnDivide(n2,n2);
RationalNumber t4 = rnDivide(n6,n0);
assert( rnEqual(t1, n6) );
assert( rnEqual(t2, t3) );
assert( !rnIsValid(t4) );
printf("successful!\n");
printf("from here on number 1.3\n");
printf("RationalNumberCollection erzeugt\n");
RationalNumberCollection* c = rncCreate(4);
//rncInit(c);
RationalNumber n={1,2};
rncAdd(c, n);
rncAdd(c,n0);
rncAdd(c,n1);
rncAdd(c,n2);
rncAdd(c,n3);
rncAdd(c,n4);
rncAdd(c,n5);
rncAdd(c,n6);
printf("hinzufuegen hat geklappt\n");
RationalNumber sum = {13,2};
assert( rnEqual(rncSum(c),sum));
assert( rncMatchNumber(rncTotalCount(c), 8));
assert( rncMatchNumber(rncTotalUniqueCount(c), 6));
assert( rncMatchNumber(rncCount(c,n5),1));
RationalNumber ava = {0,1};
assert (rnEqual(rncAverage(c),ava));
printf("Vergleiche waren erfolgreich\n");
rncDelete(c);
printf("RationalNumberCollection speicher freigegeben\n");
printf("cya around\n\n");
return 0;
}
| true |
d270274f3d280e0c5af141dd5869cfbe16318797 | C++ | JCCervera/Infinitree-LD34 | /LD34/LD34Project/Surface.cpp | UTF-8 | 1,810 | 3.375 | 3 | [] | no_license | #include "Surface.h"
//Construct absolutely nothing
Surface::Surface() {
}
//Load them surfaces
SDL_Surface* Surface::OnLoad(char* File) {
//Intialize a temporary surface and the surface to be returned
SDL_Surface* Surf_Temp = NULL;
SDL_Surface* Surf_Return = NULL;
//Load the file into the temp
if((Surf_Temp = IMG_Load(File)) == NULL){
return NULL;
}
//Format alphas for transparency
Surf_Return = SDL_DisplayFormatAlpha(Surf_Temp);
//Free the temporary surface
SDL_FreeSurface(Surf_Temp);
//Return the surface we all like and deserve
return Surf_Return;
}
//Draw the surface unto the window
bool Surface::OnDraw(SDL_Surface* Surf_Dest, SDL_Surface* Surf_Src, int X, int Y) {
//Check if we actually got some surfaces
if(Surf_Dest == NULL || Surf_Src == NULL){
return false;
}
//The surface rectangle we are drawing
SDL_Rect DestR;
//Where it will be going
DestR.x = X;
DestR.y = Y;
//Do it!
SDL_BlitSurface(Surf_Src, NULL, Surf_Dest, &DestR);
return true;
}
//A different draw that accomplishes different goals
bool Surface::OnDraw(SDL_Surface* Surf_Dest, SDL_Surface* Surf_Src, int X, int Y, int X2, int Y2, int W, int H){
//Check if we got some surfaces
if(Surf_Dest == NULL || Surf_Src == NULL){
return false;
}
//Make a rectangle
SDL_Rect DestR;
//Where we are putting it
DestR.x = X;
DestR.y = Y;
//Rectangle we are using to section off an image from the bigger image
SDL_Rect SrcR;
//Where we section off the smaller image from
SrcR.x = X2;
SrcR.y = Y2;
//how big is this smaller image
SrcR.w = W;
SrcR.h = H;
//DO IT!!!!
SDL_BlitSurface(Surf_Src, &SrcR, Surf_Dest, &DestR);
return true;
}
| true |
570783e95687208bb0a1b56b9e07f9e79e7dc7e8 | C++ | DarinaKD/Task_C | /Dictionary.cpp | WINDOWS-1251 | 9,387 | 3.140625 | 3 | [] | no_license | // Dictionary.cpp : Defines the entry point for the console application.
//
#include <iostream>
//#include <stdio.h>
//#include <conio.h>
#include <windows.h>
#include <string>
//#include <stdlib.h>
//#include <dos.h>
using namespace std;
// CLASS TREE____________________________________________
class Tree{
char* word;
Tree* left;
Tree* right;
public:
Tree(char* w){
word = new char[strlen(w)+1];
strcpy(word,w);
left=0;
right=0;
}
/* Tree(const Tree &tr){
if(tr.word){
word =new char[strlen(tr.word)+1];
strcpy(word,tr.word);
}
else word=0;
left=tr.left; right=tr.right;
} */ //
~Tree(){delete[]word;}
const char* getWord(){return word;}
Tree* find_add(char* w, bool find=false);
Tree* remove(char* w);
void printSort(bool inc=true);
};
//_____________________________________________________
typedef void (*fun)(void);
// MENU________________________________________________
struct Menu{
int x,y;
char* name;
//int color;
fun f;
};
struct WINDOW{
int x1,y1,x2,y2,back,color;
};
//_____________________________________________________
void DrawWindow (WINDOW );
void flush();
void DrawMenu (int n,Menu *m, WINDOW w);
void clrscr();
void textbackground(int text, int =8);
void gotoxy(int x,int y);
void File();
void Do();
void Exit();
// MAIN
int main()
{
Menu menu[3]={ //
{1,1,"File",File},
{6,1,"Do",Do},
{9,1,"Exit",Exit}
};
WINDOW w={3,3,77,23,1,14}; //
textbackground(0,15);
clrscr();
DrawMenu(3,menu,w); //
char* const newWord=new char[255];
cout<<"Input word ";
cin>>newWord;
Tree* dict=new Tree(newWord);
char symb;
Tree* oneWord;
while(cin>>newWord){ //Cntr+Z
// if(newWord=="\n"){cout<<"STOP";break;}
cout<<newWord<<"\n";
oneWord=dict->find_add(newWord);
}
cout<<"What find? ";
cin.clear();
cin>>newWord;
oneWord=dict->find_add(newWord, true);
if(oneWord){
//newWord=oneWord->getWord();
cout<<" this "<< oneWord->getWord()<<"\n";
}
else cout<<newWord<<"Word not found\n";
cin.clear();
cout<<"What delete:";
cin>>newWord;
cout<<"\n ";
dict->printSort();
dict=dict->remove(newWord);
cout<<"\nSort ";
dict->printSort();
cout<<"\nSort decreas: ";
dict->printSort(0);
cout<<"\n\n";
system("pause");
cout<<"\nEnd";
// cin>>symb;
return 0;
}
//TREE_____________________________________________________
Tree* Tree::find_add(char* word, bool find){
if(!word){cout<<"Empty string!"; return NULL;}
Tree *prev, *pv=this;
bool found=false;
int cmp;
while(pv){
prev=pv;
cmp =strcmp(pv->word,word);
if(!cmp){found=true; break;}
else if(cmp<0) pv=pv->right;
else pv=pv->left;
}
if(find) return pv;
// add
Tree* newpv=new Tree(word);
if(cmp<0) prev->right=newpv;
else prev->left=newpv;
return newpv;
}
Tree* Tree::remove(char* word){
//Tree* pv=this->find_add(word, true);
//if(!pv){cout<<"Word no found"; return;}
Tree *prev, *pv=this;
int cmp;
bool branch=0;
while(pv){
cmp=strcmp(pv->word,word);
if(!cmp)break;
else{
prev = pv;
if(cmp<0){pv=pv->right; branch=1;}
else {pv=pv->left; branch=0;}
}
}
if(!pv){cout<<"Such word not found"; return this;}
Tree* pvrprev=0, *pvr=0, *top=this, *displ=0;
if(pv->left){pvr=pv->left; displ=pv->left;}
else if(pv->right)displ=pv->right;
while(pvr){
pvrprev = pvr;
pvr=pvr->right;
}
if(pvrprev)pvrprev->right = pv->right;
//if(displ){
if(pv!=this) branch? prev->right=displ:prev->left=displ;
else top=displ;
//}
delete pv;
return top;
}
void Tree::printSort(bool inc){
Tree* pv=this;
if(pv){
if(inc){
pv->left->printSort(inc);
cout<<pv->word<<"; ";
pv->right->printSort(inc);
}
else {
pv->right->printSort(inc);
cout<<pv->word<<"; ";
pv->left->printSort(inc);
}
}
}
//_______________________________________
void flush(){ //
//fflush(stdin); // !
//_asm{ cli; sub ax,ax; mov es,ax; mov al,es:[41ah]; mov es:[41ch],al; sti;}
}
void DrawWindow (WINDOW w) { // w
char c[]={'','','','','','','',''};
//WINDOW(1, 1,80,25);
textbackground(0,w.back); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),w.color);
gotoxy(w.x1-1,w.y1-1);
cout<<c[0]; //cprintf("%c",c[0]);
for (int i=w.x1; i<=w.x2; i++) cout<<c[1];//cprintf ("%c",c[1]);
cout<<c[2];//cprintf ("%c",c[2]);
for (int j=w.y1; j<=w.y2; j++) {
gotoxy (w.x1-1,j);
cout<<c[3];//cprintf ("%c",c[3]);
for (int i=w.x1; i<=w.x2; i++) cout<<" ";//cprintf (" ");
cout<<c[4];//cprintf ("%c",c[4]);
}
gotoxy (w.x1-1,w.y2+1);
cout<<c[5];//cprintf ("%c",c[5]);
for (int i=w.x1; i<=w.x2; i++) cout<<c[6];//cprintf ("%c",c[6]);
cout<<c[7];//cprintf ("%c",c[7]);
}
void DrawMenu (int n, Menu *m,WINDOW w) { //
int sel=0, back=7, inactivecolor=10,activecolor=4;
DrawWindow (w); //
textbackground(back); //
for (int i=0; i<n; i++){
gotoxy(m[i].x,m[i].y);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), inactivecolor); //textcolor
cout<<m[i].name;//cprintf ("%s",m[i].str);
}
while (1) { //
gotoxy(m[sel].x,m[sel].y);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), activecolor);
cout<<m[sel].name;//cprintf ("%s",m[sel].str); //
flush(); //
int ch=cin.get(); //)
gotoxy(m[sel].x,m[sel].y); //
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), inactivecolor);
//cprintf ("%s",m[sel].name);
cout<<m[sel].name;
if (!ch) { // ?
ch=cin.get(); //
switch(ch) { //
case 72: case 75: if(sel)sel--; else sel=n-1; break; //
case 80: case 77: if(sel<n-1)sel++; else sel=0; break;
} }
else { // -
switch(ch) {
case 13: // Enter
textbackground(w.back); //
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), w.color);
//window (w.x1,w.y1,w.x2,w.y2); //
m[sel].f(); // ,
clrscr(); //,
textbackground(0); //
//window (1,1,80,25);
break;
case 27: Exit(); // Esc
}
}
}
}
//
void File() { // File -
char i=0;
// cprintf
while (!cin.get()) //kbhit()
//delay(200);
cout<<" File, %ld\r\n"<<++i;//cprintf (" File, %ld\r\n",++i);
}
void Do() { // Do -
cout<<" : ";
//cprintf (" : ");
int d;
//cscanf ("%d",&d); // cscanf
cout<<&d;
//cprintf ("\r\n %d\r\n ...",d);
cout<<"\r\n %d\r\n ..."<<d;
cin.get(); cin.get();
}
void Exit(){ //
//window(1,1,80,25);
textbackground(0);//BLACK);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);//LIGHTGRAY);
clrscr();
exit(0);
}
/*
//
void main () {
ITEM menu1[3]={ //
{2,2,"File",File},
{2,3,"Do",Do},
{2,4,"Exit",Exit}
};
WINDOW w={8,2,78,24,BLUE,YELLOW}; //
textbackground (WHITE);
clrscr();
DrawMenu (3,menu1,w); //
*/
void clrscr(void)
{
HANDLE hOut = ::GetStdHandle(STD_OUTPUT_HANDLE);
COORD start = {0, 0};
CONSOLE_SCREEN_BUFFER_INFO info;
::GetConsoleScreenBufferInfo(hOut, &info);
::FillConsoleOutputCharacter(hOut, ' ', info.dwSize.X*info.dwSize.Y, start, NULL);
::SetConsoleCursorPosition(hOut, start);
}
void gotoxy(int x,int y){
HANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );
if ( INVALID_HANDLE_VALUE != hConsole )
{
COORD pos = {x, y};
SetConsoleCursorPosition ( hConsole, pos );
}
}
void textbackground(int text, int background=8)
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, (WORD)((background << 4) | text));
} | true |
9aceb6a6ac5e46b51fbb92d3eb7762210ca25498 | C++ | sebastiandev/muxer | /musicindexer/logging/FileLogger.cpp | UTF-8 | 852 | 2.703125 | 3 | [] | no_license | #include "FileLogger.h"
#include <iostream>
#include <fstream>
#include <QDateTime>
void FileLogger::LogInfo(QString message)
{
writeToFile(QString("Info"), message);
}
void FileLogger::LogError(QString message)
{
writeToFile(QString("Error"), message);
}
void FileLogger::LogDebug(QString message)
{
writeToFile(QString("Debug"), message);
}
void FileLogger::LogWarn(QString message)
{
writeToFile(QString("Warning"), message);
}
void FileLogger::writeToFile(QString type, QString message)
{
std::ofstream myfile;
myfile.open ("musicbrowser.log", std::ios::out | std::ios::app);
myfile << type.leftJustified(8,QChar(' ')).toStdString();
myfile << " - ";
myfile << QDateTime::currentDateTime().toString().toStdString() ;
myfile << " - ";
myfile << message.toStdString() << std::endl;
myfile.close();
}
| true |
0bbe65041beb7622cbf70a5fbd3c44b377989a25 | C++ | SreeHaran/CPP-Assignments | /Assignment-5(4).cpp | UTF-8 | 4,461 | 3.953125 | 4 | [] | no_license | /*We want to store the information of different vehicles. Create a class named Vehicle with two data member named mileage and price. Create its two subclasses
*Car with data members to store ownership cost, warranty (by years), seating capacity and fuel type (diesel or petrol).
*Bike with data members to store the number of cylinders, number of gears, cooling type(air, liquid or oil), wheel type(alloys or spokes) and fuel tank size(in inches)
Make another two subclasses Audi and Ford of Car, each having a data member to store the model type. Next, make two subclasses Bajaj and TVS, each having a data
member to store the make-type.
Now, store and print the information of an Audi and a Ford car (i.e. model type, ownership cost, warranty, seating capacity, fuel type, mileage and price.) Do the same for a Bajaj and a TVS bike. */
#include <iostream>
using namespace std;
class Vehicle{
public:
int mileage, price;
protected:
void printVehicle(){
cout << "mileage is: "<< mileage << "Km/L\n";
cout << "price is: " << price << "rupees\n";
}
};
class Car : public Vehicle{
public:
int ownershipCost, warranty, seatingCapacity;
string fuelType;
protected:
void printCar(){
cout<<"Ownership Cost is: "<< ownershipCost<<"rupees\n";
cout<<"warranty of the car is :"<<warranty<<"years\n";
cout<<"Seating capacity of the car is: "<< seatingCapacity << "seats\n";
cout<<"fuel type of the car is: "<<fuelType<<"\n";
}
};
class Audi : public Car{
private:
string modelType = "AU45651";
public:
void setAudi(){
mileage = 25;
price = 2500000;
ownershipCost = 7000;
warranty = 9;
seatingCapacity = 6;
fuelType = "petrol";
}
void printAudi(){
printVehicle();
printCar();
cout<<"Model type is: "<<modelType <<"\n";
}
};
class Ford : public Car{
private:
string modelType = "FD15543";
public:
void setFord(){
mileage = 20;
price = 1200000;
ownershipCost = 4000;
warranty = 5;
seatingCapacity = 6;
fuelType = "diesel";
}
void printFord(){
printVehicle();
printCar();
cout<<"Model type is: "<<modelType <<"\n";
}
};
class Bike : public Vehicle{
public:
int cylinders, gears;
string coolingType, wheelType;
float tankSize;
protected:
void printBike(){
cout<<"the number of cylinders: "<< cylinders<<"cylinders\n";
cout<<"number of gears: "<<gears<<"gears\n";
cout<<"cooling type: "<< coolingType << "\n";
cout<<"wheel type: "<<wheelType<<"\n";
cout<<"fuel tank size: "<<tankSize<<"inches\n";
}
};
class Bajaj : public Bike{
private:
string makeType = "Iron";
public:
void setBajaj(){
mileage = 50;
price = 120000;
cylinders = 3;
gears = 2;
coolingType = "liquid";
wheelType = "alloys";
tankSize = 42.5;
}
void printBajaj(){
printVehicle();
printBike();
cout<<"Make-type of the bike is: "<<makeType<<"\n";
}
};
class Tvs : public Bike{
private:
string makeType = "Aluminium";
public:
void setTvs(){
mileage = 65;
price = 70000;
cylinders = 2;
gears = 1;
coolingType = "oil";
wheelType = "spokes";
tankSize = 35.7;
}
void printTvs(){
printVehicle();
printBike();
cout<<"Make-type of the bike is: "<<makeType<<"\n";
}
};
int main(){
Audi audi;
audi.setAudi();
cout<<"AUDI:-"<<endl;
audi.printAudi();
cout <<"\n";
Ford ford;
ford.setFord();
cout<<"FORD:-"<<endl;
ford.printFord();
cout <<"\n";
Bajaj bajaj;
bajaj.setBajaj();
cout<<"BAJAJ:-"<<endl;
bajaj.printBajaj();
cout <<"\n";
Tvs tvs;
tvs.setTvs();
cout<<"TVS:-"<<endl;
tvs.printTvs();
return 0;
} | true |
91ba06099d3066075f155c76134412b3e2fdd48e | C++ | vadfabi/pylauncher_server | /LinuxServer/tcPIp_Sockets/Thread.cpp | UTF-8 | 2,628 | 3.140625 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | #include "Thread.h"
using namespace std;
/////////////////////////////////////////////////////////////////////////////
// Sleep
// sleep in milliseconds
//
void Sleep(long millis)
{
std::this_thread::sleep_for(std::chrono::milliseconds(millis));
}
/////////////////////////////////////////////////////////////////////////////
// Thread
// base class for simple thread wrapper
//
// Constructor
//
Thread::Thread()
{
mThread = 0;
mThreadStopped = false;
mThreadRunning = false;
}
// Destructor
//
Thread::~Thread()
{
// stop running thread before destruction
if ( mThreadRunning )
{
// ASSERT - this is bad, you should stop before destruction
Cancel();
}
// clean up the memory
if ( mThread != 0 )
delete mThread;
}
// Run
// This is the thread run function
// it takes a reference to the Thread class, and calls the Thread::RunFunction() for each cycle
// note, if you have a process that never quits, you should add a sleep in your RunFunction to prevent race condition
// TODO: Room For Improvement, I have read that sleep or yeild is not necessary on modern machines, is this true ?
//
void Run(Thread& thread)
{
while ( thread.IsRunning() )
{
thread.RunFunction();
// use sleep or yeild once per cycle to avoid race condition locking up UI
// TODO: this won't compile, there is some question if it is necessary ?
// std::this_thread::yeild();
}
// we are out of the run loop, set is stopped flag
thread.SetIsStopped();
return;
}
// Start
//
void Thread::Start()
{
// stop thread if it is running
if ( mThread != 0 )
{
// ASSERT - this is bad, you should stop running thread before starting new one
Cancel();
}
// initialize thread run variables
mThreadRunning = true;
mThreadStopped = false;
// start the thread
mThread = new std::thread(Run,std::ref(*this));
return;
}
// Cancel
// Stop the thread
// this function will wait until the thread has exited before returning
//
void Thread::Cancel()
{
mThreadRunning = false;
if ( mThread )
{
// a proper cancel thread function should have an interrupt here, to kill the thread if it is sleeping
// unfortunately, std::thread can not be interrupted (I believe?)
// use the BoostThread class if you want an interruptable thread
// wait for the thread to stop
while ( ! mThreadStopped )
{
Sleep(50);
#ifdef DEBUG
printf("Thread::Cancel - Waiting for thread to stop... \n");
#endif
}
// join to the thread to ensure that thread shuts down before exit
mThread->join();
// clean up our mess
delete mThread;
mThread = 0;
}
return;
}
| true |
0786f3e7a45eff7308c877717b22f00c50a1b9e3 | C++ | surbhim18/bsc-lab | /Semester 3/Algorithms/rod_cut.cpp | UTF-8 | 3,133 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
using namespace std;
int maxLen;
void rod_cut_opt(int *p, int *r, int *s)
{
r[0] = 0;
s[0] = 0;
int i,j;
for(i=1; i<maxLen; i++)
{
int maximum = -1;
for(j=1; j<=i; j++)
{
int val = p[j] + r[i-j];
if(val > maximum)
{
maximum = val;
s[i] = j;
}
}
r[i] = maximum;
}
}
void enterPrices(int* p)
{
p[0]=0;
int i;
cout<<"\nPrices: \n";
for(i=1; i<maxLen; i++)
{
cout<<"Length "<<i<<": ";
cin>>p[i];
}
}
void printOptimalValue(int *r,int len)
{
if(len > maxLen-1)
{
cout<<"\nLength given is greater than maximum length";
return;
}
cout<<"\nOptimum value of rod of length "<<len<<" is: "<<r[len];
}
void printOptimalSolution(int *s,int len)
{
if(len > maxLen-1)
{
cout<<"\nLength given is greater than maximum length";
return;
}
int n = len;
int i=1;
while(n>0)
{
cout<<"\nCut "<<i<<": "<<s[n];
n= n-s[n];
i++;
}
}
void printAll(int *r, int *s)
{
int i;
cout<<"\nLength\tOpt Value\tOpt Cuts\n";
cout<<"---------------------------------\n";
for(i=1; i<maxLen; i++)
{
cout<<i<<"\t"<<r[i]<<"\t\t";
int n = i;
while(n>0)
{
cout<<s[n]<<" ";
n= n-s[n];
}
cout<<"\n";
}
}
int main()
{
int ch,n,len;
cout<<"\nEnter maximum size of rod: ";
cin>>n;
maxLen = n+1;
int *p = new int[maxLen];
int *r = new int[maxLen];
int *s = new int[maxLen];
enterPrices(p);
rod_cut_opt(p,r,s);
do{
cout<<"\n--------------------------------------------------------------------------\n";
cout<<" ROD CUT\n";
cout<<"1.Print optimal value for rod of length n.\n";
cout<<"2.Print optimal solution for rod of length n.\n";
cout<<"3.Print all information.\n";
cout<<"4.Exit.\n";
cout<<"\n--------------------------------------------------------------------------";
cout<<"\nEnter choice: ";
cin>>ch;
cout<<"\n--------------------------------------------------------------------------";
switch(ch)
{
case 1:
cout<<"\nEnter length of rod: ";
cin>>len;
printOptimalValue(r,len);
break;
case 2:
cout<<"\nEnter length of rod: ";
cin>>len;
printOptimalSolution(s,len);
break;
case 3:
printAll(r,s);
break;
case 4:
exit(0);
default: cout<<"\nPlease enter a valid choice\n";
}
}while(1);
cout<<"\n--------------------------------------------------------------------------\n";
delete []p;
delete []r;
delete []s;
return 0;
}
| true |
b934a8ff1a4906ba3a9d60a94d4b022664f1c4a0 | C++ | GavinBupt/LeetCode | /2019_04_06_寻找两个有序数组的中位数/Project1/源.cpp | GB18030 | 2,173 | 3.34375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int MAX = 100000;
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size();
int n = nums2.size();
if (nums1.empty()) //һΪ
{
if (n % 2 != 0)
return 1.0*nums2[n / 2];
return (nums2[n / 2] + nums2[n / 2 - 1]) / 2.0;
}
if (nums2.empty()) //һΪ
{
if (m % 2 != 0)
return 1.0*nums1[m / 2];
return (nums1[m / 2] + nums1[m / 2 - 1]) / 2.0;
}
int mid_left = (m + n + 1) / 2;
int mid_right = (m + n + 2) / 2;
double a = findKth(nums1, 0, nums2, 0, mid_left);
double b = findKth(nums1, 0, nums2, 0, mid_right);
return ( a + b ) / 2;
}
double findKth(vector<int> &a, int a_left, vector<int> &b, int b_left, int k)
{
//cout << a_left << endl;
for (int i = a_left; i < a.size(); i++)
cout << a[i] << " ";
cout << "|| ";
for (int i = b_left; i < b.size(); i++)
cout << b[i] << " ";
cout << endl;
if (a_left >= a.size()) //aָ볬a鳤ȣôλb
return b[b_left + k - 1];
if (b_left >= b.size()) //bָ볬b鳤ȣôλa
return a[a_left + k - 1];
if (k == 1) return min(a[a_left], b[b_left]);
int mid_a = (a_left + k / 2 - 1 < a.size()) ? a[a_left + k / 2 - 1] : MAX; //һΪʼλǴ0ʼ
int mid_b = (b_left + k / 2 - 1 < b.size()) ? b[b_left + k / 2 - 1] : MAX;
if (mid_a < mid_b) //aλСbλô̭aǰK/2
{
return findKth(a, a_left + k / 2, b, b_left, k - k / 2);
}
else {
return findKth(a, a_left, b, b_left + k / 2, k - k / 2);
}
//else
// return mid_a;
}
};
int Nums1[] = { 1,2,3,4,5,6,7 };
int Nums2[] = { 1,2,3,4,5,6,7 };
int main()
{
vector<int> nums1, nums2;
for (int i = 0; i < 7; i++)
nums1.push_back(Nums1[i]);
for (int i = 0; i < 7; i++)
nums2.push_back(Nums2[i]);
Solution S;
cout << S.findMedianSortedArrays(nums1, nums2);
system("pause");
} | true |
349ab82b4dd13dc380019aed448cad9bce7ca26b | C++ | Sumelt/Daily-Coding | /Primer c++/13 Folder and Message.h | UTF-8 | 1,018 | 2.921875 | 3 | [] | no_license | #include <string>
#include <set>
class Message;
class Folder{
friend void swap(Folder &, Folder &);
friend class Message;
public:
Folder() = default;
Folder(const Folder &);
Folder& operator=(const Folder &);
~Folder();
void reMsg( Message* msg ){ msgs.erase( msg ); }
void addMeg( Message* msg ){ msgs.insert( msg ); }
private:
std::set<Message*> msgs;
void add_to_Message(const Folder&);
void remove_from_Message();
};
void swap(Folder &, Folder &);
class Message{
friend class Folder;
friend void swap( Message&, Message& );
public:
explicit Message( const std::string &str = "" );
Message ( const Message& );
Message& operator=( const Message& );
~Message();
void save( Folder& );
void remove( Folder& );
private:
std::string content;
std::set< Folder* >folders;
void add_to_Folder( const Message& );
void remove_from_Folder();
void addFldr(Folder *f) { folders.insert(f); }
void remFldr(Folder *f) { folders.erase(f); }
};
void swap(Folder &, Folder &);
| true |
ba8fda6476ad0e2a4618a5970cf7d633924fb31e | C++ | Jehm09/Competitive-Programming | /CodeForces/(1-25)-08-19/SagheerandNubianMarket.cpp | UTF-8 | 1,513 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <algorithm>
#include <bits/stdc++.h>
#define ll long long int
#define lenA(ar) sizeof(ar)/sizeof(*ar)
#define LENROWs(mat) sizeof(mat)/sizeof(*mat)
#define LENCOLs(mat) sizeof(*mat)/sizeof(**mat)
#define rep(i,x,y) for(ll i=x;i<y;i++)
#define repI(i,x,y) for(ll i=x-1;i>=y;i--)
using namespace std;
/**
* Solution
* https://codeforces.com/problemset/problem/812/C
* @author Joe
*/
ll cost(int k, int n, ll arr[]){
ll temp[n];
rep(i, 0 , n){
temp[i] = arr[i] + (i+1) * k;
}
sort(temp, temp+n);
ll rst = 0;
rep(i, 0, k){
rst += temp[i];
}
return rst;
}
int main() {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
int n;
ll s, minimun = LONG_MAX, sum = 0;
scanf("%d%lld", &n, &s);
ll arr[n];
rep(i, 0, n){
scanf("%lld", &arr[i]);
sum += arr[i] + (i + 1 ) * n;
minimun = min(minimun, arr[i] + i + 1);
}
if(sum <= s){
printf("%d %ld\n", n, sum);
} else if (minimun > s) {
printf("0 0\n");
} else {
int l = 1, r = n, mid;
while (l < r) {
// mid = l + (r - l) / 2;
mid = (r + l) / 2;
if (cost(mid, n, arr) > s) {
r = mid;
} else {
l = mid + 1;
}
}
l -= 1;
printf("%d %lld\n", l, cost(l, n, arr));
}
// fclose(stdin);
// fclose(stdout);
return 0;
} | true |
c1de7491426efc5320d053c6e5d3493cebaccf36 | C++ | ninhngocnhi/C-Demo | /h2n-bai11.cpp | UTF-8 | 586 | 2.59375 | 3 | [] | no_license | #include <stdio.h>
#include <algorithm>
using namespace std;
int main() {
int n,m;
scanf ("%d%d",&n,&m);
int a[n],b[m];
for (int i=0;i<n;i++){
scanf ("%d",&a[i]);
}
for (int j=0;j<m;j++){
scanf ("%d",&b[j]);
}
sort(a,a+n);
sort(b,b+m);
for (int i=0;i<n;i++){
if (a[i]<b[0]){
printf ("%d ",a[i]);
}
}
for (int j=0;j<m-1;j++){
printf ("%d ",b[j]);
for (int i=0;i<n;i++){
if (b[j]<=a[i] && a[i]<b[j+1]){
printf ("%d ",a[i]);
}
}
}
printf ("%d ",b[m-1]);
for (int i=0;i<n;i++){
if (b[m-1]<=a[i]){
printf ("%d ", a[i]);
}
}
return 0;
}
| true |
dac1483f40c8f495b3ae52135c1f8271f9c9a3c5 | C++ | CSCUC/CS1 | /9-17-19/1D.cpp | UTF-8 | 681 | 3.5 | 4 | [] | no_license | #include<iostream>
using namespace std;
int main() {
int num1, num2, num3, num4, num5, large, small;
cout << "Enter five integers: ";
cin >> num1 >> num2 >> num3 >> num4 >> num5;
large = num1;
small = num1;
if (num2 > large)
large = num2;
if (num3 > large)
large = num3;
if (num4 > large)
large = num4;
if (num5 > large)
large = num5;
if (num2 < small)
small = num2;
if (num3 < small)
small = num3;
if (num4 < small)
small = num4;
if (num5 < small)
small = num5;
cout << "Largest Integer: " << large << "Smallest Integer: " << small << endl;
system("pause");
return 0;
}
| true |
6657d0a98fec4464e2a5f5cce56a52d401371e62 | C++ | shlomor25/AP1_ex2_planes | /MyEmployee.h | UTF-8 | 714 | 2.625 | 3 | [] | no_license | //
// Created by shlomo Rabinovich 308432517 on 26/11/18.
//
#ifndef AP2_MYEMPLOYEE_H
#define AP2_MYEMPLOYEE_H
#include "interface.h"
#include "Collection.h"
class MyEmployee : public Employee
{
private:
int seniority;
int birthYear;
Jobs title;
string ID;
Employee* employer;
public:
MyEmployee(int seniority, int birthYear, string &employerID, Jobs title, Collection* collection);
// MyEmployee(string id, Collection* collection);
MyEmployee(int seniority, int birthYear, string &employerID, Jobs title, string &id, Collection* collection);
int getSeniority();
int getBirthYear();
Employee* getEmployer();
Jobs getTitle();
string getID();
};
#endif //AP2_MYEMPLOYEE_H | true |
c6941a378ef17cd56bc36c538feb3267be8fa12e | C++ | rjxircgz/programming | /IT 211 - Data Structures/ProgrammingExercise3/MatrixOperations.cpp | UTF-8 | 2,233 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#define p printf
void random(int arr[10][10], int row, int col)
{
srand(time(NULL));
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
arr[i][j]=(rand()%20)+1;
if(arr[i][j]<10)
p("0%d ",arr[i][j]);
else
p("%d ",arr[i][j]);
}
p("\n");
}
}
bool add(int R1[10][10],int R2[10][10],int r1, int c1, int r2, int c2)
{
int R3[10][10],i,j;
if(c1==c2 && r1==r2)
{
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
R3[i][j]=R2[i][j]+R1[i][j];
if(R3[i][j]>9)
p("%d ",R3[i][j]);
else
p("0%d ",R3[i][j]);
}
p("\n");
}
}
else
{
system("cls");
return false;
}
}
bool subt(int R1[10][10],int R2[10][10],int r1, int c1, int r2, int c2)
{
int R3[10][10],i,j;
if(c1==c2 && r1==r2)
{
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
R3[i][j]=R1[i][j]-R2[i][j];
p("%d ",R3[i][j]);
}
p("\n");
}
return true;
}
else
return false;
}
void display(int R[10][10], int row, int col)
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(R[i][j]>9)
p("%d ",R[i][j]);
else
p("0%d ",R[i][j]);
}
p("\n");
}
}
void scalar(int R[10][10], int row, int col, int sc)
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(((R[i][j])*sc)<10)
p("0%d ",(R[i][j])*sc);
else
p("%d ",(R[i][j])*sc);
}
p("\n");
}
}
bool multiply(int r1[10][10], int r2[10][10], int ro2, int co1, int ro1, int co2)
{
int i=0,j=0,k;
int r3[10][10];
if(co1==ro2)
{
for(k=0;k<ro1;k++)
{
printf("\n");
for(i=0;i<ro1;i++)
{
r3[k][i]=0;
for(j=0;j<co1;j++)
{
r3[k][i]+= r1[k][j] * r2[j][i];
}
printf("%d ",r3[k][i]);
}
printf("\n");
}
}
else
return false;
}
void trans(int R[10][10], int x, int y)
{
int T[10][10];
int i,j;
int temp;
for(i=0;i<x;i++)
for(j=0;j<y;j++)
{
temp=R[i][j];
T[j][i]=temp;
}
for(i=0;i<y;i++)
{
for(j=0;j<x;j++)
{
if(T[i][j]<10)
p("0%d ",T[i][j]);
else
p("%d ",T[i][j]);
}
p("\n");
}
} | true |
db1a10b8a58405d167586375a717ec6f53ba6ea0 | C++ | HaydenMarshalla/CPhysics | /Rebuild of cphysics/Rebuild of cphysics/src/JointToBody.cpp | UTF-8 | 2,376 | 2.828125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include "CPhysics/JointToBody.h"
#include "CPhysics/Matrix2D.h"
JointToBody::JointToBody(Body* b1, Body* b2, real jointLength, real jointConstant, real dampening, bool canGoSlack,
const Vectors2D& offset1, const Vectors2D& offset2) :
Joint(b1, jointLength, jointConstant, dampening, canGoSlack, offset1)
{
object2 = b2;
this->offset2 = offset2;
Matrix2D mat1 = Matrix2D(object1->orientation);
this->object1AttachmentPoint = object1->position + (mat1 * offset1);
Matrix2D mat2 = Matrix2D(object2->orientation);
this->object2AttachmentPoint = object2->position + (mat2 * offset2);
}
JointToBody::~JointToBody()
{
object1 = nullptr;
object2 = nullptr;
}
const Vectors2D& JointToBody::getStartPos() const
{
return object1AttachmentPoint;
}
const Vectors2D& JointToBody::getEndPos() const
{
return object2AttachmentPoint;
}
void JointToBody::applyTension()
{
Matrix2D mat1 = Matrix2D(object1->orientation);
this->object1AttachmentPoint = object1->position + (mat1 * offset1);
Matrix2D mat2 = Matrix2D(object2->orientation);
this->object2AttachmentPoint = object2->position + (mat2 * offset2);
real tension = calculateTension();
Vectors2D distance = this->object2AttachmentPoint - this->object1AttachmentPoint;
distance.Normalize();
Vectors2D impulse = distance * tension;
object1->applyLinearImpulse(impulse, object1AttachmentPoint - object1->position);
object2->applyLinearImpulse(impulse.negativeVec(), object2AttachmentPoint - object2->position);
}
real JointToBody::calculateTension()
{
real distance = (object1AttachmentPoint - object2AttachmentPoint).len();
if (distance < naturalLength && canGoSlack) {
return 0;
}
real extensionRatio = distance - naturalLength;
real tensionDueToHooksLaw = extensionRatio * springConstant;
real tensionDueToMotionDamping = dampeningConstant * rateOfChangeOfExtension();
return tensionDueToHooksLaw + tensionDueToMotionDamping;
}
real JointToBody::rateOfChangeOfExtension()
{
Vectors2D distance = object2AttachmentPoint - object1AttachmentPoint;
distance.Normalize();
Vectors2D relativeVelocity = object2->velocity + (crossProduct((object2AttachmentPoint - object2->position), object2->angularVelocity)) - (object1->velocity) - (crossProduct((object1AttachmentPoint - object1->position), object1->angularVelocity));
return dotProduct(relativeVelocity, distance);
}
| true |
38a1bf1538135040c644c627430261c02a468c39 | C++ | rleboo/RSA-Encryption-Decryption | /encrypt.cpp | UTF-8 | 834 | 3.1875 | 3 | [] | no_license | // Program that encrypts user input using modPower
//
#include <iostream>
#include <fstream>
#include <math.h>
#include <fstream>
#include "numberTheory.hpp"
#include "ReallyLongInt.hpp"
//Uses modPower from numberTheory
using namespace std;
int main(int argc, char* argv[])
{
/* Input files and their order
* 1st: public.txt
* 2nd: plaintext.txt
* 3rd: encrypted.txt
*/
ifstream fin(argv[1]);
//Gets user first user input after ./encrypt
string ex; //This is e
string nu; //This is n
fin >> ex;
fin >> nu;
ReallyLongInt exp(ex);
ReallyLongInt num(nu);
ifstream inpt(argv[2]);
ofstream encrypt(argv[3]);
char c;
//unsigned long long newNumb;
while (inpt.get(c))
{
int real = int(c);
ReallyLongInt newNumb = modPower(ReallyLongInt(real), exp, num);
encrypt << newNumb << endl;
}
}
| true |
8f1d141da802a4316a9f8b216a9ffaa65e409cc6 | C++ | jsimpson9/win32proto | /Win32Proto1/Win32Proto1/Card.h | UTF-8 | 1,011 | 2.96875 | 3 | [] | no_license | #pragma once
#ifndef CARD_H
#define CARD_H
#include <windows.h>
class Card
{
private:
int _face;
int _suit;
bool _isFacedown;
static constexpr int CARD_WIDTH = 50;
static constexpr int CARD_HEIGHT = 100;
public:
Card(int face, int suit);
Card(int face, int suit, bool isFacedown);
void Paint(HDC hdc, int x, int y);
int GetFace();
int GetSuit();
int GetValue();
bool isFacedown();
void setFacedown(bool b);
static constexpr int CLUBS = 1;
static constexpr int DIAMONDS = 2;
static constexpr int HEARTS = 3;
static constexpr int SPADES = 4;
static constexpr int ACE = 1;
static constexpr int TWO = 2;
static constexpr int THREE = 3;
static constexpr int FOUR = 4;
static constexpr int FIVE = 5;
static constexpr int SIX = 6;
static constexpr int SEVEN = 7;
static constexpr int EIGHT = 8;
static constexpr int NINE = 9;
static constexpr int TEN = 10;
static constexpr int JACK = 11;
static constexpr int QUEEN = 12;
static constexpr int KING = 13;
};
#endif | true |
a65fd4d0d3cd76e9173e17c5f457247a7d75c274 | C++ | nakajimakotaro/vulkanTest | /VulkanApplication.cpp | UTF-8 | 1,239 | 2.5625 | 3 | [] | no_license | //
// Created by nakajimakotaro on 17/11/06.
//
#include "VulkanApplication.h"
VulkanApplication::VulkanApplication() {}
VulkanApplication::~VulkanApplication() {}
std::unique_ptr<VulkanApplication> VulkanApplication::instance;
extern std::vector<const char*> layerName;
extern std::vector<const char*> instanceExtensionNames;
VulkanApplication* VulkanApplication::GetInstance() {
if(!instance){
instance.reset(new VulkanApplication());
}
return instance.get();
}
VkResult VulkanApplication::createVulkanInstance(const std::vector<const char *> &layer,
const std::vector<const char *> &extensions,
char const *applicationName) {
instanceObj.createInstance(layer, extensions, applicationName);
return VK_SUCCESS;
}
VkResult VulkanApplication::createVulkanDevice() {
deviceObj.createDevice();
return VK_SUCCESS;
}
void VulkanApplication::initialize(){
createVulkanInstance(layerName, instanceExtensionNames, "name");
createVulkanDevice();
}
void VulkanApplication::prepare(){
}
void VulkanApplication::update(){
}
void VulkanApplication::render(){
}
void VulkanApplication::deInitialize(){
}
| true |
e5e21b1035082a88c1bb1f73ebf00088716e91cf | C++ | ZackaryIngram/A1_IngramZackary | /GAME1017_ShooterExample/States.h | UTF-8 | 1,763 | 2.65625 | 3 | [] | no_license | #pragma once
#ifndef _STATES_
#define _STATES_
#include <SDL.h>
#include <vector>
#include "GameObject.h"
#include <iostream>
#include "SDL.h"
#include "SDL_image.h"
#include "SDL_mixer.h"
class State
{
public:
virtual void Enter() = 0;
virtual void Update() = 0;
virtual void Render();
virtual void Exit() = 0;
virtual void Resume();
virtual ~State() = default;
GameObject* GetGameobject(const std::string& s);
auto GetIt(const std::string& s);
protected:
State() {};
std::vector<std::pair<std::string, GameObject*>> m_objects;
vector<Enemy*> m_enemyNumber;
vector<Enemy*> m_enemy;
};
class TitleState : public State
{
public:
TitleState();
virtual void Enter();
virtual void Update();
virtual void Render();
virtual void Exit();
};
class PauseState : public State
{
private:
SDL_Texture* m_pPBGTexture;
public:
PauseState();
virtual void Enter();
virtual void Update();
virtual void Render();
virtual void Exit();
Sprite m_pbg;
};
class GameState : public State
{
private:
SDL_Renderer* m_pRenderer;
SDL_Texture* m_pEnemyTexture;
SDL_Texture* m_pTexture;
SDL_Texture* m_pRules;
SDL_Texture* m_pBGTexture;
Mix_Music* m_backgroundMusic = nullptr;
Sprite m_player, m_bg1, m_bg2, m_enemy;
int m_speed = 2;
int m_dstWidth = 500, m_dstHeight = 550;
int m_srcWidth = 500, m_srcHeight = 550 , m_srcy = 0;
int m_time = 0, m_timerE = 0, m_enemyTimer = 0;
bool m_playerSpawned = true, m_plose;
int m_counter;
public:
GameState();
virtual void Enter();
virtual void Update();
virtual void Render();
virtual void Resume();
virtual void Exit();
};
class LoseState : public State
{
public:
LoseState();
virtual void Enter();
virtual void Update();
virtual void Render();
virtual void Exit();
};
#endif
| true |
fd4807f8fa2d2ef6b5425e2c223dff8eeac1fa5a | C++ | morgetai/Pacman | /Pacman/CheckBox.cpp | UTF-8 | 2,333 | 3.171875 | 3 | [] | no_license | /**
*************************************************************************************************************************
* @file Checkbox.cpp
* @author Hridin Andrii
* abgridin@gmail.com
* @date 13-March-2019
* @brief Implementation of the checkbox
**************************************************************************************************************************
*/
/*includes*/
#include "CheckBox.h"
#include"Command_base.h"
#include"Primitives.h"
/*setting sprite ptr to null*/
std::unique_ptr<Sprite> CheckBox::checkbox_sprite = nullptr;
/**
* @brief constructor
* @param1 rectangle
* @param3 command object
*/
CheckBox::CheckBox(SDL_Rect r,
std::unique_ptr<Command_Base>&& _command):
dest(r),
command(std::move(_command))
{
acted = true;
}
/*Destructor*/
CheckBox::~CheckBox()
{
}
/**
* @brief executes command
* @note
* @retval none
*/
void CheckBox::act()
{
command->execute();
/*if checkbox was set before*/
if (!acted)
{
state = ACTUATORSTATE::ACTING;
acted = true;
}
else
acted = false;
}
/**
* @brief checks to see if cursor is in the checkbox rectangle
* @note this function is called when actuator is in ACTING state.
* @param1 x of mause position
* @param2 y of mause position
* @retval true when mouse coursor is in actuator rectangle
*/
bool CheckBox::check_collision(int x, int y)
{
SDL_Point p;
p.x = x; p.y = y;
return SDL_PointInRect(&p, &dest);
}
/**
* @brief rendring the actuator
* @retval none
*/
void CheckBox::render()
{
checkbox_sprite->set_rect(dest);
switch (state)
{
case ACTUATORSTATE::NONACTIVE:
if (acted)
checkbox_sprite->render(2);
else
checkbox_sprite->render(0);
break;
case ACTUATORSTATE::ACTIVE:
if (acted)
{
checkbox_sprite->render(2);
}
else
{
checkbox_sprite->render(1);
}
break;
case ACTUATORSTATE::ACTING:
if (acted)
{
checkbox_sprite->render(2);
}
else
{
checkbox_sprite->render(1);
}
break;
}
}
/**
* @brief sets a checkbox sprite
* @param1 number of images
* @param2 renderer
* @param3 path to sprite image file
* @note
* @retval none
*/
void CheckBox::set_checkbox_sprite(std::shared_ptr<SDL_Renderer> r, std::string path)
{
std::unique_ptr<Sprite> ptr(std::make_unique<Sprite>(3, r, path, SpriteOrientation::HORIZONTAL));
CheckBox::checkbox_sprite = std::move(ptr);
} | true |
2b7984c970c96afcd1e0340a26ee0e290facadfc | C++ | phoenixperry/wellcome_forest | /libraries/AceRoutine/examples/HelloCoroutine/HelloCoroutine.ino | UTF-8 | 1,453 | 3.140625 | 3 | [
"MIT"
] | permissive | /*
* HelloCoroutine. Use 2 coroutines to print "Hello, World", the hard way.
* A 3rd coroutine spins away on the side, blinking the LED.
*/
#include <Arduino.h>
#include <AceRoutine.h>
using namespace ace_routine;
#ifdef LED_BUILTIN
const int LED = LED_BUILTIN;
#else
// Some ESP32 boards do not define LED_BUILTIN. Sometimes they have more than
// one built-in LEDs. Replace this with the pin number of your LED.
const int LED = 5;
#endif
const int LED_ON = HIGH;
const int LED_OFF = LOW;
// Use asymmetric delays to demonstrate that COROUTINES eliminate the need to
// keep track of the blinking states explicitly.
const int LED_ON_DELAY = 100;
const int LED_OFF_DELAY = 500;
COROUTINE(blinkLed) {
COROUTINE_LOOP() {
digitalWrite(LED, LED_ON);
COROUTINE_DELAY(LED_ON_DELAY);
digitalWrite(LED, LED_OFF);
COROUTINE_DELAY(LED_OFF_DELAY);
}
}
COROUTINE(printHello) {
COROUTINE_BEGIN();
Serial.print(F("Hello, "));
Serial.flush();
COROUTINE_DELAY(2000);
COROUTINE_END();
}
COROUTINE(printWorld) {
COROUTINE_BEGIN();
COROUTINE_AWAIT(printHello.isDone());
Serial.println(F("World!"));
COROUTINE_END();
}
void setup() {
#if ! defined(UNIX_HOST_DUINO)
delay(1000);
#endif
Serial.begin(115200);
while (!Serial); // Leonardo/Micro
pinMode(LED, OUTPUT);
}
// Manually execute the coroutines.
void loop() {
blinkLed.runCoroutine();
printHello.runCoroutine();
printWorld.runCoroutine();
}
| true |
abcc49e008528d2107f56e0e1e932c1366742314 | C++ | zerodarkzone/CppLoxLLVM | /src/Lox.hpp | UTF-8 | 1,025 | 2.71875 | 3 | [
"MIT"
] | permissive | //
// Created by juanb on 30/09/2018.
//
#ifndef CPPLOX_LOX_HPP
#define CPPLOX_LOX_HPP
#include <iostream>
#include <fstream>
#include <sstream>
#include "vm.hpp"
class Lox
{
public:
static void repl()
{
std::string line;
while (true)
{
std::cout << "> ";
std::getline(std::cin, line);
if (std::cin.eof())
{
std::cout << std::endl;
break;
}
m_vm.interpret(line + "\n");
}
}
static void runFile(const std::string &path)
{
std::ifstream file;
file.open(path, std::ios::in | std::ios::binary);
if (!file.good())
{
std::cerr << "Could not open or read the file \"" << path << "\"." << std::endl;
exit(47);
}
std::stringstream ss;
ss << file.rdbuf();
InterpretResult result = m_vm.interpret(ss.str());
file.close();
if (result == InterpretResult::COMPILE_ERROR)
exit(65);
if (result == InterpretResult::RUNTIME_ERROR)
exit(70);
}
private:
static VM m_vm;
};
#endif //CPPLOX_LOX_HPP
| true |
20c8aaa5051818d890c6a3aafa7f1632c3d45a54 | C++ | jefferis/sequence-graphs | /libFMD/Test/ZipMappingSchemeTests.cpp | UTF-8 | 8,864 | 2.546875 | 3 | [
"MIT"
] | permissive | // Test the Zip MappingScheme
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <ReadTable.h>
#include <SuffixArray.h>
#include "../FMDIndex.hpp"
#include "../FMDIndexBuilder.hpp"
#include "../util.hpp"
#include "ZipMappingSchemeTests.hpp"
// Register the fixture to be run.
CPPUNIT_TEST_SUITE_REGISTRATION( ZipMappingSchemeTests );
// Define constants
const std::string ZipMappingSchemeTests::filename = "Test/duplicated.fa";
ZipMappingSchemeTests::ZipMappingSchemeTests() {
}
ZipMappingSchemeTests::~ZipMappingSchemeTests() {
}
void ZipMappingSchemeTests::setUp() {
// We need a built index as a fixture, and we don't want to rebuild it for
// every test.
// Set up a temporary directory to put the index in.
tempDir = make_tempdir();
// Make a new index builder.
FMDIndexBuilder builder(tempDir + "/index.basename");
// Add the haplotypes file
builder.add(filename);
// Finish the index.
FMDIndex* tmpIndex = builder.build();
// Don't leak it.
delete tmpIndex;
// Save a pointer to a new index that we just load (so we don't have the
// full SA).
index = new FMDIndex(tempDir + "/index.basename");
// Declare every 2 adjacent positions to be a range (since everything
// appears twice in the input).
ranges = new GenericBitVector();
for(size_t i = 0; i < index->getBWTLength(); i += 2) {
ranges->addBit(i);
}
ranges->finish(index->getBWTLength());
// Make the mapping scheme. Leave the mask empty so everything is masked in,
// but use our ranges. Don't care at all about what positions are assigned
// to ranges.
scheme = new ZipMappingScheme<FMDPosition>(FMDIndexView(*index, nullptr,
ranges));
}
void ZipMappingSchemeTests::tearDown() {
// Clean up the mapping scheme
delete scheme;
// Get rid of the temporary index directory
boost::filesystem::remove_all(tempDir);
// Delete the index
delete index;
// And the ranges bit vector
delete ranges;
}
/**
* Make sure mapping works
*/
void ZipMappingSchemeTests::testMap() {
// Grab all of the duplicated contig.
std::string query = "CATGCTTCGGCGATTCGACGCTCATCTGCGACTCT";
size_t mappedBases = 0;
// Map everything and get callbacks
scheme->map(query, [&](size_t i, TextPosition mappedTo) {
// Everything that maps should be mapped to the correct position on text
// 0 or 2, which are the ones we should have merged in this direction.
CPPUNIT_ASSERT(mappedTo.getText() == 0 || mappedTo.getText() == 2);
CPPUNIT_ASSERT_EQUAL(i, mappedTo.getOffset());
mappedBases++;
});
// All the bases should map. This scheme is only weakly stable.
CPPUNIT_ASSERT_EQUAL(query.size(), mappedBases);
// Grab all of the first contig's reverse strand.
std::string query2 = "AGAGTCGCAGATGAGCGTCGAATCGCCGAAGCATG";
// Reset for the next mapping
mappedBases = 0;
// Map everything and get callbacks again
scheme->map(query2, [&](size_t i, TextPosition mappedTo) {
// Everything that maps should be mapped to the correct position on text
// 1 or 3, which are the ones we should have merged in this direction.
CPPUNIT_ASSERT(mappedTo.getText() == 1 || mappedTo.getText() == 3);
CPPUNIT_ASSERT_EQUAL(i, mappedTo.getOffset());
mappedBases++;
});
// All the abses should map. This scheme is only weakly stable.
CPPUNIT_ASSERT_EQUAL(query2.size(), mappedBases);
}
/**
* Make sure mapping works with a mask on.
*/
void ZipMappingSchemeTests::testMapWithMask() {
// Grab all of the duplicated contig.
std::string query = "CATGCTTCGGCGATTCGACGCTCATCTGCGACTCT";
// Make a mask for only one of the duplicates
auto mask = new GenericBitVector();
for(size_t i = 0; i < index->getBWTLength(); i++) {
if(index->locate(i).getContigNumber() == 0) {
// Only include the first contig
mask->addBit(i);
}
}
mask->finish(index->getBWTLength());
// Turn the genome restriction on, and don't use a merged ranges vector
delete scheme;
scheme = new ZipMappingScheme<FMDPosition>(FMDIndexView(*index, mask));
size_t mappedBases = 0;
scheme->map(query, [&](size_t i, TextPosition mappedTo) {
// Make sure each base maps in order to the first text.
CPPUNIT_ASSERT_EQUAL((size_t) 0, mappedTo.getText());
CPPUNIT_ASSERT_EQUAL(i, mappedTo.getOffset());
mappedBases++;
});
delete mask;
// All of the bases should map
CPPUNIT_ASSERT_EQUAL(query.size(), mappedBases);
}
/**
* Make sure mapping works with a mask on and ranges.
*/
void ZipMappingSchemeTests::testMapWithMaskAndRanges() {
// Grab all of the duplicated contig.
std::string query = "CATGCTTCGGCGATTCGACGCTCATCTGCGACTCT";
// Make a mask for the other of the duplicates
auto mask = new GenericBitVector();
for(size_t i = 0; i < index->getBWTLength(); i++) {
if(index->locate(i).getContigNumber() == 1) {
// Only include the second contig
mask->addBit(i);
}
}
mask->finish(index->getBWTLength());
// Turn the genome restriction on, and do use the merged ranges vector
delete scheme;
scheme = new ZipMappingScheme<FMDPosition>(FMDIndexView(*index, mask,
ranges));
size_t mappedBases = 0;
scheme->map(query, [&](size_t i, TextPosition mappedTo) {
// Make sure each base maps in order to text 2 (the one we masked in).
CPPUNIT_ASSERT_EQUAL((size_t) 2, mappedTo.getText());
CPPUNIT_ASSERT_EQUAL(i, mappedTo.getOffset());
mappedBases++;
});
delete mask;
// All of the bases should map
CPPUNIT_ASSERT_EQUAL(query.size(), mappedBases);
}
/**
* Make sure mapping works with FMDPosiutionGroups, but no mismatches.
*/
void ZipMappingSchemeTests::testMapWithGroups() {
// Grab all of the duplicated contig.
std::string query = "CATGCTTCGGCGATTCGACGCTCATCTGCGACTCT";
// Make a mask for the other of the duplicates
auto mask = new GenericBitVector();
for(size_t i = 0; i < index->getBWTLength(); i++) {
if(index->locate(i).getContigNumber() == 1) {
// Only include the second contig
mask->addBit(i);
}
}
mask->finish(index->getBWTLength());
// Turn the genome restriction on, and do use the merged ranges vector
delete scheme;
scheme = new ZipMappingScheme<FMDPositionGroup>(FMDIndexView(*index, mask,
ranges));
size_t mappedBases = 0;
scheme->map(query, [&](size_t i, TextPosition mappedTo) {
// Make sure each base maps in order to text 2 (the one we masked in).
CPPUNIT_ASSERT_EQUAL((size_t) 2, mappedTo.getText());
CPPUNIT_ASSERT_EQUAL(i, mappedTo.getOffset());
mappedBases++;
});
delete mask;
// All of the bases should map
CPPUNIT_ASSERT_EQUAL(query.size(), mappedBases);
}
/**
* Make sure mapping works with FMDPosiutionGroups and mismatches.
*/
void ZipMappingSchemeTests::testMapWithMismatches() {
// Grab all of the duplicated contig, but introduce a couple mismatches at
// 6 and 31.
// v v
std::string query = "CATGCTCCGGCGATTCGACGCTCATCTGCGAATCT";
// Make a mask for the other of the duplicates
auto mask = new GenericBitVector();
for(size_t i = 0; i < index->getBWTLength(); i++) {
if(index->locate(i).getContigNumber() == 1) {
// Only include the second contig
mask->addBit(i);
}
}
mask->finish(index->getBWTLength());
// Turn the genome restriction on, and do use the merged ranges vector
delete scheme;
scheme = new ZipMappingScheme<FMDPositionGroup>(FMDIndexView(*index, mask,
ranges));
// Allow for mismatches.
((ZipMappingScheme<FMDPositionGroup>*) scheme)->mismatchTolerance = 1;
// But require some nearby pins
((ZipMappingScheme<FMDPositionGroup>*) scheme)->minUniqueStrings = 2;
size_t mappedBases = 0;
scheme->map(query, [&](size_t i, TextPosition mappedTo) {
// Make sure mismatched bases do not map.
CPPUNIT_ASSERT(i != 6);
CPPUNIT_ASSERT(i != 31);
// Make sure each other base maps in order to text 2 (the one we masked
// in).
CPPUNIT_ASSERT_EQUAL((size_t) 2, mappedTo.getText());
CPPUNIT_ASSERT_EQUAL(i, mappedTo.getOffset());
mappedBases++;
});
delete mask;
// All but two of the bases should map
CPPUNIT_ASSERT_EQUAL(query.size() - 2, mappedBases);
}
| true |
cf577b0e1948e5bb0c880e7532921a4dadaf55a1 | C++ | bheckel/code | /misc/c/mutex.cpp | UTF-8 | 2,861 | 3.296875 | 3 | [
"Apache-2.0"
] | permissive | //////////////////////////////////////////////////////////////////////////////
// Name: mutex.cpp
//
// Summary: Demo a POSIX mutex (mutual exclusion) that implements a simple,
// single, global lock. The goal is to avoid race conditions.
//
// A program has a data race if it is possible for a thread to
// modify an addressable location at the same time that another
// thread is accessing the same location.
//
// See also mutex_condition_vari.cpp
//
// Adapted: Sun 27 Jan 2002 11:01:02 (Bob Heckel -- Martin Casado tutorial
// http://www.cse.nau.edu/~mc8/index.html)
//////////////////////////////////////////////////////////////////////////////
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream.h>
#include <fstream.h>
#include <string.h>
// In this example we are going to use a global mutex.
pthread_mutex_t myMutex = PTHREAD_MUTEX_INITIALIZER;
// File Stream for the threads to write to.
ofstream fileOut;
// Char arrays of words to write to file.
char *intro = "Once a king\n\0";
char *body = "Always a king\n\0";
char *nearend = "But....\n\0";
char *end = "Once a night's enough\n\0";
char *separator = "*************************\n\0";
// Prototypes.
void *myThreadFunc(void *arg);
void writeStoryToFile(void);
int main(void){
pthread_t thread1, thread2; // declare two threads
// Open a file to write to in append mode.
fileOut.open("junk.txt", ios::out | ios::app);
// Start the first thread running.
pthread_create(&thread1, NULL, myThreadFunc, (void *)NULL);
// Start the second thread running.
pthread_create(&thread2, NULL, myThreadFunc, (void *)NULL);
// Wait for threads to stop before we exit main().
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
fileOut.close();
cout << "junk.txt created. Exiting main().\n";
return 0;
}
// Thread function simply calls our writeStoryToFile method. What we *don't*
// want to be doing is writing to the same file at the same time.
void *myThreadFunc(void *arg){
for ( int i=0;i<5;i++ ){
writeStoryToFile();
}
return((void*)NULL);
}
// Print to file (without collisions).
void writeStoryToFile(void){
// Lock the global mutex so only one thread is writing to the file at a
// time. The other thread spins until it's unlocked.
pthread_mutex_lock(&myMutex);
// Begin "critical section". Flip the bathroom's OCCUPIED sign.
fileOut.write(intro, strlen(intro));
fileOut.write(body, strlen(body));
fileOut.write(nearend, strlen(nearend));
fileOut.write(end, strlen(end));
fileOut.write(separator, strlen(separator));
// End "critical section". Flip the bathroom's VACANT sign.
// Now Unlock the global mutex enabling thread2 to run this section of code.
pthread_mutex_unlock(&myMutex);
}
| true |
ec088f4c3b1874b34b22f2de1b5302ad7e846327 | C++ | ymladeno/resmgr | /resmgr.sample/src/main.cpp | UTF-8 | 2,229 | 2.578125 | 3 | [] | no_license | #include "factory/CResourceMngFactory.hpp"
#include "CResourceManager.hpp"
#include "parser/CommandLine.hpp"
#include "Callback.hpp"
#include <exception>
#include <iostream>
#include <sstream>
#include <functional>
#define READ_WRITE_ACCESS 0x0666
int main(int argc, const char* argv[]) {
try {
res::parser::CommandLine cmdLine{};
cmdLine.add_option('c', "config", "Ini file configuration");
cmdLine.add_option('h', "help", "This is help");
cmdLine.add_option('f', "font_color", "This is font color");
cmdLine.add_option('b', "background_color", "This is background color");
cmdLine.add_option('d', "debug_mode", "This is debug mode");
cmdLine.parse(argc, argv);
std::string l_ini_path = cmdLine.get_program_argument('c');
if (l_ini_path.empty()) {
std::cout << "No ini file\n";
}
Editor editor{};
const auto& l_font_color = cmdLine.get_program_argument("font_color");
if (!l_font_color.empty()) {
editor.set_font_color(l_font_color);
}
const auto& l_background_color = cmdLine.get_program_argument("background_color");
if (!l_background_color.empty()) {
editor.set_background_color(l_background_color);
}
Callback callback{editor};
res::factory::CResourceMngFactory factory;
std::shared_ptr<res::CResourceManagerImpl> p_qnxResMngImpl =
factory.createResManagerImpl(res::factory::CResourceMngFactory::ResManagerTypes::QnxResourceManager);
res::CResourceManager resmgr(p_qnxResMngImpl);
resmgr.init("/dev/sample", READ_WRITE_ACCESS);
resmgr.initcallback("read", std::bind(&Callback::read, &callback, std::placeholders::_1));
resmgr.initcallback("write", std::bind(&Callback::write, &callback, std::placeholders::_1));
resmgr.initcallback("devctl", std::bind(&Callback::devctl, &callback, std::placeholders::_1));
//call blocked method
resmgr.run();
//normally never execute code after line above
}
catch(std::exception& e) {
std::cout << e.what() << std::endl;
}
return 0;
}
| true |
3bc216de1fd18e911b58a3610ae36c7dc9a419d2 | C++ | kmoza/cpp_workspace | /map_multimap/src/main.cpp | UTF-8 | 641 | 3.375 | 3 | [] | no_license | /*
* main.cpp
*
* Created on: 26-Dec-2013
* Author: kmoza
*/
#include<cstring>
#include<iostream>
#include<map>
#include<utility>
using namespace std;
int main()
{
map<int,string> Employees;
// 1) Assignment using array index notation
Employees[5234] = "Mike C.";
Employees[3374] = "Charlie M.";
Employees[1923] = "David D.";
Employees[7582] = "John A.";
Employees[5328] = "Peter Q.";
cout<<"Employees[3374]="<<Employees[3374]<<endl;
cout<<"Map Size:"<<Employees.size()<<endl;
for(map<int,string>::iterator ii=Employees.begin();ii!=Employees.end();ii++)
{
cout<<(*ii).first<<":"<<(*ii).second<<endl;
}
return 0;
}
| true |
92509905e3ffd396d701cf82dcab5b4881d1ebeb | C++ | annasjiang/mini-maya | /assignment_package/src/mesh.h | UTF-8 | 752 | 2.578125 | 3 | [] | no_license | #ifndef MESH_H
#define MESH_H
#pragma once
#include "smartpointerhelp.h"
#include "face.h"
#include "vertex.h"
#include "halfedge.h"
#include "drawable.h"
#include "skeleton.h"
using namespace glm;
using namespace std;
class Mesh : public Drawable {
public:
// member vars
vector<uPtr<Vertex>> vertexList;
vector<uPtr<HalfEdge>> halfEdgeList;
vector<uPtr<Face>> faceList;
// constructor + destructor
Mesh(OpenGLContext* context);
~Mesh() override;
// functions
void create() override;
GLenum drawMode() override;
void setSym(int x, int y); // helper
void setHalfEdgeVert(int x, int y, int z); // helper
void createCube();
static void resetCount(); // for importing objs
};
#endif // MESH_H
| true |
35a76a66aea2b7015af40ed6f5d8504600c1f831 | C++ | anderfernandes/COSC_1337 | /lesson_5/question_4.cpp | UTF-8 | 1,445 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
vector <string>sentences;
string sentence;
// Loading input file into program
ifstream inputFile;
bool needFirstUpper = true;
// Opening file
inputFile.open("input.txt", ios::in);
string word;
// Loading output file into program
ofstream filterFile;
filterFile.open("filter.txt", ios::out);
//
if (!inputFile)
{
cout << "Failed to open file." << endl;
return 0;
}
// Check for file existence
if (!filterFile)
{
cout << "Failed to open file." << endl;
return 0;
}
// Reading file contents, looping through each word in the file
while (inputFile >> word)
{
// Loop through each letter
for (int i = 0; i < word.length(); i++)
{
// Make all letters lowercase
word[i] = tolower(word[i]);
}
// If the previous word ended in a period...
if (needFirstUpper)
{
// ... Set first letter to upper case
word[0] = toupper(word[0]);
// ... We won't need the next letter to be upper case
needFirstUpper = false;
}
// Check if word has a period in the end, which indicates the end of a sentence
if (word.back() == '.')
// Mark next word to have first letter uppercase
needFirstUpper = true;
// Add white space to end of the word
word.push_back(' ');
// Writing word to file
filterFile << word;
}
inputFile.close();
filterFile.close();
return 0;
} | true |
23722d01ec3b451d9957658f9e656e3923c60bd9 | C++ | mesyarik/cpp2021-test | /ref_underhood.cpp | UTF-8 | 765 | 3.28125 | 3 | [] | no_license | #include <iostream>
void f(int& r);
int main() {
int x = 0;
int* p = &x;
int& r = x;
int y = 1;
double d = 3.14;
std::cout << &x << ' ' << &p << ' ' << &y << ' ' << &d << '\n';
// memory layout:
// [x(4)][y(4)][ p(8) ][ d(8) ]
// Where is r? Nowhere!
f(x);
}
void f(int& r) {
int x = 0;
int* p = &x;
std::cout << &r << '\n';
std::cout << &x << ' ' << &p << '\n';
// ....[x(4)]|[ p==&x (8) ]
std::cout << &p-1 << ' ' << *(&p-1) << '\n';
std::cout << &p-2 << ' ' << *(&p-2) << '\n';
std::cout << &p-3 << ' ' << *(&p-3) << '\n';
// [ &x==r(8) ]|........|....[x(4)]|[ p==&x(8) ]
for (int i = 4; i <=200; ++i)
std::cout << &p-i << ' ' << *(&p-i) << '\n';
}
| true |
178bcb879ce67b16c8f6a0d481524f5f6d5d16a8 | C++ | wechatplugin/MicroChat | /test/test/python_interface_base.cpp | GB18030 | 3,050 | 2.53125 | 3 | [] | no_license | #include "stdafx.h"
#include "python_interface_base.h"
CPythonBase::CPythonBase()
{
Init();
}
CPythonBase::~CPythonBase()
{
Py_Finalize();
}
PyObject * CPythonBase::ImportModule(LPCSTR szModuleName)
{
PyObject *pModule = PyImport_ImportModule(szModuleName);
if (pModule)
{
CPyModule *pPyModule = new CPyModule;
if (pPyModule)
{
pPyModule->m_pModule = pModule;
m_map.insert(make_pair(szModuleName,pPyModule));
}
}
else
{
#ifdef USE_CONSOLE
PyErr_Print();
#endif
assert(pModule);
}
return pModule;
}
BOOL CPythonBase::RegisterPythonFunction(LPCSTR szModuleName, LPCSTR szFuncName)
{
map<CStringA, CPyModule*>::iterator iter = m_map.find(szModuleName);
if (m_map.end() != iter)
{
CPyModule *pPyModule = iter->second;
if (pPyModule && pPyModule->m_pModule)
{
PyObject* pv = PyObject_GetAttrString(pPyModule->m_pModule, szFuncName);
assert(pv);
if (pv && PyCallable_Check(pv))
{
pPyModule->m_FuncMap.insert(make_pair(szFuncName, pv));
return TRUE;
}
}
}
return FALSE;
}
PyObject * CPythonBase::CallObject(LPCSTR szModuleName, LPCSTR szFuncName, LPCSTR szArgsFormat, ...)
{
map<CStringA, CPyModule*>::iterator iter = m_map.find(szModuleName);
if (m_map.end() != iter)
{
CPyModule *pPyModule = iter->second;
if (pPyModule)
{
map<CStringA, PyObject*>::iterator it = pPyModule->m_FuncMap.find(szFuncName);
if (pPyModule->m_FuncMap.end() != it)
{
PyObject* pv = it->second;
if (pv)
{
PyObject* args = NULL;
CStringA strArgsFormat = szArgsFormat;
if (!strArgsFormat.IsEmpty())
{
//עǿתԪ顢бֵ
va_list ap;
va_start(ap, szArgsFormat);
args = Py_VaBuildValue(szArgsFormat,ap);
va_end(ap);
}
PyObject *pRet = PyEval_CallObject(pv, args);
#ifdef USE_CONSOLE
if (!pRet) PyErr_Print();
#endif
PY_FREE(args);
return pRet;
}
}
}
}
return NULL;
}
PyObject * CPythonBase::ParseResult(PyObject *p, LPCSTR szKey, LPCSTR szArgsFormat, void *pRet)
{
if (p)
{
PyObject* pValue = PyDict_GetItemString(p, szKey);
if (pValue)
{
PyArg_Parse(pValue, szArgsFormat, pRet);
}
return pValue;
}
return NULL;
}
void CPythonBase::Init()
{
//Ϊδװpythonûpython
wchar_t *szHomeDir = new wchar_t[MAX_PATH];
assert(szHomeDir);
if (szHomeDir)
{
ZeroMemory(szHomeDir,MAX_PATH);
GetCurrentDirectory(MAX_PATH, szHomeDir);
wcscat(szHomeDir, L"\\python35");
Py_SetPythonHome(szHomeDir);
}
wchar_t szFileName[MAX_PATH] = { 0 };
GetModuleFileName(NULL, szFileName, MAX_PATH);
CString strExeFileName = szFileName;
if (-1 != strExeFileName.ReverseFind('\\'))
{
strExeFileName = strExeFileName.Mid(strExeFileName.ReverseFind('\\') + 1);
}
Py_SetProgramName(strExeFileName.GetBuffer()); /* optional but recommended */
//ʼpython
Py_Initialize();
assert(Py_IsInitialized());
#ifdef USE_CONSOLE
AllocConsole();
freopen("conout$", "w", stdout);
#endif
}
| true |
41f8a80a70658e975076d1f9727ad44ef5e83f96 | C++ | jacking75/book_semina_samples | /Boost_20131105/Asio_02_Server/Session.cpp | UHC | 1,369 | 2.78125 | 3 | [
"MIT"
] | permissive | #include "Session.h"
void Session::PostReceive()
{
memset( &m_ReceiveBuffer, '\0', sizeof(m_ReceiveBuffer) );
m_Socket.async_read_some
(
boost::asio::buffer(m_ReceiveBuffer),
boost::bind( &Session::handle_receive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred )
);
}
void Session::handle_receive( const boost::system::error_code& error, size_t bytes_transferred )
{
if( error )
{
if( error == boost::asio::error::eof )
{
std::cout << "Ŭ̾Ʈ ϴ" << std::endl;
}
else
{
std::cout << "error No: " << error.value() << " error Message: " << error.message() << std::endl;
}
}
else
{
const std::string strRecvMessage = m_ReceiveBuffer.data();
std::cout << "Ŭ̾Ʈ : " << strRecvMessage << ", ũ: " << bytes_transferred << std::endl;
char szMessage[128] = {0,};
sprintf_s( szMessage, 128-1, "Re:%s", strRecvMessage.c_str() );
m_WriteMessage = szMessage;
boost::asio::async_write(m_Socket, boost::asio::buffer(m_WriteMessage),
boost::bind( &Session::handle_write, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred )
);
PostReceive();
}
} | true |
3a005a23ab47244ad3c0b0d1cddbf9c442701ee6 | C++ | Tutkovics/Prog2_NHF | /Family.cpp | UTF-8 | 230 | 2.625 | 3 | [] | no_license | #include "Family.h"
void Family::printDatas() {
Movie::printDatas();
std::cout << "Korhatár: " << ageLimit << std::endl;
}
void Family::printToFile(std::fstream &os) {
Movie::printToFile(os);
os << ageLimit ;
}
| true |
ace54e3d162c3d2261fa765055ec0c01be8d1c3b | C++ | rodrigoaramos/Morphos | /Morphos/Container.cpp | UTF-8 | 1,291 | 2.96875 | 3 | [
"BSD-3-Clause"
] | permissive | #include "Container.h"
#include <algorithm>
using namespace std;
namespace geometry
{
Container::Container() : _mrect((Rect&)Rect()) // , _grrc((Rect&)Rect())
{
//
}
Container::Container(Rect& r) : _mrect(r) //, _grrc((Rect&)Rect())
{
//
}
Container::~Container()
{
//
}
const Container& Container::operator = (const Container& ct)
{
_mrect = ct.GetRect();
//_ignore = ct.isIgnored();
vector<Container> vt = ct.GetChilds();
for (size_t i = 0; i < vt.size(); i++)
_childs.push_back(vt[i]);
return *this;
}
Rect& Container::GetRect() const
{
return _mrect;
}
void Container::SetRect(Rect& r)
{
_mrect = r;
}
/*Rect& Container::GetGroupRect() const
{
return *_grrc;
}
void Container::SetGroupRect(Rect& r)
{
_grrc = &r;
}*/
/*bool Container::isGroup() const
{
return _isgroup;
}
void Container::SetGroup(bool b)
{
_isgroup = b;
}*/
ContainerType& Container::GetType() const
{
return (ContainerType&)_tpctner;
}
void Container::SetType(ContainerType r)
{
_tpctner = r;
}
bool Container::hasChilds() const
{
return (_childs.size() > 0);
}
vector<Container>& Container::GetChilds() const
{
return (vector<Container>&)_childs;
}
void Container::Add(Container& ct)
{
_childs.push_back(ct);
}
}
| true |
bfbe1019928e15fd45d237b1083d5f9fc3c9c2a8 | C++ | WhiZTiM/coliru | /Archive2/0f/9c43ada2a1f936/main.cpp | UTF-8 | 614 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <type_traits>
template <typename T>
inline constexpr std::remove_reference_t<T> &lvalue(T &&r) noexcept {
return static_cast<std::remove_reference_t<T> &>(r);
}
struct foo {
foo() {
std::cout << "*foo\n";
}
~foo() {
std::cout << "~foo\n";
}
foo(foo const&) = delete;
foo(foo&&) = delete;
void
access() {
std::cout << "I'm being touched!\n";
}
};
struct bar {
foo* f;
};
foo
fun() {
return {};
}
bar
gun() {
return {&lvalue(fun())};
}
int
main() {
bar b = gun();
b.f->access();
}
| true |
2ddcae0ea0f76abc19e881156be15c6ccccf9381 | C++ | AntonioHernandez28/CrackingTheCodingInterview | /Trees & Graphs/Problem4_9.cpp | UTF-8 | 2,512 | 3.671875 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
#define COUNT 10
struct TreeNode{
int data;
TreeNode* left;
TreeNode* right;
};
void print2DUtil(TreeNode *root, int space)
{
if (root == NULL)
return;
space += COUNT;
print2DUtil(root->right, space);
cout<<endl;
for (int i = COUNT; i < space; i++)
cout<<" ";
cout<<root->data<<"\n";
print2DUtil(root->left, space);
}
void print2D(TreeNode *root)
{
print2DUtil(root, 0);
}
vector<vector<int> > findAllSeq(TreeNode *ptr)
{
if (ptr == NULL) {
vector<int> seq;
vector<vector<int> > v;
v.push_back(seq);
return v;
}
if (ptr -> left == NULL && ptr -> right == NULL) {
vector<int> seq;
seq.push_back(ptr -> val);
vector<vector<int> > v;
v.push_back(seq);
return v;
}
vector<vector<int> > results, left, right;
left = findAllSeq(ptr -> left);
right = findAllSeq(ptr -> right);
int size = left[0].size() + right[0].size() + 1;
vector<bool> flags(left[0].size(), 0);
for (int k = 0; k < right[0].size(); k++)
flags.push_back(1);
for (int i = 0; i < left.size(); i++) {
for (int j = 0; j < right.size(); j++) {
do {
vector<int> tmp(size);
tmp[0] = ptr -> val;
int l = 0, r = 0;
for (int k = 0; k < flags.size(); k++) {
tmp[k+1] = (flags[k]) ? right[j][r++] : left[i][l++];
}
results.push_back(tmp);
} while (next_permutation(flags.begin(), flags.end()));
}
}
return results;
}
TreeNode* MinimalTree(vector<int> arr, int begin, int end){
if(end < begin) return NULL;
int mid = (begin + end)/2;
TreeNode* nuevoNodo = new TreeNode();
nuevoNodo -> data = arr[mid];
nuevoNodo -> left = MinimalTree(arr, begin, mid - 1);
nuevoNodo -> right = MinimalTree(arr, mid + 1, end);
return nuevoNodo;
}
int main(){
/* Problem 4.9: BST Sequences: A binary search tree was created by traversing through an array from left to right and inserting each element.
Given a binary search tree with distinct elements, print all possible arrays that could have led to this tree.
OJO A ESTE NO LE ENTENDÍ NADA */
vector<int> arr = {1,2,3,4,5,6};
TreeNode* head = MinimalTree(arr, 0, arr.size() - 1);
print2D(head);
} | true |
a4f13162e29da913230a306ab2d662b26d2284a8 | C++ | gmoshkin/parcomp2 | /inc/point.h | UTF-8 | 2,639 | 3.265625 | 3 | [] | no_license | #ifndef __POINT_H__
#define __POINT_H__
#include <vector>
#include <iostream>
#ifndef WITHOUT_MPI
#include <mpi.h>
#endif
using std::ostream;
namespace Batcher {
struct Point
{
float coord[2];
int index;
Point(float x, float y, int i)
{
setX(x);
setY(y);
setIndex(i);
}
Point() {}
float getX() const
{
return this->coord[0];
}
float setX(float x)
{
return this->coord[0] = x;
}
float getY() const
{
return this->coord[1];
}
float setY(float y)
{
return this->coord[1] = y;
}
int getIndex() const
{
return this->index;
}
int setIndex(int i)
{
return this->index = i;
}
static Point makeDummy()
{
return Point(0.0f, 0.0f, -1);
}
#ifndef WITHOUT_MPI
static void getMPIDatatype(MPI_Datatype &type)
{
int count = 2;
int blockLengths[count] = { 2, 1 };
MPI_Aint floatExtent;
MPI_Type_extent(MPI_FLOAT, &floatExtent);
MPI_Aint dispacements[count] = {
static_cast<MPI_Aint>(0),
floatExtent * blockLengths[0]
};
MPI_Datatype types[count] = { MPI_FLOAT, MPI_INT };
MPI_Type_create_struct(count, blockLengths, dispacements, types, &type);
MPI_Type_commit(&type);
}
#endif
};
struct XComparablePoint: public Point
{
bool operator <(const Point &that)
{
return ((this->index >= 0) &&
((that.index < 0) ||
(this->getX() < that.getX())));
}
XComparablePoint() : Point() {}
XComparablePoint(float x, float y, int i) : Point(x, y, i) {}
XComparablePoint(const Point &p) : Point(p.getX(), p.getY(), p.getIndex()) {}
};
struct YComparablePoint: public Point
{
bool operator <(const Point &that)
{
return ((this->index >= 0) &&
((that.index < 0) ||
(this->getY() < that.getY())));
}
YComparablePoint() : Point() {}
YComparablePoint(float x, float y, int i) : Point(x, y, i) {}
YComparablePoint(const Point &p) : Point(p.getX(), p.getY(), p.getIndex()) {}
};
ostream &operator <<(ostream &out, const Point &p)
{
return out << '{' << p.getX() << ',' << p.getY() << "}[" << p.getIndex() << ']';
}
typedef std::vector<Point> points_t;
typedef points_t::const_iterator points_it;
typedef std::vector<XComparablePoint> xpoints_t;
typedef xpoints_t::const_iterator xpoints_it;
typedef std::vector<YComparablePoint> ypoints_t;
typedef ypoints_t::const_iterator ypoints_it;
}
#endif /* end of include guard: __POINT_H__ */
| true |
5ef905536799ada1caffdb7d10c8e8fe4a30d405 | C++ | arrudamarcelo/interprocess_communication | /Code/CoreObjects/ClassSerialize.h | UTF-8 | 658 | 2.859375 | 3 | [] | no_license | #pragma once
#include <list>
#include <string>
#include <vector>
#define DELIMITER '&'
/*
* Abstract Class resposible for allow the serialization of classes.
* The classes to be serialized needs to implement the pure virtual methods.
*/
class Serializible {
public:
virtual std::string serialize() = 0;
virtual void deserialize(std::string attribMessage);
virtual std::string className() = 0;
virtual std::list<std::string> classAttribs() = 0;
virtual std::list<std::string> classMethods() = 0;
virtual bool updateObj(std::vector<std::string> attributes) = 0;
virtual std::string classDescription();
virtual void printAttribValues() = 0;
};
| true |
1b35d56e9c5e69521863cd8f49c80c2bccae0aba | C++ | trinhvo/ravaged-planets | /include/game/simulation/local_player.h | UTF-8 | 971 | 2.59375 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | #pragma once
#include <game/simulation/player.h>
namespace fw {
class colour;
}
namespace game {
/**
* There's only one local_player, and it represents, US, that is, the person who's playing this instance of the game.
*/
class local_player: public player {
private:
session::session_state _last_session_state;
/**
* The session-id of this player, as they are logged in to the server (this is a secret, so we can't tell the
* other players!)
*/
uint64_t _session_id;
public:
local_player();
virtual ~local_player();
virtual void update();
/** This is a notification that the local player is ready. */
virtual void local_player_is_ready();
/** This is called when the world has loaded. We create our initial entities. */
virtual void world_loaded();
/** Our player# gets updated when we connect to a remote game. */
void set_player_no(uint8_t value) {
_player_no = value;
}
};
}
| true |
4267a55001a48e8a04f17d9377655109a85492ff | C++ | nikeorever/Cuiver | /IO/test/src/FileReadWriteTest.cpp | UTF-8 | 520 | 2.84375 | 3 | [] | no_license | #include "gtest/gtest.h"
#include "Cuiver/IO/FileReadWrite.h"
#include <string>
class DateConverterFixture : public ::testing::Test {
protected:
void SetUp() override {
file = new std::string;
*file = ".";
}
void TearDown() override {
delete file;
}
public:
std::string *file = nullptr;
};
TEST_F(DateConverterFixture, test) {
Cuiver::IO::for_each_line(file->c_str(), [](const std::string &line){
std::cout << line << std::endl;
});
EXPECT_EQ(1, 1);
} | true |
a6987a6189c84cd7156e06804de556c4cd7bf485 | C++ | montsemsanz/git-exercise-01 | /src/yizongk.cpp | UTF-8 | 858 | 2.546875 | 3 | [
"MIT"
] | permissive | /*******************************************************************************
Title : yizongk.cpp
Author : Yi Zong Kuang
Created on : September 26, 2018
Description : Hello world and a fun fact printed to standard output
Purpose : To collaborate with CS-OSSD group
Usage : Yi Zong Kuang
Build with : g++ -Wall -g -o yizongk yizongk.cpp
Modifications :
*******************************************************************************/
#include <iostream>
using namespace std;
int main() {
printf("Hello World from yizongk!\n");
printf("For the past few months, I been coding in C and I am kind of starting to like its style better than C++! Easier to read and understand! Though I still think Object-Oriented Programming is needed in big projects.\n");
return 0;
} | true |
c2c91846a2ff68220a24e652395e39e1c8d32a95 | C++ | ligand-lg/leetcode | /codingInterview/6_旋转有序数组最小数.cpp | UTF-8 | 848 | 3.015625 | 3 | [] | no_license | #include "../leetcode.h"
class Solution {
int help(const vector<int> &v, int b, int e) {
int m = (b + e) / 2;
if (v[b] < v[e]) return v[b];
if (v[m] > v[b]) return help(v, m + 1, e);
if (v[m] < v[e]) return help(v, b + 1, m);
return min(v[m], v[e]);
}
public:
int minNumberInRotateArray(vector<int> rotateArray) {
if (rotateArray.empty()) return 0;
return help(rotateArray, 0, rotateArray.size() - 1);
}
};
int main() {
Solution s;
vector<int> test_case{
6501, 6828, 6963, 7036, 7422, 7674, 8146, 8468, 8704, 8717, 9170, 9359,
9719, 9895, 9896, 9913, 9962, 154, 293, 334, 492, 1323, 1479, 1539,
1727, 1870, 1943, 2383, 2392, 2996, 3282, 3812, 3903, 4465, 4605, 4665,
4772, 4828, 5142, 5437, 5448, 5668, 5706, 5725, 6300, 6335};
cout << s.minNumberInRotateArray(test_case);
} | true |
f910abcaf932242767e3a98d0b196becb1bbb610 | C++ | IsuruMS/Bankers-Algorithm-in-Cpp | /Bankers_Algorithm_in_cpp.cpp | UTF-8 | 3,717 | 3.359375 | 3 | [] | no_license | // C++ program to illustrate Banker's Algorithm
#include<iostream>
using namespace std;
int processes[100];
int avail[10];
int maxm[100][10];
int allot[100][10];
int need[100][10];
int safeSeq[100];
int work[10];
int request[10];
int n, m;
// calculates and store the need of each process in need[][]matrix
void calculateNeed()
{
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
need[i][j] = maxm[i][j] - allot[i][j];
}
// Function to check the state is safe or not
bool isSafe()
{
// in the begining all processes are not finished
bool finish[100] = { 0 };
// Make a copy of available resources
for (int i = 0; i < m; i++)
{
work[i] = avail[i];
}
// until all processes are finished the algorithm will iterate throug every possible process
int count = 0;
while (count < n)
{
bool found = false;
//safety algorithm implementation
for (int p = 0; p < n; p++)
{
if (finish[p] == 0)
{
int j;
for (j = 0; j < m; j++)
if (need[p][j] > work[j])
break;
// If all needs of p were satisfied.
if (j == m)
{
for (int k = 0; k < m; k++)
{
work[k] += allot[p][k];
}
safeSeq[count++] = p;
finish[p] = 1;
found = true;
}
}
}
if (found == false)
{
cout << "System state : UN SAFE\nHIGHER CHANCE OF DEADLOCKS\n";
return false;
}
}
// If system is in safe state then
// safe sequence will be as below
cout << "System State : SAFE.\nPrograms will be executed in the following order: \n";
for (int i = 0; i < n; i++)
cout <<"Process "<< safeSeq[i] << " >> ";
return true;
}
// Driver code
int main()
{
int temp;
cout << "No. of Processes : ";
cin >> n;
cout << endl << "No. of Resources : ";
cin >> m;
cout << endl;
for (int i = 0; i < n; i++)
{
processes[i] = i;
}
// Available instances of resources
for (int i = 0; i < m; i++)
{
cout << "R (" << i << ") : ";
cin >> avail[i];
}
cout << "Please enter the maximum resources that can be allocated in the following manner.\n<Memory for P0>\n<Memory for P1>\n...\n...\n\n";
// Maximum R that can be allocated
// to processes
int total[10] = { 0 };
for (int j = 0; j < n; j++)
{
for (int l = 0; l < m; l++)
{
cout << "P" << j << " -> R(" << l << ") : ";
cin >> maxm[j][l];
}
}
cout << "Please enter the Pre allocated resources\\n<Memory for P0>\n<Memory for P1>\n...\n...\n\n";
// Resources allocated to processes
for (int j = 0; j < n; j++)
{
for (int l = 0; l < m; l++)
{
cout << "P" << j << " -> R(" << l << ") : ";
cin >> allot[j][l];
total[l] += allot[j][l];
}
}
for (int l = 0; l < m; l++)
{
avail[l] -= total[l];
}
// Check system is in safe state or not
// Function to calculate need matrix
calculateNeed();
bool status = isSafe();
int r;
if (status == true)
{
cout << "\n\nTo what process the new request must be added(0,1,2..) : ";
cin >> r;
bool s = 0;
jumppoint:
for (int i = 0; i < m; i++)
{
cout << "R (" << i << ") : ";
cin >> request[i];
if (request[i] > need[r][i])
{
cout << "Request is exceeding the needed resource" << endl;
goto jumppoint;
}
if (request[i] > avail[i])
{
cout << "Request is exceeding the available resource" << endl;
goto jumppoint;
}
avail[i] -= request[i];
allot[r][i] += request[i];
need[r][i] -= request[i];
s = 1;
}
if (s)
cout << "SYSTEM STATE : SAFE\n";
else
cout << "SYSTEM State : UN SAFE\n";
cout << "SYSTEM State : UN SAFE\n";
}
system("pause");
return 0;
}
| true |
d00c7d261c4dda95c486358fbd8d9b1d5bee08d4 | C++ | atom-chen/bubbleDragonSecond | /src/client/Classes/RainbowCharactor.h | GB18030 | 2,451 | 2.625 | 3 | [] | no_license | //*******************************************************************************
// : RainbowCharactor
// : <ʺӡ>
//-------------------------------------------------------------------------------
//ע :
//
//÷ : <>
//-------------------------------------------------------------------------------
// : <>, [yyy], [zzz] ...ߺͶŷָб
//*******************************************************************************
#ifndef _RAINBOW_CHARACTOR_H_
#define _RAINBOW_CHARACTOR_H_
#include "cocos2d.h"
#include "BubbleSecondConstant.h"
#include "cocostudio/CocoStudio.h"
namespace bubble_second {
class RainbowSealBubble;
class BaseBubble;
class RainbowCharactor : public cocos2d::Node
{
public:
//CREATE_FUNC(RainbowCharactor);
static RainbowCharactor* createWithFile(const std::string& path)
{
RainbowCharactor *pRet = new(std::nothrow) RainbowCharactor();
if (pRet && pRet->initWithFile(path))
{
pRet->autorelease();
return pRet;
}
else
{
delete pRet;
pRet = NULL;
return NULL;
}
}
~RainbowCharactor();
//ʼӡ
void beginSealingCharactor(RainbowSealBubble* bubble);
//ӡת
void moveSealintCharactor(RainbowSealBubble* bubble, const cocos2d::Vec2& from_point);
//ıӡɫ(ıŵСɫ)
void setRainbowColor(BubbleType color);
//ö·
void setArmaturePath(const std::string& path);
std::string getArmaturePath();
private:
RainbowCharactor();
//bool init();
bool initWithFile(const std::string& path);
void initTexture();
void setSealedBubble(BaseBubble* bubble);
BaseBubble* getSealedBubble();
void addCharactorArmature();
//void runFlyingAnimation(RainbowSealBubble* bubble, const cocos2d::Vec2& armature_point, bool armature_point_need_convert = true);
private:
//е
BaseBubble* sealed_bubble_;
cocos2d::Sprite* rainbow_swirl_;
cocos2d::Sprite* rainbow_background_;
std::string armature_path_;
};
}
#endif //_RAINBOW_CHARACTOR_H_ | true |
e9332d4910cf38f318f5e57ba54482444994e902 | C++ | LuuuuuG/TarenaNotes | /DMS1601/day03/thread.cpp | UTF-8 | 1,177 | 3.296875 | 3 | [] | no_license | #include <pthread.h>
#include <cstdio>
#include <iostream>
using namespace std;
class Thread {
public:
// 启动线程
void start (void) {
pthread_create (&m_tid, NULL, run, this);
}
private:
// 线程过程
static void* run (void* arg) {
return static_cast<Thread*> (arg)->run ();
}
// 线程任务
virtual void* run (void) = 0;
pthread_t m_tid; // 线程标识
};
class AddThread : public Thread {
private:
// 线程任务
void* run (void) {
for (;;) {
cout << '+' << flush;
usleep (200000);
}
return NULL;
}
};
class SubThread : public Thread {
private:
// 线程任务
void* run (void) {
for (;;) {
cout << '-' << flush;
usleep (50000);
}
return NULL;
}
};
class ChrThread : public Thread {
public:
ChrThread (char chr, useconds_t usec) :
m_chr (chr), m_usec (usec) {}
private:
// 线程任务
void* run (void) {
for (;;) {
cout << m_chr << flush;
usleep (m_usec);
}
return NULL;
}
char m_chr;
useconds_t m_usec;
};
int main (void) {
AddThread at;
SubThread st;
at.start ();
st.start ();
ChrThread star ('*', 100000);
ChrThread dot ('.', 400000);
star.start ();
dot.start ();
getchar ();
return 0;
}
| true |
3edb5d59dc8ad75fa94a1cd0eb615c633b92b37c | C++ | dmamills/chipate | /chip8/main.cpp | UTF-8 | 7,354 | 2.859375 | 3 | [] | no_license | //
// main.cpp
// chip8
// Created by daniel mills on 2020-01-23.
// Copyright © 2020 daniel mills. All rights reserved.
//
// CHIP-8 SPEC DOC: http://devernay.free.fr/hacks/chip8/C8TECH10.HTM
#include <iostream>
#include <string>
const int STACK_SIZE = 16;
const int NUM_REGISTERS = 16;
const int MEM_SIZE = 4096;
const int GFX_ROWS = 32;
const int GFX_COLS = 64;
class Chip8 {
public:
Chip8() {
for(auto i =0; i < MEM_SIZE;i++) {
memory[i] = 0;
}
};
~Chip8() {};
void loadFile(std::string filename) {
FILE *fp = fopen(filename.c_str(), "rb");
if(fp == NULL) {
std::cout << "Unable to open file\n";
return;
}
//Get length of binary file
fseek(fp, 0L, SEEK_END);
auto filesize = ftell(fp);
fseek(fp, 0L, SEEK_SET);
//create temporary array for storing, read in all data
auto memory = new uint8_t[filesize];
fread(memory, 1, filesize, fp);
fclose(fp);
//copy over file into c8 memory, starting at 0x200 (512)
auto startByte = 0x200;
for(auto i = 0; i < filesize; i++) {
this->memory[startByte++] = memory[i];
}
//tidy up temporary memory
delete[] memory;
}
void start() {
this->PC = 0x200;
while(this->PC < MEM_SIZE) {
this->emulateCycle();
}
}
void emulateCycle() {
uint16_t opcode = memory[PC] << 8 | memory[PC + 1];
std::cout << "Opcode: " << std::hex << opcode << "\n";
//decode pieces of opcode
uint8_t x, y, n;
uint8_t kk;
uint16_t nnn;
x = (opcode >> 8) & 0x000F; // the lower 4 bits of the high byte
y = (opcode >> 4) & 0x000F; // the upper 4 bits of the low byte
n = opcode & 0x000F; // the lowest 4 bits
kk = opcode & 0x00FF; // the lowest 8 bits
nnn = opcode & 0x0FFF; // the lowest 12 bits
switch(opcode & 0xF000) {
case 0x0000:
switch(opcode) {
case 0x00E0:
//00E0 - CLS => Clear the display.
std::cout<<"Clear screen.\n";
break;
case 0x00EE:
//00EE - RET => Return from a subroutine.
this->PC = this->stack[this->SP];
this->SP--;
break;
}
break;
case 0x1000:
// 1nnn - JP addr => Jump to location nnn.
this->PC = nnn;
break;
case 0x2000:
// 2nnn - CALL addr => Call subroutine at nnn.
this->SP++;
this->stack[this->SP] = this->PC;
this->PC = nnn;
break;
case 0x3000:
//3xkk - SE Vx, byte => Skip next instruction if Vx = kk.
if(this->V[x] == kk) {
this->PC += 2;
}
break;
case 0x4000:
// 4xkk - SNE Vx, byte => Skip next instruction if Vx != kk.
if(this->V[x] != kk) {
this->PC += 2;
}
break;
case 0x5000:
// 5xy0 - SE Vx, Vy => Skip next instruction if Vx = Vy.
if(this->V[x] == this->V[y]) {
this->PC += 2;
}
break;
case 0x6000:
// 6xkk - LD Vx, byte = >Set Vx = kk.
V[x] = kk;
break;
case 0x7000:
//7xkk - ADD Vx, byte => Set Vx = Vx + kk.
this->V[x] = this->V[x] + kk;
break;
case 0x8000:
switch(n) {
case 0:
//8xy0 - LD Vx, Vy => Set Vx = Vy.
this->V[x] = this->V[y];
break;
case 1:
// 8xy1 - OR Vx, Vy => Set Vx = Vx OR Vy.
this->V[x] = this->V[x] | this->V[y];
break;
case 2:
// 8xy2 - AND Vx, Vy => Set Vx = Vx AND Vy.
this->V[x] = this->V[x] & this->V[y];
break;
case 3:
// 8xy3 - XOR Vx, Vy => Set Vx = Vx XOR Vy.
this->V[x] = this->V[x] ^ this->V[y];
break;
case 4: {
// 8xy4 - ADD Vx, Vy => Set Vx = Vx + Vy, set VF = carry.
uint16_t foo = this->V[x] + this->V[y];
if (foo > 255) this->V[0xF] = 1;
else this->V[0xF] = 0;
this->V[x] = foo & 0xff;
break;
}
case 5: {
// 8xy5 - SUB Vx, Vy => Set Vx = Vx - Vy, set VF = NOT borrow.
if(this->V[x] > this->V[y]) {
this->V[0xF] = 1;
} else { this->V[0xF] = 0; }
uint8_t sub = this->V[x] - this->V[y];
this->V[x] = sub;
break;
}
case 6:
//8xy6 - SHR Vx {, Vy} => Set Vx = Vx SHR 1.
std::cout<< "0x8xy6 \n";
// If the least-significant bit of Vx is 1, then VF is set to 1, otherwise 0. Then Vx is divided by 2.
break;
case 7:
std::cout<< "0x8xy7 \n";
break;
case 0xE:
std::cout<< "0x8xyE \n";
break;
}
break;
case 0x9000:
if(this->V[x] != this->V[x]) {
this->PC += 2;
}
break;
case 0xA000:
this->I = nnn;
std::cout<<"0xA000\n";
break;
case 0xB000:
this->PC = (this->V[0] + nnn);
break;
case 0xC000:
std::cout<<"0xC000\n";
break;
case 0xD000:
std::cout << "0xD DRAW ROUTINE \n";
case 0xE000:
std::cout<<"0xE000 skip instruction on keyboard\n";
switch(kk) {
case 0x9E:
break;
}
break;
case 0xF000:
std::cout<<"0xE000\n";
break;
}
// std::cout << "pc: " << this->PC << "\n";
this->PC += 2;
}
private:
uint8_t memory[MEM_SIZE], V[NUM_REGISTERS], gfx[GFX_ROWS][GFX_COLS], delayTimer, soundTimer;
uint16_t I, PC, SP, stack[STACK_SIZE];
};
int main(int argc, const char * argv[]) {
Chip8 emulator;
emulator.loadFile("/Users/vehikl/Code/chipate/chip8/GUESS");
emulator.start();
return 0;
}
| true |
ae53e27d69d2d25312d824126c2426ddae7116de | C++ | bssrdf/psychopath_cpp | /utils/low_level.hpp | UTF-8 | 870 | 2.5625 | 3 | [] | no_license | #ifndef LOW_LEVEL_HPP
#define LOW_LEVEL_HPP
#include <mmintrin.h>
namespace LowLevel {
static const int cache_line_size = 64;
template <typename T>
inline void prefetch_L1(T* address) {
constexpr int lines = (sizeof(T)/cache_line_size) + ((sizeof(T)%cache_line_size) == 0 ? 0 : 1);
for (int i = 0; i < lines; ++i) {
_mm_prefetch(address+i, _MM_HINT_T0);
}
}
template <typename T>
inline void prefetch_L2(T* address) {
constexpr int lines = (sizeof(T)/cache_line_size) + ((sizeof(T)%cache_line_size) == 0 ? 0 : 1);
for (int i = 0; i < lines; ++i) {
_mm_prefetch(address+i, _MM_HINT_T1);
}
}
template <typename T>
inline void prefetch_L3(T* address) {
constexpr int lines = (sizeof(T)/cache_line_size) + ((sizeof(T)%cache_line_size) == 0 ? 0 : 1);
for (int i = 0; i < lines; ++i) {
_mm_prefetch(address+i, _MM_HINT_T2);
}
}
}
#endif // LOW_LEVEL_HPP | true |
1649bc767b9e585d88ca579a626d4c9e55e2aa0c | C++ | EthanGriffee/SoftwareDev | /assignment5/part1/bench.cpp | UTF-8 | 6,685 | 2.859375 | 3 | [] | no_license | #include "modified_dataframe.h"
#include "parser.h"
#include "array.h"
#include "string.h"
/*******************************************************************************
* Rower::
* A Rower that only wastes time, used to show that it is faster
*/
class ReallyDumbRower : public Rower {
public:
size_t sum;
ReallyDumbRower() { sum = 0;}
virtual bool accept(Row& r) {
for (int x = 0; x < 10000; x++) {
sum += 1;
}
return true;
}
virtual ReallyDumbRower* clone() {
return new ReallyDumbRower();
}
/** Once traversal of the data frame is complete the rowers that were
split off will be joined. There will be one join per split. The
original object will be the last to be called join on. The join method
is reponsible for cleaning up memory. */
virtual void join_delete(Rower* other) {
ReallyDumbRower* r = dynamic_cast<ReallyDumbRower*> (other);
if (other)
sum = sum + r->getSum();
else {
exit(1);
}
}
size_t getSum() {
return sum;
}
};
/*******************************************************************************
* Rower::
* Adds all Strings to an arraylist of strings
*/
class FieldsToArraysRower : public Rower {
public:
StringArray* str_array;
FloatArray* float_array;
BoolArray* bool_array;
IntArray* int_array;
FieldsToArraysRower() {
str_array = new StringArray();
float_array = new FloatArray();
bool_array = new BoolArray();
int_array = new IntArray();
}
virtual bool accept(Row& r) {
for (int x = 0; x < r.width(); x++) {
if (r.col_type(x) == 'S') {
str_array->add(r.get_string(x));
}
else if (r.col_type(x) == 'F') {
float_array->add(r.get_float(x));
}
else if (r.col_type(x) == 'B') {
bool_array->add(r.get_bool(x));
}
else if (r.col_type(x) == 'I') {
float_array->add(r.get_int(x));
}
}
return true;
}
virtual FieldsToArraysRower* clone() {
return new FieldsToArraysRower();
}
/** Once traversal of the data frame is complete the rowers that were
split off will be joined. There will be one join per split. The
original object will be the last to be called join on. The join method
is reponsible for cleaning up memory. */
virtual void join_delete(Rower* other) {
FieldsToArraysRower* r = dynamic_cast<FieldsToArraysRower*> (other);
if (other) {
str_array->addAll(r->getStringArray());
float_array->addAll(r->getFloatArray());
bool_array->addAll(r->getBoolArray());
int_array->addAll(r->getIntArray());
}
else {
exit(1);
}
}
StringArray* getStringArray() {
return str_array;
}
FloatArray* getFloatArray() {
return float_array;
}
BoolArray* getBoolArray() {
return bool_array;
}
IntArray* getIntArray() {
return int_array;
}
};
ModifiedDataFrame* create_dataframe_from_file(size_t factor) {
Schema s;
ModifiedDataFrame* df = new ModifiedDataFrame(s);
FILE* file = fopen("datafile.txt", "r");
fseek(file, 0, SEEK_END);
size_t file_size = ftell(file);
fseek(file, 0, SEEK_SET);
SorParser parser{file, 0, file_size / factor, file_size};
parser.guessSchema();
parser.parseFile();
ColumnSet* set = parser.getColumnSet();
for (int x = 0; x < set->getLength(); x++) {
char* str_name = new char[33];
sprintf(str_name, "%d", x);
df->add_column(set->getColumn(x), new String(str_name));
}
return df;
}
void really_dumb_testpmap() {
ModifiedDataFrame* df;
df = create_dataframe_from_file(1);
ReallyDumbRower rower = ReallyDumbRower();
df->pmap(rower);
}
void really_dumb_testmap() {
ModifiedDataFrame* df;
df = create_dataframe_from_file(1);
ReallyDumbRower rower = ReallyDumbRower();
df->map(rower);
}
void really_dumb_testpmap_half_rows() {
ModifiedDataFrame* df;
df = create_dataframe_from_file(2);
ReallyDumbRower rower = ReallyDumbRower();
df->pmap(rower);
sys.p(rower.getSum());
}
void really_dumb_testmap_half_rows() {
ModifiedDataFrame* df;
df = create_dataframe_from_file(2);
ReallyDumbRower rower = ReallyDumbRower();
df->map(rower);
}
void really_dumb_testpmap_tenth_rows() {
ModifiedDataFrame* df;
df = create_dataframe_from_file(10);
ReallyDumbRower rower = ReallyDumbRower();
df->pmap(rower);
}
void really_dumb_testmap_tenth_rows() {
ModifiedDataFrame* df;
df = create_dataframe_from_file(10);
ReallyDumbRower rower = ReallyDumbRower();
df->map(rower);
}
void df_to_string_array_testpmap() {
ModifiedDataFrame* df;
df = create_dataframe_from_file(1);
FieldsToArraysRower rower = FieldsToArraysRower();
df->pmap(rower);
}
void df_to_string_array_testmap() {
ModifiedDataFrame* df;
df = create_dataframe_from_file(1);
FieldsToArraysRower rower = FieldsToArraysRower();
df->map(rower);
sys.p(rower.getStringArray()->getSize());
}
void df_to_string_array_testpmap_half_rows() {
ModifiedDataFrame* df;
df = create_dataframe_from_file(2);
FieldsToArraysRower rower = FieldsToArraysRower();
df->pmap(rower);
}
void df_to_string_array_testmap_half_rows() {
ModifiedDataFrame* df;
df = create_dataframe_from_file(2);
FieldsToArraysRower rower = FieldsToArraysRower();
df->map(rower);
}
void df_to_string_array_testpmap_tenth_rows() {
ModifiedDataFrame* df;
df = create_dataframe_from_file(10);
FieldsToArraysRower rower = FieldsToArraysRower();
df->pmap(rower);
}
void df_to_string_array_testmap_tenth_rows() {
ModifiedDataFrame* df;
df = create_dataframe_from_file(10);
FieldsToArraysRower rower = FieldsToArraysRower();
df->map(rower);
}
int main(int argc, char **argv) {
switch(atoi(argv[1])) {
case 1: {
really_dumb_testmap();
break;
}
case 2: {
really_dumb_testpmap();
break;
}
case 3: {
really_dumb_testmap_half_rows();
break;
}
case 4: {
really_dumb_testpmap_half_rows();
break;
}
case 5: {
really_dumb_testmap_tenth_rows();
break;
}
case 6: {
really_dumb_testpmap_tenth_rows();
break;
}
case 7: {
df_to_string_array_testmap();
break;
}
case 8: {
df_to_string_array_testpmap();
break;
}
case 9: {
df_to_string_array_testmap_half_rows();
break;
}
case 10: {
df_to_string_array_testpmap_half_rows();
break;
}
case 11: {
df_to_string_array_testmap_tenth_rows();
break;
}
case 12: {
df_to_string_array_testpmap_tenth_rows();
break;
}
}
}
| true |
92b275c1756f7aee26ce8df2e598b03a40be70ce | C++ | wwlong/cpp_study | /class_learn.cpp | UTF-8 | 3,157 | 3.90625 | 4 | [] | no_license | /*
学习封装,继承,多态
人
学生,老师
*/
//
#include <iostream>
#include <cstring>
using namespace std;
//
class person {
// private:
public:
char person_name[128];
char person_sex[8];
int person_age;
person();
~person();
void set_person_info(const char *name, const char *sex, const int age);
void set_person_name(const char *name);
void set_person_sex(const char *sex);
void set_person_age(const int age);
//virtual void print_person_info();
void print_person_info();
};
/*
class person 的 构造函數
类调用的最开始运行
*/
person::person()
{
memset(person_name, 0, sizeof(person_name));
memset(person_sex, 0, sizeof(person_sex));
person_age = 0;
cout << "构造函数"<<endl;
}
/*
class person的析构函数
销毁对象的时候调用
*/
person::~person()
{
cout << "析构函数"<<endl;
}
void person::set_person_info(const char *name,const char *sex,const int age)
{
strncpy(person_name, name,strlen(name));
strncpy(person_sex, sex, strlen(sex));
person_age = age;
}
void person::set_person_name(const char *name)
{
strncpy(person_name, name,strlen(name));
}
void person::set_person_sex(const char *sex)
{
strncpy(person_sex, sex, strlen(sex));
}
void person::set_person_age(const int age)
{
person_age = age;
}
void person::print_person_info()
{
cout << person_name << "\t" << person_sex << "\t" << person_age << endl;
}
/*
在person的基础上衍生出学生
*/
class student:public person {
private:
int stu_grade;
char stu_num[64];
public:
student();
~student();
void learn(string const &course);
void set_person_info(const char* name, const char *sex, const int age, int grade, const char *student_num);
void print_person_info();
};
/*
在构造函数中可以进行初始化操作
*/
student::student()
{
memset(stu_num, 0, sizeof(stu_num));
this->stu_grade = 0;
cout << "student 构造函数"<<endl;
}
student::~student()
{
cout << "student 析构函数" << endl;
}
void student::set_person_info(const char* name, const char *sex, const int age, int grade, const char *student_num)
{
person::set_person_info(name, sex, age);
stu_grade = grade;
strncpy(stu_num, student_num, strlen(student_num));
}
void student::print_person_info()
{
cout << person_name << "\t" << person_sex << "\t" \
<< person_age << "\t" << stu_grade << "\t" << stu_num << endl;
}
int main()
{
person *moon = new person;
// string str_tmp = moon.person_name;
// cout << str_tmp;
moon->set_person_info("moon", "female", 24);
moon->print_person_info();
//delete moon;
/*
继承和多态
*/
student *john = new student;
john->set_person_info("moon", "female", 24, 12, "2012302522");
//john->set_person_info("moon", "female", 24);
john->print_person_info();
delete john;
return 0;
} | true |
8cf552e194be41a2c4ebb98ca27c74a62ec8be05 | C++ | antoniojkim/CML | /core/CML/Functions/TensorOps/TensorMultiplication.h | UTF-8 | 2,906 | 3.0625 | 3 | [] | no_license | #ifndef __CML_FUNCTIONS_TENSOROPS_TENSOR_MULTIPLICATION_H__
#define __CML_FUNCTIONS_TENSOROPS_TENSOR_MULTIPLICATION_H__
#include "TensorOps.h"
namespace cml {
template<typename T>
std::vector<tensor<T>> matmul_backward(std::vector<tensor<T>>& params, std::vector<tensor<T>> output){
#ifdef DEBUG
using namespace std;
cout << "Matrix Multiplication Backward" << endl;
#endif
auto lhs = params.at(0);
auto rhs = params.at(1);
auto output_grad = output.at(0);
tensor<T> lhs_grad = nullptr;
tensor<T> rhs_grad = nullptr;
if (lhs->computeGrad){
lhs_grad = make_tensor<T>(static_cast<DMatrix<T>>(
// TODO: Check to see if order is correct
output_grad->matrix() * rhs->matrix().transpose()
));
}
if (rhs->computeGrad){
rhs_grad = make_tensor<T>(static_cast<DMatrix<T>>(
// TODO: Check to see if order is correct
lhs->matrix().transpose() * output_grad->matrix()
));
}
return {lhs_grad, rhs_grad};
}
template<typename T>
tensor<T> matmul(tensor<T> lhs, tensor<T> rhs){
auto t = make_tensor<T>(static_cast<DMatrix<T>>(
lhs->matrix() * rhs->matrix()
), lhs->computeGrad || rhs->computeGrad);
if (t->computeGrad){
t->initGraph({lhs, rhs}, matmul_backward<T>);
}
return t;
}
/*
Coefficient wise multiplication
*/
template<typename T>
std::vector<tensor<T>> multiply_backward(std::vector<tensor<T>>& params, std::vector<tensor<T>> output){
#ifdef DEBUG
using namespace std;
cout << "Tensor Multiplication Backward" << endl;
#endif
auto lhs = params.at(0);
auto rhs = params.at(1);
auto output_grad = output.at(0);
tensor<T> lhs_grad = nullptr;
tensor<T> rhs_grad = nullptr;
if (lhs->computeGrad){
lhs_grad = lhs->empty();
lhs_grad->matrix() = rhs->matrix().array() * output_grad->matrix().array();
}
if (rhs->computeGrad){
rhs_grad = rhs->empty();
rhs_grad->matrix() = lhs->matrix().array() * output_grad->matrix().array();
}
return {lhs_grad, rhs_grad};
}
template<typename T>
tensor<T> multiply(tensor<T> lhs, tensor<T> rhs){
if (lhs->shape() != rhs->shape()){
throw CMLException("Tensor Multiplication: Shapes do not match: ", lhs->shape(), "!=", rhs->shape());
}
auto t = lhs->empty(lhs->computeGrad || rhs->computeGrad);
t->matrix() = lhs->matrix().array() * rhs->matrix().array();
if (t->computeGrad){
t->initGraph({lhs, rhs}, multiply_backward<T>);
}
return t;
}
}
#endif // __CML_FUNCTIONS_TENSOROPS_TENSOR_MULTIPLICATION_H__
| true |
1098afacf1a6ddc0ba4c624a0141d0ce305ffbc1 | C++ | AlexLai1990/Leetcode_-_- | /min_heap.h | UTF-8 | 3,688 | 3.453125 | 3 | [] | no_license | #ifndef MINHEAP_H
#define MINHEAP_H
#include "Vector_temp.h"
#include <assert.h>
template<class T>
class MinHeap {
public:
MinHeap();
~MinHeap();
void Append(T); // automatic shift up
T GetRoot() ;
T LowestKeyNode();
void ShiftDown(); // reorder new root after use and change
void print_out();
bool Empty() ;
size_t Size();
private:
inline size_t Parent( size_t ix ) { return ( ix - 1 ) / 2; };
inline size_t RightChild( size_t ix ) { return 2 * ( ix + 1 ); };
inline size_t LeftChild( size_t ix ) { return ( 2 * ix ) + 1; };
inline bool isLeaf( size_t ix ) { return LeftChild( ix ) >= m_size; };
inline bool hasOneLeaf( size_t ix ) { return m_size == RightChild( ix ); };
inline size_t idexOfLastItem();
void SiftDown( size_t ix ); // from ix downwards, reordering item
void SiftUp( size_t ix ); // from ix upwards towards root, when appending new items
inline void Swap( size_t ix, size_t iy );
vector<T> m_vec_key;
size_t m_size;
};
template<class T>
MinHeap<T>::MinHeap(){
m_size = 0;
}
template<class T>
MinHeap<T>::~MinHeap(){
}
// automatic sift up
template<class T>
void MinHeap<T>::Append( T item ){
m_vec_key.push_back( item );
++m_size;
SiftUp( idexOfLastItem() );
}
template<class T>
T MinHeap<T>::GetRoot() {
assert( 0 != m_size );
T temp = m_vec_key.get(0);
Swap( 0 , idexOfLastItem() );
m_vec_key.pop_back();
m_size--;
ShiftDown();
return temp;
};
template<class T>
T MinHeap<T>::LowestKeyNode(){
return m_vec_key.get(0);
}
template<class T>
void MinHeap<T>::SiftDown( size_t ix ){
size_t cur = ix;
while ( !isLeaf( cur ) ) {
if ( hasOneLeaf( cur ) ) {
size_t left = LeftChild( cur );
// if child less than parent, then exchange them
if ( m_vec_key.get( left ) < m_vec_key.get( cur ) ) {
Swap( left, cur );
cur = left;
}
else {
break;
}
}
else { // has two leaves
size_t right = RightChild( cur );
size_t left = LeftChild( cur );
// if left is bigger than right, then go right
bool bGoRight = !( m_vec_key.get( left ) < m_vec_key.get( right ) ) ;
if ( bGoRight ) {
if ( m_vec_key.get( right ) < m_vec_key.get( cur ) ) {
Swap( right, cur );
cur = right;
}
else {
break;
}
}
else { // go left
if ( m_vec_key.get( left ) < m_vec_key.get( cur ) ) {
Swap( left, cur );
cur = left;
}
else {
break;
}
}
}
}
}
// reorder new root after use and change
template<class T>
void MinHeap<T>::ShiftDown() {
SiftDown( 0 );
}
template<class T>
void MinHeap<T>::print_out(){
for ( size_t i = 0 ; i < m_vec_key.size(); i++ )
std::cout<< m_vec_key.get(i) << std::endl;
}
template<class T>
bool MinHeap<T>::Empty() {
if ( m_vec_key.size() == 0)
return true;
else
return false;
}
template<class T>
size_t MinHeap<T>::Size() {
return m_vec_key.size();
}
template<class T>
size_t MinHeap<T>::idexOfLastItem() {
assert( 0 < m_size );
return m_size - 1;
}
// function for siftup the element to the top
template<class T>
void MinHeap<T>::SiftUp( size_t ix ){
size_t cur = ix;
size_t parent;
while ( 0 != cur ) {
parent = Parent( cur );
if ( m_vec_key.get( parent ) < m_vec_key.get( cur ) ) {
break;
}
else {
Swap( cur, parent );
cur = parent;
}
}
}
template<class T>
void MinHeap<T>::Swap( size_t ix, size_t iy ) {
assert( ix < m_size );
assert( iy < m_size );
T tmp = m_vec_key.get( ix );
m_vec_key.set( ix, m_vec_key.get( iy ));
m_vec_key.set( iy, tmp );
}
#endif
| true |
97cae45d1f68ab90c2d15b8efd014e2f2502ba3b | C++ | andrewkatson/TheBTeam | /include/Towers/NotATower.hpp | UTF-8 | 1,083 | 2.546875 | 3 | [] | no_license | #pragma once
/*
* A stand in for a tile without a tower
* @author Andrew Katson
*/
#include "RangeTower.hpp"
#include "../Projectiles/CheesePizzaProjectile.hpp"
class NotATower : public RangeTower{
public:
NotATower(shared_ptr<TextLoader> textLoader, shared_ptr<EventManager> eventManager, shared_ptr<TextureLoader> textureLoader);
void upgrade();
/*
* set the currentProjectile to be the projectile object of the type of the tower
* this projectile will be fired from
*/
void setProjectile();
void setUpUnits(){}
void setPos(intPair pos){this->row=pos.first;this->col=pos.second;}
void setPos(int row, int col){this->row=row; this->col=col;}
float getXCoordinate(){return xCoordinate;}
float getYCoordinate(){return yCoordinate;}
void setXCoordinate(float xCor){xCoordinate = xCor;}
void setYCoordinate(float yCor){yCoordinate = yCor;}
bool canAttack(){return false;}
void attack(shared_ptr<ActorInterface> enemyInRange, float delta){}
void update(float delta){}
shared_ptr<vector<int>> getStatistics(){return RangeTower::getStatistics();}
};
| true |
0f3262884912e7cdccd06887e246de2cb0f55820 | C++ | ZhukDI/Zhuk | /1 semester/6.b)main.cpp | UTF-8 | 1,579 | 3.84375 | 4 | [] | no_license | /*b)В программе объявлен массив А целых элементов (размер массива 10).
Пользователь вводит массив c клавиатуры. Потом распечатываем массив.
Вводим число N < 10. Затем удаляем N-ый элемент массива (сдвигая остальные элементы).*/
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
void initialization(int mas[], int N)
{
cout << "Заполнение массива который содержит " << N << " элементов" << endl;
for (int i = 0; i < N; i++)
{
cin>> mas[i];
}
}
void print(int mas[], int N, int n)
{
cout <<endl << "Печеть массива" << endl;
for (int i = 0; i < N-n; i++)
{
cout << mas[i] << " ";
}
cout << endl << endl;
}
void remove(int mas[], int N, int &n)
{
int i;
cout << "Введите номер элемента от 0 до " <<N-1-n<< " который хотите удалить" << endl;
cin >> i;
if (i >= N - n) cout << "Ошибка. Вы ввели номер, который превышает размер массива." << endl;
else
{
for (i; i < N - 1; i++)
{
mas[i] = mas[i + 1];
}
n++;
}
}
int main()
{
setlocale(LC_ALL, "Russian");
int const N = 10;
int mas[N], n=0;
initialization(mas, N);//Инициализация (ручная)
print(mas, N, n);//Печать массива
remove(mas, N, n);//Удаление элемента и сдвиг
print(mas, N, n);
return 0;
} | true |
67246e50415facbcb0cf268ef82b2d7a9e70421e | C++ | Kawser-nerd/CLCDSA | /Source Codes/CodeJamData/10/01/15.java | UTF-8 | 1,463 | 2.84375 | 3 | [] | no_license | package codejam2010.qualification;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class ProblemA {
public static void main(String[] args) {
BufferedReader reader = null;
PrintWriter writer = null;
try {
String fileName = "A-large";
File folder = new File(new File("files", "codejam2010"), "qualification");
File inputFile = new File(folder, fileName + ".in");
File outputFile = new File(folder, fileName + ".out");
reader = new BufferedReader(new FileReader(inputFile));
writer = new PrintWriter(new FileWriter(outputFile));
int count = Integer.parseInt(reader.readLine());
for (int i = 0; i < count; i++) {
String[] parameters = reader.readLine().split("\\s");
writer.printf("Case #%d: %s\n", i+1,
solveIt(Integer.parseInt(parameters[0]),
Integer.parseInt(parameters[1])));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(reader);
close(writer);
}
System.out.println("Done.");
}
private static String solveIt(int n, int k) {
int allOn = (1 << n)-1;
return ((allOn & k) == allOn) ? "ON" : "OFF";
}
private static void close(Closeable file) {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| true |
3fbe962c7e908e1ce69798f3663089f8ea72d8af | C++ | Prelly95/Warman_Code | /Drive_Train/Hall_Sense_Test/Hall_Sense_Test.ino | UTF-8 | 397 | 2.859375 | 3 | [] | no_license |
#define POT 10 // analog pin used to connect the potentiometer
#define MOTOR 10
int val; // variable to read the value from the analog pin
void setup() {
pinMode(POT, INPUT);
// pinMode(MOTOR, OUTPUT);
Serial.begin(9600);
}
void loop() {
val = digitalRead(POT);
// val = analogRead(POT);
// val = map(val, 0, 1024, 0, 255);
// analogWrite(MOTOR, val);
Serial.println(val);
}
| true |
4bb200af1773d76c8caa808aab121ce59acf3300 | C++ | achen889/Warlockery_Engine | /Engine/Networking/ConnectionSocket.cpp | UTF-8 | 9,273 | 2.890625 | 3 | [
"MIT"
] | permissive | //==============================================================================================================
//ConnectionSocket.cpp
//by Albert Chen Jan-14-2016.
//==============================================================================================================
#include "ConnectionSocket.hpp"
#include "Engine\Core\Utilities.hpp"
//===========================================================================================================
///----------------------------------------------------------------------------------------------------------
///constructors
ConnectionSocket::ConnectionSocket(){
//do nothing
}
ConnectionSocket::~ConnectionSocket(){
//do nothing
}
//-----------------------------------------------------------------------------------------------------------
//===========================================================================================================
std::string AllocLocalHostName() {
char buffer[256];
//socket function get host name
if (gethostname(buffer, 256) == SOCKET_ERROR) {
return "";
}
std::string localHostName = std::string(buffer);
return localHostName;
}
//-----------------------------------------------------------------------------------------------------------
std::string GetLocalHostName() {
std::string hostName = AllocLocalHostName();
//set default host name
if (hostName == "") {
hostName = "localhost";
}
return hostName;
}
//-----------------------------------------------------------------------------------------------------------
Connection GetConnection(const std::string& host_name, const std::string& service, int addrFamily, int addrInfoFlags ) {
addrinfo hints;
addrinfo* addr;
Connection c;
c.didSucceed = true;
memset(&hints, 0, sizeof(hints)); //sets all hints to 0
hints.ai_family = addrFamily; //only get INET
hints.ai_socktype = SOCK_STREAM; // stream based, determines transport layer TCP
hints.ai_flags = addrInfoFlags; // used for binding/listening
int status = getaddrinfo(host_name.c_str(), service.c_str(), &hints, &addr);
if (status != 0) {
c.didSucceed = false;
printf("Failed to create socket address! \n");
}
c.addrInfo = addr;
c.service = service;
return c;
}
//-----------------------------------------------------------------------------------------------------------
bool Connection::CreateSocket(addrinfo* iter, SOCKET& hostSock) {
char addr_name[INET6_ADDRSTRLEN];
inet_ntop(iter->ai_family, GetInAddress(iter->ai_addr), addr_name, INET6_ADDRSTRLEN);
printf("Trying to Bind Address family[%i] type[%i] %s : %s\n", iter->ai_family, iter->ai_socktype, addr_name, service.c_str());
//create socket
hostSock = socket(iter->ai_family, iter->ai_socktype, iter->ai_protocol);
if (hostSock == INVALID_SOCKET) {
int error = WSAGetLastError();
printf("Failed to bind: Socket Error[%i]\n", error);
return false;
}
return true;
}
//-----------------------------------------------------------------------------------------------------------
SOCKET BindSocketWithConnection(Connection conn) {
SOCKET hostSock = INVALID_SOCKET;
addrinfo* iter;
for (iter = conn.addrInfo; iter != nullptr; iter = iter->ai_next) {
if (conn.CreateSocket(iter, hostSock)) {
int result = bind(hostSock, iter->ai_addr, (int)(iter->ai_addrlen));
if (result == SOCKET_ERROR) {
closesocket(hostSock);
printf("Failed to bind: Socket Error[%i]\n", GetLastError());
continue;
}
}
break;
}//end of loop
freeaddrinfo(conn.addrInfo);
if (hostSock == INVALID_SOCKET) {
printf("Could not create socket!\n");
}
printf("Socket bound...\n");
return hostSock;
}
//-----------------------------------------------------------------------------------------------------------
bool ConnectionSocket::ConnectSocketToHost(std::string& hostName, const std::string& service, int addrFamily) {
Connection host = GetConnection(hostName, service, addrFamily);
m_socketID = ConnectToHostSocket(host);
return true;
}
//-----------------------------------------------------------------------------------------------------------
bool ConnectionSocket::BindSocketToHost(std::string& hostName, const std::string& service, int addrFamily, int addrInfoFlags) {
m_name = hostName;
Connection host = GetConnection(hostName, service, addrFamily, addrInfoFlags);
m_socketID = BindSocketWithConnection(host);
return true;
}
//-----------------------------------------------------------------------------------------------------------
char* ConnectionSocket::RecieveBufferDataFromOtherSocket(SOCKET otherSocket) {
//how much data was received
char buffer[1024];
//printf("Waiting to Receive...\n");
int recvd = recv(otherSocket, buffer, 1024, 0);
if (recvd > 0) {
buffer[recvd] = NULL; //null terminate this
printf("Received:[%s]\n", buffer);
//send message back echo
return buffer;
}
return NULL;
}
//-----------------------------------------------------------------------------------------------------------
void ConnectionSocket::SendBufferDataToOtherSocket(SOCKET otherSocket, const char* buffer) {
int sent = send(otherSocket, buffer, GetCStrLength(buffer), 0);
if (sent == SOCKET_ERROR) {
std::cout << "[" << m_name.c_str() << "] failed to send: " << buffer << "\n";
}
printf("[%s] sent: %s\n", m_name.c_str(), buffer);
//std::cout <<"["<< m_name.c_str() << "] sent: " << buffer << "\n";
}
//-----------------------------------------------------------------------------------------------------------
SOCKET ServerSocket::AcceptOtherAddress(sockaddr* otherAddr, int otherAddrLen) {
printf("[%s]Waiting to Accept...\n", m_name.c_str());
SOCKET otherSocket = accept(m_socketID, (sockaddr*)otherAddr, &otherAddrLen); //accept connection on my socket ID
if (otherSocket == INVALID_SOCKET) {
//add error message here
printf("[%s]Failed to Accept!\n", m_name.c_str());
}
return otherSocket;
}
//===========================================================================================================
///----------------------------------------------------------------------------------------------------------
///connection socket friend functions
SOCKET ConnectToHostSocket(Connection conn) {
SOCKET hostSock = INVALID_SOCKET;
addrinfo* iter;
for (iter = conn.addrInfo; iter != nullptr; iter = iter->ai_next) {
if (conn.CreateSocket(iter, hostSock)) {
int result = connect(hostSock, iter->ai_addr, (int)(iter->ai_addrlen));
if (result == SOCKET_ERROR) {
closesocket(hostSock);
printf("Failed to connect: Socket Error[%i]\n", GetLastError());
continue;
}
else {
printf("Connected...\n");
}
}
break;
}//end of loop
freeaddrinfo(conn.addrInfo);
if (hostSock == INVALID_SOCKET) {
printf("Could not connect to socket!\n");
}
return hostSock;
}
//===========================================================================================================
void ServerSocket::Listen() {
int result = listen(m_socketID, m_maxConnections);
if (result == SOCKET_ERROR) {
printf("Failed to listen\n");
}
}
//-----------------------------------------------------------------------------------------------------------
SOCKET ServerSocket::Accept() {
//the last server thread has garbage data for these
sockaddr_storage otherAddr; //ext of sockaddr
int otherAddrLen = sizeof(otherAddr);
return AcceptOtherAddress((sockaddr*)&otherAddr, otherAddrLen);
}
//-----------------------------------------------------------------------------------------------------------
void ServerSocket::ServerLoop() {
Listen();
//loop this part
while (true) {
SOCKET otherSocket = Accept();
char* bufferData = RecieveBufferDataFromOtherSocket(otherSocket);
SendBufferDataToOtherSocket(otherSocket, bufferData);
}
}
//===========================================================================================================
void ClientSocket::ClientLoop(const std::string& message) {
const char* messageCstr = message.c_str();
SendBufferDataToOtherSocket(m_socketID, messageCstr);
RecieveBufferDataFromOtherSocket(m_socketID);
}
//===========================================================================================================
///----------------------------------------------------------------------------------------------------------
///static methods
//-----------------------------------------------------------------------------------------------------------
std::string WindowsErrorAsString(DWORD error_id){
if (error_id != 0) {
LPSTR buffer;
DWORD size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
error_id,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)(&buffer),
0, NULL);
std::string msg(buffer, size);
LocalFree(buffer);
return msg;
}
else {
return "";
}
}
//-------------------------------------------------------------------------------------------------------
// get sockaddr, IPv4 or IPv6:
void* GetInAddress(sockaddr *sa) {
if (sa->sa_family == AF_INET) {
return &(((sockaddr_in*)sa)->sin_addr);
}
else {
return &(((sockaddr_in6*)sa)->sin6_addr);
}
}
//===========================================================================================================
| true |
caadb4d18d3c549777f5924348884884354f7b2c | C++ | acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-Fortress117 | /src/homework/02_decisions/decisions.cpp | UTF-8 | 1,691 | 3.765625 | 4 | [
"MIT"
] | permissive | #include "decisions.h"
#include <iostream>
//write include statement for decisions header
//Write code for function get_grade_points that accepts a string letter_grade and returns
//the grade_points for as follows:
//given grade "A" returns 4
//given grade "B" returns 3
//given grade "C" returns 2
//given grade "D" returns 1
//given grade "F" returns 0
//another other value return -1
int get_grade_points(std::string letter_grade)
{
if (letter_grade == "A")
{
return 4;
}
else if(letter_grade == "B")
{
return 3;
}
else if (letter_grade == "C")
{
return 2;
}
else if (letter_grade == "D")
{
return 1;
}
else if (letter_grade == "F")
{
return 0;
}
else
{
return -1;
}
}
//Write code for function calculate_gpa that accepts an int named credit_hours and
//a double named credit_points. The function returns the quotient of credit_points divided by
//credit_hours. In the function account for division by zero by returning a -1.
double calculate_gpa(int credit_hours, double credit_points)
{
if (credit_points > 0)
return credit_points / credit_hours;
else
return -1;
}
std::string get_letter_grade_using_if(int num)
{
if (num >= 90)
{
return "A";
}
else if (num >= 80)
{
return "B";
}
else if (num >= 70)
{
return "C";
}
else if (num >= 60)
{
return "D";
}
else if (num <= 59)
{
return "F";
}
else
{
return "Invalid";
}
}
std::string get_letter_grade_using_switch(int num)
{
switch (num/10)
{
case 10:
case 9:
return "A";
case 8:
return "B";
case 7:
return "C";
case 6:
return "D";
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
return "F";
default:
return "Invalid";
}
}
| true |
94b6a0f4b2bb5b5d2380a107cb910c745131a542 | C++ | 37947538/Young3_7 | /Classes/GameBLL/RewardEquipBLL.cpp | UTF-8 | 3,972 | 2.515625 | 3 | [] | no_license | //
// RewardEquipBLL.cpp
// Zombie3_4
//
// Created by jl on 15/7/28.
//
//
#include "RewardEquipBLL.h"
#include "EnemyBase.h"
#include "GameBLL.h"
#include "GameLayer.h"
#include "APScatterAction.h"
#include "DropGold.h"
#include "DropObject.h"
#include "DropEquip.h"
#include "EnemyModel.h"
#include "EquipmentLocalBLL.h"
bool RewardEquipBLL::init()
{
return true;
}
//奖励掉落装备更新
void RewardEquipBLL::update(float arg1)
{
//做英雄与金币物理碰撞
auto mainHero=GameBLL::instance()->m_MainHero;
//获取碰撞的区域
auto herobb=mainHero->getOBB();
//遍历怪是否攻击
std::vector<DropObject*> waitRemove;
for (auto &g : m_dropObjects) {
//循环遍历怪,判断攻击距离到达后攻击怪
auto gobb=g->getOBB();
if (gobb->isCollidWithAPOBB(herobb)) {
//英雄碰撞到金币
waitRemove.push_back(g);
}
}
//影响碰撞对象
for (auto &dobj : waitRemove) {
mainHero->getDropObject(dobj);
removeEquip(dobj);
}
waitRemove.clear();
}
//随机掉落
void RewardEquipBLL::randDrop(EnemyBase* eb)
{
Vec2 vPos=eb->getPosition();
float fRand=CCRANDOM_0_1();
if (fRand > 0.7) {
//掉落金币数量 为 random(3,ROUNDDOWN((怪物权值+怪物等级/2)/5)+4)
auto model=eb->getEnemyModel();
int iMax=(model->DropValue + model->LV / 2) / 5 + 4;
int iCount=APTools::getRand(3, iMax);
for (int i=0; i<iCount; i++) {
addOneGold(vPos);
}
}
//掉落概率
float dropRate=CCRANDOM_0_1() * 100.0;
dropOneEquip(eb, dropRate);
}
//掉落一个装备
void RewardEquipBLL::dropOneEquip(EnemyBase* eb, float dropRate)
{
Vec2 vPos=eb->getPosition();
auto enemyModel=eb->getEnemyModel();
//掉落权值
int dropValue=enemyModel->DropValue;
std::vector<Weapon*> equipVector;
auto eBLL=EquipmentLocalBLL::create();
eBLL->getDropEquipment(equipVector, dropValue, dropRate);
int dropEquipCount=(int)equipVector.size();
if (dropEquipCount>0) {
int randIndex=APTools::getRand(0, dropEquipCount - 1);
auto equip=equipVector.at(randIndex);
int dropEquipIndex=equip->WeaponID - 1;
addOneEquip(vPos, dropEquipIndex);
}
}
//增加金币
void RewardEquipBLL::addOneGold(const Vec2& goldPos)
{
auto callFunc= CallFuncN::create(CC_CALLBACK_1(RewardEquipBLL::removeEquip,this));
//加金币
float height = APTools::getRandFloat(200,650);
auto gold = DropGold::create();
gold->setPosition(goldPos);
auto apscatt = APScatterAction::create(height, 0.2); //APScatterAction::createWithRotation(0.2);
auto blink = Blink::create(1, 3);
auto blink2 = Blink::create(1.3, 4);
auto sqe = Sequence::create(apscatt,DelayTime::create(1.5f),blink,blink2,callFunc, NULL);
gold->runAction(sqe);
auto gamelayer=GameBLL::instance()->m_GameLayer;
gamelayer->addGameObject(gold);
m_dropObjects.pushBack(gold);
}
//增加一个装备
void RewardEquipBLL::addOneEquip(const Vec2& ePos, int weaponIndex)
{
auto callFunc=CallFuncN::create(CC_CALLBACK_1(RewardEquipBLL::removeEquip,this));
//加装备
float height = APTools::getRandFloat(200,350);
auto equip = DropEquip::create(weaponIndex);
equip->setPosition(ePos);
auto apscatt = APScatterAction::create(height);
auto blink = Blink::create(1, 3);
auto blink2 = Blink::create(1.3, 4);
auto sqe = Sequence::create(apscatt,DelayTime::create(1.5f),blink,blink2,callFunc, NULL);
equip->runAction(sqe);
auto gamelayer=GameBLL::instance()->m_GameLayer;
gamelayer->addGameObject(equip);
m_dropObjects.pushBack(equip);
}
//删除装备
void RewardEquipBLL::removeEquip(Node* gold)
{
auto obj=dynamic_cast<DropObject*>(gold);
m_dropObjects.eraseObject(obj);
obj->removeFromParentAndCleanup(true);
}
| true |
c4aa816e18ac2d65f93bde8d7407a8e6a22d42f4 | C++ | RumRaisins/ProjectEuler | /ProjectEuler/ProjectEuler/3_600851475143的素数.cpp | UTF-8 | 756 | 2.59375 | 3 | [] | no_license | #include"ReadText.h"
using namespace std;
int main() {
//long long int n = 600851475143;
//int *isPrime = new int[0x7fffffe]();
//for (int i = 2; i < n; i++) {
// if (!isPrime[i]) {
// isPrime[++isPrime[0]] = i;
// if ( n % i == 0) {
// //cout << i<<" ";
// n = n / i;
// cout << n<<" ";
// if (n == 0)
// break;
// }
// }
// for (int j = 1 ; j <= isPrime[0] && i*isPrime[j] <= n; j++){
// isPrime[i*isPrime[j]] = 1;
// if (i%isPrime[j] == 0) {
// break;
// }
// }
//}
int32_t n = 600851475143;
int maxPrime = 2;
for (size_t i = 2; i*i < n; i++)
{
while(n %i == 0){
n = n / i;
maxPrime = i;
}
}
if (n != 1) maxPrime = n;
cout << n;
system("pause");
return 0;
} | true |
342b3b48713e4be79fc2595855f1a16bb2d88677 | C++ | GillesAnneSophie/ProjetCPPBanque | /src/CompareEventPriority.h | UTF-8 | 345 | 2.703125 | 3 | [] | no_license | /*
* @author Anne-Sophie GILLES
*/
#ifndef PROJECT_COMPARE_EVENT_PRIORITY_H
#define PROJECT_COMPARE_EVENT_PRIORITY_H
#include "Event.h"
class CompareEventPriority{
public:
/**
* Compare events priority
* @param e1 Event
* @param e2 Event
* @return Int - 0 or 1
*/
int operator() (Event * & e1, Event * & e2);
};
#endif | true |
9eb6990a05009a87ee2b72d8bb3bf13db663346b | C++ | cocteautwins/SIRIUS-develop | /src/Density/generate_rho_radial_integrals.cpp | UTF-8 | 4,229 | 2.515625 | 3 | [
"BSD-2-Clause"
] | permissive | #include "density.h"
namespace sirius
{
/** type = 0: full-potential radial integrals \n
* type = 1: pseudopotential valence density integrals \n
* type = 2: pseudopotential code density integrals
*/
mdarray<double, 2> Density::generate_rho_radial_integrals(int type__)
{
runtime::Timer t("sirius::Density::generate_rho_radial_integrals");
mdarray<double, 2> rho_radial_integrals(unit_cell_.num_atom_types(), ctx_.gvec().num_shells());
/* split G-shells between MPI ranks */
splindex<block> spl_gshells(ctx_.gvec().num_shells(), ctx_.comm().size(), ctx_.comm().rank());
if (type__ == 4)
{
/* rho[r_] := Z*b^3/8/Pi*Exp[-b*r]
* Integrate[Sin[G*r]*rho[r]*r*r/(G*r), {r, 0, \[Infinity]}, Assumptions -> {G >= 0, b > 0}]
* Out[] = (b^4 Z)/(4 (b^2 + G^2)^2 \[Pi])
*/
double b = 4;
for (int igs = 0; igs < ctx_.gvec().num_shells(); igs++)
{
double G = ctx_.gvec().shell_len(igs);
for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++)
{
rho_radial_integrals(iat, igs) = std::pow(b, 4) * unit_cell_.atom_type(iat).zn() / (4 * std::pow(std::pow(b, 2) + std::pow(G, 2), 2) * pi);
}
}
return rho_radial_integrals;
}
#pragma omp parallel
{
/* splines for all atom types */
std::vector< Spline<double> > sa(unit_cell_.num_atom_types());
for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++)
{
/* full potential radial integrals requre a free atom grid */
sa[iat] = (type__ == 0) ? Spline<double>(unit_cell_.atom_type(iat).free_atom_radial_grid())
: Spline<double>(unit_cell_.atom_type(iat).radial_grid());
}
/* spherical Bessel functions */
Spherical_Bessel_functions jl;
#pragma omp for
for (int igsloc = 0; igsloc < (int)spl_gshells.local_size(); igsloc++)
{
int igs = (int)spl_gshells[igsloc];
for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++)
{
auto& atom_type = unit_cell_.atom_type(iat);
if (type__ == 1 || type__ == 2)
jl = Spherical_Bessel_functions(0, atom_type.radial_grid(), ctx_.gvec().shell_len(igs));
if (type__ == 0)
{
if (igs == 0)
{
for (int ir = 0; ir < sa[iat].num_points(); ir++) sa[iat][ir] = atom_type.free_atom_density(ir);
rho_radial_integrals(iat, igs) = sa[iat].interpolate().integrate(2);
}
else
{
double G = ctx_.gvec().shell_len(igs);
for (int ir = 0; ir < sa[iat].num_points(); ir++)
{
sa[iat][ir] = atom_type.free_atom_density(ir) *
std::sin(G * atom_type.free_atom_radial_grid(ir)) / G;
}
rho_radial_integrals(iat, igs) = sa[iat].interpolate().integrate(1);
}
}
if (type__ == 1)
{
for (int ir = 0; ir < sa[iat].num_points(); ir++)
sa[iat][ir] = jl[0][ir] * atom_type.uspp().total_charge_density[ir];
rho_radial_integrals(iat, igs) = sa[iat].interpolate().integrate(0) / fourpi;
}
if (type__ == 2)
{
for (int ir = 0; ir < sa[iat].num_points(); ir++)
sa[iat][ir] = jl[0][ir] * atom_type.uspp().core_charge_density[ir];
rho_radial_integrals(iat, igs) = sa[iat].interpolate().integrate(2);
}
}
}
}
int ld = unit_cell_.num_atom_types();
ctx_.comm().allgather(rho_radial_integrals.at<CPU>(), static_cast<int>(ld * spl_gshells.global_offset()),
static_cast<int>(ld * spl_gshells.local_size()));
return std::move(rho_radial_integrals);
}
};
| true |
7a53903644bfb5b4f369e1ffb45bfa01bf837e51 | C++ | zacharytay1994/GPPAssignment2 | /DirectXFramework/Rail.h | UTF-8 | 1,092 | 2.84375 | 3 | [] | no_license | #pragma once
#include "Entity.h"
class Rail : public Entity
{
public:
enum class Direction {
Vertical,
Horizontal,
RTopCurved,
RBottomCurved,
LBottomCurved,
LTopCurved
};
private:
Direction direction_ = Direction::Horizontal;
bool is_ghost_ = false;
public:
Rail(const std::string& image, std::shared_ptr<Graphics> gfx, std::shared_ptr<Input> input, std::shared_ptr<ResourceLibrary> rl);
void Update(const float& dt) override;
void Render() override;
Direction GetDirection() { return direction_; }
void SetDirection(Direction direction);
void MakeGhost();
QuaternionUWU ToQuaternion(Vecf3 rot) // yaw (Z), pitch (Y), roll (X)
{
// Abbreviations for the various angular functions
double cy = cos(rot.z * 0.5);
double sy = sin(rot.z * 0.5);
double cp = cos(rot.y * 0.5);
double sp = sin(rot.y * 0.5);
double cr = cos(rot.x * 0.5);
double sr = sin(rot.x * 0.5);
QuaternionUWU q;
q.w = cy * cp * cr + sy * sp * sr;
q.x = cy * cp * sr - sy * sp * cr;
q.y = sy * cp * sr + cy * sp * cr;
q.z = sy * cp * cr - cy * sp * sr;
return q;
}
};
| true |
d6090e99b440d9b1b119514cce579b8700900336 | C++ | mashroormamun/interviewbits | /Largest Number/main.cpp | UTF-8 | 556 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
bool comp(int i, int j) {
string a = to_string(i);
string b = to_string(j);
return (a + b) > (b + a);
}
string largestNumber(const vector<int>& AA) {
vector<int> A(AA.begin(), AA.end());
sort(A.begin(), A.end(), comp);
if (A[0] == 0) return "0";
string res = "";
for (int i = 0; i < A.size(); i++) {
res += to_string(A[i]);
}
return res;
}
int main()
{
vector<int>A({ 3, 30, 34, 5, 9 });
cout << largestNumber(A) << endl;
return 0;
} | true |
0f17fc703b3881d91b917ff54eeacea7de4ebe46 | C++ | GIacial/Pokemon | /TestPokemon/Pokemon/Statut/statut_paralysie.cpp | UTF-8 | 494 | 2.5625 | 3 | [] | no_license | #include "statut_paralysie.h"
Statut_Paralysie::Statut_Paralysie(PokemonInterface &cible) : AbstractStatut("Paralysie",cible)
{
}
Statut_Paralysie::~Statut_Paralysie() throw (){
}
bool Statut_Paralysie::effect(){
bool attaqueOK = rand()%100 > COEF_ATT_POSSIBLE;
if(!attaqueOK){
emit sendMsg("La "+this->getName()+" empeche "+this->getCible().getNom()+ " d'attaquer");
}
return attaqueOK;
}
double Statut_Paralysie::getCoefAltVit()const{
return COEF_ALT_VIT;
}
| true |
d299a5fd8687285b2441eb7035a5e74e0e271339 | C++ | Lukasz-Madry/TestRepos | /chesstestuntlanslatenotfinaldonttouch/chesstestuntlanslatenotfinaldonttouch/Board.h | UTF-8 | 670 | 2.5625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include "ClassChess.h"
#include"Pawn.h"
#include"Knight.h"
#include"Bishop.h"
#include"Rook.h"
#include"Queen.h"
#include"King.h"
class Board
{
public:
Piece*** board;
void Start();
void PerformMove();
void Show();
Board();
void GameStart();
int size = 100;
int move = 0;
int x, y;
int boardcells[8][8] =
{ 2, 3, 4, 5, 6, 4, 3, 2,
1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-1,-1,-1,-1,-1,-1,-1,-1,
-2,-3,-4,-5,-6,-4,-3,-2,};
}; | true |
04d30ce56a40be233776bde082e3d957ef795f33 | C++ | SeanCST/Algorithm_Problems | /LeetCode/031_下一个排列.cpp | UTF-8 | 783 | 3.21875 | 3 | [] | no_license | class Solution {
public:
void nextPermutation(vector<int>& nums) {
int i = 0, j = 0;
int n = nums.size();
for(int k = n - 1; k >= 1; k--) {
// nums[j...n-1] 递减, nums[i] < nums[j]
if(nums[k - 1] < nums[k]) {
i = k - 1;
j = k;
break;
}
}
if(i >= 0) {
for(int k = n - 1; k >= i; k--) {
// 从右往左找到第一个比 nums[i] 大的数
if(nums[k] > nums[i]){
swap(nums[i], nums[k]);
break;
}
}
}
int left = j, right = n - 1;
while(left < right) {
swap(nums[left++], nums[right--]);
}
}
};
| true |
db6d1fddafc738fc256db6c7f711a07d40e2ed8a | C++ | tiozo/Training | /vnoj/nkguard.cpp | UTF-8 | 2,709 | 2.75 | 3 | [
"MIT"
] | permissive | #include<bits/stdc++.h>
using namespace std;
#define nd second
#define st first
typedef vector<vector<int>> vii;
class graph {
private:
queue<pair<int,int>> s;
vector<vector<int>> check;
vector<pair<int,int>> ke{{-1,-1},{0,1},{0,-1},{1,0},{-1,0},{1,1},{-1,1},{1,-1}};
int res = 0;
int high = 0;
public:
graph (int size) {
check.resize(size+1);
for (int i=0;i<=size;++i) {
check[i].resize(size+1,0);
}
}
void clear( queue<pair<int,int>> &q )
{
queue<pair<int,int>> empty;
swap( q, empty );
}
void BFS(vii &g,int xx,int yy,int N,int M) {
int x,y;
clear(s);
pair<int,int> u;
s.push({xx,yy});
check[xx][yy] = 1;
while (!s.empty()) {
u = s.front();
s.pop();
for (pair<int,int> k: ke) {
x = u.first + k.first;
y = u.second + k.second;
if (x < 0 || y < 0 || x > N || y > M) {
continue;
}
if (!check[x][y] && g[x][y] == g[xx][yy]) {
s.push({x,y}); check[x][y] = true;
} else if (g[xx][yy] < g[x][y]) high = 0;
}
}
}
void DFS(vii &g,int xx,int yy,int N,int M) {
check[xx][yy] = 1;
for (auto k: ke) {
int x = xx + k.first, y = yy + k.second;
if (x < 0 || y < 0 || x > N || y > M) continue;
if (!check[x][y] && g[x][y] == g[xx][yy]) {
DFS(g,x,y,N,M);
} else if (high && g[x][y] > g[xx][yy]) high = 0;
}
}
void solve(vii &g,int N,int M) {
for (int i = 1;i<=N;++i) {
for (int j=1;j<=M;++j) {
if (!check[i][j]) {
high = 1;
DFS(g,i,j,N,M);
// BFS(g,i,j,N,M);
/*
dùng DFS vì đỉnh ta tìm có thể ở xa so với đỉnh hiện tại đang xét
tối ưu hơn về tốc độ khi có nhiều nhánh tìm bị ra ngoài.
THỰC CHẤT: queue làm cho BFS chậm hơn DFS
và vì đề bài không có yêu cầu tìm lân cận
*/
res += high;
}
}
}
cout << res;
}
};
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int N,M;
cin >> N >> M;
graph g(max(N,M));
vector<vector<int>> a(N+1,vector<int> (M+1,0));
for (int i=1;i<=N;++i) {
for (int j=1;j<=M;++j) {
cin >> a[i][j];
}
}
g.solve(a,N,M);
return 0;
} | true |
a65f4d01afb064f92cd5026ed52528a24ea7aa95 | C++ | Azrrael-exe/FingerPrint-Handler | /C++/src/test.cpp | UTF-8 | 487 | 2.921875 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stddef.h>
#include <string.h>
#include <iostream>
#include <fstream>
int test(unsigned char** d, unsigned int* s){
unsigned char* val = (unsigned char*)malloc(10);
for(int i = 0; i<10; i++){
val[i] = 'A';
}
*s = sizeof(char[10]);
*d = val;
return 1;
}
int main() {
unsigned char* data;
unsigned int size;
test(&data ,&size);
printf("size: %d\n", size);
printf("%s\n", data);
return 0;
}
| true |
f61c1f48c7efca964932356ec2df96194a24b897 | C++ | mahdi7najafi/DataStructure | /DataStructure/Source.cpp | UTF-8 | 22,239 | 3.703125 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
class room {
public:
int length;
int initial;
// Enum class for different types of rooms
enum class roomType { main_hall, exam_hall, lecture_room, tutorial_room, design_studio, meeting_room };
// struct
struct node {
string data;
int id;
int memId;
int capacity;
int year, month, day;
int hour, minute;
roomType type;
node* next;
};
node* front;
node * tail;
// Constructor
room() {
length=0;
initial=1;
//------------
front = NULL;
tail = NULL;
}
// check number of rooms (not exceeding 15)
bool isFull () { return length>=15; }
// Add Rooms
void room::addRoom() {
system("cls");
if (isFull()) {
cout<<" No more than 15 rooms are allowed\n"<<endl;
return;
}
cout << "Enter the capacity" << endl;
int a;
cin >> a;
node* temp = new node();
temp->data = "Not_Reserved";
temp->id = initial;
temp->year = 0;
temp->month = 0;
temp->day = 0;
temp->hour = 0;
temp->minute = 0;
initial++;
temp->capacity = a;
temp->next = NULL;
if (front == NULL && tail == NULL)
{
front = temp;
tail = temp;
}
else {
tail->next = temp;
tail = temp;
}
cout << "Choose The type" << endl;
cout << "1- Main Hall \t 2- Lecture Room \t 3- Exam Hall \t 4- Meeting Room \t 5- Design Studio \t 6- Tutorial Room" << endl;
int t;
cin >> t;
if (t == 1)
{
temp->type = roomType::main_hall;
}
else if (t == 2)
{
temp->type = roomType::lecture_room;
}
else if (t == 3)
{
temp->type = roomType::exam_hall;
}
else if (t == 4)
{
temp->type = roomType::meeting_room;
}
else if (t == 5)
{
temp->type = roomType::design_studio;
}
else if (t == 6)
{
temp->type = roomType::tutorial_room;
}
else {cout << "Wrong Input!" << endl;}
length++;
cout<<"\n Successfully Created!\n\n";
system("pause");
save();
}
// Delete Room
void deleteRoom()
{
system("cls");
room::show();
cout << "================================================" << endl;
cout << "Enter the room ID you want to delete!";
int x;
cin >> x;
node* tmp = front;
node* prv = NULL;
while (tmp != NULL)
{
if (tmp->id == x)
{
if (prv != NULL)
{
prv->next = tmp->next;
}
else
{
front = tmp->next;
}
delete tmp;
break;
}
prv = tmp;
tmp = tmp->next;
}
cout << "-------------------Successfully Deleted ----------------" << endl;
system("pause");
save();
}
// room type to string coversion
string typeToText (roomType type) {
switch (type) {
case roomType::design_studio:
return "Design_Studio";
break;
case room::roomType::exam_hall:
return "Exam_Hall";
break;
case roomType::lecture_room:
return "Lecture_Room";
break;
case roomType::main_hall:
return "Main_Hall";
break;
case roomType::meeting_room:
return "Meeting_Room";
break;
case roomType::tutorial_room:
return "Tutorial_Room";
break;
}
}
room::roomType room::textToType(string text)
{
if(text == "Design_Studio")
{
return roomType::design_studio ;
}
else if(text == "Exam_Hall")
{
return room::roomType::exam_hall ;
}
else if(text == "Lecture_Room")
{
return roomType::lecture_room ;
}
else if(text == "Main_Hall")
{
return roomType::main_hall ;
}
else if(text == "Meeting_Room")
{
return roomType::meeting_room ;
}
else if(text == "Tutorial_Room")
{
return roomType::tutorial_room ;
}
}
// show Rooms
void room::show()
{
node* tmp = front;
while (tmp != NULL)
{
cout << "ID " << tmp->id << "\t" << tmp->data << "\t Date: " << tmp->year<<"/"<<tmp->month<<"/"<<tmp->day << "\t Time: "<< tmp->hour<< " : " << tmp->minute <<"\t"<< typeToText(tmp->type) << "\t" << tmp->capacity << "\n";
tmp = tmp->next;
}
}
// Reserve Room
void reserveRoom()
{
system("cls");
show();
cout << "=============================================================" << endl;
cout << "Enter the room ID you want to Book !" << endl;
int id;
cin >> id;
node* tmp = front;
while (tmp != NULL) {
if (tmp->id == id) {
if(tmp->data == "Not_Reserved"){
tmp->data = "Reserved";
int y,m,d;
int min, hr;
cout << "Enter the year " << endl;
cin >> y;
cout << "Enter the month " << endl;
cin >> m;
cout << "Enter the day " << endl;
cin >> d;
cout << "Enter the Hour " << endl;
cin >> hr;
cout << "Enter the Minute " << endl;
cin >> min;
tmp->year = y;
tmp->month = m;
tmp->day = d;
tmp->hour = hr;
tmp->minute = min;
cout << "Room Reserved!" << endl;
}
else{
cout << "This room has been reserved!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
}
}
tmp = tmp->next;
}
system("pause");
room::save();
}
// save file
void save()
{
system("cls");
cout << "Do you want to Save it? " << endl;
int i;
cout << "1- Yes \t" << "2- No" << endl;
cin >> i;
ofstream file;
file.open("Room.txt");
node* tmp = front;
switch (i)
{
case 1:
while (tmp != NULL)
{
file << tmp->id << "-" << tmp->data << "-" << tmp->year<<"-"<<tmp->month<<"-"<<tmp->day << "-"<< typeToText(tmp->type) << "-" << tmp->capacity << "-" << tmp->hour << "-" << tmp->minute <<"\n";
tmp = tmp->next;
}
file.close();
break;
case 2:
cout << "Operation Canceled!" << endl;
break;
}
}
// delete the previous records by giving a date
void delPreviousBooking(){
//loadRecords();
show();
cout << "Enter the date to delete the previous days record" << endl;
cout << "Enter the year" << endl;
int ye,mo, da;
//int idate;
cin >> ye;
cout << "Enter the month" << endl;
cin >> mo;
cout << "Enter the day" << endl;
cin >> da;
//idate = ye+mo+da;
node* tmp = front;
while (tmp != NULL)
{
//tmp->deleteDate <= idate
if (tmp->year <= ye )
{
if(tmp->month <= mo){
if(tmp->day <= da || (tmp->month -1 <= mo && tmp->month < mo ) ){
tmp->data = "Not_Reserved";
tmp->year =0;
tmp->month =0;
tmp->day = 0;
tmp->hour = 0;
tmp->minute = 0;
}
}
}
tmp = tmp->next;
}
save();
}
// modify a room
void updateRoom()
{
system("cls");
room::show();
int x;
cout << "Enter the Room ID You want to update it: " << endl;
cin >> x;
node* tmp = front;
while (tmp != NULL)
{
if (tmp->id == x)
{
int c;
int t;
cout << "Enter New Capacity" << endl;
cin >> c;
cout << "Choose The type" << endl;
cout << "1- Main Hall \t 2- Lecture Room \t 3- Exam Hall \t 4- Meeting Room \t 5- Design Studio \t 6- Tutorial Room" << endl;
cin >> t;
tmp->capacity = c;
if (t == 1)
{
tmp->type = roomType::main_hall;
cout << "Data Changed!" << endl;
}
else if (t == 2)
{
tmp->type = roomType::lecture_room;
cout << "Data Changed!" << endl;
}
else if (t == 3)
{
tmp->type = roomType::exam_hall;
cout << "Data Changed!" << endl;
}
else if (t == 4)
{
tmp->type = roomType::meeting_room;
cout << "Data Changed!" << endl;
}
else if (t == 5)
{
tmp->type = roomType::design_studio;
cout << "Data Changed!" << endl;
}
else if (t == 6)
{
tmp->type = roomType::tutorial_room;
cout << "Data Changed!" << endl;
}
else cout << "Wrong Input!" << endl;
}
tmp = tmp->next;
}
save();
}
// upload records
void loadRecords(){
string line;
ifstream myFile ("Room.txt");
if(myFile.is_open()){
while(getline(myFile, line)){
cout << line << "\n";
}
myFile.close();
}
else cout << "Unable to open the file" << endl;
}
// search a room by id
void searchBooking(int x)
{
node* tmp = front;
while (tmp != NULL)
{
if (tmp->id == x)
{
cout << tmp->id << "\t" << tmp->data << "\t Date: " << tmp->year<<"/"<<tmp->month<<"/"<<tmp->day << "\t"<< typeToText(tmp->type) << "\t" << tmp->capacity << "\t Time: " << tmp->hour << " : " << tmp->minute<< "\n";
}
tmp = tmp->next;
}
system("pause");
}
// load records and save them to linked list when application starts
void loadRooms()
{
string line;
ifstream myFile ("Room.txt");
if(myFile.is_open())
{
std::string word; /* string to hold words */
std::string sTemp;
std::stringstream s;
std::stringstream wordstream;
while (getline (myFile, line))
{ /* read each line into line */
node* tmp = new node();
initial++;
s.str(line);
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>tmp->id;
wordstream.clear();
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>tmp->data;
wordstream.clear();
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>tmp->year;
wordstream.clear();
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>tmp->month;
wordstream.clear();
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>tmp->day;
wordstream.clear();
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>sTemp;
tmp->type = textToType(sTemp);
wordstream.clear();
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>tmp->capacity;
wordstream.clear();
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>tmp->hour;
wordstream.clear();
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>tmp->minute;
wordstream.clear();
s.clear();
tmp->next = NULL;
if (front == NULL && tail == NULL)
{
front = tmp;
tail = tmp;
}
else {
tail->next = tmp;
tail = tmp;
}
}
}
}
};
class member {
public:
int pk;
// Struct
struct nodetype {
int id;
string name;
string password;
string type;
string email;
nodetype* next;
};
// Constructor
member() {
start = NULL;
pk=1;
}
// Create a new Member
void addMember(string n, string p, string t, string e) {
nodetype* temp = new nodetype();
temp->id = pk;
pk++;
temp->name = n;
temp->password = p;
temp->type = t;
temp->email = e;
temp->next = start;
start = temp;
saveMember();
system("pause");
}
// Showing data
void showMember()
{
nodetype* temp = start;
while (temp != NULL)
{
cout << temp->id << "\t" << temp->name << "\t" << temp->type << "\t" << temp->password << "\t" << temp->email << endl;
temp = temp->next;
}
}
// Delete a member
void deleteMember()
{
showMember();
cout << "Enter member's id you want to delete" << endl;
int x;
cin >> x;
nodetype* tmp = start;
nodetype* prv = NULL;
while (tmp != NULL)
{
if (tmp->id == x)
{
if (prv != NULL)
{
prv->next = tmp->next;
}
else
{
start = tmp->next;
}
delete tmp;
break;
}
prv = tmp;
tmp = tmp->next;
}
saveMember();
system("pause");
}
// Modify a member
void updateMember()
{
loadMember();
cout << "Enter the member's id you want to modify" << endl;
int x;
cin >> x;
nodetype* tmp = start;
while (tmp != NULL)
{
if (tmp->id == x)
{
string n;
string t;
string p;
string e;
cout << "Enter New Name" << endl;
cin >> n;
cout << "Enter New Type" << endl;
cin >> t;
cout << "Enter New Password" << endl;
cin >> p;
cout << "Enter New Email" << endl;
cin >> e;
tmp->name = n;
tmp->password = p;
tmp->type = t;
tmp->email = e;
}
tmp = tmp->next;
}
cout << "--------------Successfully Updated ------------------" << endl;
system("pause");
saveMember();
}
// Save to text file
void saveMember(){
system("cls");
cout << "Do you want to Save it? " << endl;
int i;
cout << "1- Yes \t" << "2- No" << endl;
cin >> i;
ofstream file;
// open file
file.open("Member.txt");
nodetype* tmp = start;
switch (i)
{
case 1:
while (tmp != NULL)
{
file << tmp->id << "-" << tmp->name << "-" << tmp->type << "-" << tmp->password << "-"<< tmp->email << "\n";
tmp = tmp->next;
}
file.close();
break;
case 2:
// cancel save operation
cout << "OK!" << endl;
break;
}
}
// show memeber only
void loadMember(){
string line;
ifstream myFile ("Member.txt");
if(myFile.is_open()){
while(getline(myFile, line)){
cout << line << "\n";
}
myFile.close();
}
else cout << "Unable to open the file" << endl;
}
// load the text file and save each word seperated by "-" to its position
void MemberloadStarter()
{
string line;
ifstream myFile ("Member.txt");
if(myFile.is_open())
{
std::string word; /* string to hold words */
std::string sTemp;
std::stringstream s;
std::stringstream wordstream;
while (getline (myFile, line))
{ /* read each line into line */
nodetype* tmp = new nodetype();
pk++;
s.str(line);
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>tmp->id;
wordstream.clear();
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>tmp->name;
wordstream.clear();
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>tmp->type;
wordstream.clear();
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>tmp->password;
wordstream.clear();
getline (s, word, '-'); /* read hyphen separated words */
wordstream.str(word);
wordstream>>tmp->email;
wordstream.clear();
s.clear();
tmp->next = start;
start = tmp;
}
}
}
// check whether the password is correct or not
bool checkPassword(int i, string pass){
nodetype* tmp = start;
int o =0;
while (tmp != NULL)
{
if (tmp->id == i && tmp->password == pass)
{
o = 1;
}
tmp = tmp->next;
}
if(o == 1){
return true;
}
else return false;
}
// show member without its password to user to choose his/her id
void showID()
{
nodetype* temp = start;
while (temp != NULL)
{
cout << "==================================================" << endl;
cout <<" \t"<< temp->id << "\t " << temp->name << "\t " << temp->type << " "<<endl;
cout << "==================================================" << endl;
temp = temp->next;
}
}
private:
nodetype* start;
};
class menu{
public:
menu(){
}
// show the login section
void logShow(){
system("cls");
cout << "=============================================== \n";
cout << "|| please choose an item on the menu below || \n";
cout << "||-------------------------------------------|| \n";
cout << "|| Log in As: || \n";
cout << "||-------------------------------------------|| \n";
cout << "|| (1) Administrator || \n";
cout << "|| (2) Staff || \n";
cout << "|| (3) Students || \n";
cout << "||-------------------------------------------|| \n";
cout << "|| (4) Quit || \n";
cout << "=============================================== \n";
cout << "Your Choice: ";
}
// Staff menu
void staffShow(){
system("cls");
cout << "=============================================== \n";
cout << "|| please choose an item on the menu below || \n";
cout << "||-------------------------------------------|| \n";
cout << "|| (1) Perform Booking || \n";
cout << "|| (2) View All rooms || \n";
cout << "|| (3) View My Booking || \n";
cout << "||-------------------------------------------|| \n";
cout << "|| (4) Quit || \n";
cout << "=============================================== \n";
cout << "Your Choice: ";
}
// student menu
void studentShow(){
system("cls");
cout << "=============================================== \n";
cout << "|| please choose an item on the menu below || \n";
cout << "||-------------------------------------------|| \n";
cout << "|| (1) Perform Booking || \n";
cout << "|| (2) View My Booking || \n";
cout << "||-------------------------------------------|| \n";
cout << "|| (3) Quit || \n";
cout << "=============================================== \n";
cout << "Your Choice: ";
}
// admin menu
void adminShow(){
system("cls");
cout << "=============================================== \n";
cout << "|| please choose an item on the menu below || \n";
cout << "||-------------------------------------------|| \n";
cout << "|| (1) Add Rooms || \n";
cout << "|| (2) Delete Room || \n";
cout << "|| (3) Modify Rooms || \n";
cout << "|| (4) Add Member || \n";
cout << "|| (5) Delete Member || \n";
cout << "|| (6) Modify Members || \n";
cout << "|| (7) Perform Booking || \n";
cout << "|| (8) Search the Records || \n";
cout << "|| (9) Delete Previous Records || \n";
cout << "|| (10) View All records || \n";
cout << "||-------------------------------------------|| \n";
cout << "|| (11) Quit || \n";
cout << "=============================================== \n";
cout << "Your Choice: ";
}
};
int main() {
// creating object of each class
room obj;
member ins;
menu me;
//string for adding a member
string a,b,c,d;
// for room id
int x;
// for menu condition
int ym = 1;
// Because we need to populate the nodes
// upload member and save the parameters so we check each one by its password and id when app starts
ins.MemberloadStarter();
me.logShow();
int logO;
cin >> logO;
// Admin section
if(logO == 1)
{
system("cls");
string password;
cout << "Enter your Password" << endl;
cin >> password;
obj.loadRooms();
// create the check password function
if(password == "1234"){
while(ym==1) {
me.adminShow();
int adminOp;
cin >> adminOp;
switch (adminOp)
{
case 1:
obj.addRoom();
break;
case 2:
obj.deleteRoom();
break;
case 3:
obj.updateRoom();
break;
case 4:
cout << "Enter the name" << endl;
cin >> a;
cout << "Enter the password" << endl;
cin >> b;
cout << "Enter the type Student || Staff " << endl;
cin >> c;
cout << "Enter the Email" << endl;
cin >> d;
ins.addMember(a,b,c,d);
break;
case 5:
ins.deleteMember();
break;
case 6:
ins.updateMember();
break;
case 7:
obj.reserveRoom();
break;
case 8:
cout << "Enter the room id you want to check" << endl;
cin >> x;
obj.searchBooking(x);
break;
case 9:
system("cls");
obj.delPreviousBooking();
break;
case 10:
system("cls");
cout << "----------------------------------------------------------" << endl;
cout << "-------------------------Rooms----------------------------" << endl;
cout << "" << endl;
obj.loadRecords();
cout << "----------------------------------------------------------" << endl;
cout << "------------------------Members---------------------------" << endl;
cout << "" << endl;
ins.loadMember();
system("pause");
break;
default:
ym = 0;
system("exit");
break;
}
}
}
else{
cout << "Wrong Password" << endl;
system("pause");
}
}
// staff section
else if(logO == 2)
{
system("cls");
ins.showID();
cout << "enter your id" << endl;
int mId;
cin >> mId;
string password;
cout << "Enter your Password" << endl;
cin >> password;
// create the check password function
if(ins.checkPassword(mId, password)){
while(ym == 1) {
me.staffShow();
int stafOp;
cin >> stafOp;
switch (stafOp)
{
case 1:
obj.loadRooms();
obj.reserveRoom();
break;
case 2:
obj.show();
system("pause");
break;
case 3:
cout << "Enter The room Id you booked" << endl;
int k;
cin >> k;
obj.searchBooking(k);
break;
default:
ym = 0;
break;
}
}
}
else{
cout << "Wrong Password" << endl;
system("pause");
}
}
//Student section
else if(logO == 3)
{
system("cls");
ins.showID();
cout << "enter your id" << endl;
int mId;
cin >> mId;
string password;
cout << "Enter your Password" << endl;
cin >> password;
// create the check password function
if(ins.checkPassword(mId,password)){
while(ym == 1) {
me.studentShow();
int stuOp;
cin >> stuOp;
switch (stuOp)
{
case 1:
obj.loadRooms();
obj.reserveRoom();
//menuLoop = true;
break;
case 2:
cout << "Enter The room Id you booked" << endl;
int k;
cin >> k;
obj.searchBooking(k);
break;
default:
ym = 0;
break;
}
}
}
else{
cout << "Wrong Password" << endl;
system("pause");
}
}
}
| true |
8ffe029caafe80f8ed4409a02b34b7fc09b69ecf | C++ | 264aayush/my-cpp-codes | /kmp.cpp | UTF-8 | 1,230 | 2.546875 | 3 | [] | no_license | #include <bits/stdc++.h>
#define loop(i,a,b) for(int i=a;i<b;i++)
typedef long long ll;
using namespace std;
void lps(int arr[],string str){
int n=str.length();
int j=0;
for(int i=1;i<n;i++){
if(str[i]==str[j]){
arr[i]=j+1;
j++;
}
else{
if(j>0){
j=arr[j-1];
i--;
}
}
}
}
void kmp(string str, string ptr, int lps[]){
int i=0,j=0;
int n=str.length();
int m=ptr.length();
for(i=0;i<n;i++){
if(j==m){
cout<<i-m+1<<" ";
j=lps[j-1];
i--;
}
else if(str[i]==ptr[j]){
j++;
}
else{
if(j>0){
j=lps[j-1];
i--;
}
}
}
if(j==m)
cout<<n-m+1<<" ";
}
int main() {
int t;
cin>>t;
while(t--){
string str,ptr;
cin>>str>>ptr;
int n=ptr.length();
int pi[n];
memset(pi,0,sizeof(pi));
lps(pi,ptr);
for(int i=0;i<ptr.length();i++)
cout<<pi[i]<<" ";
cout<<endl;
cout<<str<<endl<<ptr<<endl;
kmp(str,ptr,pi);
}
return 0;
} | true |
7cb32f86961461117972bfc255da6f92c4843888 | C++ | tranphuquy19/Digital-Signal-Processing | /XLTHS001.cpp | UTF-8 | 935 | 2.75 | 3 | [] | no_license | #include<stdio.h>
void InputSignal(float a[], int &nH0, int nH)
{
printf("Nhap tin hieu: \n");
for(int i=0; i<nH; i++)
{
scanf("%f", &a[i]);
}
printf("n0 tai phan tu thu may (n0 > 0): ");
scanf("%d", &nH0);
}
void ShowSignal(float a[], int nH0, int nH)
{
for(int i=0; i<nH; i++)
{
printf("%.3f ", a[i]);
}
printf("\n");
for(int i=0; i<nH0-1; i++)
{
printf(" ");
}
printf("n0");
}
void DaoXung(float a[], float H[], int nH, int &n0, int nH0)
{
int count = 0;
for(int i = nH-1; i >= 0; i--)
{
a[count]= H[i];
count++;
}
n0 = nH + 1 - nH0;
}
int main()
{
/*
nH la so xung cua TH H
nH0 la vi tri n0 cua TH H
*/
printf("H[n] co bao nhieu xung? ");
int nH, nH0;
scanf("%d", &nH);
fflush(stdin);
float H[nH], H1[nH];
InputSignal(H, nH0, nH);
ShowSignal(H, nH0, nH);
printf("\n");
int nDao0;
DaoXung(H1, H, nH, nDao0, nH0);
ShowSignal(H1, nDao0, nH);
return 0;
}
| true |
d2b1086cb19ea75c3294bd33284ce78f6579157e | C++ | aslupin/task-problemset | /codeforces/cpp/Magic Spheres.cpp | UTF-8 | 680 | 2.640625 | 3 | [] | no_license | #include <stdio.h>
int spheres[3][3];
int spheres_cpy[3];
int check_i(int i){
spheres[0][i] = spheres[0][i]-2;
if(i != 2) // position isn't 2 (last position) because last have not next
spheres[0][i+1] += 1;
else spheres[0][i-1] += 1;
if(spheres[0][i] != spheres[1][i])
check_i(i);
else return 0;
}
main(){
for(int j=0;j<2;j++){
for(int i=0;i<3;i++){
scanf("%d",&spheres[j][i]);
}}
// base is [1][0] [1][1] [1][2]
for(int i=0;i<3;i++){
if(spheres[0][i] != spheres[1][i]){
if((spheres[0][i] > spheres[1][i]) && spheres[0][i]%2 == 0)
check_i(i);
else if((spheres[0][i] < spheres[1][i]) && spheres[0][i]%2 == 0)
}
}
| true |
1932bcd3a90fd02df3be28750d0764abe2b3a0f0 | C++ | 15831944/cstd | /include/net/net_impl.inl | WINDOWS-1252 | 15,556 | 3.1875 | 3 | [] | no_license | /*%
* WARNING: Don't even consider trying to compile this on a system where
* sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX.
*/
/*
* Copy src to string dst of size siz. At most siz-1 characters
* will be copied. Always NUL terminates (unless siz == 0).
* Returns strlen(src); if retval >= siz, truncation occurred.
*/
static size_t my_strlcpy(char* __restrict dst, const char* __restrict src, size_t siz)
{
char* d = dst;
const char* s = src;
size_t n = siz;
/* Copy as many bytes as will fit */
if (n != 0) {
while (--n != 0) {
if ((*d++ = *s++) == '\0') {
break;
}
}
}
/* Not enough room in dst, add NUL and traverse rest of src */
if (n == 0) {
if (siz != 0) {
*d = '\0'; /* NUL-terminate dst */
}
while (*s++)
;
}
return(s - src - 1); /* count does not include NUL */
}
/* const char *
* inet_ntop4(src, dst, size)
* format an IPv4 address
* return:
* `dst' (as a const)
* notes:
* (1) uses no statics
* (2) takes a char* not an in_addr as input
* author:
* Paul Vixie, 1996.
*/
static char* inet_ntop4(const uchar* src, char* dst, int size)
{
static const char fmt[] = "%u.%u.%u.%u";
char tmp[sizeof "255.255.255.255"];
int l;
l = snprintf(tmp, sizeof(tmp), fmt, src[0], src[1], src[2], src[3]);
if (l <= 0 || (int) l >= size) {
return (NULL);
}
my_strlcpy(dst, tmp, size);
return (dst);
}
/* const char *
* inet_ntop6(src, dst, size)
* convert IPv6 binary address into presentation (printable) format
* author:
* Paul Vixie, 1996.
*/
static char* inet_ntop6(const uchar* src, char* dst, int size)
{
/*
* Note that int32_t and int16_t need only be "at least" large enough
* to contain a value of the specified size. On some systems, like
* Crays, there is no such thing as an integer variable with 16 bits.
* Keep this in mind if you think this function should have been coded
* to use pointer overlays. All the world's not a VAX.
*/
char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp;
struct {
int base, len;
} best, cur;
#define NS_IN6ADDRSZ 16
#define NS_INT16SZ 2
uint words[NS_IN6ADDRSZ / NS_INT16SZ];
int i;
/*
* Preprocess:
* Copy the input (bytewise) array into a wordwise array.
* Find the longest run of 0x00's in src[] for :: shorthanding.
*/
memset(words, '\0', sizeof words);
for (i = 0; i < NS_IN6ADDRSZ; i++) {
words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
}
best.base = -1;
best.len = 0;
cur.base = -1;
cur.len = 0;
for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
if (words[i] == 0) {
if (cur.base == -1) {
cur.base = i, cur.len = 1;
}
else {
cur.len++;
}
}
else {
if (cur.base != -1) {
if (best.base == -1 || cur.len > best.len) {
best = cur;
}
cur.base = -1;
}
}
}
if (cur.base != -1) {
if (best.base == -1 || cur.len > best.len) {
best = cur;
}
}
if (best.base != -1 && best.len < 2) {
best.base = -1;
}
/*
* Format the result.
*/
tp = tmp;
for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
/* Are we inside the best run of 0x00's? */
if (best.base != -1 && i >= best.base &&
i < (best.base + best.len)) {
if (i == best.base) {
*tp++ = ':';
}
continue;
}
/* Are we following an initial run of 0x00s or any real hex? */
if (i != 0) {
*tp++ = ':';
}
/* Is this address an encapsulated IPv4? */
if (i == 6 && best.base == 0 && (best.len == 6 ||
(best.len == 7 && words[7] != 0x0001) ||
(best.len == 5 && words[5] == 0xffff))) {
if (!inet_ntop4(src + 12, tp, sizeof tmp - (tp - tmp))) {
return (NULL);
}
tp += strlen(tp);
break;
}
tp += sprintf(tp, "%x", words[i]);
}
/* Was it a trailing run of 0x00's? */
if (best.base != -1 && (best.base + best.len) ==
(NS_IN6ADDRSZ / NS_INT16SZ)) {
*tp++ = ':';
}
*tp++ = '\0';
/*
* Check for overflow, copy, and we're done.
*/
if ((int)(tp - tmp) > size) {
return (NULL);
}
strcpy(dst, tmp);
return (dst);
}
/* char *
* inet_ntop(af, src, dst, size)
* convert a network format address to presentation format.
* return:
* pointer to presentation format address (`dst'), or NULL (see errno).
* author:
* Paul Vixie, 1996.
*/
static char* _inet_ntop(int af, const void* src, char* dst, int size)
{
switch (af) {
case AF_INET:
return (inet_ntop4((const unsigned char*)src, dst, size));
case AF_INET6:
return (inet_ntop6((const unsigned char*)src, dst, size));
default:
return (NULL);
}
/* NOTREACHED */
}
int addr_tostr(const void* addr, char* dst, int size)
{
int af = *(const short*)addr;
const struct sockaddr_in* addr4 = (const struct sockaddr_in*)addr;
const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*)addr;
char* ret = NULL;
int port = 0;
sock_init();
switch (af) {
case AF_INET:
port = ntohs(addr4->sin_port);
ret = (inet_ntop4((const unsigned char*)(&addr4->sin_addr), dst, size));
break;
case AF_INET6:
port = ntohs(addr6->sin6_port);
ret = (inet_ntop6((const unsigned char*)(&addr6->sin6_addr), dst, size));
break;
}
return ret ? port : 0;
}
/*%
* WARNING: Don't even consider trying to compile this on a system where
* sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX.
*/
/* int
* inet_pton4(addr, dst)
* like inet_aton() but without all the hexadecimal and shorthand.
* return:
* 1 if `src' is a valid dotted quad, else 0.
* notice:
* does not touch `dst' unless it's returning 1.
* author:
* Paul Vixie, 1996.
*/
static int inet_pton4(const char* src, uchar* dst)
{
static const char digits[] = "0123456789";
int saw_digit, octets, ch;
#define NS_INADDRSZ 4
char tmp[NS_INADDRSZ], *tp;
saw_digit = 0;
octets = 0;
*(tp = tmp) = 0;
while ((ch = *src++) != '\0') {
const char* pch;
if ((pch = strchr(digits, ch)) != NULL) {
uint newt = *tp * 10 + (pch - digits);
if (saw_digit && *tp == 0) {
return (0);
}
if (newt > 255) {
return (0);
}
*tp = newt;
if (!saw_digit) {
if (++octets > 4) {
return (0);
}
saw_digit = 1;
}
}
else if (ch == '.' && saw_digit) {
if (octets == 4) {
return (0);
}
*++tp = 0;
saw_digit = 0;
}
else {
return (0);
}
}
if (octets < 4) {
return (0);
}
memcpy(dst, tmp, NS_INADDRSZ);
return (1);
}
/* int
* inet_pton6(src, dst)
* convert presentation level address to network order binary form.
* return:
* 1 if `src' is a valid [RFC1884 2.2] address, else 0.
* notice:
* (1) does not touch `dst' unless it's returning 1.
* (2) :: in a full address is silently ignored.
* credit:
* inspired by Mark Andrews.
* author:
* Paul Vixie, 1996.
*/
static int inet_pton6(const char* src, uchar* dst)
{
static const char xdigits_l[] = "0123456789abcdef", xdigits_u[] = "0123456789ABCDEF";
#define NS_IN6ADDRSZ 16
#define NS_INT16SZ 2
uchar tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp;
const char* xdigits, *curtok;
int ch, seen_xdigits;
uint val;
memset((tp = tmp), '\0', NS_IN6ADDRSZ);
endp = tp + NS_IN6ADDRSZ;
colonp = NULL;
/* Leading :: requires some special handling. */
if (*src == ':')
if (*++src != ':') {
return (0);
}
curtok = src;
seen_xdigits = 0;
val = 0;
while ((ch = *src++) != '\0') {
const char* pch;
if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) {
pch = strchr((xdigits = xdigits_u), ch);
}
if (pch != NULL) {
val <<= 4;
val |= (pch - xdigits);
if (++seen_xdigits > 4) {
return (0);
}
continue;
}
if (ch == ':') {
curtok = src;
if (!seen_xdigits) {
if (colonp) {
return (0);
}
colonp = tp;
continue;
}
else if (*src == '\0') {
return (0);
}
if (tp + NS_INT16SZ > endp) {
return (0);
}
*tp++ = (char)(val >> 8) & 0xff;
*tp++ = (char) val & 0xff;
seen_xdigits = 0;
val = 0;
continue;
}
if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) && inet_pton4(curtok, tp) > 0) {
tp += NS_INADDRSZ;
seen_xdigits = 0;
break; /*%< '\\0' was seen by inet_pton4(). */
}
return (0);
}
if (seen_xdigits) {
if (tp + NS_INT16SZ > endp) {
return (0);
}
*tp++ = (char)(val >> 8) & 0xff;
*tp++ = (char) val & 0xff;
}
if (colonp != NULL) {
/*
* Since some memmove()'s erroneously fail to handle
* overlapping regions, we'll do the shift by hand.
*/
const int n = tp - colonp;
int i;
if (tp == endp) {
return (0);
}
for (i = 1; i <= n; i++) {
endp[- i] = colonp[n - i];
colonp[n - i] = 0;
}
tp = endp;
}
if (tp != endp) {
return (0);
}
memcpy(dst, tmp, NS_IN6ADDRSZ);
return (1);
}
/* int
* inet_pton(af, src, dst)
* convert from presentation format (which usually means ASCII printable)
* to network format (which is usually some kind of binary format).
* return:
* 1 if the address was valid for the specified address family
* 0 if the address wasn't valid (`dst' is untouched in this case)
* -1 if some other error occurred (`dst' is untouched in this case, too)
* author:
* Paul Vixie, 1996.
*/
static int _inet_pton(int af, const char* src, void* dst)
{
//printf("_inet_pton\n");
switch (af) {
case AF_INET:
return (inet_pton4(src, (unsigned char*)dst));
case AF_INET6:
return (inet_pton6(src, (unsigned char*)dst));
default:
return (-1);
}
/* NOTREACHED */
}
int addr_set(void* addr, const char* ip, int port)
{
struct addrinfo hints, *res, *res0;
char portStr[32] = {0};
int ret = 0;
sock_init();
snprintf(portStr, 32, "%d", port);
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
ret = getaddrinfo(ip, portStr, &hints, &res0);
if (ret != 0)
{
//DEBUG_INFO("getaddrinfo(ret=%d) err: %s", ret, gai_strerror(ret));
return 0;
}
if (1)
{
int i = 0;
char buf[256];
//DEBUG_INFO("getaddrinfo(ret=%d) ret: %s", ret, gai_strerror(ret));
for (res = res0; res; res = res->ai_next)
{
addr_tostr(res->ai_addr, buf, 256);
// DEBUG_INFO("addr=%s flags=%d family=%d type=%d protocol=%d len=%d", buf,
// res->ai_flags, res->ai_family,
// res->ai_socktype, res->ai_protocol,
// res->ai_addrlen);
++i;
}
}
ret = 0;
for (res = res0; res; res = res->ai_next) {
if (res->ai_family == AF_INET) {
memcpy(addr, res->ai_addr, sizeof(struct sockaddr_in));
ret = sizeof(struct sockaddr_in);
break;
} else if (res->ai_family == AF_INET6) {
memcpy(addr, res->ai_addr, sizeof(struct sockaddr_in6));
ret = sizeof(struct sockaddr_in6);
break;
}
}
freeaddrinfo(res0);
return ret;
}
#define READ_ARRAY_TIME_OUT(sockArray, sizeArray, time, bTimeOut, frds) {\
int sock = 0;\
struct timeval rtval;\
int i = 0;\
FD_ZERO(&frds);\
for (; i < (int)sizeArray; ++i) {\
FD_SET(sockArray[i], &frds);\
if( sockArray[i] > sock ) sock = sockArray[i];\
}\
rtval.tv_sec = 0;\
rtval.tv_usec = (time*1000);\
bTimeOut = select(sock+1, &frds, NULL, NULL, &rtval) <= 0; }
int select_run(select_thd_t* s, int delay)
{
int Array[FD_SETSIZE] = {0};
socket_info_t* sis[FD_SETSIZE] = {0};
uint32 nSize = 0, i;
bool bTimeOut = 0;
fd_set frds;
{
socket_info_t* si = s->si;
sys_lock_lock(s->m_synSOCKMap);
for (; si; si = si->next) {
Array[nSize] = si->sock;
sis[nSize] = si;
nSize++;
}
sys_lock_unlock(s->m_synSOCKMap);
}
if (nSize == 0) {
//sys_sleep(delay);
return 0;
}
READ_ARRAY_TIME_OUT(Array, nSize, delay, bTimeOut, frds);
if (bTimeOut) {
//sys_sleep(delay);
return 0;
}
for (i = 0; i < nSize; ++i) {
if (FD_ISSET(Array[i], &frds)) {
if (sis[i]->fun) {
sis[i]->fun(Array[i], sis[i]->user);
}
}
}
return 0;
}
int select_start() {
static int inited = 0;
static select_thd_t st[1] = {0};
if (0==inited) {
sys_thread_create(st->th);
}
return 0;
}
int sock_recv(int s, void* buf, int len, int flag) {
return recv(s, (char*)buf, (SOCK_LENTH)len, flag);
}
int sock_send(int s, const void* buf, int len, int flags) {
return send(s, (const char*)buf, (SOCK_LENTH)len, flags);
}
int sock_sendto(int s, const void* buf, int len, int flags, const addr_in* to) {
return sendto(s, (const char*)buf, (SOCK_LENTH)len, flags, (const struct sockaddr*)to, sizeof(addr_in));
}
int sock_recvfrom(int sock, void* buf, int len, int flags, addr_in* from) {
SOCK_LENTH size = sizeof(addr_in);
len = recvfrom(sock, (char*)buf, len, flags, (struct sockaddr*)from, &size) ;
return len;
}
int sock_set_add(int fd, sock_set* set) {
fd_set* fds = (fd_set*)set;
FD_SET(fd, fds);
return 0;
}
int sock_set_clr(int fd, sock_set* set) {
fd_set* fds = (fd_set*)set;
FD_CLR(fd, fds);
return 0;
}
int sock_select(int nfds, sock_set* readfds, sock_set* writefds, sock_set *exceptfds, const timeval_t *timeout) {
struct timeval tv[1] = {0};
if (timeout) {tv->tv_sec = timeout->tv_sec, tv->tv_usec = tv->tv_usec; }
if (sizeof(sock_set)<sizeof(fd_set)) {
printf("err: sock_select sizeof(sock_set)=%d sizeof(fd_set)=%d\n", sizeof(sock_set), sizeof(fd_set));
}
return select(nfds, (fd_set*)readfds, (fd_set*)writefds, (fd_set*)exceptfds, timeout ? tv : NULL);
}
int sock_shutdown(int s, int how) {
return shutdown(s, how);
}
int sock_accept(int sock, addr_in* addr)
{
SOCK_LENTH len = sizeof(addr_in);
int sock_new = accept(sock, (struct sockaddr*)addr, &len);
return sock_new;
}
//int sock_ioctl(int sock, int cmd, ulong* argp) { return ioctlsocket(sock, cmd, argp);}
int sock_listen(int s, int backlog) {
return listen(s, backlog);
}
//#define ANYIP(af) (AF_INET6==(af)) ? "::0" : "0.0.0.0"
int sock_open(const char* ip, int port, SOCK_TYPE type, addr_in* addr) {
int sock = -1;
addr_in _addr[1] = {0};
addr = addr ? addr : _addr;
ip = ip ? ip : "0.0.0.0";
//sock_init();
if (addr_set(addr, ip, port)) {
int type1 = SOCK_TCP==type ? SOCK_STREAM : SOCK_DGRAM;
sock = socket(addr->family, type1, 0);
if (sock>0) {
int size = 1<<16;
u_long ul=1;
setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (const char*)&size, sizeof(size));
setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (const char*)&size, sizeof(size));
//ioctlsocket(sock, FIONBIO, &ul); // no block
}
}
return sock;
}
int sock_connect(int s, const addr_in* addr) {
//sock_ioctl (sock, FIONBIO , true ); //õSSLʧ
int ret = connect(s, (const struct sockaddr*)addr, sizeof(addr_in));
return ret;
}
int sock_bind(int s, const addr_in* addr)
{
int on = 1;
int ret;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const int8*)&on, sizeof(on));
ret = bind(s, (const struct sockaddr*)addr, sizeof(addr_in));
//printf("%s", strerror(GetLastError()));
return ret;
}
int sock_close(int s) {
return closesocket(s);
}
//#include "test_sys_net.inl"
| true |