Dataset Viewer
Auto-converted to Parquet
seed
stringlengths
16
5.99k
id
int64
0
213
int main() { // your code goes here string s1,s2; cin>>s1>>s2; int m,n; m=s1.length(); n=s2.length(); cout<<editDistance(s1,s2,m,n); return 0; }
0
void read_sensors() { num_hits = 0; // global variable num_hits += digitalRead(radar); num_hits += digitalRead(pir1); num_hits += digitalRead(pir2); digitalWrite (led, (num_hits==0)); // active low }
1
inline double getBilinearInterpolatedValue(const Mat &img, const Vector2d &pt) { uchar *d = &img.data[int(pt(1, 0)) * img.step + int(pt(0, 0))]; double xx = pt(0, 0) - floor(pt(0, 0)); double yy = pt(1, 0) - floor(pt(1, 0)); return ((1 - xx) * (1 - yy) * double(d[0]) + xx * (1 - yy) * double(d[1]) + (1 - xx) * yy * double(d[img.step]) + xx * yy * double(d[img.step + 1])) / 255.0; }
2
int main() { float acum; float dato; int i; int n; float prom; cout << "Ingrese la cantidad de alumnos:" << endl; cin >> n; acum = 0; for (i=1;i<=n;i++) { cout << "Ingrese la edad " << i << ":" << endl; cin >> dato; acum = acum+dato; } prom = acum/n; cout << "El promedio de las edades del grupo de " << n << " alumnos es: " << prom << endl; return 0; }
3
int main(){ string N; cin>>N; int d[10]={0}; int len=N.length(); for(int i=0;i<len;i++) d[N[i]-'0']++; for(int i=0;i<10;i++){ if(d[i]!=0) cout<<i<<":"<<d[i]<<endl; } return 0; }
4
inline bool e_server_msg_type_Parse( const ::std::string& name, e_server_msg_type* value) { return ::google::protobuf::internal::ParseNamedEnum<e_server_msg_type>( e_server_msg_type_descriptor(), name, value); }
5
void add(int u,int v,int w){e[++ecnt]={v,w,head[u]};head[u]=ecnt;}
6
int main() { int s; for(int a=1; a<=100;a=a+2) { s=s+a; } printf("Tong so le den so 100 la: %d \n",s); return 0; }
7
void low_volt_alert() // Function to send blynk push notifiction if low voltage is detected { if(lowvoltagenotificationflag == true && underVoltageAlertOnOffState == 0 && blynkConnectionStatusForNotification == true){ Serial.println("Sending Under voltage Blynk notification"); Blynk.notify("Low Voltage Detected!"); lowvoltagenotificationflag = false; } }
8
void setup(){ //setup all VCC main settings VCC.setup(); }
9
static int8_t CDC_Control_FS(uint8_t cmd, uint8_t* pbuf, uint16_t length) { /* USER CODE BEGIN 5 */ switch (cmd) { case CDC_SEND_ENCAPSULATED_COMMAND: break; case CDC_GET_ENCAPSULATED_RESPONSE: break; case CDC_SET_COMM_FEATURE: break; case CDC_GET_COMM_FEATURE: break; case CDC_CLEAR_COMM_FEATURE: break; /*******************************************************************************/ /* Line Coding Structure */ /*-----------------------------------------------------------------------------*/ /* Offset | Field | Size | Value | Description */ /* 0 | dwDTERate | 4 | Number |Data terminal rate, in bits per second*/ /* 4 | bCharFormat | 1 | Number | Stop bits */ /* 0 - 1 Stop bit */ /* 1 - 1.5 Stop bits */ /* 2 - 2 Stop bits */ /* 5 | bParityType | 1 | Number | Parity */ /* 0 - None */ /* 1 - Odd */ /* 2 - Even */ /* 3 - Mark */ /* 4 - Space */ /* 6 | bDataBits | 1 | Number Data bits (5, 6, 7, 8 or 16). */ /*******************************************************************************/ case CDC_SET_LINE_CODING: break; case CDC_GET_LINE_CODING: break; case CDC_SET_CONTROL_LINE_STATE: break; case CDC_SEND_BREAK: break; default: break; } return (USBD_OK); /* USER CODE END 5 */ }
10
bool cmp(const eg& e1,const eg&e2) { return e1.v<e2.v; }
11
void fpcM_Execute(void* pProc) { fpcEx_Execute((base_process_class*)pProc); }
12
void loop() { // The transmitter sends in this example the signal A90 (hex. dezimal form) in the encoding "RC5" // It will be transmitted 3 times after that it will make a 5 second break for (int i = 0; i < 3; i++) { // irsend.sendRC5(0xA90, 12); // [0xA90] signal | [12] Bit-length signal (hex A90=1010 1001 0000) irsend.sendSAMSUNG(0xE0E0F00F,32); // Parametros: Tecla MUTE sacada del receptor, numero de bits del codigo de Samsung delay(40); } delay(5000); // 5 second break between the sending impulses }
13
void Exact_Source(float *b, int Nx) { int i,j; float x, y, h; h = 1.0/(Nx+1); #pragma acc parallel loop gang present(b) for(i=0;i<Nx;++i) { x = (i+1)*h; #pragma acc loop vector for(j=0;j<Nx;++j) { //k = j + i*(N-1); y = (j+1)*h; b[Nx*i+j] = -(1.0+4.0)*h*h*M_PI*M_PI*sin(M_PI*x)*sin(2*M_PI*y); } } }
14
int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> m >> n >> h; totalnum = m * n * h; for (int k = 1; k <= h; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> map1[i][j][k]; if (map1[i][j][k] == '1') { q.push({ i,j,k }); tomato++; } else if (map1[i][j][k] == '-') { char s; cin >> s; totalnum--; } } } } while (!q.empty()) { bool flag = true; int qs = q.size(); cnt++; while (qs--) { int x = q.front().x; int y = q.front().y; int z = q.front().z; q.pop(); for (int i = 0; i < 6; i++) { int nx = x + dr[i]; int ny = y + dc[i]; int nz = z + dz[i]; if (nx <= 0 || nx > n || ny <= 0 || ny > m || nz <= 0 || nz > h) continue; if (map1[nx][ny][nz] == '0') { tomato++; map1[nx][ny][nz] = '1'; q.push({ nx,ny, nz }); } } } } if (totalnum != tomato) { cout << "-1\n"; return 0; } cout << cnt << '\n'; return 0; }
15
void p3(Node *h){ Node *p = h; while(p){ Node *pn = p->next; if(pn == NULL || pn->c != '.') { p = p->next; continue; } Node *pnn = pn->next; if(pnn == NULL || pnn->c != '.') { p = p->next; continue; } Node *pnnn = pnn->next; if(pnnn == NULL || pnnn->c != '.') { p = p->next; continue; } // cout<<"p3"<<endl; Node *node; node = new Node(' '); p = insert(p,node); node = new Node(' '); pnnn = insert(pnnn,node); p = pnnn; } }
16
void DiscreteMasterProperty__float4___ObjInit_2(DiscreteMasterProperty__float4* __this, ::app::Uno::UX::Property__float4* property, ::app::Fuse::Animations::MixerBase* mixerBase) { ::app::Fuse::Animations::MasterProperty__float4___ObjInit_1(__this, property, mixerBase); }
17
void ticker(){ read_sensors(); // read PIR and radar... update_status(); // ...and then compute occupancy status if (network.available()) // this is usually a while() loop read_command(); }
18
void sendtoBlynk() // Here we are sending PZEM data to blynk { Blynk.virtualWrite(vPIN_VOLTAGE_1, voltage_usage_1); Blynk.virtualWrite(vPIN_CURRENT_USAGE_1, current_usage_1); Blynk.virtualWrite(vPIN_ACTIVE_POWER_1, active_power_1); Blynk.virtualWrite(vPIN_ACTIVE_ENERGY_1, active_energy_1); Blynk.virtualWrite(vPIN_FREQUENCY_1, frequency_1); Blynk.virtualWrite(vPIN_POWER_FACTOR_1, power_factor_1); Blynk.virtualWrite(vPIN_VOLTAGE_2, voltage_usage_2); Blynk.virtualWrite(vPIN_CURRENT_USAGE_2, current_usage_2); Blynk.virtualWrite(vPIN_ACTIVE_POWER_2, active_power_2); Blynk.virtualWrite(vPIN_ACTIVE_ENERGY_2, active_energy_2); Blynk.virtualWrite(vPIN_FREQUENCY_2, frequency_2); Blynk.virtualWrite(vPIN_POWER_FACTOR_2, power_factor_2); Blynk.virtualWrite(vPIN_VOLTAGE_3, voltage_usage_3); Blynk.virtualWrite(vPIN_CURRENT_USAGE_3, current_usage_3); Blynk.virtualWrite(vPIN_ACTIVE_POWER_3, active_power_3); Blynk.virtualWrite(vPIN_ACTIVE_ENERGY_3, active_energy_3); Blynk.virtualWrite(vPIN_FREQUENCY_3, frequency_3); Blynk.virtualWrite(vPIN_POWER_FACTOR_3, power_factor_3); Blynk.virtualWrite(vPIN_SUM_VOLTAGE, sum_of_voltage); Blynk.virtualWrite(vPIN_SUM_CURRENT_USAGE, sum_of_current); Blynk.virtualWrite(vPIN_SUM_ACTIVE_POWER, sum_of_power); Blynk.virtualWrite(vPIN_SUM_ACTIVE_ENERGY, sum_of_active_energy); Blynk.virtualWrite(vPIN_SUM_FREQUENCY, sum_of_frequency); Blynk.virtualWrite(vPIN_SUM_POWER_FACTOR, sum_of_power_factor); Blynk.virtualWrite(VPIN_BUILD_NUMBER, BUILD_NUMBER); }
19
void printDateTime(time_t t, const char *tz) { char buf[32]; char m[4]; // temporary storage for month string (DateStrings.cpp uses shared buffer) strcpy(m, monthShortStr(month(t))); sprintf(buf, "%.2d:%.2d:%.2d %s %.2d %s %d %s", hour(t), minute(t), second(t), dayShortStr(weekday(t)), day(t), m, year(t), tz); Serial.println(buf); }
20
bool isScramble(string& s1, string& s2) { if (s1.size() != s2.size()) return false; if (s1.size() == 1) return s1 == s2; string combined(s1); combined.append(s2); if (memo.find(combined) != memo.end()) return memo.at(combined); int size = s1.size(); int part_length = 1; while (part_length <= size/2) { string s1_k1_p1 = s1.substr(0, part_length); string s1_k1_p2 = s1.substr(part_length); string s1_k2_p1 = s1.substr(size - part_length); string s1_k2_p2 = s1.substr(0, size - part_length); string s2_k1_p1 = s2.substr(0, part_length); string s2_k1_p2 = s2.substr(part_length); string s2_k2_p1 = s2.substr(size - part_length); string s2_k2_p2 = s2.substr(0, size - part_length); string sorted_s1_k1_p1 = genSortedString(s1_k1_p1); string sorted_s1_k1_p2 = genSortedString(s1_k1_p2); string sorted_s1_k2_p1 = genSortedString(s1_k2_p1); string sorted_s1_k2_p2 = genSortedString(s1_k2_p2); string sorted_s2_k1_p1 = genSortedString(s2_k1_p1); string sorted_s2_k1_p2 = genSortedString(s2_k1_p2); string sorted_s2_k2_p1 = genSortedString(s2_k2_p1); string sorted_s2_k2_p2 = genSortedString(s2_k2_p2); if (sorted_s1_k1_p1 == sorted_s2_k1_p1 && sorted_s1_k1_p2 == sorted_s2_k1_p2) { if (isScramble(s1_k1_p1, s2_k1_p1) && isScramble(s1_k1_p2, s2_k1_p2)) { return true; } } if (sorted_s1_k2_p1 == sorted_s2_k1_p1 && sorted_s1_k2_p2 == sorted_s2_k1_p2) { if (isScramble(s1_k2_p1, s2_k1_p1) && isScramble(s1_k2_p2, s2_k1_p2)) { return true; } } if (sorted_s1_k1_p1 == sorted_s2_k2_p1 && sorted_s1_k1_p2 == sorted_s2_k2_p2) { if (isScramble(s1_k1_p1, s2_k2_p1) && isScramble(s1_k1_p2, s2_k2_p2)) { return true; } } if (sorted_s1_k2_p1 == sorted_s2_k2_p1 && sorted_s1_k2_p2 == sorted_s2_k2_p2) { if (isScramble(s1_k2_p1, s2_k2_p1) && isScramble(s1_k2_p2, s2_k2_p2)) { return true; } } part_length ++; } memo[combined] = false; return false; }
21
void dfs(ll i, ll sum,ll arr[]) { if(i==n) { st[sum]++; return; } dfs(i+1,sum+arr[i],arr); dfs(i+1,sum,arr); }
22
void checkPhysicalButton() // Here we are going to check push button pressed or not and change relay state { if (digitalRead(PUSH_BUTTON_1) == LOW) { if (pushButton1State != LOW && (lowvoltageflag == false && highvoltageflag == false && phasefailureflag == false) ) { // pushButton1State is used to avoid sequential toggles relay1State = !relay1State; // Toggle Relay state digitalWrite(RELAY_PIN_1, relay1State); Blynk.virtualWrite(VPIN_BUTTON_1, relay1State); // Update Button Widget } pushButton1State = LOW; } else { pushButton1State = HIGH; } if (digitalRead(PUSH_BUTTON_2) == LOW) { if (pushButton2State != LOW && (lowvoltageflag == false && highvoltageflag == false && phasefailureflag == false) ) { // pushButton2State is used to avoid sequential toggles relay2State = !relay2State; // Toggle Relay state digitalWrite(RELAY_PIN_2, relay2State); Blynk.virtualWrite(VPIN_BUTTON_2, relay2State); // Update Button Widget } pushButton2State = LOW; } else { pushButton2State = HIGH; } }
23
void p11(Node *h){ Node *p = h; while(p){ Node *pn = p->next; if(pn == NULL || pn->c == '\''){ p = p->next; continue; } Node *pnn = pn->next; if(pnn == NULL || pnn->c != '\''){ p = p->next; continue; } Node *pnnn = pnn->next; if(pnnn == NULL || pnnn->c != ' '){ p = p->next; continue; } // cout<<"p11"<<endl; Node *node = new Node(' '); pn = insert(pn,node); p = pnnn; } }
24
int Pow(int x,int k){int t=1;for(;k;k>>=1,x=1ll*x*x%mod) if(k&1) t=1ll*t*x%mod;return t;}
25
void calc_error(const char *s) { std::cout << s << std::endl; }
26
void p12(Node *h){ Node *p = h; while(p){ Node *pn = p->next; if(pn == NULL || pn->c != '\''){ p = p->next; continue; } Node *pnn = pn->next; if(pnn == NULL || ( pnn->c != 's' && pnn->c != 'S' && pnn->c != 'm' && pnn->c != 'M' && pnn->c != 'd' && pnn->c != 'D')){ p = p->next; continue; } Node *pnnn = pnn->next; if(pnnn == NULL || pnnn->c != ' '){ p = p->next; continue; } // cout<<"p12 "<<p->c<<endl; Node *node = new Node(' '); p = insert(p,node); p = pnnn; } }
27
int main(int argc,char **argv){ ros::init(argc,argv,"listener"); ros::NodeHandle n; ros::Subscriber sub=n.subscribe("filePub",1000,chatterCallback); ros::spin();//第一次操作 }
28
void p8(Node *h){ Node *p = h; while(p){ Node *pn = p->next; if(pn == NULL || pn->c != '-'){ p = p->next; continue; } Node *pnn = pn->next; if(pnn == NULL || pnn->c != '-'){ p = p->next; continue; } // cout<<"p8"<<endl; Node *node = new Node(' '); p = insert(p,node); node = new Node(' '); pnn = insert(pnn,node); p = pnn; } }
29
int test(int size) { if (size <= 0) return 0; double *A = new double[size * size]; std::fill(A, A + size * size, 0.0); if (size > 1) { A[0] = 2.0; A[1] = -1.0; for (int i = 1; i < size - 1; ++i) { A[i * size + i - 1] = -1.0; A[i * size + i ] = 2.0; A[i * size + i + 1] = -1.0; } A[size * size - 2] = -1.0; A[size * size - 1] = 2.0; } else if (size == 1) { A[0] = 2.0; } int *rowptr, *colidx; double *values; full_to_csr_ref(size, size, A, size, &rowptr, &colidx, &values); double *d_A; cudaError_t cudaErr = cudaMalloc(reinterpret_cast<void **>(&d_A), size * size * sizeof(double)); assert(cudaErr == cudaSuccess); cudaErr = cudaMemcpy(d_A, A, size * size * sizeof(double), cudaMemcpyHostToDevice); assert(cudaErr == cudaSuccess); int *d_rowptr, *d_colidx; double *d_values; full_to_csr(size, size, d_A, size, &d_rowptr, &d_colidx, &d_values); // Verify results int *h_rowptr = new int[size + 1]; int *h_colidx = new int[rowptr[size]]; double *h_values = new double[rowptr[size]]; cudaErr = cudaMemcpy(h_rowptr, d_rowptr, (size + 1) * sizeof(int), cudaMemcpyDeviceToHost); assert(cudaErr == cudaSuccess); cudaErr = cudaMemcpy(h_colidx, d_colidx, h_rowptr[size] * sizeof(int), cudaMemcpyDeviceToHost); assert(cudaErr == cudaSuccess); cudaErr = cudaMemcpy(h_values, d_values, h_rowptr[size] * sizeof(double), cudaMemcpyDeviceToHost); assert(cudaErr == cudaSuccess); int errcnt = 0; for (int i = 0; i < size + 1; ++i) { if (rowptr[i] != h_rowptr[i]) errcnt += 1; } for (int i = 0; i < rowptr[size]; ++i) { if (colidx[i] != h_colidx[i]) errcnt += 1; } for (int i = 0; i < rowptr[size]; ++i) { if (values[i] != h_values[i]) errcnt += 1; } cudaFree(d_A); cudaFree(d_rowptr); cudaFree(d_colidx); cudaFree(d_values); delete[] rowptr; delete[] colidx; delete[] values; delete[] h_rowptr; delete[] h_colidx; delete[] h_values; return errcnt; }
30
void p1(Node *h){ Node *p = h; Node *pn = p->next; if(pn != NULL && pn->c == '\"'){ // cout<<"p1"<<endl; Node *node; node = new Node('`'); p = insert(p,node); node = new Node('`'); p = insert(p,node); node = new Node(' '); p = insert(p,node); del(p); } }
31
static int8_t CDC_DeInit_FS(void) { /* USER CODE BEGIN 4 */ return (USBD_OK); /* USER CODE END 4 */ }
32
int main(int argc, char** argv){ string a; Node* h; char c[20]; istream *in; if(argc >= 2) in = new ifstream(argv[1]); else in = &std::cin; ostream *out; if(argc >= 3) out = new ofstream(argv[2]); else out = &std::cout; while(getline(*in,a)){ h = new Node(); init_List(h,a); p1(h); p2(h); p3(h); p4(h); p5(h); p6(h); p7(h); p8(h); p9(h); p10(h); p11(h); p12(h); memcpy(c,"'ll",3); p13(h,c); memcpy(c,"'re",3); p13(h,c); memcpy(c,"'ve",3); p13(h,c); memcpy(c,"n't",3); p13(h,c); memcpy(c,"'LL",3); p13(h,c); memcpy(c,"'RE",3); p13(h,c); memcpy(c,"'VE",3); p13(h,c); memcpy(c,"N'T",3); p13(h,c); memcpy(c," cannot ",8); p14(h,c,8,3); memcpy(c," Cannot ",8); p14(h,c,8,3); memcpy(c," d'ye ",6); p14(h,c,6,2); memcpy(c," D'ye ",6); p14(h,c,6,2); memcpy(c," gimme ",7); p14(h,c,7,3); memcpy(c," Gimme ",7); p14(h,c,7,3); memcpy(c," gonna ",7); p14(h,c,7,3); memcpy(c," Gonna ",7); p14(h,c,7,3); memcpy(c," gotta ",7); p14(h,c,7,3); memcpy(c," Gotta ",7); p14(h,c,7,3); memcpy(c," lemme ",7); p14(h,c,7,3); memcpy(c," Lemme ",7); p14(h,c,7,3); memcpy(c," more'n ",8); p14(h,c,8,4); memcpy(c," More'n ",8); p14(h,c,8,4); memcpy(c," 'tis ",6); p14(h,c,6,2); memcpy(c," 'Tis ",6); p14(h,c,6,2); memcpy(c," 'twas ",7); p14(h,c,7,2); memcpy(c," 'Twas ",7); p14(h,c,7,2); memcpy(c," wanna ",7); p14(h,c,7,3); memcpy(c," Wanna ",7); p14(h,c,7,3); p15(h); // cout<<"ok"<<endl; Node *p = h->next; while(p){ if(p->c == '(') (*out)<<"-LRB-"; else if(p->c == ')') (*out)<<"-RRB-"; else if(p->c == '[') (*out)<<"-LSB-"; else if(p->c == ']') (*out)<<"-RSB-"; else if(p->c == '{') (*out)<<"-LCB-"; else if(p->c == '}') (*out)<<"-RCB-"; else (*out)<<p->c; p = p->next; } (*out)<<endl; clean_List(h); } return 0; }
33
int main() { int n; int avgta=0; int avgwt=0; cout<<"Enter number process:";cin>>n; Priority*ob=new Priority[n]; for(int i=0;i<n;i++) { cin>>ob[i]; } for(int i=0;i<n;i++) { for(int j=i;j<n;j++) { if(ob[i].pt<ob[j].pt) { Myswap(ob[i],ob[j]); } if(ob[i].pt==ob[j].pt&&ob[i].bt>ob[j].bt) { Myswap(ob[i],ob[j]); } } } for(int i=0;i<n;i++) { ob[i].calc_ct(); ob[i].calc_ta(); ob[i].calc_wt(); avgta+=ob[i].ta; avgwt+=ob[i].wt; } for(int i=0;i<n;i++) { cout<<ob[i]; cout<<"ta: "<<ob[i].ta<<endl; cout<<"wt: "<<ob[i].wt<<endl; cout<<endl; } cout<<"Avg wating time: "<<(avgwt/n)<<endl; cout<<"Avg turn around time: "<<(avgta/n)<<endl; delete []ob; return 0; }
34
double rootMeanSquare(double valueSum, int valueCount) { return sqrt(valueSum / valueCount); }
35
void bfs() { while (!q.empty()) { bool flag = true; int qs = q.size(); cnt++; while (qs--) { int x = q.front().x; int y = q.front().y; int z = q.front().z; q.pop(); for (int i = 0; i < 6; i++) { int nx = x + dr[i]; int ny = y + dc[i]; int nz = z + dz[i]; if (nx <= 0 || nx > n || ny <= 0 || ny > m || nz <= 0 || nz > h) continue; if (map1[nx][ny][nz] == '0') { tomato++; map1[nx][ny][nz] = '1'; q.push({ nx,ny, nz }); } } } } }
36
void loop() { measureAndCalculateRMS(); sendValuesAsIntegerPerPrint(rmsFrontSensor, rmsBackSensor); }
37
int main() { ProductManager manager; while (manager.canAddProduct()) { handleUI(manager); } }
38
int main() { deque<int> coll; for(int i=1; i<=9; ++i) { coll.push_back(i); coll.push_front(i); } PrintAll(coll, "coll default without sort"); sort(coll.begin(), coll.end()); PrintAll(coll, "coll sort default"); sort(coll.begin(), coll.end(), greater<int>()); PrintAll(coll, "coll sort greater"); return 0; }
39
void DisplayItem(InventoryItem* const e) { for(int index = 0; index < 5; index++) { cout << setw(5) << index + 1 << setw(20) << e[index].getDescription() << setw(20) << e[index].getUnits() << endl; } }
40
int main() { int T; cin >> T; while (T--) { int N, M; cin >> N >> M; int u, v; Graph g(N); while (M--) { cin >> u >> v; g.addEdge(u, v); } int s, e; cin >> s >> e; cout << g.countPaths(s, e) << endl; } return 0; }
41
void update_status() { if (!occupied && auto_mode) if (num_hits > 1) // at least two sensors fired - occupy the room occupy_room(); if (num_hits > 0) // at least one fired; so the room is in use tick_counter = 0; // keep resetting it, if there is any motion tick_counter++; // Note: the sensors can keep tick_counter perpetually zero! So, status_counter++; // you need a separate status_counter if (status_counter == status_ticks) { send_status(); status_counter = 0; } if (tick_counter == buzzer_ticks) { if (occupied && auto_mode) warn(); // warn about the imminent release } else if (tick_counter >= release_ticks){ tick_counter = 0; if (occupied && auto_mode) release_room(); } }
42
void beeper (int mode) { switch (mode) { case 0: // useful before entering T.update loop digitalWrite(buzzer, LOW); // active low delay(200); digitalWrite(buzzer, HIGH); break; case 1: T.pulse(buzzer, 4000, HIGH); // active low break; default: T.pulse(buzzer, 200, HIGH); // active low break; } }
43
int gcd(int a,int b) { if(b==0) { return a; } return(gcd(b,a%b)); }
44
void loop() { T.update(); mesh.update(); // keep the network updated }
45
int main(int argc, char** argv) { int next_option; /* A string listing valid short options letters. */ const char* const short_options = "hc:sxgvna:"; /* An array describing valid long options. */ const struct option long_options[] = { { "help", 0, NULL, 'h' }, { "config", 1, NULL, 'c' }, { "standard", 0, NULL, 's' }, { "xml", 0, NULL, 'x' }, { "graphic", 0, NULL, 'g' }, { "verbose", 0, NULL, 'v' }, { "height", 1, NULL, 'e' }, { "width", 1, NULL, 'w' }, { "rough", 1, NULL, 'r' }, { "seed", 1, NULL, 'd' }, { "offset", 1, NULL, 'f' }, { "plate", 1, NULL, 'p' }, { "erosion", 1, NULL, 'o' }, { "negative", 0, NULL, 'n' }, { "randomseed", 1, NULL, 'a' }, { NULL, 0, NULL, 0 } /* Required at end of array. */ }; /* Remember the name of the program, to incorporate in messages. The name is stored in argv[0]. */ char* program_name = argv[0]; if (fopen(config_file.c_str(), "r")) read_json_config(); do { next_option = getopt_long(argc, argv, short_options, long_options, NULL); switch (next_option) { case 'h': /* -h or --help */ /* User has requested usage information. Print it to standard output, and exit with exit code zero (normal termination). */ print_usage(stdout, 0, program_name); break; case 'c': //config file if(strcmp(config_file.c_str(),optarg) != 0) { config_file = optarg; read_json_config(); } break; case 's': /* -s --standard */ //Use default output format //do nothing break; case 'x': /* -x --xml*/ //Use xml output format output_format = STANDARD_XML; break; case 'g': /* -g --graphical*/ //Display the map as 3d opengl representation output_format = OPENGL_VIEW; break; case 'v': /* -v or --verbose */ verbose = 1; break; case 'e': /* --height use next argument as crop height */ crop_height = atoi(optarg); if(crop_height < 1) print_usage(stderr, 1, program_name); break; case 'w': /* --width use next argument as crop width */ crop_width = atoi(optarg); if(crop_width < 1) print_usage(stderr, 1, program_name); break; case 'r': /* --rough roughness ratio */ offset_dr = atof(optarg); if(offset_dr<0 || offset_dr>1) { print_usage(stderr, 1, program_name); } break; case 'd': /* --seed value */ seed = atoi(optarg); if(seed<0) print_usage(stderr, 1, program_name); break; case 'f': /* --offset value */ random_offset = atoi(optarg); if(random_offset<0) print_usage(stderr, 1, program_name); break; case 'p': /* --plate vonornoi interpolation value */ voronoi_alpha = atof(optarg); if(voronoi_alpha<0 || voronoi_alpha>1) { print_usage(stderr, 1, program_name); } break; case 'o': /* --erosion number of erosion iterations */ erosion_steps = atoi(optarg); if(erosion_steps<0) print_usage(stderr, 1, program_name); break; case 'n': /* allow negative values */ neg = true; break; case 'a': /* random seed value */ // srand ( time(NULL) ); break; case '?': /* The user specified an invalid option. */ /* Print usage information to standard error, and exit with exit code one (indicating abnormal termination). */ print_usage(stderr, 1, program_name); break; case -1: /* Done with options. */ break; default: /* Something else: unexpected. */ abort(); break; } } while (next_option != -1); generate(); return 0; }
46
int main(int argc, char *argv[]) { SwarmValues *v = new SwarmValues(); v->proj_weight = 0; v->align_weight = 0; v->noise_weight = 1-v->proj_weight-v->align_weight; environment_food_init(200); Environment *env = new Environment(); env->onDraw = &environment_food_onDraw; env->onFrame = &environment_food_onFrame; /* //environment_food_init(200); Environment *env = new Environment(); env->onDraw = &environment_displacement_onDraw; env->onFrame = &environment_displacement_onFrame; */ Simulation *s = new Simulation(50, v); s->reset(); s->setEnvironment(env); //uncomment this to add an environment //s->runSimulation(10000); double i, j; int k; double step = 0.04; #define SAMPLE_NUMBER 7 #define RUN_TIME 1000 float progress = 0.0; float progress_step_size = 1.0/(float)( ((1/step)*(1/step))/2); // ^Points in a grid long start_time = time(NULL); cerr << endl; cerr << " \r"; cout << " [" << endl; //Grid start for(i=0.0; i<1.0; i+=step) { cout << " [" << endl; //Row start for(j=0.0; j<1.0; j+=step) { long long value_a[SAMPLE_NUMBER] = {0}; if(i+j<=1.0) { //long runCount = 0; for(k=0; k<SAMPLE_NUMBER; k++) { s->reset(); srand(time(NULL) ^ (k<<8) ^ ((int)i<<16) ^ ((int)j<<24)); v->proj_weight = i; v->align_weight = j; v->noise_weight = 1 - v->proj_weight - v->align_weight; s->setSwarmValues(v); //environment_displacement_init(200); environment_food_init(200); s->setScore(0); s->runSimulation(RUN_TIME); environment_food_destroy(); //if(s->getScore() >=0) { // runCount++; value_a[k] = s->getScore(); //} //environment_displacement_destroy(); } sort(value_a, value_a+SAMPLE_NUMBER); cout << " ["; //COL start for(int a=0; a<SAMPLE_NUMBER; a++) { cout<<value_a[a]; if(a != SAMPLE_NUMBER-1) cout << ","; } cout << "]," << endl; //COL end //Give an indication of the progress so far progress += progress_step_size; long time_taken = time(NULL)-start_time; long total_time_prediction = time_taken * 1/progress; // Carriage return (\r) makes it re-write the line again // with the up to date information cerr << "\r Progress: "; fprintf(stderr, "%5.2f", progress*100 ); cerr << "% Remaining: " << ((total_time_prediction-time_taken)/60.0) << "min \r"; } else { cout << " []," << endl; } //cout << value << " "; } cout << " []" << endl; //To fix the floating comma in the row cout << " ]," << endl; //ROW end } cout << " []" << endl; //To fix the floating comma in the column cout << " ]" << endl; // end GRID //Print info on the time taken cerr << endl << endl; long time_taken = time(NULL)-start_time; int hours = floor(time_taken/(60*60)); int mins = floor((time_taken%60)/(60)); int secs = floor((time_taken%(60*60))); cerr << "Time taken: " << hours << "h " << mins << "m " << secs << "s" << " (" << time_taken << "s)" << endl; delete s; delete v; delete env; }
47
int main(int argc, char *argv[]) { Elev elev; cout << elev.GetAge() << endl; ++elev; cout << elev.GetAge() << endl; elev++; cout << elev.GetAge() << endl; return 0; }
48
void p2(Node *h){ Node *p = h; while(p){ Node *pn = p->next; if(pn == NULL || (pn->c != '(' && pn->c != '[' && pn->c != ' ' && pn->c != '{' && pn->c != '<')){ p = p->next; continue; } Node *pnn = pn->next; if(pnn == NULL || pnn->c != '\"'){ p = p->next; continue; } // cout<<"p2"<<endl; Node *node; node = new Node(' '); pn = insert(pn,node); node = new Node('`'); pn = insert(pn,node); node = new Node('`'); pn = insert(pn,node); node = new Node(' '); pn = insert(pn,node); del(pn); p = pn; } }
49
static int8_t CDC_Init_FS(void) { /* USER CODE BEGIN 3 */ /* Set Application Buffers */ USBD_CDC_SetTxBuffer(&hUsbDeviceFS, UserTxBufferFS, 0); USBD_CDC_SetRxBuffer(&hUsbDeviceFS, UserRxBufferFS); return (USBD_OK); /* USER CODE END 3 */ }
50
void setup() { }
51
void fpcM_PauseDisable(void* pProc, u8 param_2) { fpcPause_Disable((process_node_class*)pProc, param_2 & 0xFF); }
52
void DiscreteMasterProperty__bool___ObjInit_2(DiscreteMasterProperty__bool* __this, ::app::Uno::UX::Property__bool* property, ::app::Fuse::Animations::MixerBase* mixerBase) { ::app::Fuse::Animations::MasterProperty__bool___ObjInit_1(__this, property, mixerBase); }
53
void DiscreteMasterProperty__float__OnComplete(DiscreteMasterProperty__float* __this) { float nv = __this->RestValue(); float str = 0.5f; for (::app::Uno::Collections::List1_Enumerator__Fuse_Animations_MixerHandle_float_ enum_123 = ::uPtr< ::app::Uno::Collections::List__Fuse_Animations_MixerHandle_float_*>(__this->Handles)->GetEnumerator(); enum_123.MoveNext(); ) { ::app::Fuse::Animations::MixerHandle__float* v = enum_123.Current(); if (::uPtr< ::app::Fuse::Animations::MixerHandle__float*>(v)->HasValue() && (::uPtr< ::app::Fuse::Animations::MixerHandle__float*>(v)->Strength > str)) { nv = ::uPtr< ::app::Fuse::Animations::MixerHandle__float*>(v)->Value; str = v->Strength; } } ::uPtr< ::app::Uno::UX::Property__float*>(__this->Property)->Set(nv, (::uObject*)__this); }
54
float getFilteredSignal(int pin_x, int pin_y, int pin_z) { float instant_value_x = analogRead(pin_x) - mean_x; float instant_value_y = analogRead(pin_y) - mean_y; float instant_value_z = analogRead(pin_z) - mean_z; float instant_value = sqrt(pow(instant_value_x,2) + pow(instant_value_y,2) + pow(instant_value_z,2)); accel_values_put(instant_value); float result = RMS(accel_values); return result; }
55
void release_room() { if (!NORELAY) digitalWrite(relay, LOW); // active high occupied = false; send_status(); }
56
int main() { Game game; if(!game.init()) return EXIT_FAILURE; return game.run(); }
57
static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len) { /* USER CODE BEGIN 6 */ uint8_t n = *Len; uint8_t i; for (i = 0; i < n; i++) { if (Buf[i] == '\r') { //slcan_parse_str(slcan_str, slcan_str_index); //slcan_str_index = 0; auto result = slcan_parse_str(slcan_str, slcan_str_index); slcan_str_index = 0; if(result == -1) { CDC_Transmit_FS((uint8_t *)"\a", 1); } else if(result == 0) { CDC_Transmit_FS((uint8_t *)"\r", 1); } } else { slcan_str[slcan_str_index++] = Buf[i]; } } // prepare for next read //USBD_CDC_SetRxBuffer(hUsbDevice_0, UserRxBufferFS); //USBD_CDC_ReceivePacket(hUsbDevice_0); USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]); USBD_CDC_ReceivePacket(&hUsbDeviceFS); return (USBD_OK); /* USER CODE END 6 */ }
58
void sendValuesAsIntegerPerPrint(double value1, double value2) { int v1 = value1 * 100; int v2 = value2 * 100; Serial.print(v1); Serial.print(','); Serial.println(v2); }
59
void clean_List(Node *h){ Node *p; while(h){ p = h->next; delete h; h = p; } }
60
void setup() { pinMode(led, OUTPUT); pinMode(relay, OUTPUT); pinMode(buzzer, OUTPUT); if (!NORELAY) digitalWrite(relay, HIGH); // active high; start with relay operated digitalWrite(led, HIGH); // active low digitalWrite(buzzer, HIGH); // active low pinMode(dhtsensor, INPUT); pinMode(radar, INPUT); pinMode(pir1, INPUT); pinMode(pir2, INPUT); //beeper(0); // TODO: disable this for production blinker(); Serial.begin(9600); Serial.println(F("Occupancy sensor starting...")); //EEPROM.get(0, mute_buzzer); // TODO: save tick interval also in EEPROM // Set the nodeID manually mesh.setNodeID(nodeID); // increment this when burning every device status_payload.node_id = nodeID; Serial.print(F("Slave Node ID: ")); Serial.println(nodeID); Serial.print(F("Simulation = "));Serial.println(SIMULATION); Serial.print(F("NORELAY = "));Serial.println(NORELAY); Serial.println(F("Connecting to the mesh...")); unsigned long ms = millis(); bool result = mesh.begin(MESH_DEFAULT_CHANNEL,RF24_1MBPS,8000); Serial.println(F("Time taken: ")); Serial.println(millis()-ms); if (result) Serial.println(F("Connected to mesh.")); else Serial.println(F("Connection timed out.")); /* int palevel = radio.getPALevel(); Serial.print(F("Radio PA level: ")); Serial.println(palevel); radio.setPALevel (RF24_PA_LOW); Serial.print(F("New PA level: ")); palevel = radio.getPALevel(); Serial.println(palevel); Serial.println(F("Joined the meash.")); */ randomSeed(analogRead(FREE_PIN)); // noise from an unconnected pin status_ticks = status_ticks + random(0, 10); // stagger the transmissions Serial.print(F("Status tick interval: ")); Serial.println(status_ticks*100U); // convert to mSec T.every(tick_interval, ticker); T.every(data_interval, read_temperature); // just update readings; do not send it T.every(network_check_interval, renew_network); // check connection and renew if necessary occupy_room(); // start life in occupied state (this needs the mesh running) }
61
inline void getline(std::istream& cin, std::string& s) { char c = cin.get(); std::getline(cin, s); if (c != '\n') s = c + s; }
62
void read_temperature() { // Reading the DHT11 takes about 250 milliseconds D.read11(dhtsensor); temperature = D.temperature; humidity = D.humidity; }
63
void generate() { //set crop height and width if (crop_height < 1) crop_height = tmap_size; if (crop_width < 1) crop_width = tmap_size; //if a crop value is set //set tmap_size to fit the cropped values int max_size = std::max(crop_height, crop_width); int max_size_tmp = max_size - 1; if ((max_size_tmp & (max_size_tmp - 1)) == 0) { //leave set size as highest crop value tmap_size = max_size; } else { //find smallest value such that (value is power of 2) + 1 and value > max_size int t = ceil(log2(max_size)) + 1; tmap_size = (1 << t) + 1; } double finish = 0; //display info if (verbose) { std::cout << "Using " << config_file << std::endl; std::cout << "Staring square diamond" << std::endl; std::cout << "Size: " << crop_width << " x " << crop_height << " original size " << tmap_size << std::endl; std::cout << "Starting seed value " << seed << std::endl; std::cout << "Starting random offset " << random_offset << std::endl; std::cout << "Random offset decrease ratio " << offset_dr << std::endl; } //init map array tmap = new int*[tmap_size]; for (int i = 0; i < tmap_size; ++i) { tmap[i] = new int[tmap_size]; for (int j = 0; j < tmap_size; j++) tmap[i][j] = 0; } // initialize random seed: // use for generating a random map every time // srand ( time(NULL) ); //harcoded for now as produces a nice map for testing srand(12); //fill the array with values square_diamond(); //interpolate voronoi diagram //TODO: add noise to voronoi if (verbose) { std::cout << "Voronoi points " << voronoi_size << std::endl; /* for (int i = 0; i < voronoi_size; ++i) { std::cout << "\t" << voronoi_points[i][0] << "," << voronoi_points[i][1] << std::endl; } */ } voronoi(); erosion(); if (!neg) clear_neg(); // finish = clock() - start; if (verbose) std::cout << "Finished square diamond " << (finish / 1000000) << std::endl; double sqadia = (finish / 1000000); if (normalise) { if (verbose) std::cout << "Normalising with value range " << normalise_min << "-" << normalise_max << std::endl; normalise_map(); } if (output_format == STANDRARD_HEIGHTS) { print_map(fopen(output_file.c_str(), "w")); } else if (output_format == STANDARD_XML) { print_map_xml(fopen(output_file.c_str(), "w")); } if (scale > 0 && crop_height > 256 && crop_width > 256) { // start = clock(); if (verbose) std::cout << "Generating rivers" << std::endl; rivers(); // finish = clock() - start; if (verbose) std::cout << "Done " << (finish / 1000000) << std::endl; double rivers_time = (finish / 1000000); print_rivers(0); // start = clock(); if (verbose) std::cout << "Generating vegetation" << std::endl; vegetation(verbose); // finish = clock() - start; if (verbose) std::cout << "Done " << (finish / 1000000) << std::endl; double veg_time = (finish / 1000000); print_vegetation(0); if (verbose) std::cout << "Generating settlements" << std::endl; settlements(); // finish = clock() - start; if (verbose) std::cout << "Done " << (finish / 1000000) << std::endl; double settlement_time = (finish / 1000000); print_settlements(0); std::cout << crop_height << "\t" << (sqadia + rivers_time + veg_time + settlement_time) << "\t" << sqadia << "\t " << rivers_time << "\t" << veg_time << "\t" << settlement_time << std::endl; } std::cout << "Drawing contours" << std::endl; contour_map(32, 32, verbose); print_contour(0); print_kf(0); }
64
void solve() { double k1, k2, k3, v; cin >> k1 >> k2 >> k3 >> v; const int DISTANCE = 100,RECORD = 958; double speed = k1*k2*k3*v; int time = round(100*DISTANCE/speed); cout << (time < RECORD ? "Yes" : "No") << "\n"; }
65
int setColor(String command) { // Look through the list of colors to find the one that was requested for(int iColor = 0; iColor < NUM_COLORS; iColor++) { if(command == colorName[iColor]) { // When it matches, look up the RGB values for that color in the table, // and write the red, green, and blue values. RGB.control(true); RGB.color(colorRGB[iColor][0], colorRGB[iColor][1], colorRGB[iColor][2]); analogWrite(pinRed,colorRGB[iColor][0]); analogWrite(pinGreen,colorRGB[iColor][1]); analogWrite(pinBlue,colorRGB[iColor][2]); return 0; } } return -1; }
66
int main(int argc, char const *argv[]) { goodGrowArray<double> a(4); a.insertStart(10.1); a.insertStart(20.1); a.insertStart(30.1); a.insertStart(40.1); a.insert(2, 1111); a.remove(3); int len = a.getlen(); int capacity = a.getCapacity(); double* data = a.getData(); cout << len << " " << capacity << endl; for(int i=0; i<len; i++){ cout << data[i] <<" "; } cout << endl; return 0; }
67
char checkForFloat(char *s) { char decimalPoint = false; int i; for(i=0; s[i] != '\0'; i++) { switch(s[i]) { case '.': if(decimalPoint) return false; decimalPoint = true; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break; default: return false; } } return true; }
68
void fpcM_PauseEnable(void* pProc, u8 param_2) { fpcPause_Enable((process_node_class*)pProc, param_2 & 0xFF); }
69
void init_List(Node *h, const string &a){ Node *p = h; for(int i = 0; i < a.size(); i ++){ Node *current = new Node(a[i]); p->next = current; p = current; } }
70
bool comp(ll i,ll j) { return i>j; }
71
float RMS(float values[]) { float result; result = 0; for(int i = 0; i < RMS_window; i++) { result += pow(values[i], 2); } result = sqrt(result/10); return result; }
72
void high_voltage_check() { if(voltage_usage_1 > HIGH_VOLTAGE_1_CUTOFF || voltage_usage_2 > HIGH_VOLTAGE_2_CUTOFF || voltage_usage_3 > HIGH_VOLTAGE_3_CUTOFF){ Serial.println("High voltage detected..."); highvoltageflag = true; swith_off(); } else { highvoltageflag = false; } }
73
bool renew_network() { if (mesh.checkConnection()) { return (true); } else { Serial.println(F("Renewing network address...")); unsigned int addr = mesh.renewAddress(3000UL); if (addr != 0) { Serial.print(F("New address: ")); Serial.println(addr); return (true); } } return (false); }
74
void pzemdevice3() // Function to get PZEM device 1 data { Serial.println("===================================================="); // PZEM Device 1 data fetching code starts here Serial.println("Now checking PZEM Device 3"); uint8_t result3; ESP.wdtDisable(); // Disable watchdog during modbus read or else ESP crashes when no slave connected result3 = node3.readInputRegisters(0x0000, 10); ESP.wdtEnable(1); // Enable watchdog during modbus read if (result3 == node3.ku8MBSuccess) { voltage_usage_3 = (node3.getResponseBuffer(0x00) / 10.0f); current_usage_3 = (node3.getResponseBuffer(0x01) / 1000.000f); active_power_3 = (node3.getResponseBuffer(0x03) / 10.0f); active_energy_3 = (node3.getResponseBuffer(0x05) / 1000.0f); frequency_3 = (node3.getResponseBuffer(0x07) / 10.0f); power_factor_3 = (node3.getResponseBuffer(0x08) / 100.0f); Serial.print("VOLTAGE: "); Serial.println(voltage_usage_3); // V Serial.print("CURRENT_USAGE: "); Serial.println(current_usage_3, 3); // A Serial.print("ACTIVE_POWER: "); Serial.println(active_power_3); // W Serial.print("ACTIVE_ENERGY: "); Serial.println(active_energy_3, 3); // kWh Serial.print("FREQUENCY: "); Serial.println(frequency_3); // Hz Serial.print("POWER_FACTOR: "); Serial.println(power_factor_3); Serial.println("===================================================="); } else { Serial.println("Failed to read PZEM Device 3"); Serial.println("PZEM Device 3 Data"); voltage_usage_3 = 0; // Assigning 0 if it fails to read PZEM device current_usage_3 = 0; active_power_3 = 0; active_energy_3 = 0; frequency_3 = 0; power_factor_3 = 0; Serial.print("VOLTAGE: "); Serial.println(voltage_usage_3); // V Serial.print("CURRENT_USAGE: "); Serial.println(current_usage_3, 3); // A Serial.print("ACTIVE_POWER: "); Serial.println(active_power_3); // W Serial.print("ACTIVE_ENERGY: "); Serial.println(active_energy_3, 3); // kWh Serial.print("FREQUENCY: "); Serial.println(frequency_3); // Hz Serial.print("POWER_FACTOR: "); Serial.println(power_factor_3); Serial.println("===================================================="); swith_off(); } }
75
void p6(Node *h){ Node *p = h; while(p){ Node *pn = p->next; if(pn == NULL || (pn->c != '?' && pn->c != '!')){ p = p->next; continue; } // cout<<"p6"<<endl; Node *node = new Node(' '); p = insert(p,node); node = new Node(' '); pn = insert(pn,node); p = pn; } }
76
int askdist(int u,int v) { int res=0; if(deep[u]<deep[v]) std::swap(u,v); for(int i=19;~i;i--) if(deep[fa[u][i]]>=deep[v]) res=mul(res+val[u][i]),u=fa[u][i]; if(u==v) return res; for(int i=19;~i;i--) if(fa[u][i]!=fa[v][i]) res=(res+val[u][i]+val[v][i])%mod,u=fa[u][i],v=fa[v][i]; res=mul(res+val[u][0]+val[v][0]); return res; }
77
void full_to_csr_ref( int m, int n, double *A, int lda, int **rowptr, int **colidx, double **values) { *rowptr = new int[m + 1]; int zero = 0; std::fill(*rowptr, *rowptr + m + 1, zero); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { rowptr[0][j + 1] += (A[i * lda + j]) ?1 :0; } } for (int i = 0; i < m; ++i) { rowptr[0][i + 1] += rowptr[0][i]; } *colidx = new int[rowptr[0][m]]; *values = new double[rowptr[0][m]]; int pos = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (A[i * lda + j]) { colidx[0][pos] = j; values[0][pos] = A[i * lda + j]; ++pos; } } } }
78
void PrintMs(const char* text = "") { static long long last = 0; long long cur = getTickCount(); if (last == 0) { last = cur; return; } long long ms = 0; ms = ((double)(cur - last) / getTickFrequency()) * 1000; if (*text != 0) { printf("%s = %dms\n", text, ms); } last = getTickCount(); }
79
void print_matrix(float *x, int N) { int i, j; for(i=0;i<N;i++) { for (j=0;j<N;j++) printf(" %f ", x[N*i+j]); printf("\n"); } }
80
int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "rt", stdin); freopen("output.txt", "wt", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); ll n; cin >> n; string s, t; cin >> s >> t; set<ll> s0, s1; f(0, n) { if (s[i] != t[i]) { if (s[i] == '1') s1.insert(i); else s0.insert(i); } } if (s0.size() == 0 && s1.size() == 0) { cout << "0\n"; return 0; } if (s0.size() != s1.size()) { cout << "-1\n"; return 0; } ll i0 = *s0.begin(); ll i1 = *s1.begin(); ll f = 2; int ans=0; while (!(s0.empty() && s1.empty())) { if (f == 2) { ans++; i0 = *s0.begin(); i1 = *s1.begin(); f=0; } if(i0<i1) { s0.erase(i0); s1.erase(i1); auto p =s0.upper_bound(i1); if(p==s0.end()){ f=2; continue; } i0 = *p; } else { s0.erase(i0); s1.erase(i1); auto p =s1.upper_bound(i0); if(p==s1.end()){ f=2; continue; } i1 = *p; } } cout<<ans<<"\n"; }
81
void loop(void) { //////////STILL TRYING TO GET ZULU WITH A DIFFERENT LIBRARY time_t utc = now(); time_t local = myTZ.toLocal(utc, &tcr); Serial.println(); printDateTime(utc, "UTC"); printDateTime(local, tcr -> abbrev); delay(10000); //THIS WORKS - Now integrate it into the matrix disp //////////END STILL TRYING TO GET ZULU WITH A DIFFERENT LIBRARY ////////// TRYING TO FIX TEMP SENSOR // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float hum = dht.readHumidity(); // Read temperature as Celsius (the default) float temp = dht.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true) // float fern = dht.readTemperature(true); // Check if any reads failed and exit early (to try again). if (isnan(hum) || isnan(temp)) { // if (isnan(hum) || isnan(temp)) { return; } ////////THIS MAKES THE SKETCH STOP FOR A MOMENT - WHY??? //////// END TEMP SENSOR static uint32_t lastTime = 0; // millis() memory static uint8_t display = 0; // current display mode static bool flasher = false; // seconds passing flasher //char phln = (RTC.h - 420); float frnt = (temp*1.8+32); //Changed int to float to get decimals - WORKS P.displayAnimate(); P.setIntensity(0); //Intensity - Change with time later if (P.getZoneStatus(0)) { switch (display) { case 0: //SET AS ZULU TIME P.setTextEffect(0, PA_FADE, PA_FADE); display++; ///////// Now I just need to stop the glitch ///////// and add 420 to time (ZULU) /// getTime((szTime), phln ); /// strcpy(phln, szMesg); ///////// I've tried to get this to flash like the other clock but it ///////// isn't working strcpy(szMesg, "W6LU"); // getTime((szMesg), "z"); // const int offset = -8; // Pacific Standard Time (USA) - This line breaks it. break; /* case 1: // Temperature deg C P.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_UP_LEFT); display++; dtostrf(temp, 3, 1, szMesg); strcat(szMesg, "$"); break; case 2: // Temperature deg F P.setTextEffect(0, PA_SCROLL_UP_LEFT, PA_SCROLL_LEFT); display++; dtostrf(frnt, 3, 1, szMesg); strcat(szMesg, "&"); break; case 3: // Relative Humidity P.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_LEFT); display++; dtostrf(hum, 3, 0, szMesg); strcat(szMesg, "% H "); break; case 4: // Call Sign P.setTextEffect(0, PA_GROW_UP, PA_GROW_DOWN); //I like PA_WIPE too - display++; strcpy(szMesg, "W6LU"); break; case 5: // day of week P.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_LEFT); display++; dow2str(szMesg, "W6LU", MAX_MESG); // dow2str(RTC.dow, szMesg, MAX_MESG); break; */ default: // Calendar P.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_LEFT); display = 0; strcpy(szMesg, "W6LU"); // getDate(szMesg); break; } P.displayReset(0); } // Finally, adjust the time string if we have to if (millis() - lastTime >= 1000) { lastTime = millis(); printDateTime(utc, szTime); flasher = !flasher; P.displayReset(1); } }
82
void setup() { Serial.begin(9600); pzemSerial.begin(9600); /* start Modbus/RS-485 serial communication */ node1.begin(pzemSlave1Addr, pzemSerial); node2.begin(pzemSlave2Addr, pzemSerial); node3.begin(pzemSlave3Addr, pzemSerial); /*********************************************************************************************\ Change PZEM address \*********************************************************************************************/ /* changeAddress(OldAddress, Newaddress) By Uncomment the function in the below line you can change the slave address from one of the nodes (pzem device), only need to be done ones. Preverable do this only with 1 slave in the network. If you forgot or don't know the new address anymore, you can use the broadcast address 0XF8 as OldAddress to change the slave address. Use this with one slave ONLY in the network. This is the first step you have to do when connecting muliple pzem devices. If you haven't set the pzem address, then this program won't works. 1. Connect only one PZEM device to nodemcu and powerup your PZEM 2. uncomment the changeAddress function call below i.e., changeAddress(OldAddress, Newaddress) 3. change the Newaddress value to some other value. Ex: 0x01, 0x02, 0xF7 etc., 4. upload this program to nodemcu 5. if you see "Changing Slave Address" on serial monitor, then it successfully changed address 6. if you don't see that message, then click on RESET button on nodemcu 7. Once this done you have successfully assigned address to pzem device. 8. do the same steps for as many devices as you want. */ // changeAddress(0XF8, 0x02); // uncomment to set pzem address /*********************************************************************************************\ RESET PZEM Energy \*********************************************************************************************/ /* By Uncomment the function in the below line you can reset the energy counter (Wh) back to zero from one of the slaves. resetEnergy(pzemSlaveAddr); */ // resetEnergy(0x01); // uncomment to reset pzem energy #if defined(USE_LOCAL_SERVER) WiFi.begin(WIFI_SSID, WIFI_PASS); // Non-blocking if no WiFi available Blynk.config(AUTH, SERVER, PORT); Blynk.connect(); #else WiFi.begin(WIFI_SSID, WIFI_PASS); // Non-blocking if no WiFi available Blynk.config(AUTH); Blynk.connect(); #endif /*********************************************************************************************\ RELAY code \*********************************************************************************************/ pinMode(RELAY_PIN_1, OUTPUT); pinMode(PUSH_BUTTON_1, INPUT_PULLUP); digitalWrite(RELAY_PIN_1, relay1State); pinMode(RELAY_PIN_2, OUTPUT); pinMode(PUSH_BUTTON_2, INPUT_PULLUP); digitalWrite(RELAY_PIN_2, relay2State); pinMode(RELAY_PIN_3, OUTPUT); digitalWrite(RELAY_PIN_3, relay3State); pinMode(RELAY_PIN_4, OUTPUT); digitalWrite(RELAY_PIN_4, relay4State); timer.setInterval(GET_PZEM_DATA_TIME, get_pzem_data); // How often you would like to call the function timer.setInterval(AUTO_MODE_TIME, auto_mode); timer.setInterval(PHYSICAL_BUTTON_TIME, checkPhysicalButton); // Setup a Relay function to be called every 100 ms timer.setInterval(SEND_TO_BLYNK_TIME, sendtoBlynk); // Send PZEM values blynk server every 10 sec }
83
void warn() { T.oscillate (buzzer,50, HIGH, 4); // the end state is HIGH, i.e, buzzer is off * }
84
void resetEnergy(uint8_t slaveAddr) // Function to reset energy value on PZEM device. { /* The command to reset the slave's energy is (total 4 bytes): Slave address + 0x42 + CRC check high byte + CRC check low byte. */ uint16_t u16CRC = 0xFFFF; static uint8_t resetCommand = 0x42; u16CRC = crc16_update(u16CRC, slaveAddr); u16CRC = crc16_update(u16CRC, resetCommand); Serial.println("Resetting Energy"); pzemSerial.write(slaveAddr); pzemSerial.write(resetCommand); pzemSerial.write(lowByte(u16CRC)); pzemSerial.write(highByte(u16CRC)); delay(1000); }
85
void setup() { analogReference(EXTERNAL); pinMode(X_ACCEL, INPUT); pinMode(Y_ACCEL, INPUT); pinMode(Z_ACCEL, INPUT); pinMode(ledPin, OUTPUT); queue_position = 0; Serial.begin(9600); Serial1.begin(9600); mean_x = 0; mean_y = 0; mean_z = 0; mean_counter = 0; // Serial.begin(9600); filtered_value = new FilterBuHp2(); // Get mean value for threshold // Serial.println("Starting callibration..."); t0 = millis(); while (millis() - t0 < 4000) { mean_x += getSeparatedValues(X_ACCEL); mean_y += getSeparatedValues(Y_ACCEL); mean_z += getSeparatedValues(Z_ACCEL); mean_counter++; } mean_x /= mean_counter; mean_y /= mean_counter; mean_z /= mean_counter; // Serial.print("Callibration done! With samples: "); // Serial.println(mean_counter); // Get mean value for threshold /*Serial.println("Starting accel callibration. Please stand still for 5 seconds."); int t0 = millis(); while (millis() - t0 < 4000) { mean_value = getFilteredSignal(X_ACCEL, Y_ACCEL, Z_ACCEL); }*/ // Serial.print("Callibration done! With samples: "); // Serial.println(mean_counter); state = 0; t0 = millis(); }
86
void defineConstantFunction(MincBlockExpr* scope, const char* name, PawsType* returnType, std::vector<PawsType*> argTypes, std::vector<std::string> argNames, FuncBlock body, void* funcArgs) { PawsFunc* pawsFunc = new PawsConstFunc(name, returnType, argTypes, argNames, body, funcArgs); scope->defineSymbol(name, PawsFunctionType::get(pawsSubroutineScope, returnType, argTypes), new PawsFunction(pawsFunc)); }
87
void transpose(float *data_in, float *data_out, int Nx, int Ny) { int i, j; #pragma acc parallel loop independent present(data_in[0:Nx*Ny],data_out[0:Ny*Nx]) for(i=0;i<Ny;i++) { #pragma acc loop independent for(j=0;j<Nx;j++) { data_out[i+j*Ny] = data_in[i*Nx+j]; } } }
88
void fdst_gpu(float *data, float *data2, float *data3, int Nx, int Ny, int Lx) { float s; s = sqrt(2.0/(Nx+1)); #pragma acc data present(data3[0:2*Lx*Ny],data[0:Nx*Ny],data2[0:Lx*Ny]) { expand_data(data, data2, Nx, Ny, Lx); expand_idata(data2, data3, Nx, Ny, Lx); // Copy data to device at start of region and back to host and end of region // Inside this region the device data pointer will be used #pragma acc host_data use_device(data3) { void *stream = acc_get_cuda_stream(acc_async_sync); cuda_fft(data3, Lx, Ny, stream); } #pragma acc parallel loop independent for (int i=0;i<Ny;i++) { #pragma acc loop independent for (int j=0;j<Nx;j++) data[Nx*i+j] = -1.0*s*data3[2*Lx*i+2*j+3]/2; } }// end data region }
89
void myOnFrame(void *simulation) { cout << "FRAME!" << endl; }
90
double toKilo(double x){ double numKilo = x * kilograms; return numKilo; }
91
inline bool inside(const Vector2d &pt) { return pt(0, 0) >= boarder && pt(1, 0) >= boarder && pt(0, 0) < width - boarder && pt(1, 0) <= height - boarder; }
92
int main() { long int t,a[3],i; scanf("%li", &t); while(t--) { for(i=0;i<3;++i) scanf("%li", &a[i]); sort(a,a+3); printf("%li\n", a[1]); } return 0; }
93
int main() { char choice = 'N'; int numSelected; // Entered by user int qtySelected; // Entered by user double subTotal; // Local variable for subTotal double tax; // Local variable for tax double total; // Local variable for total InventoryItem inventory[5] = { InventoryItem("Adjustable Wrench", 3.49, 10), InventoryItem("Screwdriver", 5.99, 20), InventoryItem("Pliers", 2.69, 35), InventoryItem("Ratchet", 3.99, 10), InventoryItem("Socket Wrench", 2.49, 7) }; do { cout << left << setw(5) << "#" << setw(20) << "Item" << setw(20) << "qty on Hand" << endl; cout << "-------------------------------------------------------" << endl; // Display the inventory item DisplayItem(inventory); // Ask the user which item do they want to buy cout << endl << "Which item above is beging purchased?" << endl; cin >> numSelected; // Validate the user's input is on the list while ((numSelected - 1) < 0 || (numSelected - 1) > 4) { cout << "Invalid entry, please enter the valid number of goods: "; cin >> numSelected; } // Validate the item is not out of stock while (inventory[numSelected - 1].getUnits() == 0) { cout << "Sorry, this item is out of stock." << endl; cout << "Please choose another item: "; cin >> numSelected; } // Ask the user how many items do they want cout << "How many units?" << endl; cin >> qtySelected; // Validate the qtySelected is not a negative value while (qtySelected < 0) { cout << "Error. Cannot enter negetive number" << endl; cout << "Please enter again: "; cin >> qtySelected; } // Validate the inventory of item is not being a negative value while (inventory[numSelected - 1].getUnits() < qtySelected) { cout << "Sorry. We do not have enough items." << endl; cout << "Please enter again: "; cin >> qtySelected; } // Update InventoryItem inventory[numSelected - 1].setUnits(inventory[numSelected - 1].getUnits() - qtySelected); // Define an instance of the CashRegister class CashRegister Sale = CashRegister(inventory[numSelected - 1], qtySelected); cout << endl; // Get subtotal, tax, and total subTotal = Sale.GetSubtotal(); tax = Sale.GetTax(); total = Sale.GetTotal(); // Display subtotal, tax, and total cout << fixed << showpoint << setprecision(2); cout << "Subtotal: $ " << subTotal << endl; cout << "Tax: $ " << tax << endl;; cout << "Total: $ " << total << endl << endl; // Ask user to run again or not cout << "Do you want to purchase another item? (Y/N) "; cin >> choice; cout << endl; } while (choice == 'Y' || choice == 'y'); cout << endl; return 0; }
94
int main() { UnitTest test; test.run(); }
95
void dfs(int u,int fath) { fa[u][0]=fath;deep[u]=deep[fath]+1; for(int i=head[u];i;i=e[i].next) { int v=e[i].v; if(v==fath) continue; val[v][0]=e[i].w; dfs(v,u); } }
96
int main() { int p, q, r, s, Nx, Ny, Lx; float *x, *u, *b, *data2, *data3; clock_t t1, t2; // Initialize the numbers of discrete points. // Here we consider Nx = Ny. printf("\n"); printf(" Input N = 2^p * 3^q * 5^r * 7^s - 1, (p, q, r, s) = "); scanf("%d %d %d %d", &p, &q, &r, &s); Nx = pow(2, p) * pow(3, q) * pow(5, r) * pow(7, s) - 1; printf(" N = %d \n\n", Nx); Ny = Nx; // Prepare the expanded length for discrete sine transform. Lx = 2*Nx + 2 ; // Create memory for solving Ax = b, where r = b-Ax is the residue. // M is the total number of unknowns. // Prepare for two dimensional unknown F // where b is the one dimensional vector and // F[i][j] = F[j+i*(N-1)]; b = (float *) malloc(Nx*Ny*sizeof(float)); x = (float *) malloc(Nx*Ny*sizeof(float)); // data2 : Prepare for dst. // data3 : Prepare for complex value to data2 and do the cufft. data2 = (float *) malloc(Lx*Ny*sizeof(float)); data3 = (float *) malloc(2*Lx*Ny*sizeof(float)); #pragma acc enter data create(b[0:Nx*Ny], x[0:Nx*Ny], data2[0:Lx*Ny], data3[0:2*Lx*Ny]) // Prepare for two dimensional unknowns U // where u is the one dimensional vector and // U[i][j] = u[j+i*(N-1)] u = (float *) malloc(Nx*Ny*sizeof(float)); Exact_Solution(u, Nx); Exact_Source(b, Nx); t1 = clock(); fast_poisson_solver_gpu(b, x, data2, data3, Nx, Ny, Lx); #pragma acc update host(x[0:Nx*Ny]) t2 = clock(); printf(" Fast Poisson Solver: %f secs\n", 1.0*(t2-t1)/CLOCKS_PER_SEC); printf(" For N = %d error = %e \n", Nx, Error(x, u, Nx)); /* printf(" \n \n"); printf(" u matrix \n"); print_matrix(u, Nx); printf(" \n \n"); printf(" x matrix \n"); print_matrix(x, Nx); #pragma acc exit data delete(b[0:Nx*Ny], x[0:Nx*Ny], data2[0:Lx*Ny], data3[0:2*Lx*Ny]) */ return 0; }
97
void TriggerDictionaryInitialization_BMHitClusterDict() { TriggerDictionaryInitialization_BMHitClusterDict_Impl(); }
98
int main() { int t; cin>>t; getchar(); while(t--) { char a[1001]; cin.getline(a,1001); int n=strlen(a); for(int i=0;i<n;i++) { int k=i; while(a[k]!=' '&&a[k]!='\0') k++; for(int j=k-1;j>=i;j--) cout<<a[j]; i=k; if(a[i]==' ') cout<<' '; } cout<<endl; } }
99
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1