Q:

Text property in a UserControl in C#

I have a control with a inner TextBox. I want to make a direct relationship between the Text property of the UserControl and the Text property of the TextBox. The first thing I realized is that Text was not being displayed in the Properties of the UserControl. Then I added the Browsable(true) attribute.
[Browsable(true)]
public override string Text
{
    get
    {
        return m_textBox.Text;
    }

    set
    {
        m_textBox.Text = value;
    }
}

Now, the text will be shown for a while, but then is deleted. This is because the information is not written automatically within the xxxx.Designer.cs file. How can this behviour be changed?

A:

You need more attributes:
[EditorBrowsable(EditorBrowsableState.Always)]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Bindable(true)]
public override string Text { get; set; }

A:

Reflector is a crucial tool for a .NET developer.  It is immediately obvious what you need to do when you use it to look at the UserControl.Text property:
[Bindable(false), EditorBrowsable(EditorBrowsableState.Never), Browsable(false),
 DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override string Text
{
    get
    {
        return base.Text;
    }
    set
    {
        base.Text = value;
    }
}

Ho showed you what you need to do to cancel these attributes, too bad he didn't show you how he found out.  Reflector is was free, download it from redgate.com or check the alternatives here : Something Better than .NET Reflector?


Q:

Run command in linux terminal using java program?

I want to run unset DISPLAY as a command in the linux terminal, using a Java program.
I tried using Runtime.getRuntime().exec("unset DISPLAY");, but it doesn't work.
What could I do here?

A:

This won't work, and here's why. Environment variables are inherited from the parent process. A child can't control a parent's environment. Here's what's happening in your setup:
 bash   ->   java   ->   unset
   |           |           |
 parent      child     grand-child
   |           |           |
unaffected unaffected   affected

So in actuality your command IS working, however it's not having the effect you want it to. Sadly java won't be able to change the parent's environment.
Your java program can modify environment variables of its own, and any children spawned by java will inherit those variables. So you could potentially have java launch a bash shell for you, and then use that bash shell interactively, but that seems like a lot of overhead.
See this post for how to set java's environment variables:
How do I set environment variables from Java?
If you're willing to sidestep the whole java problem, what most people do in this situation is source a special file. For example, create a file called "no-x.sh" that looks like this:
# Unset the display variable
unset DISPLAY

And then from your current (interactive) shell, source the file like this:
$> source no-x.sh

and now your main bash shell has had its environment changed. Note that this is a HACK (or for all of you bash zealots out there -- a feature) and you should never expect to duplicate this functionality with anything else (like java).

A:

You need to run it using bash executable like this:
 Runtime.getRuntime().exec("/bin/bash -c \"unset DISPLAY\"");


Q:

Similar To function in sql

I am working on the query
(Select d_name from Direction where d_name  SIMILAR TO '(WEST|NORTH)%' )
this gives me the result as
WEST 1
WEST 2
NORTH 2
WEST
NORTH

But I want the result as
WEST
NORTH

with the same statement Similar To. Someone please modify the same query to get the 2nd result.
Thanks

A:

(select 'WEST' from Direction where d_name  SIMILAR TO 'WEST%')
UNION
(select 'NORTH' from Direction where d_name  SIMILAR TO 'NORTH%');

A:

I got the solution
Select d_name
from Direction
where d_name  SIMILAR TO '(WEST|NORTH)'

Just remove % from the query.


Q:

Unfortunately App has stopped

I am trying to develop an app which it download my content from the my server and play locally, so soon as i click on to the icon the initial screen appears(that is initial activity is executing fine where as once it goes to the second activity it is showing error as

Unfortunately app has stopped

This is my log cat
01-13 00:25:41.070: E/AndroidRuntime(955): FATAL EXCEPTION: main
01-13 00:25:41.070: E/AndroidRuntime(955): Process: com.tmp.timbremediaplayer, PID: 955
01-13 00:25:41.070: E/AndroidRuntime(955): java.lang.RuntimeException: Unable to resume activity {com.tmp.timbremediaplayer/com.tmp.timbremediaplayer.MusicPlayerActivity}: android.util.SuperNotCalledException: Activity {com.tmp.timbremediaplayer/com.tmp.timbremediaplayer.MusicPlayerActivity} did not call through to super.onResume()
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.os.Handler.dispatchMessage(Handler.java:102)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.os.Looper.loop(Looper.java:136)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread.main(ActivityThread.java:5017)
01-13 00:25:41.070: E/AndroidRuntime(955):  at java.lang.reflect.Method.invokeNative(Native Method)
01-13 00:25:41.070: E/AndroidRuntime(955):  at java.lang.reflect.Method.invoke(Method.java:515)
01-13 00:25:41.070: E/AndroidRuntime(955):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-13 00:25:41.070: E/AndroidRuntime(955):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-13 00:25:41.070: E/AndroidRuntime(955):  at dalvik.system.NativeStart.main(Native Method)
01-13 00:25:41.070: E/AndroidRuntime(955): Caused by: android.util.SuperNotCalledException: Activity {com.tmp.timbremediaplayer/com.tmp.timbremediaplayer.MusicPlayerActivity} did not call through to super.onResume()
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.Activity.performResume(Activity.java:5312)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778)
01-13 00:25:41.070: E/AndroidRuntime(955):  ... 12 more

This is the initial activity
public class SyncActivity extends Activity {
    private Button btnProgressBar;
    private ProgressDialog prgDialog;
    // Progress Dialog type (0 - for Horizontal progress bar)
    public static final int progress_bar_type = 0;
    // Music resource URL
    private static String file_url = "https://docs.google.com/uc?export=download&id=0B_TtB7EjzcYCUXVuRTFmRzNkczg";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Show Download Music Button
        btnProgressBar = (Button) findViewById(R.id.btnProgressBar);
        // Download Music Button click listener
        btnProgressBar.setOnClickListener(new View.OnClickListener() {
            // When Download Music Button is clicked
            public void onClick(View v)
            {
                // Disable the button to avoid playing of song multiple times
                btnProgressBar.setEnabled(false);
                // Downloaded Music File path in SD Card
                File sdcard = Environment.getExternalStorageDirectory();
                File dir = new File(sdcard.getAbsolutePath()+"/timbre media");
                dir.mkdirs();
                File file = new File(Environment.getExternalStorageDirectory().getPath()+"/timbre media/song.mp3");
                // Check if the Music file already exists
                if (file.exists())
                {
                    Toast.makeText(getApplicationContext(), "File already exist under SD card, playing Music", Toast.LENGTH_SHORT).show();
                    /* Play Music
                     * Include the player activity
                     * and playing starts from here if the music file
                     * already exist
                     */
                    Intent i = new Intent(getApplicationContext(), MusicPlayerActivity.class);
                    startActivityForResult(i, 100);
                // If the Music File doesn't exist in SD card (Not yet downloaded)
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "File doesn't exist under SD Card, downloading Mp3", Toast.LENGTH_SHORT).show();
                    // Trigger Async Task (onPreExecute method)
                    new DownloadMusic().execute(file_url);
                }
            }
        });
    }

    // Show Dialog Box with Progress bar
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type:
            prgDialog = new ProgressDialog(this);
            prgDialog.setMessage("Downloading Mp3 file. Please wait...");
            prgDialog.setIndeterminate(false);
            prgDialog.setMax(100);
            prgDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            prgDialog.setCancelable(false);
            prgDialog.show();
            return prgDialog;
        default:
            return null;
        }
    }

    // Async Task Class
    class DownloadMusic extends AsyncTask<String, String, String>
    {

        // Show Progress bar before downloading Music

        @SuppressWarnings("deprecation")
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Shows Progress Bar Dialog and then call doInBackground method
            showDialog(progress_bar_type);
        }

        // Download Music File from Internet
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // Get Music file length
                int lenghtOfFile = conection.getContentLength();
                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(),10*1024);
                // Output stream to write file in SD card
                OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/timbre media/song.mp3");
                byte data[] = new byte[1024];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // Publish the progress which triggers onProgressUpdate method
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // Write data to file
                    output.write(data, 0, count);
                }
                // Flush output
                output.flush();
                // Close streams
                output.close();
                input.close();
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            return null;
        }

        // While Downloading Music File
        protected void onProgressUpdate(String... progress) {
            // Set progress percentage
            prgDialog.setProgress(Integer.parseInt(progress[0]));
        }

        // Once Music File is downloaded

        @SuppressWarnings("deprecation")
        @Override
        protected void onPostExecute(String file_url) {
            // Dismiss the dialog after the Music file was downloaded
            dismissDialog(progress_bar_type);
            Toast.makeText(getApplicationContext(), "Download complete, playing Music", Toast.LENGTH_LONG).show();
            /*
             *  Play the music
             */

                Intent i = new Intent(getApplicationContext(), MusicPlayerActivity.class);
                startActivityForResult(i, 100);

        }
    }

}

