Mariam Elbarbary

Without some goal and some effort to reach it, no one can live.

Simple Java Code to Copy folders/files from one directory to another — May 20, 2015

Simple Java Code to Copy folders/files from one directory to another

This is a simple Java class  that  open the source Folder and read the content of the folder

If it contains folders or files with  ‘offline’ in its name  move it to the offline folder and if it contains ‘online’ move it to the Online folder.

if you have any questions don’t hesitate to ask.

/* Mariam Elbarbary */
import java.io.*;
import java.nio.file.Files;
import java.util.*;
import javax.swing.*;

public class Main {

public static void copyDirectory(File sourceLocation, File targetLocation) throws IOException
{
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i=0; i<children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation); // Copy the bits from instream to outstream byte[] buf = new byte[1024]; int len; try { while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
//}
} catch (IOException e) {
e.printStackTrace();
}
in.close();
out.close();
//}
}
public static void main(String[] args) throws IOException {
String DirectorySource = “C:\\workset\\CopySource”;
File source = new File(DirectorySource);
if(!source.exists()){
System.out.println(“Directory does not exist.”);
}
String dest2 = “C:\\workset\\Offline”;
String dest1 = “C:\\workset\\Online”;
File destination1 = new File(dest1);
File destination2 = new File(dest2);
// If folder doesn’t exist create a new folder
if(!destination1.exists()){
destination1.mkdir();
}
if(!destination2.exists()){
destination2.mkdir();
}
/***
Open Source DIrectory and read the name of the folders
If it contains Offline move it to the offline folder and if it contains Online move it to the Online folder
***/
// source.renameTo(destination);
//list all the directory contents
String files[] = source.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(source, file);
File destFile = new File(file);
if(file.contains(“Offline”)){
destFile = new File(destination2, file);
}else if (file.contains(“Online”)) {
destFile = new File(destination1, file);
}
copyDirectory(srcFile, destFile);
}
}
}


How to Use Facebook SDK for Windows Phone – Part 1 — December 4, 2014

How to Use Facebook SDK for Windows Phone – Part 1

This is a series of tutorials on How to use Facebook SDK for Windows Phone.

When i started using Facebook SDK I couldn’t find enough documentation for the functionality and usage of the SDK, It took me alot of time to figure them out.

I hope these tutorials will be helpful , If you have any Questions don’t hesitate to ask.

Facebook provides official SDKs for iOS, Android, JavaScript and PHP but for Windows Phone  it is not an official one.

Before you get started, you need to register a Facebook Application by visiting the Facebook developer portal and obtaining an application ID. For more information, see for example, Register and Configure a Facebook Application.

How to make the Login Page and log in facebook

There is many different way to implement the facebook Login in windows phone , I chose an old one as you can use this tutorial with any version of the Windows Phone SDK.

After Installing the Windows Phone SDK. 1- In Visual Studio 2012 Create a new project  –> Visual C# –> Windows Phone APP lets call it Windows Phone APP

Windows Phone APP Select Windows Phone OS 8.0 as the target operating system version. 3- Add the Facebook Client Library to your new project. Open the Package Manager Console from Tools –> Library Package Manager –> Manage NuGet Packages for solutions.. Search for Facebook as shown in the figure then press install NuGet

Note If you don’t have the NuGet Library Installed It should be installed from here : http://docs.nuget.org/docs/start-here/installing-nuget

otherwise , The Facebook SDK should be installed successful then press ok .

4- By the same way install Facebook Client as in the example facebookClient

5-Open MainPage.xaml in your project and switch to its XAML view. In the title Panel in the xaml code  Change the Title as in the example bellow

<!--TitlePanel contains the name of the application and page title-->
   <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="FACEBOOK Integration" Style="{StaticResource PhoneTextNormalStyle}"/>
        </StackPanel>

6- now we will add the login button , add the following lines of code in the Xaml code at the end of the page directly before the end of the layout grid'(</Grid>)

<!-- login control -->
  <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Button Content="Login To Facebook" Height="73" HorizontalAlignment="Left" Margin="101,252,0,0" x:Name="btnFacebookLogin" VerticalAlignment="Top" Width="276" Click="btnFacebookLogin_Click" >
            </Button>
        </Grid>

you will notice that the button is added in the design at the middle  of the page.

Facebook Authentication on Windows Phone works using OAuth. The Facebook.Client library comes built in with the FacebookSessionClient construct which automatically displays a WebBrowser for the Facebook login. Whenever we make a login call from within a page, we will first see the UI in the page which made the login call and then we will navigate to the Login page and then back to the original page or the page we want to navigate to.

