• Breaking News

    Sunday, March 17, 2019

    Linking Files in C Ask Programming

    Linking Files in C Ask Programming


    Linking Files in C

    Posted: 17 Mar 2019 08:40 PM PDT

     main.c long long int x=0; int y; int* pointer; int func(int* p); int main(int argc, char**argv) { int my_array[5]; pointer=(int*)malloc(100); y=1; func(&pointer[0]); func(&y); printf("%d,%d\n",y,pointer[0]); } func.c double x; int y=10; int func(int* p) { static int s=0; s+=1; y+=1; *p=y+s; x+=0.25; printf("x=%f,s=%d\n",x,s); } 

    When linking the files main.c and func.c, the output is: x=0.25, s=1 x=0.500000,s=2 5,3

    I understand the first line of output, but could someone please explain the last two lines? Thank you!

    submitted by /u/salt_schedule
    [link] [comments]

    Why is immutable data all the rage these days?

    Posted: 17 Mar 2019 05:42 PM PDT

    What makes immutable data better than mutable data?

    submitted by /u/SanitizedTeapot
    [link] [comments]

    Haaaalp. Working on this problem in pig latin, and nothing is working for the store

    Posted: 17 Mar 2019 10:35 PM PDT

    -- convert data to workable forms
    allData = LOAD 'nonrenewable.csv' USING org.apache.pig.piggybank.storage.CSVExcelStorage(',', 'NO_MULTILINE', 'UNIX', 'SKIP_INPUT_HEADER');
    -- select specific columns
    data = FOREACH allData GENERATE (chararray) $1 as State, (int) $2 as CoalNET, (int) $3 as OilNet, (int) $4 as GasNet, (int) $5 as NukeNet;
    -- select specific rows
    pnwData = FILTER data BY State == 'Washington' OR State == 'Oregon' OR State == 'Idaho';
    STORE pnwData INTO 'pig_out' USING org.apache.pig.piggybank.storage.CSVExcelStorage(',', 'NO_MULTILINE', 'UNIX', 'SKIP_INPUT_HEADER');

    I put a dump data after data and got this, where I believe it should be putting all of the ints instead-
    https://imgur.com/a/3bnGEj9

    submitted by /u/pac-sama
    [link] [comments]

    Java: Setters and Getters not replacing variable values of other objects

    Posted: 17 Mar 2019 11:33 AM PDT

    package studentclient; public class StudentClient { public static void main(String[] args) { Student s1 = new Student("John","111-22-3333",3.5); Student s2 = new Student("Tyler","999-88-7777",3.1); System.out.println("Name: " + s1.getName() + ", SSN: " + s1.getSSN() + ", GPA: " + s1.getGPA()); System.out.println(s2.toString()); if(s1.equals(s2)) { System.out.println("Students are equals"); } else System.out.println("Students are not equals"); 

    ** ISSUE OCCURRING RIGHT HERE ** Trying to replace the values of s2 with the values of s1.

     s2.setName(s1.getName()); System.out.println(s1.getName() + s2.getName()); s2.setSSN(s1.getSSN()); s2.setGPA(s1.getGPA()); System.out.println(s2.toString()); if(s1.equals(s2)) { System.out.println("Students are equals"); } else { System.out.println("Students are not equals"); } } } package studentclient; public class Student { private String name; private String SSN; private double GPA; public Student (String name, String SSN, double GPA) { this.name = name; this.SSN = SSN; this.GPA = GPA; } public String getName() { return this.name; } public void setName (String Name) { this.name=name; } public String getSSN() { return this.SSN; } public void setSSN (String newSSN) { this.SSN = SSN; } public double getGPA() { return this.GPA; } public void setGPA(double GPA) { if (GPA >= 0 && GPA <= 4.0) { this.GPA = GPA; } if (GPA < 0 || GPA > 4.0) { System.out.println("ERROR, improper GPA."); } } @Override public String toString() { return "Name: " + name + ", SSN: " + SSN + ", GPA: " + GPA; } @Override public boolean equals(Object o ) { Student x = (Student) o; if (!((this.name).equals(x.name))) { return false; } if (!((this.SSN).equals(x.SSN))) { return false; } if (this.GPA!=x.GPA){ return false; } return true; } } 
    submitted by /u/VexxySmexxy
    [link] [comments]

    Is it possible to offer and poll elements from a queue at the same time?

    Posted: 17 Mar 2019 06:03 PM PDT

    My program simulates waiting in line. A random number generator chooses how long to wait before a customer enters the line and another random number generator chooses how long the customer waits before exiting the line. I'm trying to make it so that new customers can enter the line while the previous customer waits. Each customer is represented by a 1. Here's my code:

    public static void main(String [] args) throws InterruptedException{ Queue<Integer> line = new LinkedList<Integer>(); for(int secCounter = 0; secCounter < 20;){ //20 seconds is how long the simulation runs for; int secCustArrive = (int)(Math.random() * 5); //how long until a customer arrives TimeUnit.SECONDS.sleep(secCustArrive); line.offer(1); System.out.println(line); secCounter += secCustArrive; System.out.println("Seconds waited for customer: " + secCustArrive); int secCustWait = (int)(Math.random() * 5);//how long customer waits in line TimeUnit.SECONDS.sleep(secCustWait); line.poll(); System.out.println("Seconds customer waited in line " + secCustWait); secCounter+= secCustWait; } } 

    And here's the output:

    [1] Seconds waited for customer: 2 Seconds customer waited in line 4 [1] Seconds waited for customer: 4 Seconds customer waited in line 3 [1] Seconds waited for customer: 4 Seconds customer waited in line 2 [1] Seconds waited for customer: 1 Seconds customer waited in line 3 

    My desired output is something along the lines of the queue having more than one customer at a time:

    [1] Seconds waited for customer: 2 Seconds customer waited in line 4 [1,1,1] Seconds waited for customer: 4 Seconds customer waited in line 3 [1,1,1,1,1] Seconds waited for customer: 4 Seconds customer waited in line 2 [1,1,1,1] Seconds waited for customer: 1 Seconds customer waited in line 3 

    I understand that with my code the for loop will offer a customer but then will remove said customer right away, leaving only one customer in queue at a time. My only solution to this is to be able to offer() and poll() at the same time.

    submitted by /u/glhf426
    [link] [comments]

    Angular Project having trouble routing to the next page after login

    Posted: 17 Mar 2019 09:38 PM PDT

    Hey!, I am creating an Angular 7 application for a college project that consists of signing in as an admin to change the data base full of students and for students to sign in and only being able to see their own personal information. I ran into an issue where my normal login wont route to the main dashboard page at all even tho firebase reads me logging in successfully. Anyone have any ideas where things have gone wrong or an easier approach to this? Here are my files below

    app-routing.module.ts

    import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { CommonModule } from '@angular/common'; // Required components for which route services to be activated import { SignInComponent } from '../../components/sign-in/sign-in.component'; import { SignUpComponent } from '../../components/sign-up/sign-up.component'; import { DashboardComponent } from '../../components/dashboard/dashboard.component'; import { ForgotPasswordComponent } from '../../components/forgot-password/forgot-password.component'; import { VerifyEmailComponent } from '../../components/verify-email/verify-email.component'; //Required components for which route services will be activated for admins import { AdminSignInComponent } from '../../components/admin-sign-in/admin-sign-in.component'; import { AdminDashboardComponent } from '../../components/admin-dashboard/admin-dashboard.component'; import { AddStudentComponent } from '../../components/add-student/add-student.component'; import { StudentsListComponent } from '../../components/students-list/students-list.component'; import { EditStudentComponent } from '../../components/edit-student/edit-student.component'; // Import canActivate guard services import { AuthGuard } from "../../shared/guard/auth.guard"; import { SecureInnerPagesGuard } from "../../shared/guard/secure-inner-pages.guard"; import { AdminSecureInnerPagesGuard } from "../../shared/guard/admin-secure-inner-pages.guard"; // Include route guard in routes array const routes: Routes = [ { path: '', redirectTo: '/sign-in', pathMatch: 'full'}, { path: 'sign-in', component: SignInComponent, canActivate: [SecureInnerPagesGuard]}, { path: 'register-user', component: SignUpComponent, canActivate: [SecureInnerPagesGuard]}, { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }, { path: 'forgot-password', component: ForgotPasswordComponent, canActivate: [SecureInnerPagesGuard] }, { path: 'verify-email-address', component: VerifyEmailComponent, canActivate: [SecureInnerPagesGuard] }, { path: 'admin-dashboard', component: AdminDashboardComponent, canActivate: [AuthGuard] }, { path: 'register-student', component: AddStudentComponent, canActivate: [AdminSecureInnerPagesGuard] }, { path: 'view-students', component: StudentsListComponent, canActivate: [AdminSecureInnerPagesGuard] }, { path: 'edit-student/:id', component: EditStudentComponent, canActivate: [AdminSecureInnerPagesGuard] }, { path: 'admin-sign-in', component: AdminSignInComponent, canActivate: [AdminSecureInnerPagesGuard]} ]; @NgModule({ imports: [CommonModule,RouterModule.forRoot(routes)], exports: [RouterModule], declarations: [] }) export class AppRoutingModule { } 

    auth.service.ts

    import { Injectable, NgZone } from '@angular/core'; import { User } from "../services/user"; import { auth } from 'firebase/app'; import { AngularFireAuth } from "@angular/fire/auth"; import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore'; import { Router } from "@angular/router"; @Injectable({ providedIn: 'root' }) export class AuthService { userData: any; // Save logged in user data constructor( public afs: AngularFirestore, // Inject Firestore service public afAuth: AngularFireAuth, // Inject Firebase auth service public router: Router, public ngZone: NgZone // NgZone service to remove outside scope warning ){ /* Saving user data in localstorage when logged in and setting up null when logged out */ this.afAuth.authState.subscribe(user => { if (user) { this.userData = user; localStorage.setItem('user', JSON.stringify(this.userData)); JSON.parse(localStorage.getItem('user')); } else { localStorage.setItem('user', null); JSON.parse(localStorage.getItem('user')); } }) } // Sign in with email/password SignIn(email, password) { return this.afAuth.auth.signInWithEmailAndPassword(email, password) .then((result) => { this.ngZone.run(() => { this.router.navigate(['dashboard']); }); this.SetUserData(result.user); }).catch((error) => { window.alert(error.message) }) } AdminSignIn(email, password) { return this.afAuth.auth.signInWithEmailAndPassword(email, password) .then((result) => { this.ngZone.run(() => { this.router.navigate(['admin-dashboard']); }); this.SetUserData(result.user); }).catch((error) => { window.alert(error.message) }) } // Sign up with email/password SignUp(email, password) { return this.afAuth.auth.createUserWithEmailAndPassword(email, password) .then((result) => { /* Call the SendVerificaitonMail() function when new user sign up and returns promise */ this.SendVerificationMail(); this.SetUserData(result.user); }).catch((error) => { window.alert(error.message) }) } // Send email verfificaiton when new user sign up SendVerificationMail() { return this.afAuth.auth.currentUser.sendEmailVerification() .then(() => { this.router.navigate(['verify-email-address']); }) } // Reset Forggot password ForgotPassword(passwordResetEmail) { return this.afAuth.auth.sendPasswordResetEmail(passwordResetEmail) .then(() => { window.alert('Password reset email sent, check your inbox.'); }).catch((error) => { window.alert(error) }) } // Returns true when user is looged in and email is verified get isLoggedIn(): boolean { const user = JSON.parse(localStorage.getItem('user')); return (user !== null && user.emailVerified !== false) ? true : false; } /* Sign in with Google */ GoogleAuth() { return this.AuthLogin(new auth.GoogleAuthProvider()); } // Auth logic to run auth providers AuthLogin(provider) { return this.afAuth.auth.signInWithPopup(provider) .then((result) => { this.ngZone.run(() => { this.router.navigate(['dashboard']); }) this.SetUserData(result.user); }).catch((error) => { window.alert(error) }) } /* Setting up user data when sign in with username/password, sign up with username/password and sign in with social auth provider in Firestore database using AngularFirestore + AngularFirestoreDocument service */ SetUserData(user) { const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`); const userData: User = { uid: user.uid, email: user.email, displayName: user.displayName, photoURL: user.photoURL, emailVerified: user.emailVerified } return userRef.set(userData, { merge: true }) } // Sign out SignOut() { return this.afAuth.auth.signOut().then(() => { localStorage.removeItem('user'); this.router.navigate(['sign-in']); }) } } 

    --- Edit--

    Auth.guard.ts

    import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { AuthService } from "../../shared/services/auth.service"; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor( public authService: AuthService, public router: Router ){ } canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { if(this.authService.isLoggedIn !== true) { this.router.navigate(['sign-in']) } return true; } } 

    secure-inner-pages.guard.ts

    import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { AuthService } from "../../shared/services/auth.service"; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class SecureInnerPagesGuard implements CanActivate { constructor( public authService: AuthService, public router: Router ) { } canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { if(this.authService.isLoggedIn) { window.alert("You are not allowed to access this URL!"); this.router.navigate(['dashboard']) } return true; } } 

    admin-secure-inner-pages.guard.ts

    import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { AuthService } from "../../shared/services/auth.service"; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AdminSecureInnerPagesGuard implements CanActivate { constructor( public authService: AuthService, public router: Router ) { } canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { if(this.authService.isLoggedIn) { window.alert("You are not allowed to access this URL!"); this.router.navigate(['admin-dashboard']) } return true; } } 

    github: https://github.com/LamarRJ1/StudentInformationSystem

    submitted by /u/Xamaslg1
    [link] [comments]

    Could use some help moving arrays in Irvine Assembly

    Posted: 17 Mar 2019 05:48 PM PDT

    how can I split a string and then assign it to a string array?

    Posted: 17 Mar 2019 11:28 AM PDT

    what I'm trying to do is I get string from txt file and split them with using . Split('\n') to lines then I want to assing this lines to a string array.

    like;

    first sentence array[0] first sentece

    second sentence ------------> array[1] second sentence

    third sentence array[2] third sentence

    submitted by /u/EmircanD
    [link] [comments]

    Best way to construct a cache key whose uniqueness is defined by 6 properties

    Posted: 17 Mar 2019 10:43 AM PDT

    Currently I am tasked to fix cache for an ecommerce like system whose prices depend on many factors. The cache backend is redis. For a given product the factors that influence the price are:

    1. sku
    2. channel
    3. sub channel
    4. plan
    5. date

    Currently the cache is structured like this in redis:

    product1_channel1_subchannel1: {sku_1: {plan1: {2019-03-18: 2000}}} 

    The API caters to requests for multiple products, skus and all the factors above . So they decided to query all the data on a product_channel_subchannel level and filter the data in the app which is very slow. Also they have decided that, on a cache miss they will construct the cache for all skus for 90 days of data. This way only one request will face the wrath while the others gets benefited from it (only the catch is now we are busting cache more often which is also dragging the system down)

    The downside of going with all these factors included in the keys is there will be too many keys. To ball park there are 400 products each made up of 20 skus with 20 channels, 200 subchannels 3 types of plans and 400 days of pricing. To avoid these many keys at some place we must group the data.

    The system is currently receives about 10 rps and the has to respond within 100ms.

    Question is:

    1. Is the above cache structure fine? Or how do we go about flattening this structure?
    2. How are caches stored in pricing systems in general. I feel like this a very trivial task nonetheless I find it very hard to justify my approaches
    3. Is it okay to sacrifice one request to warm cache for bulk of the data? Or is it better to have a cache warming strategy?

    submitted by /u/thulasi_ram
    [link] [comments]

    What framework is the best to learn: Flask or Pylons?

    Posted: 17 Mar 2019 03:05 AM PDT

    I know Reddit uses Pylons

    submitted by /u/elonmusque
    [link] [comments]

    Need help.. Path issue for MSBuild.

    Posted: 17 Mar 2019 03:38 PM PDT

    No matter what i try i cannot seem to get a correct path.

    Starting: Check dependencies

    The system cannot find the path specified.

    Error: Could not find the MSBuild executable. Please make sure you have Microsoft Visual Studio or Microsoft Build Tools installed.

    Press any key to continue . . .

    Two days now. i have tried to solve this with no luck.

    Yes i also have the required VS packages.

    submitted by /u/SnuggleBunzTV
    [link] [comments]

    How to do SSR for a website built in ReactJS on the Symfony 4 Framework?

    Posted: 17 Mar 2019 02:52 PM PDT

    For a client website, our team decided to build a website in ReactJS, on the Symfony 4 Framework, using Directus as a headless CMS.

    I did not take SSR (Server-side rendering) into account until we were well along in the build process. SSR is important strictly for SEO purposes.

    At the moment, all of our routes are being done in ReactJS on the front-end, along with the rest of the website. The only thing we are using Symfony for is to make a call to the Directus CMS API to grab our data/content. We are also just specifying all of the routes in annotations in the Symfony controller, which allows us the deep link to that route.

    What would be the best process to implement SSR rendering since everything is currently happening in the front-end? Does it make sense to stay on Symfony?

    submitted by /u/guiness_as_usual
    [link] [comments]

    Need help picking the right programming language and database

    Posted: 17 Mar 2019 09:05 AM PDT

    Here's the overview:

    I'm looking to create a browser based trivia game. The trivia players will be using a mobile device (tablet) to access the game.

    For the trivia game, I want a master device. The master is responsible for sending the trivia question and multiple choice responses to each device at the same time.

    Each tablet has 4 touch activated multiple choice buttons. The user will select an answer and be locked into that answer without being able to change. Once all the answers are received the team name and selections will appear on screen in descending order of quickness.

    I already started a concept for this game and have a working example in PHP/MySQL. I feel like this is the wrong approach, perhaps you can advise.

    The problem is the game isn't very efficient. It relies on a high frequency setInterval function (runs on a <1 second loop until question is sent) to ping the database for the new question and multiple choice answers. Since speed is a factor in this game If I have more than 12 players, I begin to overload the db and run out of available sockets.

    submitted by /u/blamatina
    [link] [comments]

    What is your approach to handling different development environments?

    Posted: 17 Mar 2019 08:58 AM PDT

    Currently, I mostly use a traditional workflow (and sometimes Vagrant). I install all project dependencies on my machine. It gets ugly when I'm working on multiple projects at the same time. You end up with issues such as trying to get MariaDB and MySQL to co-exist. Over time, there will be ghost configuration files sitting around.

    Here's my best, though likely biased, conception of pros/cons of different workflows. I'm interested in hearing the community's thoughts.

    • Traditional : Can become management hell, has best performance.
    • Docker : Limited to Linux-based host-os based containers, performance better than VMs, reproducible (can have weird kernel-land issues).
    • Vagrant : Can use a variety of environments (FreeBSD, Windows), performance penalty, reproducible.
    • PXE & Network Booting : Annoying to make .ISOs for each environment, performance good (completely native).
    • Qubes : immature and more geared towards security, dependent on hardware supported by Xen hypervisor, limited supported operating systems.

    Thinking about this problem a bit more, unit tests are not a replacement for a debugger. But, the debugger is often tightly integrated to the IDE. It seems like there's not really an easy way to run your IDE debugger in a container or VM. I feel that the Qubes and PXE approaches could allow for reproducible environments with use of a GUI. However, Qubes and PXE seem a lot more exotic than having disposable containers or VMs.

    submitted by /u/qwerty_danny
    [link] [comments]

    pthread_join fwrite for loop only writing a single threads data to my file (C)

    Posted: 17 Mar 2019 04:40 AM PDT

    I have 4 threads, using C

    FILE* out = fopen(fileout, "wb"); for (int i = 0; i < NUM_OF_THREADS; i++) { unsigned char* temp; pthread_join(tid[i], (void**)&temp); fwrite(temp, sizeof(char), header.size, out); } 

    I've tried using mutex's and ftrylockfile(out). Thinking that other threads are attempting the same action, but only the bottom 1/4 of the file actually gets written. If I count down from i, the top 1/4 of the file gets written, but acquiring/releasing a lock don't seem to actually do anything. Maybe I'm not using fwrite correctly?

    Not real familiar with IO functions in C, but I believe they are thread safe? Not sure what's going on here.

    submitted by /u/bazgrim_dev
    [link] [comments]

    What programming should I pick to create an intelligent Bot

    Posted: 17 Mar 2019 11:16 AM PDT

    Hi, I'm a beginner to this domain and I want my first project to be an intelligent bot for a video game. The problem is I'm really lost and I don't know where to begin, I watched few videos on YouTube but they weren't really helpful therefore I decided why not get some advice from here. What programming language should I learn first? And how much time do you think it can take me? And what is the best website/YouTube channel should I use as a source of information?

    submitted by /u/HaytamJ
    [link] [comments]

    What's a good book to make some practice on Spark?

    Posted: 17 Mar 2019 10:51 AM PDT

    I am looking for some books with practical case studies or smaller exercises and solutions with Spark. I interested in both structured and unstructured data cases.

    submitted by /u/ReggaeReggaeFloss
    [link] [comments]

    Frustrated finding coop

    Posted: 17 Mar 2019 09:39 AM PDT

    I'm been looking for co-op for the last two semesters and have found very little outside web. Considering my background is in other things and asking around seems low level doesn't have many co-ops. Can someone explain why this is as there doesn't seem to be a reason considering full time is fine.

    submitted by /u/Haweh123456
    [link] [comments]

    How to Make Facebook Kind of Like Button Using PHP Programming Language

    Posted: 17 Mar 2019 07:39 AM PDT

    In this tutorial we're going to make Facebook kind of like button. To engage users, like button is another important thing to think about. There are so many ways in which one can make a like button.

    These are the require basic tables to make this like button in the tutorial are:

    • Users table
    • Article table
    • Like table

    But I am not going to make all these tables, I'm going to skip users-table and article-table.Note: We're going to use the getting value from url/link method. So if you have not read through how to get a value from url then click here to read.So now I hope you know all about getting value from link. The next thing is to make your like-table. The like_table carry the following rows, like_id, user_id and post_id. read more

    submitted by /u/superguideblog
    [link] [comments]

    No comments:

    Post a Comment