This is the second activity
public class MusicPlayerActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {

private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnPlaylist;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private ImageButton btnClose;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
public MediaPlayer mp;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private SongsManager songManager;
private Utilities utils;
public int length=0;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
String TAG = "phoneCallListener";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.player);

    // All player buttons
    btnPlay = (ImageButton) findViewById(R.id.btnPlay);
    btnForward = (ImageButton) findViewById(R.id.btnForward);
    btnBackward = (ImageButton) findViewById(R.id.btnBackward);
    btnNext = (ImageButton) findViewById(R.id.btnNext);
    btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
    btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
    btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
    btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
    btnClose = (ImageButton) findViewById(R.id.btnClose);
    songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
    songTitleLabel = (TextView) findViewById(R.id.songTitle);
    songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
    songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);

    // Mediaplayer
    mp = new MediaPlayer();
    songManager = new SongsManager();
    utils = new Utilities();

    // Listeners
    songProgressBar.setOnSeekBarChangeListener(this); // Important
    mp.setOnCompletionListener(this); // Important

    // Getting all songs list
    songsList = songManager.getPlayList();

    // By default play first song
    playSong(0);

    /**
     * Play button click event
     * plays a song and changes button to pause image
     * pauses a song and changes button to play image
     * */
    btnPlay.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // check for already playing
            if(mp.isPlaying()){
                if(mp!=null){
                    mp.pause();
                    length = mp.getCurrentPosition();

                    // Changing button image to play button

                    btnPlay.setImageResource(R.drawable.btn_play);
                        }

            }else if(mp!=null)
            {
                // Resume song
                mp.start();
                // Changing button image to pause button
                btnPlay.setImageResource(R.drawable.btn_pause);

            }
            else
            {
            onResume();
            }
        }
    });
            /**
     * Forward button click event
     * Forwards song specified seconds
     * */
    btnForward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // get current song position
            int currentPosition = mp.getCurrentPosition();
            // check if seekForward time is lesser than song duration
            if(currentPosition + seekForwardTime <= mp.getDuration()){
                // forward song
                mp.seekTo(currentPosition + seekForwardTime);
            }else{
                // forward to end position
                mp.seekTo(mp.getDuration());
            }
        }
    });

    /*
     * Close image button
     */
    btnClose.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            openAlert(v);
        }
    });
    /*private void openAlert(View view) {

    }
    */

    /**
     * Backward button click event
     * Backward song to specified seconds
     * */
    btnBackward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // get current song position
            int currentPosition = mp.getCurrentPosition();
            // check if seekBackward time is greater than 0 sec
            if(currentPosition - seekBackwardTime >= 0){
                // forward song
                mp.seekTo(currentPosition - seekBackwardTime);
            }else{
                // backward to starting position
                mp.seekTo(0);
            }

        }
    });

    /**
     * Next button click event
     * Plays next song by taking currentSongIndex + 1
     * */
    btnNext.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // check if next song is there or not
            if(currentSongIndex < (songsList.size() - 1)){
                playSong(currentSongIndex + 1);
                currentSongIndex = currentSongIndex + 1;
            }else{
                // play first song
                playSong(0);
                currentSongIndex = 0;
            }

        }
    });

    /**
     * Back button click event
     * Plays previous song by currentSongIndex - 1
     * */
    btnPrevious.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(currentSongIndex > 0){
                playSong(currentSongIndex - 1);
                currentSongIndex = currentSongIndex - 1;
            }else{
                // play last song
                playSong(songsList.size() - 1);
                currentSongIndex = songsList.size() - 1;
            }

        }
    });

    /**
     * Button Click event for Repeat button
     * Enables repeat flag to true
     * */
    btnRepeat.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(isRepeat){
                isRepeat = false;
                Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
                btnRepeat.setImageResource(R.drawable.btn_repeat);
            }else{
                // make repeat to true
                isRepeat = true;
                Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
                // make shuffle to false
                isShuffle = false;
                btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
                btnShuffle.setImageResource(R.drawable.btn_shuffle);
            }
        }
    });

    /**
     * Button Click event for Shuffle button
     * Enables shuffle flag to true
     * */
    btnShuffle.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(isShuffle){
                isShuffle = false;
                Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
                btnShuffle.setImageResource(R.drawable.btn_shuffle);
            }else{
                // make repeat to true
                isShuffle= true;
                Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
                // make shuffle to false
                isRepeat = false;
                btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
                btnRepeat.setImageResource(R.drawable.btn_repeat);
            }
        }
    });

    /**
     * Button Click event for Play list click event
     * Launches list activity which displays list of songs
     * */
    btnPlaylist.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent i = new Intent(getApplicationContext(), PlayListActivity.class);
            startActivityForResult(i, 100);
        }
    });

}

public void onCallStateChanged(int state, String incoming_Number)
    {

    Intent i = new Intent(getApplicationContext(),Call_Exception.class);
    startActivityForResult(i, 100);

    }

protected void onResume(){
if(mp.isPlaying()== false)
{
    if(mp!=null)
    {
        mp.seekTo(length);
        super.onResume();
        mp.start();
        btnPlay.setImageResource(R.drawable.btn_pause);

    }

}
}

protected void openAlert(View v) {
    // TODO Auto-generated method stub
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MusicPlayerActivity.this);

     alertDialogBuilder.setTitle(this.getTitle()+ " decision");
     alertDialogBuilder.setMessage("Are you sure?");
             // set negative button: No message
     alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                // cancel the alert box and put a Toast to the user
                dialog.cancel();
                Toast.makeText(getApplicationContext(), "You choose a negative answer",
                        Toast.LENGTH_SHORT).show();
            }
        });
     // set neutral button: Exit the app message
     alertDialogBuilder.setNeutralButton("Exit the app",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                // exit the app and go to the HOME
                MusicPlayerActivity.this.finish();
            }
        });

     AlertDialog alertDialog = alertDialogBuilder.create();
     // show alert
    alertDialog.show();
}

/**
 * Receiving song index from playlist view
 * and play the song
 * */
@Override
protected void onActivityResult(int requestCode,
                                 int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == 100){
         currentSongIndex = data.getExtras().getInt("songIndex");
         // play selected song
         playSong(currentSongIndex);
    }

}

/**
 * Function to play a song
 * @param songIndex - index of song
 * */
public void  playSong(int songIndex){
    // Play song
    try {
        mp.reset();
        mp.setDataSource(songsList.get(songIndex).get("songPath"));
        mp.prepare();
        mp.start();

        // Displaying Song title
        String songTitle = songsList.get(songIndex).get("songTitle");
        songTitleLabel.setText(songTitle);

        // Changing Button Image to pause image
        btnPlay.setImageResource(R.drawable.btn_pause);

        // set Progress bar values
        songProgressBar.setProgress(0);
        songProgressBar.setMax(100);

        // Updating progress bar
        updateProgressBar();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * Update timer on seekbar
 * */
public void updateProgressBar() {
    mHandler.postDelayed(mUpdateTimeTask, 100);
}

/**
 * Background Runnable thread
 * */
private Runnable mUpdateTimeTask = new Runnable() {
       public void run() {
           long totalDuration = mp.getDuration();
           long currentDuration = mp.getCurrentPosition();

           // Displaying Total Duration time
           songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
           // Displaying time completed playing
           songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

           // Updating progress bar
           int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
           //Log.d("Progress", ""+progress);
           songProgressBar.setProgress(progress);

           // Running this thread after 100 milliseconds
           mHandler.postDelayed(this, 100);
       }
    };

/**
 *
 * */
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

}

/**
 * When user starts moving the progress handler
 * */
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // remove message Handler from updating progress bar
    //mHandler.removeCallbacks(mUpdateTimeTask);

}

/**
 * When user stops moving the progress hanlder
 * */
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    //mHandler.removeCallbacks(mUpdateTimeTask);
    //int totalDuration = mp.getDuration();
    // currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

    // forward or backward to certain seconds
    //mp.seekTo(currentPosition);

    // update timer progress again
    //updateProgressBar();
    Toast.makeText(getApplicationContext(), "This facility is disabled",Toast.LENGTH_SHORT).show();

}

/**
 * On Song Playing completed
 * if repeat is ON play same song again
 * if shuffle is ON play random song
 * */
@Override
public void onCompletion(MediaPlayer arg0) {

    // check for repeat is ON or OFF
    if(isRepeat){
        // repeat is on play same song again
        playSong(currentSongIndex);
    } else if(isShuffle){
        // shuffle is on - play a random song
        Random rand = new Random();
        currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
        playSong(currentSongIndex);
    } else{
        // no repeat or shuffle ON - play next song
        if(currentSongIndex < (songsList.size() - 1)){
            playSong(currentSongIndex + 1);
            currentSongIndex = currentSongIndex + 1;
        }else{
            // play first song
            playSong(0);
            currentSongIndex = 0;
        }
    }
}

@Override
 public void onDestroy(){
 super.onDestroy();
    mp.release();
 }

}

A:

From the log what it says is you "did not call through to super.onResume()"
So in your Activity class if you are overriding 'onResume' it should be like below
protected void onResume()
{
    super.onResume();//This is important

    //Your code goes here
}

If you have done this already please post your Activity code


Q:

Emit Events To Socket.IO Not Working From Server

i am trying to get a chat program to work using socket.io but it doesnt seem to work properly.
i am using a Node.js server and it seems to be running properly. i think this may have something to do with emitting to rooms.
the code i have on the client browser is:
<script>

   var socket = io("https://localhost:3000/userChat");
   socket.on('connect', function(){
     socket.emit('initialiseConnection', "user1");
   });

   socket.on('messageIn', function(msg){
     console.log(msg);
     $('#messages').append($('<li>').text(msg.message));
   });

</script>

so when the page loads, socket.io it connects to the server and emits the "initialiseConnection" event on the server with "user1". which is a new room specifically for that user.
on the server, the code i have handling "initialiseConnection" is:
socket.on("initialiseConnection", function(username){
    socket.join(username);
    console.log(username + " has joined.");

    Message.find({recipient:username}, function (err, message){
       console.log("messages for "+username+": "+message.length);
       for (var x = 0; x < message.length; x++){
         console.log(username+"'s message "+x);
         console.log(message[x]);

         socket.to(username).emit("messageIn", {"message":message[x]});
       }
    });
});

this code as you can see, creates and joins a room with the same name as the username. the looks in the database for any messages, and tries to emit those messages to the user. i log the message. there is definately a message and the username in the "socket.to()" method is also correctly shown in the logs. but the "socket.on('messageIn')" on the client browser doesnt seem to be picking up the event.
i have also tried putting:
setTimeout(function() {
  socket.to(username).emit("messageIn", {"message":"test message"});
}, 5000);

immediately after the socket.join(), in case this was related to some backbround processing that needed to complete
can anyone see where i may have gone wrong on this?
Thanks.
--EDIT 1--------------------------------------
var https = require('https');
var express = require('express');
var app = express();
var server = https.createServer(https_options, app).listen(3000);
var io = require('socket.io')(server);

var userChat = io.of("/userChat");
userChat.on('connection', function(socket){
  console.log('a user connected');

  socket.on("initialiseConnection", function(username){
     ...
  });

  socket.on('disconnect', function(){
    socket.leave(socket.room);
  });
});

A:

You need to change this:
socket.to(username).emit("messageIn", {"message":message[x]});

to this:
socket.emit("messageIn", {"message":message[x]});

A socket is the endpoint.  When sending, you just send directly to the socket.  You don't send to a user in a room?  You just send to a socket.  Since you already have the socket in your socket variable, that's what you send to.


Q:

Shell - How to remove a particular string after nth occurrence of pipe

I have a file which has pipe delimited data and i want to remove this string "EES" after 17th occurrence of pipe and write the data back to same file again
Below is the input i want to pass
AMC|FRS|M|123456|01/30/1992|QWERT||WERTYU|OK|USA|74000|1234567|QQ|34567142|11/01/2011|12/31/9999|Y|V3EES|13

below is the output i'm expecting
AMC|FRS|M|123456|01/30/1992|QWERT||WERTYU|OK|USA|74000|1234567|QQ|34567142|11/01/2011|12/31/9999|Y|V3|13

Help is appreciated, Thanks in advance!!!

A:

Following awk should help you in same.
awk -F"|" '{sub("EES","",$18)} 1' OFS="|"   Input_file > temp_file && mv temp_file Input_file