7- Now we will add the code behind this button but first we need to create the page that will host the WebBrowser control for OAuth.

To do so, right click on the Project that we previously named it (Windows Phone APP)and select Add New Item. Select Visual C# on the left in the Add Dialog and then select Windows Phone Portrait Page in the middle pane and name it FacebookLogin.xaml. We need the FacebookLogin page to be a blank page so we will remove parts of the auto generated  code from FacebookLogin.xaml.

Remove this block of code, Now the page will be blank

<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>

Back to Our MainPage.Xaml.cs lets add the button click implementation , This lines of code will navigate the MainPage to the page we just create it , The one that will host the facebook login page.

private void btnFacebookLogin_Click(object sender, RoutedEventArgs e)
{
    NavigationService.Navigate(new Uri("/Pages/FacebookLogin.xaml", UriKind.Relative));
}

Once the user has navigated, to the OAuth page, we want to connect the event handlers so that the FacebookLogin will load the OAuth dialog using FacebookSessionClient.

8- First add the following line to the FacebookLogin constructor, which invokes the Facebook login as soon as we navigate to the FacebookLogin: In FacebookLogin.xaml.cs in the constructor after InitializeComponent(); add this line

this.Loaded += FacebookLoginPage_Loaded;

Then add the following code snippet to FacebookLogin.xamls.cs, which checks if the user is already authenticated and if not, invokes the Authentication.

async void FacebookLoginPage_Loaded(object sender, RoutedEventArgs e)
{
    if (!App.isAuthenticated)
    {
        App.isAuthenticated = true;
        await Authenticate();
    }
}

As the final step of Autentication add the following code to perform the Authentication and request read permissions for the user’s profile and other data when the login succeeded. But first we need to create a new page the same as we did before lets call it LandingPage.Xaml we will navigate to this new page directly after login.

private FacebookSession session;
private async Task Authenticate()
{
    string message = String.Empty;
    try
    {
        session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");
        App.AccessToken = session.AccessToken;
        App.FacebookId = session.FacebookId;

        Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/LandingPage.xaml", UriKind.Relative)));
    }
    catch (InvalidOperationException e)
    {
        message = "Login failed! Exception details: " + e.Message;
        MessageBox.Show(message);
    }
}

You will find alot of errors and red lines in the code , Don’t Panic 😀

on every error rightClick on it –> resolve –> choose Facebook.client for example  as shown bellow

resolve

In App.xaml.cs add   the Facebook App ID here with your Facebook App ID that you obtained earlier when you created your app on the Facebook Developer Portal and add  the following four variables to hold the Facebook OAuth Access Token, the User’s ID once they have logged in into Facebook, a flag to keep track that the user has already been authenticated and the FacebookSessionClient class which wraps the Facebook OAuth login. at the begining of the class right before the constructor

public static readonly string FacebookAppId = "ADD YOUR APP ID";
internal static string AccessToken = String.Empty;
internal static string FacebookId = String.Empty;
public static bool isAuthenticated = false;
public static FacebookSessionClient FacebookSessionClient = new FacebookSessionClient(FacebookAppId);

Now the facebook should login Successfully after resolving any missing dependency .

One more things recently there is a bug in the facebook SDK where when you run the application and click on the login button you will see this instead of the login page

Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.
The solution for this issue is to do as bellow

There is currently a bug which will prevent Facebook Login for Windows Phone from working if you have any entries in the “Valid OAuth redirect URIs” field in the Advanced section of your app settings. This can be worked around by adding “https://m.facebook.com/dialog/return/ms” in this field.

Try different links this one worked for me

http://www.facebook.com/

facebookbug

  This is  my first tutorial, if you have any suggestions for improvement in the next tutorials please write it in the comments.

Best Windows 8 Apps — January 20, 2014
Personal Success — July 11, 2013

Personal Success

I have watched some videos about personal success and read lots of books in  this topic.
so i will write here just some notes to keep in mind during your life to keep you on track to help you achieving what you want , Hope its helpful 🙂

Innovation for life