Explanation: Making here field separator as |(pipe) as per OP's Input_file then using awk's substitute utility sub where I am mentioning that replace string EES with NULL in column 18. Now mentioning 1 which will print the lines(edited/non-edited 18th column). Setting OFS(Output field separator as |(pipe)) here to get | in output, then mentioning the Input_file.


Q:

Sort list in either desc or asc, depending on what it currently is

I've got a list, and I want to sort the results in the opposite order of what it currently is, to mimic the user clicking the column header hyperlink. Currently, I've the following:
 dsList.Sort((x, y) => String.CompareOrdinal(x.DisplayName, y.DisplayName));

But this only sorts ascending. I know to sort descending I would do:
 dsList.Sort((x, y) => String.CompareOrdinal(x.DisplayName, y.DisplayName)*-1);

but, I don't want to have to detect what it currently is and decide which sort to do.
Make sense?
Gracias.
To clarify, I can't use Reverse because I have more than 1 column that can be sorted by, so I need the ability to specify the value to sort on.
The below works, but not for null values. If there's a blank the sort gets stuck.
  dsList.Sort((x, y) => String.CompareOrdinal(x.Surname, y.Surname) * (strB != null && (strA != null && String.Compare(strA, strB) == -1) ? -1 : 1));

A:

How about
dsList.Sort((x, y) => String.CompareOrdinal(x.DisplayName, y.DisplayName)*(dsList[0] < dsList[1]?-1:1));

EDIT: in your comment it seems like you are having issues when there are duplicate or null values... this should fix that
dsList.Sort((x, y) => String.CompareOrdinal(x.DisplayName, y.DisplayName)*String.CompareOrdinal(dsList[0].DisplayName, dsList[dsList.Length-1].DisplayName));


Q:

CSS position:fixed without top gives unexpected layout?

Given:

       Fixed div

Non-fixed div

Non-fixed div

Non-fixed div

And:
* { box-sizing: border-box; }

body {
    margin: 0;
    padding: 0;
 }

#fixed {
    position: static;
    width: 100%;
    border: 3px solid #f00;
}
#nonfixed {
    margin-top: 50px;
    border: 3px solid #00f;
}

Note that position:static, this gives the expected result (fiddle):

However, change position:static to fixed, and you get this (fiddle)

Even though the #fixed div is not inside #nonfixed, it has taken on the top margin of #nonfixed.  This happens in both Chrome and Firefox. Curiously, the dev tools in both browsers do not show the #fixed div having any margins, so clearly it's being positioned as if it was fixed inside the #nonfixed div.
If I add top:0 to the #fixed ruleset the div goes back to the top of the window, but shouldn't this appear at the top (i.e. where it would in normal flow, but without affecting other elements) in the absence of a top specification?
For completeness: position:relative produces the same result as static and absolute looks the same as fixed.
I cannot find anything in the spec that directly addresses why an absolutely positioned element should be positioned relative to a subsequent sibling.   In fact, reading the spec I find (emphasis mine):

10.6.4 Absolutely positioned, non-replaced elements
...
If all three of 'top', 'height', and 'bottom' are auto, set 'top' to the static position and apply rule number three below.
...

'height' and 'bottom' are 'auto' and 'top' is not 'auto', then the height is based on the content per 10.6.7, set 'auto' values for 'margin-top' and 'margin-bottom' to 0, and solve for 'bottom'

This seems to indicate the #fixed box should indeed be at the top of the viewport.
Since both FF and Chrome do the same thing I'm guessing it's supposed to work this way, but I'd like to know why.  Can anyone explain this behavior in terms of the spec?

A:

You'll notice that the "fixed" div is actually at the top of the body, the position and size of which match those of the "nonfixed" div.
This is most certainly due to the top margins of the body and div#nonfixed collapsing. See http://www.w3.org/TR/CSS21/box.html#collapsing-margins

8.3.1 Collapsing margins
In CSS, the adjoining margins of two or more boxes (which might or
  might not be siblings) can combine to form a single margin. Margins
  that combine this way are said to collapse, and the resulting combined
  margin is called a collapsed margin.
(...)
Two margins are adjoining if and only if:

both belong to in-flow block-level boxes that participate in the same
  block formatting context
no line boxes, no clearance, no padding and
  no border separate them (Note that certain zero-height line boxes (see
  9.4.2) are ignored for this purpose.)
both belong to vertically-adjacent box edges, i.e. form one of the following pairs:

top margin of a box and top margin of its first in-flow
(...)

The topis relative to the containing block, which is apparently not bodybut html (the root element).


Q:

How would I do an Angular JS ng-repeat on this JSON parse?

How would I do an Angular JS ng-repeat on this JSON parse?
    .controller('TeamsCtrl', function($scope) {

    var text = '{"employees":[' +
        '{"name":"John Doe"},' +
        '{"name":"Sam Doe"},' +
        '{"name":"Jack Doe"}]}';
    /* create scope property that will be recognized in view*/
    $scope.tasks =  JSON.parse(text);

});

Here is the area I want populated with the new content:
    <ion-content class="has-header" ng-controller="TeamsCtrl">

{{employee.name}}

A:

You aren't assigning the parsed results to a scope variable
Controller should be more like:
.controller('TeamsCtrl', function($scope) {

    var text = '{"employees":[' +
        '{"name":"John Doe"},' +
        '{"name":"Sam Doe"},' +
        '{"name":"Jack Doe"}]}';
    /* create scope property that will be recognized in view*/
    $scope.tasks =  JSON.parse(text);

});

Then in markup you can do something like:

{{employee.name}}

DEMO


Q:

Keeping returned records from mysql unique

Is there a quick way to make sure the records you return from a MySQL JOIN query are unique?
The code below could potentially bring back the same category twice.  Its the category ID which should be distinct!
SELECT
   exp_categories.cat_name, exp_categories.cat_id, exp_categories.cat_url_title
  ,exp_category_posts.entry_id, exp_channel_titles.status
FROM (exp_categories
LEFT JOIN exp_category_posts
       ON exp_categories.cat_id = exp_category_posts.cat_id)
LEFT JOIN exp_channel_titles
       ON exp_category_posts.entry_id = exp_channel_titles.entry_id
WHERE exp_categories.group_id = 2
  AND exp_category_posts.entry_id IS NOT NULL
  AND exp_channel_titles.status = 'open'
ORDER BY RAND()
LIMIT 2

A:

    SELECT
   exp_categories.cat_name, exp_categories.cat_id, exp_categories.cat_url_title
  ,exp_category_posts.entry_id, exp_channel_titles.status
FROM (exp_categories
LEFT JOIN exp_category_posts
       ON exp_categories.cat_id = exp_category_posts.cat_id)
LEFT JOIN exp_channel_titles
       ON exp_category_posts.entry_id = exp_channel_titles.entry_id
WHERE exp_categories.group_id = 2
  AND exp_category_posts.entry_id IS NOT NULL
  AND exp_channel_titles.status = 'open'
  GROUP BY exp_categories.cat_id
ORDER BY RAND()
LIMIT 2

edit: Adding the column you want to be distinct in the GROUP BY clause will ensure there's only 1 returned.  Also, the ORDER BY RAND() is heavily discouraged, see: http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/


Q:

Random Number Generator not working with 2D arrays that output - C++

Okay, so I have a problem. I am trying to get the code to output to the console in a format like this:
123456
789012
345678
901234
567890
123456

But it is displaying like this:
123456

I don't know what the problem is, but here is the code:
void mazeLayout() {
    srand(time(NULL));
    const int mazeLayoutArraySize = 6;
    int mazeLayoutOne = rand()%6+1;
    int mazeLayoutTwo = rand()%6+1;
    int mazeLayoutThree = rand()%6+1;
    int mazeLayoutFour = rand()%6+1;
    int mazeLayoutFive = rand()%6+1;
    int mazeLayoutSix = rand()%6+1;
    int mazeLayoutSeven = rand()%6+1;
    int mazeLayoutEight = rand()%6+1;
    int mazeLayoutNine = rand()%6+1;
    int mazeLayoutTen = rand()%6+1;
    int mazeLayoutEleven = rand()%6+1;
    int mazeLayoutTwelve = rand()%6+1;
    int mazeLayoutThirteen = rand()%6+1;
    int mazeLayoutFourteen = rand()%6+1;
    int mazeLayoutFifteen = rand()%6+1;
    int mazeLayoutSixteen = rand()%6+1;
    int mazeLayoutSeventeen = rand()%6+1;
    int mazeLayoutEightteen = rand()%6+1;
    int mazeLayoutNineteen = rand()%6+1;
    int mazeLayoutTwenty = rand()%6+1;
    int mazeLayoutTwentyOne = rand()%6+1;
    int mazeLayoutTwentyTwo = rand()%6+1;
    int mazeLayoutTwentyThree = rand()%6+1;
    int mazeLayoutTwentyFour = rand()%6+1;
    int mazeLayoutTwentyFive = rand()%6+1;
    int mazeLayoutTwentySix = rand()%6+1;
    int mazeLayoutTwentySeven = rand()%6+1;
    int mazeLayoutTwentyEight = rand()%6+1;
    int mazeLayoutTwentyNine = rand()%6+1;
    int mazeLayoutThirty = rand()%6+1;
    int mazeLayoutThirtyOne = rand()%6+1;
    int mazeLayoutThirtyTwo = rand()%6+1;
    int mazeLayoutThirtyThree = rand()%6+1;
    int mazeLayoutThirtyFour = rand()%6+1;
    int mazeLayoutThirtyFive = rand()%6+1;
    int mazeLayoutThirtySix = rand()%6+1;
    int mazeLayoutArray[mazeLayoutArraySize][mazeLayoutArraySize]={{mazeLayoutOne, mazeLayoutTwo, mazeLayoutThree, mazeLayoutFour, mazeLayoutFive, mazeLayoutSix},
                               {mazeLayoutSeven, mazeLayoutEight, mazeLayoutNine, mazeLayoutTen, mazeLayoutEleven, mazeLayoutTwelve},
                               {mazeLayoutThirteen, mazeLayoutFourteen, mazeLayoutFifteen, mazeLayoutSixteen, mazeLayoutSeventeen, mazeLayoutEightteen},
                               {mazeLayoutNineteen, mazeLayoutTwenty, mazeLayoutTwentyOne, mazeLayoutTwentyTwo, mazeLayoutTwentyThree, mazeLayoutTwentyFour},
                               {mazeLayoutTwentyFive, mazeLayoutTwentySix, mazeLayoutTwentySeven, mazeLayoutTwentyEight, mazeLayoutTwentyNine, mazeLayoutThirty},
                               {mazeLayoutThirtyOne, mazeLayoutThirtyTwo, mazeLayoutThirtyThree, mazeLayoutThirtyFour, mazeLayoutThirtyFive, mazeLayoutThirtySix}};

//for loop to read rows
for(int index1=0; index1<6; index1++){
        for(int index2=0; index2<6; index2++) {
            cout << mazeLayoutArray[index1][index2];
        }
        cout << endl;
        exit(0);
    }

}

If you have any questions, just ask me!

A:

for(int index1=0; index1<6; index1++){
    for(int index2=0; index2<6; index2++) {
        cout << mazeLayoutArray[index1][index2];
    }
    cout << endl;
    exit(0);
}

After the inner loop prints out the first line, you just exit()'d the program.


Q:

Not navigating back to list after pressing Create Button

My code is here
I am taking this course
I added an action to navigate back to the employee list after hitting the create button but i am not navigating back. Can you help me understand what i might be doing wrong?
Here is the action creator file:
import firebase from 'firebase';
import Actions from 'react-native-router-flux';
import {
  EMPLOYEE_UPDATE,
  EMPLOYEE_CREATE
} from './types';

export const employeeUpdate = ({ prop, value }) => {
    return {
      type: EMPLOYEE_UPDATE,
      payload: { prop, value }
    };
};

export const employeeCreate = ({ name, phone, shift }) => {
const { currentUser } = firebase.auth();

  return (dispatch) => {
    firebase.database().ref(`/users/${currentUser.uid}/employees`)
      .push({ name, phone, shift })
      .then(() => {
        dispatch({ type: EMPLOYEE_CREATE });
        Actions.employeeList({ type: 'reset' });
      });
  };
};

This is the screen i am not navigating away from:

A:

I got this to work:
Router.js:
 const RouterComponent = () => {
    return (
       <Router sceneStyle={{ paddingTop: 0 }}>
       <Stack key="root" hideNavBar="true" >
         <Scene key="auth">
            <Scene key="login" component={LoginForm} title="Please Login" />
       </Scene>

       <Scene key="main">
         <Scene
           key="employeeList"
           onRight={() => Actions.employeeCreate()}
           rightTitle="Add"
           component={EmployeeList}
           title="Employees List"
           initial
        />
      <Scene key="employeeCreate" component={EmployeeCreate}
           title="Create Employee" />
      <Scene key="employeeEdit" component={EmployeeEdit} title="Edit
         Employee" />
    </Scene>
  </Stack>
</Router>
 );
};

EmployeeActions.js:
 export const employeeCreate = ({ name, phone, shift }) => {
   const { currentUser } = firebase.auth();

 return (dispatch) => {
   firebase.database().ref(`/users/${currentUser.uid}/employees`)
    .push({ name, phone, shift })
    .then(() => {
       dispatch({ type: EMPLOYEE_CREATE });
       Actions.main({ type: 'reset' });
    });
  };
};


Q:

java.lang.ClassCastException: org.neo4j.kernel.TopLevelTransaction

Trying java Program to connect to Neo4J i got following error
/home/mkgs/Desktop/placement/
Mar 21, 2014 2:53:41 PM org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog doInternalRecovery
INFO: Non clean shutdown detected on log [/home/mkgs/Desktop/placement/nioneo_logical.log.1Recovery started ...
Mar 21, 2014 2:53:42 PM org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog doInternalRecovery
INFO: Non clean shutdown detected on log [/home/mkgs/Desktop/placement/index/lucene.log.1]. Recovery started ...
Exception in thread "main" java.lang.ClassCastException: org.neo4j.kernel.TopLevelTransaction cannot be cast to javax.transaction.Transaction
    at neo.main(neo.java:22)

The java code is as follows
//import javax.transaction.Transaction;

import javax.transaction.Transaction;
import org.neo4j.cypher.ExecutionEngine;
import org.neo4j.cypher.javacompat.ExecutionResult;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.kernel.EmbeddedGraphDatabase;

public class neo {
    public static void main(String args[])
{
    final String DB_PATH = "/home/mkgs/Desktop/placement/";
    GraphDatabaseService graphDb;

    System.out.println(DB_PATH);

    graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);

    Transaction tx = (Transaction) graphDb.beginTx();

    try  {
        ExecutionEngine engine = new ExecutionEngine(graphDb, null);
        ExecutionResult result = (ExecutionResult) engine.execute("START
n=node(*) MATCH n-[r]-m RETURN type(r), count(*) ORDER BY count(*) desc");
        System.out.println(result);
    }

    finally {
        ((org.neo4j.graphdb.Transaction) tx).finish();
    }
}
}

A:

Don't use
import javax.transaction.Transaction;

but use
import org.neo4j.graphdb.Transaction;

This is what's causing your ClassCastException.


Q:

Buying Skyrim Legendary Edition while already having Skyrim

Hello guys I want to buy Skyrim Legendary Edition because it will be cheaper than buying all the DLCs.
But I already have Skyrim. What would happen if I buy Legendary Edition that including Skyrim. Will there be any problem or Steam add me only those DLC's ? [Sorry for English :D]

A:

Steam considers Skyrim and Skyrim: Legendary Edition to be separate games. You won't be able to gift or trade the Skyrim base game, but you can purchase it and you'll have two Skyrim games in your Steam Library. I've done this several times for Deluxe/GOTY editions as well.
Edit: You can tell steam considers them to be separate games because they exist separately in the store. (Search for Skyrim and you'll see what I mean.)


Q:

Meteor Dynamic Template Events

I'm new to Meteor, I could not find a sufficient answer to this but how does one go about referencing a Template's event handlers programmatically.
For example I would like to add or update or trigger an event defined in a template without actually as an example (pressing or clicking a button).
In the Template object I can see the events object below and can I access it but is this the right way?
Template.myTemplate._tmpl_data.events[]
Thanks!

A:

You can define the handler outside the event map and call it as a function:
someHandler = function(this, evt,tpl) {
  // do something with this, evt, and tpl
}

Template.myTemplate.events({
  'click .myButton': function(event,template) {
    var self = this;
    return someHandler(self, event,template);
  }
});

// Call someHandler whereever you want passing in whichever args you want

This is not a complete example, but should be able to get you going on some workable direction. If it works, please edit this answer to reflect a more complete example.


Q:

Unexpected invalid memory address or nil pointer dereference

I'm getting a runtime error for an invalid memory address.
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x10 pc=0x4e0f24]

goroutine 1192592 [running]:
panic(0x793540, 0xc420010040)
#011/usr/local/go/src/runtime/panic.go:500 +0x1a1
foobar/sd.(*Channel).Attributes(0x0, 0xc420110101, 0xc42278f9b0, 0x9)
#011/home/app/go/src/foobar/sd/channel.go:36 +0x54

channel.go looks like this:
35 func (m *Channel) Attributes() (*ChannelAttrs, error) {
36    redisHash := "sd:channels:" + m.hash
37
38    rc := m.ctx.RedisPool.Get()
39    values, err := redis.Values(rc.Do("HGETALL", redisHash))
40    rc.Close()
41    if err != nil {
42        return nil, err
43    }
44    attrs := ChannelAttrs{}
45    redis.ScanStruct(values, &attrs)
46    return &attrs, nil
47 }

How is it possible that the line 36 is causing this? Is it somehow possible for m to be nil? If so, how?
Note: hash is defined as string

A:

This means that Attributes is being called with receiver m as nil.
In principle methods can be called with nil receivers (and this may even be useful if they check for nil) - see here - but this particular method Attributes() is not designed to be called with a nil receiver, as m is being dereferenced without a nil check. This (method being called with a nil receiver m) is what is happening in your calling code.
See a simplified example on the playground here, and note that commenting out + m.hash makes the whole thing work fine, as here.
Code below:
package main

import (
    "fmt"
)

type Channel struct {
    hash string
}

func (m *Channel) Attributes() {
    r := "x" + m.hash
    fmt.Println(r)
}

func main() {
    var c *Channel
    c.Attributes()
}

The output of which is:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0x20131]

goroutine 1 [running]:
panic(0x102360, 0x1040a038)
    /usr/local/go/src/runtime/panic.go:500 +0x720
main.(*Channel).Attributes(0x0, 0x104000f0)
/tmp/sandbox285779060/main.go:12 +0x131
main.main()
    /tmp/sandbox285779060/main.go:18 +0x20


Q:

How should I practice the piano piece Fantaisie-Impromptu?

It has always been a childhood dream of mine
to play well the piano piece Fantaisie-Impromptu.
Unfortunately, I was not able to learn the piece with my piano teacher
while I was learning the piano.
Recently, as an adult who is almost 20 years removed from piano lessons,
I decided to try to learn the piece,
and I noticed that the piece is fairly difficult.
As explained by Wikipedia:

[Fantaisie-Impromptu] uses many cross-rhythms (the right hand plays sixteenth notes against the left hand playing triplets).

It's fairly easy for me to play
the right hand part and the left hand part separately,
but I find it very difficult to keep the correct rhythm
when I try to play both hands together.
In addition, most performers seem to play the piece very fast!
How should I practice this difficult piano piece?
Note: I do think that this is a piece that I should be able to learn
with a reasonable amount of practice,
as it was very easy for me to pick up easier pieces such as
The Piano Sonata No. 16 in C major, K. 545, by Wolfgang Amadeus Mozart
and Rondo Alla Turca.

A:

You could start by practising the cross-rhythms just as five-finger exercises, for example

Use a metronome to keep the main beats even. Don't try to space out all the notes "mathematically", just make sure the notes on the beats line up, and the ones in between are even. And don't try to practice this too slow - start at about MM 80 or 100. Going slower makes it harder, not easier.
When you can do that without too much effort, try playing scales and arpeggios using the same idea.
You might like to try the first few exercises here as well: http://imslp.org/wiki/51_Exercises,_WoO_6_(Brahms,_Johannes)
Then go back to the Chopin!

A:

Fantasie Impromptu contains polyrythms. A "Polyrythm"is the use of two different rythms playing together, and the Fantasie Impromptu also has a Polyrythm. The right hand plays semiquavers, while the left hand plays triplets. This piece is quite similar to both his Etude Op.25 No.1 and No.3.
You can take one part of these two pieces and practice it. So first you have to be comfortable with the rhythm, practice, practice, practice. From slow to fast. You can mark highlight notes from the treble and bass clef that are on the same beat. So every time you come across those notes, you can stomp your feet to indicate an accent. That goes to the rest of the piece.
Fantasie Impromptu is a fairly hard piece to learn just after learning a few Mozart pieces? Well that's a huge jump, I wish you all the best!

A:

I am doing this piece, and have "finished" the piece within 5 months (1h/day) and am right now polishing it. This is how I attempt most pieces. Note that this post is not a "for dummies" guide.
(Note 1 : Keep in mind that what makes this piece sound beautiful is that throughout the chaos of all the notes, there is an accented melody throughout the piece. )

Go slow! Correctness is more important than speed. However, do not go ridiculously slow, otherwise the piece ironically gets harder.
Practice the polyrhythm a lot. While playing, you can tell yourself "together, right, left, right, left, right, (cont...) "
As you get to the section where there there are high notes and notes an octave lower, know that the accents will be easier to play when the piece is faster.
At this point, hopefully, you are somewhat proficient in the first section (the song is in an A-B-A format). Aim to speed up the first section until you can hear the accent/melody. Add whatever dynamics in :)
Work on the part B; that is, the coordination easiest part of the song. This song requires a significant amount of endurance so your fingers don't die. Use this section as a rest period (but remember, there are occasional trills).
Again, the second section is just like the first, but this time, the polyrhythm is gone at the end.

Remember to add the following when you feel that you are ready:

dynamics (gradual volume changes and the pp and ff)
slurs
bring out the accent/melody
tempo changes


Q:

Why is an antipodal-symmetrically colored circle guaranteed to have an odd number of multicolored edges?

I'm reading a proof of 2D Tucker's Lemma.  It asserts the following claim without proof:
Drop points on a circle in antipodal fashion (i.e. if there is a point at position $p$, then there also must be a point on the other end of the diameter through $p$).  Label each point on the circle with one element of the set $\{-1, 1, -2, 2\}$ such that if a point is labeled $x$, then its antipodal point is labeled $-x$.  Conclusion: If no arcs have endpoints labeled $(-1, 1)$ or $(-2, 2)$ (in either order), then there are an odd number of arcs labeled $(-1, 2)$.
I can't figure out why this is true.  Any ideas?

A:

If two vertices labelled $1$ are adjacent, collapse them to a single vertex labelled $1$, and collapse the antipodal vertices to a single vertex labelled $-1$. Repeat until there are no adjacent vertices labelled $1$. Then do the same thing with adjacent vertices labelled $2$. You still have a properly labelled division of the circle, and all edges now have labels $\langle -1,2\rangle$, $\langle 1,-2\rangle$, $\langle 1,2\rangle$, or $\langle -1,-2\rangle$ in one order or the other. I’ll refer to an edge whose endpoints are $-1$ and $2$ (in either order) as an edge of type $\langle -1,2\rangle$, and similarly for the other three types. As you traverse the circle, the absolute values of the labels now alternate between $1$ and $2$.
Suppose that there is no edge of type $\langle 1,2\rangle$; then every edge is a sign-changing edge. But every edge also changes the absolute value of the label, so either the labels of the vertices are alternately $1$ and $-2$, or they are alternately $-1$ and $2$, neither of which is possible.
Thus, there is an edge $e$ of type $\langle 1,2\rangle$; its antipodal edge $e'$ is a type $\langle -1,-2\rangle$ edge. Consider the arc of the circle from the $2$ vertex of $e$ to the $-1$ vertex of $e'$. This arc must have an odd number of edges, since the absolute values of the labels at its ends are different. Their signs are also different, so there must be an odd number of sign-changing edges, i.e., edges of types $\langle -1,2\rangle$ and $\langle 1,-2\rangle$. Suppose that there are $m$ edges of type $\langle -1,2\rangle$ and $n$ of type $\langle 1,-2\rangle$. Then the antipodal arc has $n$ of type $\langle -1,2\rangle$ and $m$ of type $\langle 1,-2\rangle$, and $m+n$ is odd, so there are an odd number of each of the types $\langle -1,2\rangle$ and $\langle 1,-2\rangle$.


Q:

Order by clause confusion

Below are the contents of sid column in a table ( where "S05201215" is
a fixed string and remaining part of the Sring is a sequence of
numbers)
S052012151
S052012152
S052012153
S052012154
S052012155
S052012156

I want to sort the the remaining part of the string (i.e.
the numbers that i've appended to the string S05201215  in
descending order ..  what modifications should i do to the below query
to get desired output?
SELECT `sid` FROM `mytable` order by SUBSTRING(`sid`,10,length(`sid`))

A:

To sort in descending order, just add "DESC" to the end of your ORDER BY:
SELECT `sid`
FROM `mytable`
ORDER BY SUBSTRING(`sid`, 10, length(`sid`)) DESC

However, if the values of sid are of different lengths, you are probably going to want to cast the values to a numeric type before sorting:
SELECT `sid`
FROM `mytable`
ORDER BY CAST(SUBSTRING(`sid`, 10, length(`sid`)) AS SIGNED) DESC


Q:

Undefined offset: 1 Laravel/PHP uploading CSV

I'm using a package > http://csv.thephpleague.com/
But I'm getting a Undefined offset: 1 when uploading, although the CSV does upload and works this error is thrown which obviously I don't the client see or think there's a problem.
Here's the method in question:
public function postUpload()
{
    $file = Input::file('file');
    $name = time() . '-' . $file->getClientOriginalName();
    $moved = $file->move(public_path() . '/uploads/CSV', $name);

    DB::table('wc_program_1')->truncate();

    $csv = new Reader($moved);
    $csv->setOffset(0); //because we don't want to insert the header
    $nbInsert = $csv->each(function ($row) use (&$sth) {
        DB::table('wc_program_1')->insert(
            array(

                'Road' => $row[0],
                'Parish' => $row[1],
                'WorkType' => $row[2],
                'TrafficManagement' => $row[3],
                'Duration' => $row[4],
                'Start' => $row[5]
            )
        );
        return true;
    });

    return Redirect::to('admin/programmes')->with('flash_success', 'Upload completed & new data inserted.');
}

And here the table structure:

A:

There must be more to the error? Undefined Offset: 1 in somefile.php on line #4323 or w/e
Anyways it references a missing index from an array.
The only array I see is $row so $row[1] does not exist.
If you just want to quickly patch it then I suggest this:
'Parish' => (isset($row[1]) ? $row[1] : ''),

It would probably be a good idea to do this for all of them such as:
'Road' => (isset($row[0]) ? $row[0] : ''),


Q:

Discrete Opamp SMPS design

I'm an electronic eng student and for a design project I need to design a switch mode power supply. Catch is I can't use any off the shelf SMPS ICs, only opamps and logic. Rough specifications are 0-5v adjustable output, +-5% regulation, 20-30VDC input, 250mA constant current/protection. Can anyone point me in the direction of some resources for discrete SMPS design?

A:

With the spec you have said (+/-5% regulation and output no greater than 250mA) there are fairly simple design topologies that you can use. Consider the synchronous buck regulator - it drives a top transisitor and a bottom transistor and produces a square wave output whose mark-space ratio largely defines the output voltage: -
Output voltage  = Input voltage x mark-space ratio
This means you find an op-amp circuit that can produce a variable mark-space ratio signal (hell even a 555 can do this) and drive two MOSFETs from it - one a P channel up to the +tive rail and one an N channel down to the negative/ground rail. The hardest bit in this is driving the P channel MOSFET because it requires a level translation but I'm not going to all the work for you!!!
You also need to ensure that the square wave (variable duty cycle) that drives the MOSFETs is adjusted (for each MOSFET) to create a few tens of nano seconds "dead-band" because you don't want the top MOSFET turning on while the N channel is in the process of turning off and vice versa.
This is easily accomplished with a couple of logic gates and a small RC delay.
I've suggested a synchronous buck regulator because there are fewer things it has to deal with when you apply close-loop control via an op-amp. A non-synchronous buck uses a flyback diode and this means that to keep its output voltage constant, a variable load situation calls for cleverer stability in the design. A synchro buck doesn't much need to worry about the load varying because it follows the formula stated above largely.
Where both have issues is with a varying input voltage but this is usually slow moving so any half-decent control op-amp can do the job of keeping it stable. The beauty of a synch buck is that you can use the level of the input voltage to "pre-adjust" the mark-space ratio. Again this means that the op-amp that does the final sanitizing of the output voltage has to do very little and is really very unlikely to go unstable.
Going into instability is a problem that can sometimes be hard to solve so I'm suggesting the synch buck method because, with input voltage compensation (feed-forward it's called) you might get away without any negative feedback (given your moderate specification).


Q:

Is it possible to perform a batch upload to amazon s3?

Does amazon s3 support batch uploads?
I have a job that needs to upload each night ~100K of files that can be up to 1G but is strongly skewed towards small files (90% are less than 100 bytes and 99% are less than 1000 bytes long).
Does the s3 API support uploading multiple objects in a single HTTP call?
All the objects must be available in S3 as individual objects. I cannot host them anywhere else (FTP, etc) or in another format (Database, EC2 local drive, etc). That is an external requirement that I cannot change.

A:

Alternatively, you can upload S3 via AWS CLI tool using the sync command.

aws s3 sync local_folder s3://bucket-name

You can use this method to batch upload files to S3 very fast.

A:

Does the s3 API support uploading multiple objects in a single HTTP call?

No, the S3 PUT operation only supports uploading one object per HTTP request.
You could install S3 Tools on your machine that you want to synchronize with the remote bucket, and run the following command:
s3cmd sync localdirectory s3://bucket/

Then you could place this command in a script and create a scheduled job to run this command each night.
This should do what you want.
The tool performs the file synchronization based on MD5 hashes and filesize, so collision should be rare (if you really want you could just use the "s3cmd put" command to force blind overwriting of objects in your target bucket).
EDIT: Also make sure that you read the documentation on the site I linked for S3 Tools - there are different flags needed for whether you want files deleted locally to be deleted from the bucket or ignored etc.


Q:

Makefile vpath %.o not finding obj files

I'm using the following vpath to attempt locating my $(OBJ) files:
vpath %.o ./lib/obj

And my target is setup as such:
# Link target
link:
    @echo "\nLinking files"
    $(CC) $(LINK_FLAGS) -o main.elf $(OBJS)

When looking at the output, I get (for all the *.o files):
...error: misc.o: No such file or directory

My project structure looks as follows:
.
├── Makefile
├── inc
│   └── main.h
├── lib
│   ├── inc
│   │   ├── cmsis
│   │   │   ├── arm_common_tables.h
│   │   │   ├── ...
│   │   ├── peripherals
│   │   │   ├── misc.h
│   │   │   ├── ...
│   │   └── stm32f4xx
│   │       ├── stm32f4xx.h
│   │       ├── ...
│   ├── obj
│   │   ├── misc.o
│   ├── src
│   │   ├── peripherals
│   │   │   ├── misc.c
│   │   │   ├── ...
│   │   └── system_stm32f4xx.c
│   └── startup_stm32f4xx.s
├── src
│   └── main.c
└── stm32f4.ld