My message today is mainly about nurturing or building or reinforcing your creative potential, your creativity, your capacities for innovation so that they can stand the test of time. I think both the good news and the bad news on this young at heart thing comes from Pablo Picasso who said a long time ago, he said,    “Every child is an artist ” I think what Picasso was talking about is that as you get older and as responsibilities start piling on to you, the next thing you know it will almost seem as if circumstances are conspiring against you. There are forces like erosion and entropy that try to chip away at your creative energy. But if you’re willing to work at it a little bit, you can reinforce your abilities. You can prevent that from happening or you can at least fight against those forces as a way to stay young at heart.

“I think someone or something has told you it’s not OK to be an artist.”  If you don’t remember anything else I say its OK  but  I want you to remember it’s OK to be an artist.  And so this is part of my message today; it’s OK to be an artist. It’s OK to be an innovator. It’s OK to be a design thinker even if it causes people around you to raise their eyebrows.

This idea about innovator for life is all about starting good habits , you can start now mental or behavioral habits that will help you to be an innovator for life its really about forming habits now that will help you later on, these are 5 habits there is a lot more but we will start with those , and if you think you could come up with a lot more.

1-  Think like traveler

Ever notice when you go to a distant city, especially when you travel internationally, ever notice that there’s a piece of your brain that is turned up on high. You’re in this hyper aware state where you notice everything.

All I’m saying is whatever part of that brain is that is super active when you’re traveling internationally, try to turn up that part of your brain all the time. Because if you can do that, if you can have a higher state of awareness that people around you have, you will spot more opportunities and those opportunities will have value for it. So if you can observe more, if you can learn more, if you can get a better or more up-to-date view of human behavior, that gives you power. That gives you credibility as an innovator.
you’ve got to remember you are the world, undisputed expert of your own experience. So try to capture the lessons from your experiences.

“The real act of discovery consist not in finding new lands,” that’s traveling, “but in seeing with new eyes.” Which is thinking like a traveler.

And so that’s this message about think like a traveler, be an anthropologist. Use your powers of observation. Have that part of your brain turned up as high as you can all along.

2- Treat life as an experiment

This is partly about risk. This is partly about actually being willing to fail because experiments,  they’re not all successes; that’s why they call them experiments. And so if you treat life like an experiment, you got to be prepared for some stuff not to work out.

if mom raised you that once you start something you got to finish it, then a 300-page book, there’s some big risk in cracking it open. Whereas if you treat that as an experiment and say, “Look, I’m just going to read the first 10 pages and see how I feel. And if that’s good I’m going to continue,” then a book is not so scary. Then the next thing you know you read 10, 20 and 30. And if it’s a good book you get all the way through it. But what got you into in the first place is you were willing to treat it as an experiment. Because if you go whole hog, if you’ve got to do the whole thing that scares people away. And so you can go through your whole life with this method. It’s like, “Look, I’m going to try this. I can put up with anything for a day. I’m going to see how this works.” And so you get in the habit of you’re failing but ideally you’re failing forward. You’re failing in a way that has a little bit of learning attached to each one.

“I haven’t failed. I’ve just found 10,000 ways that do not work.” said Thomas Edison .

He had lots of failures. He was willing to tolerate lots of failures and it worked out pretty well for him in the end.

3- Cultivating an Attitude of Wisdom

this idea of an attitude of wisdom which is a healthy balance between confidence in what you know and distrusting what you know just enough that keeps you thirsty for more knowledge. Because we’ve all met people in our lives who they get to be an expert, they develop this deep expertise and they want to rest on their laurels. “I know a lot about that. I don’t need to know more.” I bet you’ve encountered some people like that. And this resting on your laurels, especially with respect to learning – never a good idea.

“It’s not what you don’t know that gets you into trouble; it’s what you know for sure that ain’t so.” And this “know for sure” stuff could be really a problem for lots of people.

4- Tortoise Mind

Use this thing that Guy Claxton calls your “tortoise mind”. There’s this great book, it’s called “Hare Brain, Tortoise Mind” and he says the hare brain is the one that you know really well. Hare brain, that’s the brain you can focus, you can concentrate with, it’s under your direct control. But he says there’s this other part of your brain that is not under your direct control, that’s actually smarter than the hare brain. He calls it the “tortoise mind”. And this is where contemplation happens. This is where rumination happens. Your tortoise mind is working on things in the background all the time. And if you work at it, you can actually assign little tasks to the tortoise mind. There are people who are really good at this. They’ll write a question down before they go to sleep in the hopes that their brain will work on it overnight and maybe come up with an answer. So there are ways, if you can address the tortoise mind, you can do things with them.