Why are my .o files not being found?
Full output for reference:

arm-none-eabi-gcc -T"stm32f3.ld" -nostartfiles -Wl,-Map,"main.map"
  -mcpu=cortex-m4 -mthumb -g3 -gdwarf-2 -L"./" -o main.elf misc.o stm32f4xx_adc.o stm32f4xx_can.o stm32f4xx_crc.o stm32f4xx_cryp.o
  stm32f4xx_cryp_aes.o stm32f4xx_cryp_des.o stm32f4xx_cryp_tdes.o
  stm32f4xx_dac.o stm32f4xx_dbgmcu.o stm32f4xx_dcmi.o stm32f4xx_dma.o
  stm32f4xx_exti.o stm32f4xx_flash.o stm32f4xx_fsmc.o stm32f4xx_gpio.o
  stm32f4xx_hash.o stm32f4xx_hash_md5.o stm32f4xx_hash_sha1.o
  stm32f4xx_i2c.o stm32f4xx_iwdg.o stm32f4xx_pwr.o stm32f4xx_rcc.o
  stm32f4xx_rng.o stm32f4xx_rtc.o stm32f4xx_sdio.o stm32f4xx_spi.o
  stm32f4xx_syscfg.o stm32f4xx_tim.o stm32f4xx_usart.o stm32f4xx_wwdg.o
  system_stm32f4xx.o

A:

$(OBJS) is just a variable, and gets expanded as text.  When it appears in the text of the command in your link rule, it is simply expanded as text.
vpath searches are applied to prerequisites, so you will have to arrange for your $(OBJS) to appear as prerequisites to your link rule and for the rule's commands to use those prerequisites (via automatic variables, rather than just using $(OBJS) directly).
So your rule needs to look more like
# Link target
link: main.elf

main.elf: $(OBJS)
    @echo "\nLinking files"
    $(CC) $(LINK_FLAGS) -o $@ $+

(I have also taken the liberty of writing out the file generated (main.elf) as the non-phony target of an intermediate rule.  Making these things explicit to Make is generally a good idea.)

A:

Although the other answers are correct in the details of what they say, there is a larger point here: it is not possible to use VPATH/vpath reliably to find derived files, like .o files that you build from your makefile.  VPATH/vpath is only useful for finding source files, such as .c files.
You should read http://make.mad-scientist.net/vpath.html

A:

vpath just tells make where to find the files, not the compiler/linker.  You have to get make to tell the compiler/linker where it found them.  The easiest way is to make them proper dependencies (so they get rebuilt before linking) and then use $^:
# Link target
link: $(OBJS)
        @echo "\nLinking files"
        $(CC) $(LINK_FLAGS) -o main.elf $^


Q:

MD5 and Base64 encoding mismatch in R and Java/JavaScript

I am trying to encode in base64 a string that was calculated from MD5 function in R. But the result seems to be different than what I am getting Scala/Java/JavaScript:
Scala/Java/JavaScript for an empty string is giving as a result: 1B2M2Y8AsgTpgAmY7PhCfg==
import java.security.MessageDigest
import org.apache.commons.codec.binary.Base64

object Test extends  App {

  val empty = ""
  val md5 = MessageDigest.getInstance("MD5").digest(empty.getBytes("UTF-8"))

  val base64 = new String(Base64.encodeBase64(md5))
  println(base64)

  //Result: 1B2M2Y8AsgTpgAmY7PhCfg==

}

Similarly, in JavaScript, see https://www.npmjs.com/package/js-md5
md5.base64(''); // 1B2M2Y8AsgTpgAmY7PhCfg==

But in R, I am getting a different result: ZDQxZDhjZDk4ZjAwYjIwNGU5ODAwOTk4ZWNmODQyN2U=
> library(digest)
> md5 <- digest("", algo="md5", serialize=F)
> md5 [1] "d41d8cd98f00b204e9800998ecf8427e"
> base64encode(md5) [1] "ZDQxZDhjZDk4ZjAwYjIwNGU5ODAwOTk4ZWNmODQyN2U="

I am wondering if md5 does not encode in hex?

A:

When you do the digest, just ask for the raw vector and base64 encode that (add raw=TRUE).
library(digest)
md5 <- digest("", algo="md5", serialize=FALSE, raw=TRUE)
openssl::base64_encode(md5)
# [1] "1B2M2Y8AsgTpgAmY7PhCfg=="


Q:

Remember "repeat last change" on exit

Vim's . (repeat last change) is a very useful feature.
Is there any way to remember the last change on exit (similar to how you can set up your vimrc and viminfo files to remember the last file position on exit)?
I'd like to be able to run Vim from the command line to open a file, hit ., and have Vim make the same change I just made to the last file I edited.

A:

No. But you can record your change in a register and play it back later:
qa              "start recording into register a
(do your thing)
q               " stop recording
@a              " play back the macro saved in register a

Or open your files from the same Vim session.


Q:

Ember version 2.12.2: view isn't showing up

I am writing a research paper and as a part of it I am doing a performance benchmark between Ember's KVO change detection method and React's Virtual DOM change detection method.
I made 2 identical applications - one with Ember and one with React, but I realized afterwards that I've used an old version of ember(1.8.0). I am now trying to change and refactor it to version 2.12.2.
For now I replaced ObjectControllers with Controllers.
Now the problem is - when application is initialized, there should be a link that when pressed shows tweet list. Now with v2.12.2. the link is not shown, I am not getting any error messages.

Here is a jsfiddle of the v2.12.2 version of this app, which does not work fiddle
Here is a fiddle of the v1.8.0 version of this app, which works fiddle
Any hints on where is the problem?

A:

Looks like it's a combination of JSFiddle loading resources in the wrong order plus invalid HTML in your Handlebars template. Here's a working fiddle.
Basically, I moved the Ember.js files from "External Resources"  into  tags, and then corrected an unclosed
 and a closing  (which is invalid).
Also, please note that {{bind-attr}} is deprecated


Q:

Python for loop for list

I have a list containing some integer values.
My list is l = [5,10,15,25,30,45].
I want to write a program that the values in list is between 5 to 35
list1 = [15,35]
list2 = ['Height','Weight','5','10','25','30','40']
res = [int(ele) if ele.isdigit() else ele for ele in list2]
print([ x for x in res if type(x)==int ])

this is the code that I written,now I want to compare list 1 and list 2 , then print values in list 2 of range in the first list

A:

You can use range function
>>> l = [5,10,15,25,30,45]
>>> result = [i for i in l if i in range(5,36)]
>>> result
[5, 10, 15, 25, 30]


Q:

Read each value one by one in a column with respect to another values in another column from a text file

For example, I have a text file like this. There are three columns.
data 5 0.1
data 4 0.2
data 2 0.3
data 1 0.5

Codes I have:
for line in open("myfile.txt", "r").readlines():
    line = line.split()
    if len(line)>1 and line[0] == 'data':
        time = line[1]
        volume = line[2]
        volume_per_time=float(volume)/float(time)
print(volume_per_time)

I want to print the volume_per_time in a while loop. i.e. I want to call the 3nd column 1st value with respect to 2nd column 1st value. And then one by one with loop function.

A:

you can insert the calculated value to an array and use it for the plotting.
volume_per_time = []
for line in open("myfile.txt", "r").readlines():
    line = line.split()
    if len(line)>1 and line[0] == 'data':
        time = line[1]
        volume = line[2]
        volume_per_time.append(float(volume)/float(time))

print(volume_per_time)


Q:

What is the ideal way to send a date parameter over a GET request in Play Framework?

I am new to Play Framework. I am able to send simple data types like string, integer etc directly via the request and access them in the Back end Java method.
When I try doing this in the route file,
GET    /food/fetchMealInfo/:noOfDays/:dateSelected     controllers.trackandplan.FoodController.fetchMealInfo(noOfDays : Integer, dateSelected : Date)

I am getting an error saying
Compilation error
not found: type Date

What is the correct, safe and clean way to transfer a date object from a front end AngularJS application to the Java application in Play Framework.
Please guide.

A:

You have a couple options. The slightly easier way to understand is to simply transmit the date/time as a Long (unix timestamp), and convert it to a Date in the controller method.
GET    /food/fetchMealInfo/:noOfDays/:dateSelected     controllers.trackandplan.FoodController.fetchMealInfo(noOfDays: Integer, dateSelected: Long)

public static Result fetchMealInfo(Integer noOfDays, Long dateSelected) {
    Date date = new Date(dateSelected.longValue());
    ...
}

The more sophisticated way would be to use a PathBindable, which would allow you to use Date within the routes file itself. However, you would still need to transmit the Date as a Long (the PathBindable would make the conversion if possible). Unfortunately, since we obviously don't have control over Date, we have to implement PathBindable in Scala, and not Java (Java would require implementing an interface for Date, which we can't).
app/libs/PathBinders.scala
package com.example.libs

import java.util.Date
import play.api.mvc.PathBindable
import scala.util.Either

object PathBinders {

    implicit def bindableDate(implicit longBinder: PathBindable[Long]) = new PathBindable[Date] {

        override def bind(key: String, value: String): Either[String, Date] = {
            longBinder.bind(key, value).right.map(new Date(_))
        }

        override def unbind(key: String, date: Date): String = key + "=" + date.getTime().toString

    }

}

In order for the routes file to be able to pick this up, you'll need to add the following to your build.sbt file:
PlayKeys.routesImport += "com.example.libs.PathBinders._"

PlayKeys.routesImport += "java.util.Date"

Now you can use Date within your routes file (as Long), without the need to handle it specially for every method that uses it.
GET    /food/fetchMealInfo/:noOfDays/:dateSelected     controllers.trackandplan.FoodController.fetchMealInfo(noOfDays: Integer, dateSelected: Date)

Note: This might not compile straight away if you're using an older Play version. I tested it with Play 2.3.8 and sbt 0.13.5.
It is also possible to modify the PathBindable I made here to use an underlying String instead, and accept a specific date format.
package com.example.libs

import java.util.Date
import java.text.SimpleDateFormat
import play.api.mvc.PathBindable
import scala.util.{Either, Failure, Success, Try}

object PathBinders {

    implicit def bindableDate(implicit stringBinder: PathBindable[String]) = new PathBindable[Date] {

        val sdf = new SimpleDateFormat("yyyy-MM-dd")

        override def bind(key: String, value: String): Either[String, Date] = {
            for {
                dateString <- stringBinder.bind(key, value).right
                date <- Try(sdf.parse(dateString)).toOption.toRight("Invalid date format.").right
            } yield date
        }

        override def unbind(key: String, date: Date): String = key + "=" + sdf.format(date)

    }

}


Q:

Is it possible to have have one login link to many other sites?

So a client has asked me if I could build an interface where they would have their account and from there be able to link and see all there other accounts on other sites, like sportsbook.com, etc...
I would create this in php and got somewhat of an idea.  If you know a great way that I could go off this please let me know!

A:

In principle this is possible by simulating the form post of the login screen for the other sites.  For example, if you wanted to login to mysite.com, you would first look at the login page for that site.  It will probably have something like this:
<form action="mysite.com/logincheck.aspx">
    .. stuff here
    Username: <input type="text" name="theusername" />
    .. more stuff here
    Password: <input type="password" name="secretpassword" />
</form>

The key pieces of information here are:

the action tag (mysite.com/logincheck.aspx), which is the page handling the login request
the name of the user input field (theusername)
the name of the password input field (secretpassword)

Simulating a form request is relatively easy.  You can build your own copy of the form that posts directly to the site with the client's correct credentials pre-filled in (behind their initial password login), or use the concepts from this question, for example.  You could do it as a tabbed interface with iframes or something to that effect.


Q:

Basic update database table using php question

I seem to be missing something quite fundamental here and yet my code doesn't seem to be any different to any of the numerous online tutorials that I have looked at.
What I would like is for someone to look at this and say....Oh you have forgotten to...etc;
This is what I have on a separate update page which is intended to perform the update then cycle back to the main admin page:
require_once('../Connections/MyConn.php');
$sql_statement = "UPDATE skyscrapers SET ";
$sql_image = "Ad_image = '" . $_REQUEST['image'] . "', ";
$sql_expire = "Ad_Expires = '" . $_REQUEST['expire'] . "'";