And so there are researchers now looking into the science of epiphany. People have these flashes of brilliance. Allegedly Newton is under the apple tree, the apple falls, and he suddenly has a fully formed point of view of the idea called gravity. I seriously doubt that it happened exactly that way but there are epiphanies. There are “ah-ha moments” and what’s really happening in that “ah-ha moment”, according to the neurosciences looking into this, is it’s not like you had a lightning bolt come down and deliver all that knowledge to you. It’s that your tortoise mind has been working on this for days, or weeks or months or in some cases, even years and you’ve just crossed the finish line. You’ve just gotten to a place where you say, “Oh, it’s obvious now, isn’t it.” But it wasn’t obvious for the previous how-ever-many number of years. So here’s the thing is, if your mind running like this, like Grand Central Station, it is a big distraction to the tortoise mind because the tortoise mind needs a little space. And so what you have to do, and this is sometimes easier said than done, you’ve got to find a way to take some time to daydream.

5- Do What you Love

Look, this is really simple. Do what you love not because you just want to be self interested ,  Do it because you’ll be better at it.”

And so, pretty obvious do what you love because you’ll be better. You’ll be willing to put in the extra time, the extra mental energy because you love it.

Try to think of what you should do next. Think about these three circles. The first circle is what are you good at?by the time you reach a certain age most people have a sense of what they’re good at.But watch out for this circle because in this circle lives the curse of competence. Just because you’re good at something doesn’t mean you should do it. If you look around your school or your office, you might discover you’re the fastest person you ever met on the keyboard. Does that mean you should be a data entry operator? Probably not.”

Next I’ll give some examples to deliver some important concepts on a guy we will call him “Jim”.

He said he was really good at math and everybody said to him, “Jim, you should be a math major.” And so he listened to that advice and he got to school and he continued to be good at math but he ran into people living in the second circle. And the second circle is “What are you born to do?” When are you the happiest? When are you in a state of flow ? , and he said he met people who were never happier than when they were solving equations and doing proofs. And he said, “I realized that good as I was at math, this was not my true calling.” And so he thought about those two circles. Then he thought about this third one. Don’t over emphasize this one but you got to think about it.” Which is, “What will people pay you to do?” Because they say do what you love and the money will follow , it’s not literally true.  Think about this intersection , Think about where you are, Then there’s this other thing called ‘who’.” which is who are you going to work with? Who’s on the bus with you? Because you can show up for work everyday and you can do stuff you’re good at, you can do stuff you’re born to do. You can do stuff that people pay you to do, but if you’re working with people that you hate or that hate you or they have no respect for you, still not going to be a happy camper.

Jim said, “I was kind of a nerdy kid. When I was a kid I’d get out my magnifying glass and I would watch a bug.” He says, “And I’ll get one of these old style laboratory notebooks and I’d write down my observations. Everyday I’d watch that bug and how does he eat and does he sleep and what’s the bug doing all day.”

so that’s what he would do.  he found himself at this point in life,he was working for Hewlett Packard, great company which he openly acknowledges, but he wasn’t happy. And so he got out one of those laboratory notebooks and he wrote on it “A Bug” at the top. And then he wrote “A Bug Called Jim”. And for two years he kept a laboratory notebook on himself. It wasn’t a journal. He wasn’t writing down the occurrences of the day. He wrote down during the day, during each day for two years when did I feel at my best. When was I in a state of flow? When did I feel the happiest because that’s really important. And  it took him two years of discovery, this is the tortoise mind again. It took him two years of discovery but he eventually figured out he was happiest when he was teaching and when he was working on systems, things with lots of little complexities and moving parts. And he said, “I figured out I should be teaching about systems.” And so he did and I think he taught about systems at Stanford for awhile as well until he found another calling. But he kept a lab notebook on himself.   And so if you’re wondering, if you’re drawing those three circles in your head and you’re wondering, “What am I born to do?” I encourage you to try this lab notebook. It’s an experiment. Can’t hurt.

Motivational Quote —

Motivational Quote

this is kind of hard to understand but, sometimes you can try so hard at something, sometimes you can be so, so prepared….but still fail. and with every time you fail, its painful. it causes sadness & it causes disappointment. i’ve often said, “a mans character is not judged, after he celebrates a victory, but by the way he acts when his back is against the wall.” so no matter how great the setback, how severe the failure, you never give up. YOU NEVER GIVE UP. YOU PICK YOURSELF UP, YOU BRUSH YOURSELF OFF, YOU PUSH FORWARD, YOU MOVE ON, YOU ADAPT, YOU OVERCOME, THAT IS WHAT I BELIEVE. so, there are those that have been so offended with my actions, they might have lost faith in me. i absolutely respect your decision to do that. an, im not talking to them, im talking to those people who still believe, tonight, i speak to those who still proudly stand next to me. you have not given up on me, and i will not give up on you. this is my everything. so im not gunna say tonight that im gunna work harder, that im going to be more dedicated, I WONT BE STOPPED. I CAN’T.BE.STOPPED .