$result = mysql_query($sql_statement . $sql_image . $sql_expire . " WHERE Ad_ID=" . $_REQUEST['ADID']);
if (!$result) {
  echo("
Error performing query: " . mysql_error() . "
");
  exit();
}

mysql_close ($MyConn);
header("location:Admin_skyscrapers.php");

However when I run this I get the following error:-
"Error performing query: No database selected"
Well, haven't I selected the database in the connection script which already works everywhere else?
I realise the code isn't very pretty and I am being naughty using the url to pass variables at the moment - I do promise to change this when I get it to work :)
So, any pointers would be helpful, thanks in advance.
Edit to add...
This is the connection script with the sensitive stuff redacted:-
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_MyConn = "*************.co.uk";
$database_MyConn = "db**********";
$username_MyConn = "dbo*********";
$password_MyConn = "*****";
$MyConn = mysql_pconnect($hostname_MyConn, $username_MyConn, $password_MyConn) or trigger_error(mysql_error(),E_USER_ERROR);

A:

This may or may not be declared in your MyConn.php but all you need is a line:
mysql_select_db($db_name);

Where $db_name is the name of your database.
This should come before you attempt to execute the query.


Q:

IE7-8 issue with jQuery click

I'm really just lost as to why IE would throw a fit. It works in Chrome and IE9. Here's my script:
var utilityNav = function() {
$('#head-nav a').click(function(e) {
    e.preventDefault();

    $('#head-nav a').removeClass('head-link-active').next('div').removeClass('shadow').slideUp('fast').css('z-index', '7999');
    if ($(this).next('div').is(':hidden')) {
        var linkPos = $(this).position().left + $(this).width()/2 + 4;
        $(this).addClass('head-link-active');
        $(this).next('div').addClass('shadow').slideDown().css('left', linkPos + 'px').css('z-index', '8000');
    }
});
$('.utility-three').children('.utility-three-block').eq(1).addClass('borders');
};

I don't think anything is syntactically wrong with it, but I'd really appreciate some help. Thanks.

A:

Ended up being a code conflict with bxSlider. Thanks for the help.


Q:

Laravel combining has() and whereHas()

I'm trying to combine some methods in Eloquent but can't seem to get it together properly. I have a query that pulls all items where the hasMany count is 0.
So basically I want to know where the relationship is "empty". In this case I have an item with audio samples. So, I want to get items where there are no audio samples yet.
return $this->hasMany('App\Models\Item')->has('audios', '=', 0);

This works completely fine. However I also want to add a filter based on male and female audio samples. If I use whereHas I can get the filter but only directly and can't get the has 0 clause on it.
return $this->hasMany('App\Models\Item')->whereHas('audios', function ($q) {
    $q->where('gender', 'female');
});

But no I want combine them and can't figure this bit out. So "get all items with no female audio samples".
Not a lot of documentation on these except in the trivial case, I tried a few variations but it's not coming up right. Just completely empty sets or only female or male directly without that "empty" 0 set.
Here is the query I would like to get:
SELECT *
FROM `items`
WHERE (
    SELECT COUNT(*)
    FROM `audios`
    WHERE `audios`.`item_id` = `items`.`id`
    AND `audios`.`gender`='female'
) = 0

A:

whereHas, doesntHave etc are all methods that, in the end, call has. If you look at the signature of whereHas you can see that it allows a count to be passed as well:
public function whereHas($relation, Closure $callback, $operator = '>=', $count = 1)

So you could do that, or just use whereDoesntHave:
return $this->hasMany('App\Models\Item')->whereDoesntHave('audios', function ($q) {
    $q->where('gender', 'female');
});


Q:

How do I show components below textinput when keyboard is open in react native?

I want the tags below the interests textbox to display while the keyboard is open. The chip components are the tags input from the react native paper library. I've tried using scrollview, keyboardavoidingview, and keyboardawarescrollview to get the tags to display while the keyboard is open but none of the views fixed the issue. What would I be missing or doing wrong?
  GetTags = () => {
    const tagsComponent = [];
    if (typeof this.state.interests !== "undefined") {
      for (let i = 0; i < this.state.interests.length; i++) {
        tagsComponent.push(
          <Chip
            key={i}
            style={{ margin: 3 }}
            onClose={() => {
              this.setState(prevState => ({
                interests: prevState.interests.filter(
                  x => x !== prevState.interests[i]
                )
              }));
            }}
          >
            {this.state.interests[i]}
          </Chip>
        );
      }
    }
    return tagsComponent;
  };

  render() {
    const displayTags = this.GetTags();
    return (
      <ScrollView style={{ marginTop: 20 }} keyboardShouldPersistTaps="always">
        <View
          style={{
            flex: 1,
            alignItems: "center",
            justifyContent: "center"
          }}
        >
          {this.state.profile ? (
            <Avatar
              size="xlarge"
              rounded
              source={{ uri: this.state.profile }}
              showEditButton
              onEditPress={() => this.onChooseImageUpload()}
            />
          ) : (
            <Avatar
              {...this.state.avatarError}
              size="xlarge"
              rounded
              icon={{
                name: "user",
                type: "font-awesome"
              }}
              showEditButton
              onEditPress={() => this.onChooseImageUpload()}
            />
          )}
          <Text
            style={{
              fontWeight: "500",
              fontSize: 20,
              marginTop: 8,
              marginRight: "70%",
              color: "#5b5b5b"
            }}
          >
            About me
          </Text>
          <TextInput
            style={{
              borderColor: Themes.layoutTheme,
              borderWidth: 1,
              width: "100%",
              marginTop: 5,
              padding: 5,
              textAlignVertical: "top"
            }}
            multiline
            numberOfLines={7}
            placeholder="Type something about yourself..."
            onChangeText={text => this.setState({ bio: text })}
            value={this.state.bio}
          />
          <View style={{ flexDirection: "row" }}>
            <Text
              style={{
                fontWeight: "500",
                fontSize: 20,
                marginTop: 22,
                color: "#5b5b5b"
              }}
            >
              Interests
            </Text>
            <RNPTextInput
              ref={input}
              style={{
                height: 45,
                marginTop: 10,
                marginRight: 82,
                marginLeft: 10
              }}
              underlineColor={Themes.primaryTheme}
              placeholder="Example: Skydiving,"
              theme={{ colors: { primary: Themes.primaryTheme } }}
              onChangeText={text => {
                if (text.endsWith(",")) {
                  const newText = text.replace(",", "");
                  if (typeof this.state.interests === "undefined") {
                    this.setState({ interests: [newText] });
                  } else {
                    this.setState(prevState => ({
                      interests: [...prevState.interests, newText]
                    }));
                  }
                  input.current.clear();
                }
              }}
            />
          </View>
          <View
            style={{
              marginTop: 15,
              flexDirection: "row",
              flexWrap: "wrap",
              alignItems: "flex-start"
            }}
          >
            {displayTags}
          </View>
          {this.state.loading ? (
            <Progress.Bar
              style={{ marginTop: 25 }}
              indeterminate
              color={Themes.primaryTheme}
            />
          ) : (
            <Button
              raised
              containerStyle={{
                width: "25%",
                marginTop: 20
              }}
              buttonStyle={{ backgroundColor: Themes.primaryTheme }}
              title="Save"
              onPress={() => {
                if (fireStoreDB.getAvatar == null) {
                  this.setState({
                    avatarError: {
                      containerStyle: { borderWidth: 1, borderColor: "red" }
                    }
                  });
                } else {
                  fireStoreDB
                    .updateProfile(this.state.bio, this.state.interests)
                    .then(() => this.props.navigation.navigate("Home"));
                }
              }}
            />
          )}
        </View>
      </ScrollView>
    );
  }

A:

I solved the issue by wrapping content inside KeyboardAvoidingView with the padding behavior and displaying the chips above the text input.
<KeyboardAvoidingView style={{ flex: 1 }} behavior="padding">
  <Content>
    <View style={{ marginTop: "7%" }} />
    {this.state.profile ? (
      <Avatar
        size="xlarge"
        rounded
        containerStyle={{ alignSelf: "center" }}
        source={{ uri: this.state.profile }}
        showEditButton
        onEditPress={() => this.onChooseImageUpload()}
      />
    ) : (
      <Avatar
        {...this.state.avatarError}
        size="xlarge"
        rounded
        containerStyle={{ alignSelf: "center" }}
        icon={{
          name: "user",
          type: "font-awesome"
        }}
        showEditButton
        onEditPress={() => this.onChooseImageUpload()}
      />
    )}
    <Text
      uppercase={false}
      style={{
        fontWeight: "500",
        fontSize: 20,
        marginTop: "6%",
        marginLeft: "1%",
        color: "#5b5b5b"
      }}
    >
      About me
    </Text>
    <TextInput
      style={{
        borderColor: Themes.layoutTheme,
        borderWidth: 1,
        width: "100%",
        marginTop: 5,
        padding: 5,
        textAlignVertical: "top"
      }}
      multiline
      numberOfLines={7}
      placeholder="Type something about yourself..."
      onChangeText={text => this.setState({ bio: text })}
      value={this.state.bio}
    />
    <Text
      style={{
        fontWeight: "500",
        fontSize: 20,
        marginTop: 22,
        marginLeft: "1.5%",
        color: "#5b5b5b"
      }}
    >
      Interests
    </Text>
    <View
      style={{
        marginTop: 15,
        flexDirection: "row",
        flexWrap: "wrap",
        alignItems: "flex-start"
      }}
    >
      {displayTags}
    </View>
    <Input
      ref={input}
      style
      inputContainerStyle={{
        borderBottomColor: Themes.layoutTheme
      }}
      placeholder="What, are, your, interests"
      onChangeText={text => {
        if (text.endsWith(",")) {
          const newText = text.replace(",", "");
          if (typeof this.state.interests === "undefined") {
            this.setState({ interests: [newText] });
          } else {
            this.setState(prevState => ({
              interests: [...prevState.interests, newText]
            }));
          }
          input.current.clear();
        }
      }}
    />
  </Content>
</KeyboardAvoidingView>


Q:

How can i create a video overlay?

Hi i have seen a few blogs that doe this but i was wondering how they got it done, I don't know exactly what to look up concerning this.
Check out this link http://concreteloop.com/2013/02/video-nicki-minaj-french-montanas-freaks-behind-the-scenes
notice that they have an image and a playbutton, and once you click the play button, the image disappears and the video plays. I was wondering if anyone knows where i can learn to create this function.

A:

This is a simple sample of what you're trying to achieve. Having the video initially hidden, and then shown and played when the user clicks on the image.

    <video width="320" height="240" controls style="display: none;">
        <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4">
    </video>


Q:

Best practice to call webservices from Magento custom module

Can anybody tell me, what will be the the best practice to call webservices from a Magento custom module?
Is there any functionality in the Magento / Zend Framework? Or should I use standard PHP functionality?

A:

Zend Framework provides clients for REST and SOAP webservices.
Check lib/Zend/Rest and lib/Zend/Soap


Q:

What is the right approach to update many records in MongoDB using Mongoose

I am pulling some records from MongoDB using Mongoose, importing them into another system and then I would like to set status (document attribute) for all these documents to processed.
I could find this solution: Update multiple documents by id set. Mongoose
I was wondering if that is the right approach, to build up a criterion consisting of all document ids and then perform the update. Please also take into account a fact that it's going to be many documents.
(What is the limit of the update query? Couldn't find it anywhere. Official documentation: http://mongoosejs.com/docs/2.7.x/docs/updating-documents.html)

A:

The approach of building up a criterion consisting of all document ids and then performing the update is bound to cause potential issues. When you iterate a list of documents sending an update operation with each doc, in Mongoose you run the risk of blowing up your server especially when dealing with a large dataset because you are not waiting for an asynchronous call to complete before moving on to the next iteration. You will be essentially building a "stack" of unresolved operations until this causes a problem - Stackoverflow.
Take for example, supposing you had an array of document ids that you wanted to update the matching document on the status field:
const processedIds = [
  "57a0a96bd1c6ef24376477cd",
  "57a052242acf5a06d4996537",
  "57a052242acf5a06d4996538"
];

where you can use the updateMany() method
Model.updateMany(
  { _id: { $in: processedIds } },
  { $set: { status: "processed" } },
  callback
);

or alternatively for really small datasets you could use the forEach() method on the array to iterate it and update your collection:
processedIds.forEach(function(id)){
  Model.update({ _id: id}, { $set: { status: "processed" } }, callback);
});

The above is okay for small datasets. However, this becomes an issue when you are faced with thousands or millions of documents to update as you will be making repeated server calls of asynchronous code within the loop.
To overcome this use something like async's eachLimit and iterate over the array performing a MongoDB update operation for each item while never performing more than x parallel updates the same time.

The best approach would be to use the bulk API for this which is extremely efficient in processing updates in bulk. The difference in performance vs calling the update operation on each and every one of the many documents is that instead of sending the update requests to the server with each iteration, the bulk API sends the requests once in every 1000 requests (batched).
For Mongoose versions >=4.3.0 which support MongoDB Server 3.2.x, you can use bulkWrite() for updates. The following example shows how you can go about this:
const bulkUpdateCallback = function(err, r){
  console.log(r.matchedCount);
  console.log(r.modifiedCount);
}

// Initialize the bulk operations array
const bulkUpdateOps = [], counter = 0;

processedIds.forEach(function (id) {
  bulkUpdateOps.push({
    updateOne: {
      filter: { _id: id },
      update: { $set: { status: "processed" } }
    }
  });
  counter++;

  if (counter % 500 == 0) {
    // Get the underlying collection via the Node.js driver collection object
    Model.collection.bulkWrite(bulkUpdateOps, { ordered: true, w: 1 }, bulkUpdateCallback);
    bulkUpdateOps = []; // re-initialize
  }
})

// Flush any remaining bulk ops
if (counter % 500 != 0) {
  Model.collection.bulkWrite(bulkOps, { ordered: true, w: 1 }, bulkUpdateCallback);
}

For Mongoose versions ~3.8.8, ~3.8.22, 4.x which support MongoDB Server >=2.6.x, you could use the Bulk API as follows
var bulk = Model.collection.initializeOrderedBulkOp(),
    counter = 0;

processedIds.forEach(function(id) {
    bulk.find({ "_id": id }).updateOne({
        "$set": { "status": "processed" }
    });

    counter++;
    if (counter % 500 == 0) {
        bulk.execute(function(err, r) {
           // do something with the result
           bulk = Model.collection.initializeOrderedBulkOp();
           counter = 0;
        });
    }
});

// Catch any docs in the queue under or over the 500's
if (counter > 0) {
    bulk.execute(function(err,result) {
       // do something with the result here
    });
}

A:

You can use {multi: true} option in your update query for bulk update.
Example:
employees.update({ _id: { $gt: 3 } },{$inc: { sortOrder: -1 }},{'multi':true});

The above code in mongoose is equivalent to the below code in mongodb:
db.employees.updateMany({ _id: { $gt: 3 } },{$inc: { sortOrder: -1 }});


Q:

Why is the constructor function for a custom class getting called multiple times?

I have created a custom class (the .as is below:). It exists throughout my main timeline in three instances (panel1, panel2, and panel3), and has only one keyframe at present.
When I debug my file, in Frame 1 the constructor function is called for each instance. Cool. However, a little later the constructor function is called AGAIN for each instance, wiping out any changes I have made.
The instances are all placed on the stage by dragging them from the library. There are no " = new Scorepanel() lines in my scripts.
What triggers this and how can I prevent it?
--Ken (incredibly frustrated) Franklin
{
import flash.display.MovieClip;
import fl.text.TLFTextField;

public class scoreunit extends MovieClip
{
    private var team:String = "WHOAMI";
    private var points:Number = 0;
    private var scorevalue:String;
    private var teamname:String;
    private var inited:Boolean = false;

    function scoreunit()
    {
        if (! inited)
        {
            this.teamname = team;
            this.scorevalue = String(points);
            var teamnamebox=new TLFTextField();
            teamnamebox.x = 2.25;
            teamnamebox.y = 295.25;
            teamnamebox.width = 295.25;
            teamnamebox.height = 70;
            teamnamebox.text = team;
            var scorevaluebox=new TLFTextField();
            scorevaluebox.x = 2.25;
            scorevaluebox.y = 95.80;
            scorevaluebox.width = 295;
            scorevaluebox.height = 97.5;
            scorevaluebox.text = scorevalue;
            trace("I set the starting values");
            trace("teamnamebox = ",teamnamebox.text);
            trace("scorevalue = ",scorevaluebox.text);
            inited = true;
        }
    }

    public function score():Number
    {
        return points;
    }

    public function winpoints(n:Number)
    {
        points +=  n;
        scorevalue = String(points);
        scorevaluebox.text = scorevalue;
    }

    public function losepoints(n:Number)
    {
        points -=  n;
        scorevalue = String(points);
        scorevaluebox.text = scorevalue;
    }

    public function setname(s:String)
    {
        team = s;
        teamname = team;
        teamnamebox.text = s;
        trace("I changed the name to ",teamnamebox.text);
    }

    public function buzzin()
    {
        this.gotoAndStop("buzzedin");
    }

    public function makeddselect()
    {
        this.gotoAndStop("ddtarget");
    }

    public function makeyay(y:Number)
    {
        switch (y)
        {
            case 1 :
                this.gotoAndStop("yay1");
                break;
            case 2 :
                this.gotoAndStop("yay2");
                break;
            case 3 :
                this.gotoAndStop("yay3");
                break;
            case 4 :
                this.gotoAndStop("yay4");
                break;
            case 5 :
                this.gotoAndStop("yay5");
                break;
            case 6 :
                this.gotoAndStop("yay6");
                break;
            default :
                trace("CRASH! "+y+" IS NOT A VALID YAY!");
        }
    }

    public function makeboo(b:Number)
    {
        switch (b)
        {
            case 1 :
                this.gotoAndStop("boo1");
                break;
            case 2 :
                this.gotoAndStop("boo2");
                break;
            case 3 :
                this.gotoAndStop("boo3");
                break;
            case 4 :
                this.gotoAndStop("boo4");
                break;
            case 5 :
                this.gotoAndStop("boo5");
                break;
            case 6 :
                this.gotoAndStop("boo6");
                break;
            default :
                trace("CRASH! "+b+" IS NOT A VALID BOO!");
        }
    }

    public function makescrewing()
    {
        this.gotoAndStop("evilface");
    }

    public function makescrewed()
    {
        this.gotoAndStop("screwed");
    }

    public function makesplat()
    {
        this.gotoAndStop("eekface");
    }

    public function makefreeze()
    {
        this.gotoAndStop("frozen");
    }

    public function makehome()
    {
        this.gotoAndStop("inactive");
    }

}

}

A:

The problem you have here isn't coming from your code, but from the timeline. The code from your class can only access the elements of the current displayed frame, and loose access to the others instances, symboles, anything which is outside the current frame.
Your problem is that flash goes through each frame a first time, highlighting in debug that each object is correctly built, but once it'll reach the last frame on the timeline, it gets back to the very first frame, executing again everything from there, as any object present on frame is re-instancied again.
You need to avoid placing class instance on stage by hand.
Also but this is personnal practice, if you need to work with frames and code, prefer to work with single-frame clips, and addChild() icon libraries, assets, and gotoAndStop()'em from the code. you'll have much more control at the end, and less frustration. But overall, if you're coding, avoid using frame whenever possible ;)
Hope this helped !