Operating System Concepts C/C++ — December 13, 2012

Operating System Concepts C/C++

This is my first blog post , I hope it is useful .

In this post we will talk about some important concepts in Operating Systems , Mainly we will talk about processes and scheduling in the operating systems.

All the functions and examples given will be written in C/C++.

What is an Operating System?

  • Os controls all computer resources and provides the base upon which the application programs can be written
  • Os is the software layer that is on top of the hardware to manage all parts of the system, and present the user with interface or virtual machine  that is easier to understand and program.

History of OS

OS historically have been closely tied to the architecture of the computers on which, they run. So looking at generation of the computers enables us to see what their OS were like.

  • The first generation: Vacuum tubes and plugboards (1945-55)
  • The second generation: Transistors and batch systems (1955-65)
  • The third generation: ICs and multiprogramming: (1956-1980)
  • The forth generation: Personal Computers (1980- present)
    1. Workstations and network operating systems and distributed systems
    2. MSDOS, UNIX (supports IEEE POSIX standard system calls interface), WINDOWS
    3. MINIX is Unix like operating system written in C for educational purposes (1987)
    4. Linux is the extended version of MINIX.

We will start by the definition of a Process

A process  is basically a single running program. It may be a “system” program (e.g login, update, csh) or program initiated by the user (textedit, dbxtool or a user written one).

Process table: A link list for each existing process that contains all  information about the process, other than the contents of its own address.
When the process is suspended all of its information is saved in process table.
Command interpreter (Shell) reads the user commands from terminal to create a process.

A process can create child processes and communicate with them (interprocess communication)

Process Control: <stdlib.h>,<unistd.h>

When UNIX runs a process it gives each process a unique number – a process ID, pid.

The UNIX command ps will list all current processes running on your machine and will list the pid.

The C function int getpid() will return the pid of process that called this function.

System Calls for process control

you can man each of these function in linux terminal to know more details about them.
fork()
wait()
execl(), execlp(), execv(), execvp()
exit()
signal(sig, handler)
kill(sig, pid)
System Calls for IPC
pipe(fildes)
dup(fd)

Process Execution States

For convenience, we describe a process as being in one of several basic states.
Most basic:
Running
Ready
Blocked (or sleeping)

Context Switching

A context switch involves two processes:
One leaves the Running state
Another enters the Running state
The status (context) of one process is saved; the status of the second  process restored.

Concurrent Processes occurs in several ways

Multiprogramming: Creates logical parallelism by running several processes/threads at a time.  The OS keeps several jobs in memory simultaneously. It selects a job from the ready state and starts executing it. When that job needs to wait for some event the CPU is switched to another job. Primary objective: eliminate CPU idle time

Time sharing: An extension of multiprogramming. After a certain amount of time the CPU is switched to another job regardless of whether the process/thread needs to wait for some operation. Switching between jobs occurs so frequently that the users can interact with each program while it is running.

Multiple processors on a single computer run multiple processes at the same time.  Creates physical parallelism.

Process Scheduling

  • Process scheduling decides which process to dispatch (to the Run state) next.
  • In a multiprogrammed system several processes compete for a single processor
  • Preemptive scheduling: a process can be removed from the Run state before it completes or blocks (timer expires or higher priority process enters Ready state).

Scheduling Algorithms

  • FCFS (first-come, first-served): non-preemptive: processes run until they complete or block themselves for event wait
  • RR (round robin): preemptive FCFS, based on time slice

Time slice  = length of time a process can run before being preempted
Return to Ready state when preempted

Scheduling Goals

Optimize turnaround time and/or response time
Optimize throughput
Avoid starvation (be “fair” )
Respect priorities
Static
Dynamic

Privacy Policy — November 18, 2012

Privacy Policy

This application does not collect or transmit any user’s personal information, with the exception of technical information included in HTTP requests (such as your IP address). No personal information is used, stored, secured or disclosed by services this application works with. If you would like to report any violations of this policy, please contact us using the contact form.