text:
Q: How can I redirect to the browser after login using Android In the emulator of android studio, it's working. It's redirecting to the browser or URL. But the problem is, when I'm trying to use my personal phone, it's not working.
//Java Code
if(data.equals("found"))
{
    SharedPreferences sp=getSharedPreferences("credentials",MODE_PRIVATE);
    SharedPreferences.Editor editor=sp.edit();
    editor.putString("uname",t1.getText().toString());
    editor.commit();
    Intent httpIntent = new Intent(Intent.ACTION_VIEW);
    httpIntent.setData(Uri.parse("http://www.test.co.kr");
    startActivity(httpIntent);
}

//PHP backend code
<?php
$conn=mysqli_connect("localhost","root","");
mysqli_select_db($conn,"android_db");

$uname=$_GET['t1'];
$pwd=$_GET['t2'];

$qry="select * from tbl_user where username='$uname' and password='$pwd'";
$raw=mysqli_query($conn,$qry);
$count=mysqli_num_rows($raw);

if($count>0)
 echo "found";
else
 echo "not found";
?>

Please any help about this situation.


text:
Q: How can I use an array variable inside the IN operator for Oracle SQL? I declare a type TYPE arr_type is TABLE of VARCHAR2(11 BYTE); and then I initialize it: MY_array arr_type := arr_type();.
I insert some varchars into it, and then attempt to use it with an IN operator.
set serveroutput on;
DECLARE
  TYPE arr_type is TABLE of VARCHAR2(11 BYTE);
  my_array arr_type := arr_type();
  my_array_two arr_type := arr_type();
BEGIN

  SELECT MY_ID BULK COLLECT INTO my_array FROM XYZ_REQUEST;
  SELECT ANOTHER_ID BULK COLLECT INTO my_array_TWO FROM ABC_REQUEST WHERE PARENT_ID IN my_array;

   FOR i IN 1..cm_array.COUNT LOOP
     DBMS_OUTPUT.PUT_LINE(my_array(i));
   END LOOP;
END;
/

I get the error: local collection types not allowed in SQL statements on the line containing: SELECT ANOTHER_ID BULK COLLECT INTO my_array_TWO FROM ABC_REQUEST WHERE PARENT_ID IN my_array;, but it doesn't make sense because if I comment out that line, my_array prints fine, which means TYPE arr_type is TABLE of VARCHAR2(11 BYTE);.
I suspect the issue is because I'm trying to use an unbounded array with the IN operator i.e. PARENT_ID IN my_array.
I tried wrapping the variable inside parenthesis, but it doesn't help. How can I use the IN operator with an array?
I understand that in this case I can use subqueries or joins, but I am wondering is it possible to use an array with an IN operator.

A: WHERE PARENT_ID IN my_array;

This will not work. First, as the error message states, you are not allowed to use local collection types in SQL statements, you need to define them in the database. Second, that syntax does not exist.
So first you define the type:
CREATE TYPE arr_type is TABLE of VARCHAR2(11 BYTE);

And after that, you can use the collection with the TABLE() function as below:
set serveroutput on;
DECLARE
  my_array arr_type := arr_type();
  my_array_two arr_type := arr_type();
BEGIN

  SELECT MY_ID BULK COLLECT INTO my_array FROM XYZ_REQUEST;
  SELECT ANOTHER_ID BULK COLLECT INTO my_array_TWO FROM ABC_REQUEST
  WHERE PARENT_ID IN (select * from table(my_array)); -- <==========================

   FOR i IN 1..cm_array.COUNT LOOP
     DBMS_OUTPUT.PUT_LINE(my_array(i));
   END LOOP;
END;
/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Codeigniter set_value() and populate the form value My form field looks like this
    echo form_label('Quantity', 'quantity');
    echo form_input('quantity', $quantityx);

I modified it to retain form values
    echo form_label('Quantity', 'quantity');
    echo form_input('quantity', $this->input->post('quantity'));

I set the $quantityx above in the code behind in order to populate a value from the database so a user can edit a row.
How can I retain the value for validations, and have a variable to populate from the database at the same time?
I have tried this a well
    echo form_label('Quantity', 'quantity');
    echo form_input('quantity', set_value($quantityx));

Thanks for any suggestions

A: You can set them like this, if set_value('columnanme') returns false then a form $_POST did not take place so what it will do is get the data from the data base example
$profile->firstname
$firstname = set_value('firstname') == false ? $profile->firstname : set_value('firstname');
$lastname = set_value('lastname') == false ? $profile->lastname : set_value('lastname');

Use it like:
echo form_label('Firstname', 'fname');
echo form_input('firstname', $firstname);
echo form_label('Firstname', 'lnamey');
echo form_input('firstname', $lastname);

in your case you can do:
$quantity = set_value('Quantity') == false ? $quantityx : set_value('Quantity');

ANd on your form:
echo form_label('Quantity', 'quantity');
    echo form_input('quantity', $quantity);

Assuming that $quantityx holds the data from your databse
EDIT
=============================================
Just use set_values() second parameter as the default value. i.e set_value('name_of_input_field',$data_from_databse_as_default);
If this does not work, then use my first answer.

A: To populate the value below code worked for me.
form_input('cat_name','{YOUR VALUE}',array('id' => 'cat_name', ''placeHolder'' => 'Enter Cat Name'));

A: You can try this code to set the value in the text field while validating and fetch the value from the database.
form_input(array('id' => 'cat_name', 'name' => 'cat_name','value'=>set_value('cat_name',$cat_name)));

A: There are 3 basic types of inputs. Here's how to repopulate each of them.
Text Inputs
$quantity = getValueFromDb();
echo form_input(
    ['name' => 'textInput',],
    set_value('textInput', $quantity, false)
);

Use false as third parameter of set_value to avoid double html escaping, which is done by form_input as well.
Dropdowns
$quantity = getValueFromDb();
$quantities = getQuantitiesList();
echo form_dropdown(
    [ 'name' => 'formDropdown'],
    [''=>'-- Select Quantity --'] + $quantities,
    set_value('formDropdown', $quantity, false)
);

Radio Buttons
$quantity = getValueFromDb();
echo form_radio(
    ['name'=>'formRadio'],
    5,
    set_radio('formRadio', 5, $quantity === 5)
), 5;
echo form_radio(
    ['name'=>'formRadio'],
    10,
    set_radio('formRadio', 10, $quantity === 10)
), 10;

For radio inputs, use loops for substituting literals.
Checkboxes
Checkboxes can be made in a similar fashion by replacing form_radio with form_checkbox and set_radio with set_checkbox.
$values = [ 5 => 'Five', 10 => 'Ten', 15 => 'Fifteen',];
$selectedValues = [5, 15];
foreach ($values as $value => $label) {
    echo form_checkbox(
        ['name' => 'formCheckbox[]'],
        $value,
        set_checkbox(
            'formCheckbox[]',
            $value,
            in_array($value, $selectedValues, true)
        )
    ), $label;
}


text:
Q: Unsuccess in using URLOpenBlockingStream to check if online file exists I followed the approach presented here -- How to check if a link exists or not in VC++?
and I also tried this code
IStream* pStream = NULL;
if (URLOpenBlockingStream(0, sUrl, &pStream, 0, 0) == S_OK)
{
    pStream->Release(); // don't need the data
    return TRUE;
}

return FALSE;

I get a TRUE return whether the file exists or doesn't exist.
I'm using URLDownloadToFile successfully so I assume I am linking to the proper library.
Any idea what I am doing wrong or is there an alternate approach?


text:
Q: Forgot to include --with-curl when configuring PHP.  How to add without disrupting other extensions? If I compile PHP 5 from source and realize I forgot a --with-curl in it, can I run the same ./configure command and add --with-curl at the end and it will add it?  Or can I just do ./configure --with-curl and it will add it to the everything that is already installed?

A: You have to reconfigure and then recompile.

A: You need to added it to the end of your old configuration like this
./configure --with-something1 --with-something2 --with-curl

A: You should run ./configure (previous command + new addition), make, make install, make clean.

A: ./configure doesn't remember the parameters you last used to call it, although you can fish them out of config.status if you have forgotten them.

A: You need to run the correct configure command and compile using the make command. If you wane more information about autoconf see http://www.gnu.org/software/autoconf/#introduction basically ./configure just sets up the build and you can change options using it.


text:
Q: How to check browser cookies support with Pyramid I would like to know, when is the right moment and how to check the browser cookies support.
I understand I have to check the next request and for instance, with beaker, looking for the session key _creation_time or request.headers['Cookie']... and raise an exception if not found but I don't want to do that or something similar for every request. Some parts of my application don't require cookies, like the home page or info, faq page...
When a user logs out, the session gets deleted or invalidated and I used to redirect to the home view, if I check the session key at that moment, I'll not find it but it doesn't mean there is this issue.
An example I used at the beginning of login view:
 try: request.headers['Cookie']
 except KeyError:
   return HTTPFound(location=request.route_url('home'))

Please also note that if I try to print an error message using request.session.flash(msg, 'error') or use the snippet again at the beginning of the home view and render a message with the template using a control return variable, after logout it will be erroneous displayed.
I am looking for the most elegant way to resolve issue...maybe subscribe to a event?...write down a function to call in some interested view?

A: There are a few things that could the cause of your problems.
Before I continue... FYI Pyramid uses WebOb to handle request and response objects

*

*WebOb Overview

*WebOb Class Documentation
Scenario 1
If you call set_cookie under Pyramid , and then do a redirect, the set_cookie will not be sent.  This is because redirects create a new response object.
There are a few ways around this:

*

*The most straightforward is to just copy response headers into the cookie when you raise/return a redirect
return HTTPfound( "/path/to/redirect", headers=[ (k,v) for (k,v)\
in self.request.response.headers.iteritems() if k == 'Set-Cookie']  )

OR
resp = HTTPFound(location='/path/to/redirect')
return self.request.response.merge_cookies(resp)

I should also note that MOST browsers accept cookies on redirects, however Safari does not.

*another way is to use pyramid's hooks to convert cookies behind the scenes.  i wrote subscribers that automate this.  they're on pypi and github. https://github.com/jvanasco/pyramid_subscribers_cookiexfer
Scenario 2
There are two ways of handling sessions in Pyramid.  Pyramid has its own session library, and then there is Beaker, which handled sessions for Pylons and has Pyramid support that many people use.  I can't speak of pyramid.session, but Beaker has two modes to kill the session:
delete()
Delete the cookie, and clear the session

invalidate()
Clear the contents and start a new session

If you call invalidate(), the Beaker session cookie stays the same and all the session data is cleared -- so you can start storing new data into an empty session object.
If you call delete(), the cookie gets killed as does the session data.  If you put new information into the session, IIRC, it will go into a new sessionid / cookie .  However, as I noted in the first part above, set_cookie will get called but then thrown out during the redirect.  So if you delete() the session and then don't migrate the set_cookie headers... the client will never receive a session identifier.
Some example behaviors of cookies under pyramid
Behavior of redirect

*

*User visits site and is given cookie: SessionId=1

*User clicks login

*

*App saves login status to session "1"

*App calls set_cookie with "LoggedIn=1"

*App calls redirect to /home

*Redirect sent, no cookies

*User lands on /home

*

*App only sees cookie for "SessionId=1"

Behavior of delete with redirect:

*

*User clicks logout

*

*App calls 'delete()' on session, killing the datastore and placing a set_cookie in request.response to expire the old cookie.  if a new sessionid is created, that is sent as well.

*If app renders a response, then client receives cookies

*If app redirects, client does not receive headers to expire the cookie or set up a new one

Behavior of invalidate with redirect:

*

*User clicks logout

*

*App calls 'invalidate()' on session, killing the datastore

*App sets a custom "loggedout=0" cookie

*If app renders a response, then client receives cookies

*If app redirects:

*

*Client does not receive "loggedout=0" header

*Client still has the old session cookie, but it was invalidated/purged on the backend, so they are effectively locked out.

side note: I personally don't like using the request.headers interface -- which handles all headers -- to get at cookies.  I've had better luck with request.cookies -- which returns a dictionary of cookies.


text:
Q: Capture HTTP 307 redirect URL I am making calls to the Facebook API and am trying to capture the access token from the response.
When I make a call to the following URL:
https://www.facebook.com/dialog/oauth?client_id={client_id}&display=popup&redirect_uri=http://www.facebook.com/connect/login_success.html&response_type=token

I get a brief redirect to a URL which shows the access token if I am already logged in, or displays the FB Login Form in my browser:
https://www.facebook.com/connect/login_success.html#access_token={access_token}&expires_in={time}

The above URL only shows for a second or two before finally being redirected to:
https://www.facebook.com/connect/blank.html#_=_

My question is, how can I capture the access token in the second URL?
I have been trying to capture the URL via the following method:
private void FBBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) {
    String urlResponse = e.Uri.ToString();
    Console.WriteLine("FB URL Response: " + urlResponse);
}

The problem is that the URL being picked up by the listener is the first URL to which I make a call, not the response URL which is what I am after.
(Please note that I have removed the access_token and client_id from the URL's for security purposes)
Additional Note - after doing some inspection of the request sequence in the browser, I noticed that the first response is HTTP 302, followed by a HTTP 307. The location header of the 307 Response is what I need to parse using C# as it contains the access token.

A: It seems there is an issue with capturing characters after a '#' symbol when using the WPF Web Browser Control. This poses a problem with access tokens as they are returned as follows in the URL:
#access_token='token_code'&expires_in='time'

This blog post covers a workaround by using the System.Windows.Controls.WebBrowser instead. By adapting this technique I was able to finally parse the access token from the URL.
I hope this helps anyone else who may have run into a similar issue.


text:
Q: Can't remote debug Chromecast I have a Chromecast (original) registered on my Cast developer console, but I can't debug any receivers. I've had it for a few years and used to be able to debug them remotely by visiting *ip_of_chromecast*:9222, but apparently that was removed in favor of chrome://inspect.
Unfortunately I can't get chrome://inspect to work. Here's what I see when casting either a Styled Media Receiver or a completely custom receiver:

I'm pretty sure there's supposed to be a page I can inspect under the Chromecast, but there's never anything there. I've tried rebooting and doing a factory reset.
Any ideas?

A: Fixed by unregistering and reregistering my Chromecast in the Cast Developer Console.


text:
Q: Saving current directory to bash history I'd like to save the current directory where the each command was issued alongside the command in the history.  In order not to mess things up, I was thinking about adding the current directory as a comment at the end of the line.  An example might help:
$ cd /usr/local/wherever
$ grep timmy accounts.txt

I'd like bash to save the last command as:
grep timmy accounts.txt # /usr/local/wherever

The idea is that this way I could immediately see where I issued the command.

A: hcmnts - short function version
Here is a short version in the form of a function. I've also posted a one-liner (the original) and a longer function with several added features. I like the function versions because they won't clobber other variables in your environment and they're much more readable than the one-liner. Read the entry for the one-liner for additional information on how this works and some limitations. I've posted each version in its own answer in order to keep things more organized.
To use this one, save it in a file called hcmnts in a location like /usr/local/bin (you can chmod +x it if you want) then source it in your ~/.bashrc like this:
source /usr/local/bin/hcmnts

Comment out the line that sets hcmntextra if you don't want the date and time (or you can change its format or use some other command besides date).
That's all there is to it.
#!/bin/bash
hcmnts() {
    # adds comments to bash history entries

    # the *S*hort version of hcmnt (which has many more features)

    # by Dennis Williamson
    # http://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history
    # (thanks to Lajos Nagy for the idea)

    # INSTALLATION: source this file in your .bashrc

    # will not work if HISTTIMEFORMAT is used - use hcmntextra instead
    export HISTTIMEFORMAT=

    # HISTTIMEFORMAT still works in a subshell, however, since it gets unset automatically:

    #   $ htf="%Y-%m-%d %R "    # save it for re-use
    #   $ (HISTTIMEFORMAT=$htf; history 20)|grep 11:25

    local hcmnt
    local cwd
    local extra

    hcmnt=$(history 1)
    hcmnt="${hcmnt# *[0-9]*  }"

    if [[ ${hcmnt%% *} == "cd" ]]
    then
        cwd=$OLDPWD
    else
        cwd=$PWD
    fi

    extra=$(eval "$hcmntextra")

    hcmnt="${hcmnt% ### *}"
    hcmnt="$hcmnt ### ${extra:+$extra }$cwd"

    history -s "$hcmnt"
}
export hcmntextra='date +"%Y%m%d %R"'
export PROMPT_COMMAND='hcmnts'

A: One-liner version
Here is a one-liner version. It's the original. I've also posted a short function version and a long function version with several added features. I like the function versions because they won't clobber other variables in your environment and they're much more readable than the one-liner. This post has some information on how they all work which may not be duplicated in the others.
Add the following to your ~/.bashrc file:
export PROMPT_COMMAND='hpwd=$(history 1); hpwd="${hpwd# *[0-9]*  }"; if [[ ${hpwd%% *} == "cd" ]]; then cwd=$OLDPWD; else cwd=$PWD; fi; hpwd="${hpwd% ### *} ### $cwd"; history -s "$hpwd"'

This makes a history entry that looks like:
rm subdir/file ### /some/dir

I use ### as a comment delimiter to set it apart from comments that the user might type and to reduce the chance of collisions when stripping old path comments that would otherwise accumulate if you press enter on a blank command line. Unfortunately, the side affect is that a command like echo " ### " gets mangled, although that should be fairly rare.
Some people will find the fact that I reuse the same variable name to be unpleasant. Ordinarily I wouldn't, but here I'm trying to minimize the footprint. It's easily changed in any case.
It blindly assumes that you aren't using HISTTIMEFORMAT or modifying the history in some other way. It would be easy to add a date command to the comment in lieu of the HISTTIMEFORMAT feature. However, if you need to use it for some reason, it still works in a subshell since it gets unset automatically:
$ htf="%Y-%m-%d %R "    # save it for re-use
$ (HISTTIMEFORMAT=$htf; history 20)|grep 11:25

There are a couple of very small problems with it. One is if you use the history command like this, for example:
$ history 3
echo "hello world" ### /home/dennis
ls -l /tmp/file ### /home/dennis
history 3

The result will not show the comment on the history command itself, even though you'll see it if you press up-arrow or issue another history command.
The other is that commands with embedded newlines leave an uncommented copy in the history in addition to the commented copy.
There may be other problems that show up. Let me know if you find any.
How it works
Bash executes a command contained in the PROMPT_COMMAND variable each time the PS1 primary prompt is issued. This little script takes advantage of that to grab the last command in the history, add a comment to it and save it back.
Here it is split apart with comments:
hpwd=$(history 1)              # grab the most recent command
hpwd="${hpwd# *[0-9]*  }"      # strip off the history line number
if [[ ${hpwd%% *} == "cd" ]]   # if it's a cd command, we want the old directory
then                           #   so the comment matches other commands "where *were* you when this was done?"
    cwd=$OLDPWD
else
    cwd=$PWD
fi
hpwd="${hpwd% ### *} ### $cwd" # strip off the old ### comment if there was one so they
                               #   don't accumulate, then build the comment
history -s "$hpwd"             # replace the most recent command with itself plus the comment

A: hcmnt - long function version
Here is a long version in the form of a function. It's a monster, but it adds several useful features. I've also posted a one-liner (the original) and a shorter function. I like the function versions because they won't clobber other variables in your environment and
they're much more readable than the one-liner.  Read the entry for the one-liner and the commments in the function below for additional information on how it works and some limitations. I've posted each version in its own answer in order to keep things more organized.
To use this one, save it in a file called hcmnt in a location like /usr/local/bin (you can chmod +x it if you want) then source it in your ~/.bashrc like this:
source /usr/local/bin/hcmnt
export hcmntextra='date "+%Y%m%d %R"'
export PROMPT_COMMAND='hcmnt'

Don't edit the function's file where PROMPT_COMMAND or hcmntextra are set. Leave them as is so they remain as defaults. Include them in your .bashrc as shown above and edit them there to set options for hcmnt or to change or unset hcmntextra. Unlike the short function, with this one you must both have the hcmntextra variable set and use the -e option to make that feature work.
You can add several options which are documented (with a couple of examples) in the comments in the function. One notable feature is to have the history entry with appended comment logged to a file and leave the actual history untouched. In order to use this function, just
add the -l filename option like so:
export PROMPT_COMMAND="hcmnt -l ~/histlog"

You can use any combination of options, except that -n and -t are mutually exclusive.
#!/bin/bash
hcmnt() {

# adds comments to bash history entries (or logs them)

# by Dennis Williamson - 2009-06-05 - updated 2009-06-19
# http://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history
# (thanks to Lajos Nagy for the idea)

# the comments can include the directory
# that was current when the command was issued
# plus optionally, the date or other information

# set the bash variable PROMPT_COMMAND to the name
# of this function and include these options:

    # -e - add the output of an extra command contained in the hcmntextra variable
    # -i - add ip address of terminal that you are logged in *from*
    #      if you're using screen, the screen number is shown
    #      if you're directly logged in, the tty number or X display number is shown
    # -l - log the entry rather than replacing it in the history
    # -n - don't add the directory
    # -t - add the from and to directories for cd commands
    # -y - add the terminal device (tty)
    # text or a variable

# Example result for PROMPT_COMMAND='hcmnt -et $LOGNAME'
#     when hcmntextra='date "+%Y%m%d %R"'
# cd /usr/bin ### mike 20090605 14:34 /home/mike -> /usr/bin

# Example for PROMPT_COMMAND='hcmnt'
# cd /usr/bin ### /home/mike

# Example for detailed logging:
#     when hcmntextra='date "+%Y%m%d %R"'
#     and PROMPT_COMMAND='hcmnt -eityl ~/.hcmnt.log $LOGNAME@$HOSTNAME'
#     $ tail -1 ~/.hcmnt.log
#     cd /var/log ### dave@hammerhead /dev/pts/3 192.168.1.1 20090617 16:12 /etc -> /var/log

# INSTALLATION: source this file in your .bashrc

    # will not work if HISTTIMEFORMAT is used - use hcmntextra instead
    export HISTTIMEFORMAT=

    # HISTTIMEFORMAT still works in a subshell, however, since it gets unset automatically:

    #   $ htf="%Y-%m-%d %R "    # save it for re-use
    #   $ (HISTTIMEFORMAT=$htf; history 20)|grep 11:25

    local script=$FUNCNAME

    local hcmnt=
    local cwd=
    local extra=
    local text=
    local logfile=

    local options=":eil:nty"
    local option=
    OPTIND=1
    local usage="Usage: $script [-e] [-i] [-l logfile] [-n|-t] [-y] [text]"

    local newline=$'\n' # used in workaround for bash history newline bug
    local histline=     # used in workaround for bash history newline bug

    local ExtraOpt=
    local LogOpt=
    local NoneOpt=
    local ToOpt=
    local tty=
    local ip=

    # *** process options to set flags ***

    while getopts $options option
    do
        case $option in
            e ) ExtraOpt=1;;        # include hcmntextra
            i ) ip="$(who --ips -m)" # include the terminal's ip address
                ip=($ip)
                ip="${ip[4]}"
                if [[ -z $ip ]]
                then
                    ip=$(tty)
                fi;;
            l ) LogOpt=1            # log the entry
                logfile=$OPTARG;;
            n ) if [[ $ToOpt ]]
                then
                    echo "$script: can't include both -n and -t."
                    echo $usage
                    return 1
                else
                    NoneOpt=1       # don't include path
                fi;;
            t ) if [[ $NoneOpt ]]
                then
                    echo "$script: can't include both -n and -t."
                    echo $usage
                    return 1
                else
                    ToOpt=1         # cd shows "from -> to"
                fi;;
            y ) tty=$(tty);;
            : ) echo "$script: missing filename: -$OPTARG."
                echo $usage
                return 1;;
            * ) echo "$script: invalid option: -$OPTARG."
                echo $usage
                return 1;;
        esac
    done

    text=($@)                       # arguments after the options are saved to add to the comment
    text="${text[*]:$OPTIND - 1:${#text[*]}}"

    # *** process the history entry ***

    hcmnt=$(history 1)              # grab the most recent command

    # save history line number for workaround for bash history newline bug
    histline="${hcmnt%  *}"

    hcmnt="${hcmnt# *[0-9]*  }"     # strip off the history line number

    if [[ -z $NoneOpt ]]            # are we adding the directory?
    then
        if [[ ${hcmnt%% *} == "cd" ]]    # if it's a cd command, we want the old directory
        then                             #   so the comment matches other commands "where *were* you when this was done?"
            if [[ $ToOpt ]]
            then
                cwd="$OLDPWD -> $PWD"    # show "from -> to" for cd
            else
                cwd=$OLDPWD              # just show "from"
            fi
        else
            cwd=$PWD                     # it's not a cd, so just show where we are
        fi
    fi

    if [[ $ExtraOpt && $hcmntextra ]]    # do we want a little something extra?
    then
        extra=$(eval "$hcmntextra")
    fi

    # strip off the old ### comment if there was one so they don't accumulate
    # then build the string (if text or extra aren't empty, add them plus a space)
    hcmnt="${hcmnt% ### *} ### ${text:+$text }${tty:+$tty }${ip:+$ip }${extra:+$extra }$cwd"

    if [[ $LogOpt ]]
    then
        # save the entry in a logfile
        echo "$hcmnt" >> $logfile || echo "$script: file error." ; return 1
    else

        # workaround for bash history newline bug
        if [[ $hcmnt != ${hcmnt/$newline/} ]] # if there a newline in the command
        then
            history -d $histline # then delete the current command so it's not duplicated
        fi

        # replace the history entry
        history -s "$hcmnt"
    fi

} # END FUNCTION hcmnt

# set a default (must use -e option to include it)
export hcmntextra='date "+%Y%m%d %R"'      # you must be really careful to get the quoting right

# start using it
export PROMPT_COMMAND='hcmnt'

update 2009-06-19: Added options useful for logging (ip and tty), a workaround for the duplicate entry problem, removed extraneous null assignments

A: For those who want this in zsh I've modified Jeet Sukumaran's implementation and percol to allow interactive keyword searching and extraction of either the command or path it was executed in. It's also possible to filter out duplicate commands and hide fields (date, command, path)

A: Here's a one liner of what I use.   Sticking it here because it's vastly simpler, and I have no problem with per-session history, I just also want to have a history with the working directory.
Also the one-liner above mucks with your user interface too much.
export PROMPT_COMMAND='if [ "$(id -u)" -ne 0 ]; then echo "$(date "+%Y-%m-%d.%H:%M:%S") $(pwd) $(history 1)" >> ~/.bash.log; fi'

Since my home dir is typically a cross-mounted gluster thingy, this has the side effect of being a history of everything I've ever done.  Optionally add $(hostname) to the echo command above... depending on your working environment.
Even with 100k entries, grep is more than good enough.   No need to sqlite log it.   Just don't type passwords on the command line and you're good.  Passwords are 90's tech anyway!
Also, for searching I tend to do this:
function hh() {
    grep "$1" ~/.bash.log
}

A: You could install Advanced Shell History, an open source tool that writes your bash or zsh history to a sqlite database.  This records things like the current working directory, the command exit code, command start and stop times, session start and stop times, tty, etc.
If you want to query the history database, you can write your own SQL queries, save them and make them available within the bundled ash_query tool.  There are a few useful prepackaged queries, but since I know SQL pretty well, I usually just open the database and query interactively when I need to look for something.
One query I find very useful, though, is looking at the history of the current working directory.  It helps me remember where I left off when I was working on something.
vagrant@precise32:~$ ash_query -q CWD
session
    when                   what
1
    2014-08-27 17:13:07    ls -la
    2014-08-27 17:13:09    cd .ash
    2014-08-27 17:16:27    ls
    2014-08-27 17:16:33    rm -rf advanced-shell-history/
    2014-08-27 17:16:35    ls
    2014-08-27 17:16:37    less postinstall.sh
    2014-08-27 17:16:57    sudo reboot -n

And the same history using the current working directory (and anything below it):
vagrant@precise32:~$ ash_query -q RCWD
session
    where
        when                   what
1
    /home/vagrant/advanced-shell-history
        2014-08-27 17:11:34    nano ~/.bashrc
        2014-08-27 17:12:54    source /usr/lib/advanced_shell_history/bash
        2014-08-27 17:12:57    source /usr/lib/advanced_shell_history/bash
        2014-08-27 17:13:05    cd
    /home/vagrant
        2014-08-27 17:13:07    ls -la
        2014-08-27 17:13:09    cd .ash
    /home/vagrant/.ash
        2014-08-27 17:13:10    ls
        2014-08-27 17:13:11    ls -l
        2014-08-27 17:13:16    sqlite3 history.db
        2014-08-27 17:13:43    ash_query
        2014-08-27 17:13:50    ash_query -Q
        2014-08-27 17:13:56    ash_query -q DEMO
        2014-08-27 17:14:39    ash_query -q ME
        2014-08-27 17:16:26    cd
    /home/vagrant
        2014-08-27 17:16:27    ls
        2014-08-27 17:16:33    rm -rf advanced-shell-history/
        2014-08-27 17:16:35    ls
        2014-08-27 17:16:37    less postinstall.sh
        2014-08-27 17:16:57    sudo reboot -n

FWIW - I'm the author and maintainer of the project.

A: Gentleman this works better.. The only thing I can not figure out is how to make the script NOT log to syslog on login and log the last command in history. But works like a charm so far.

#!/bin/bash

trackerbash() {
    # adds comments to bash history entries

    # by Dennis Williamson
    # http://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history
    # (thanks to Lajos Nagy for the idea)

    #Supper Enhanced by QXT

    # INSTALLATION: source this file in your .bashrc

    export HISTTIMEFORMAT=
#    export HISTTIMEFORMAT='%F   %T    '

    local hcmnt
    local cwd
    local extra
    local thistty
    local whoiam
    local sudouser
    local shelldate
    local TRACKIP
    local TRACKHOST

            thistty=`/usr/bin/tty|/bin/cut -f3-4 -d/`
            whoiam=`/usr/bin/whoami`
            sudouser=`last |grep $thistty |head -1 | awk '{ print $1 }' |cut -c 1-10`
            hcmnt=$(history 1)
            hcmnt="${hcmnt# *[0-9]*  }"
            cwd=`pwd`

            hcmnt="${hcmnt% ### *}"
            hcmnt=" $hcmnt ${extra:+$extra }"

            shelldate=`date +"%Y %b %d %R:%S"`
            TRACKHOST=`whoami | sed -r "s/.*\((.*)\).*/\\1/"`
            TRACKIP=`last |grep $thistty |head -1 | awk '{ print $3 }'`

            logger -p local1.notice -t bashtracker -i -- "$sudouser ${USER}: $thistty: $TRACKIP: $shelldate: $cwd : $hcmnt"
            history -w

}
export PROMPT_COMMAND='trackerbash'

A: Full disclosure: I'm the author of the FOSS-tool
shournal - A (file-) journal for your shell:
Using it's bash integration, the working directory of a command is also stored within shournal's sqlite-database and can be retrieved via
shournal --query -cmdcwd "$PWD"

Querying for sub-working-directories can be done with
shournal --query -cmdcwd -like "$PWD/%"

A: You could consider an independent project (I wrote it) that supports saving the path for each command: https://github.com/chrissound/MoscoviumOrange
Where you can add a hook into Bash to save each entry with:
$(jq -n --arg command "$1" --arg path "$PWD" '{"command":$command, "path":$path}' | "$(echo 'readlink -f $(which nc)' | nix run nixpkgs.netcat)" -N -U ~/.config/moscoviumOrange/monitor.soc &)


text:
Q: communicating between modules in zend framework 2 I have an authentication module. Now, I want to ensure that every module passes (communicates) with that authentication module. I guess you could say its the authentication to the entire application. How do I accomplish this?

A: Well one simple way would be getting that module/module_class via namespaces, then you could just extend the class. Have the functionality automatically called in the parent class or call the method in the child class. This would be a pretty basic way:
// Auth class
class SomeAuthClass
{
    public function __construct()
    {
        // go ahead and call doAuthCrap here, or wait
        // and let the child class call it manually
    }

    protected function doAuthCrap()
    {
        // code
    }
}

use Your\AuthModule\SomeAuthClass;

class SomeOtherModuleClass extends SomeAuthClass
{
     public function zippy_snipp()
     {
          // call some method from the parent auth class (doAuthCrap)
     }
}

Or to adhere to some of the new ways ZF2 does things, you could access the auth class via the service manager and write the config for it in service config in your module.php file. There's really multiple ways to go about doing this one and ZF2 offers quite a bit of options for doing stuff like this.
zf2:
// in controller
$auth = $this->getServiceLocator()->get('someAuth');

// in service config in module.php
public function getServiceConfig()
{
    return array(
        'factories' => array(
            'someAuth' => function ($serviceManager) {
                // code here
            },
        )
    );
}


text:
Q: How to filter all files of type containing a pattern I want to locate all the .gradle files containing some text in my project.  Right now I am in \Git\ProjectRoot.  I run
find . -type f -name \*.gradle
I want to search the contents of all the files in the list for the pattern grep -i hibernate.  I want the result to be a list of all these files by name.

A: Just add another clause to your find statement:
find . -type f -name \*.gradle -exec grep -il hibernate {} +

This will give a bunch of .gradle files to grep to work on and grep will then list the names (if any) of those that had the hibernate string in them in a case-insensitive manner.


text:
Q: How to check whether a media type is supported by my browser? I am giving the functionality to the users of uploading videos . After they upload the video i grab the video from the file input tag using the following code
document.getElementById(
      "video_file_chooser"
    ).files[0];

And Now I want to play this video . Now I have no filters , hence a user can upload any format (eg:mp4,avi etc). What I want to do is to check that whether the uploaded format is supported by my browser (can be played) or not ? Can I do this with the help of js?Thanks for the help

A: You can use following code:

var obj = document.createElement('video');
console.log(obj.canPlayType('video/mp4'));

There are three possibilities which can occur:

*

*probably: The specified media type appears to be playable.

*maybe: Cannot tell if the media type is playable without playing it.

*'' (empty string): The specified media type definitely cannot be played.


text:
Q: Supress default browser: Java, Android studio I'm setting up a simple AI, chat functions etc. Right now, I'm working on a small web view "browser". Opens up to google by default, then has a little textedit and button for further navigation. However, whenever a link is clicked on or I try to navigate, it opens the default browser instead. I tried using some code from simmilar questions, but it led to further issues so I removed it. Thanks for any help, here's my code:
Xml, manifest, and method for button:
manifest file
 <?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".Main"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/app_name"
        android:theme="@style/FullscreenTheme" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="comi.coding.prometheus.ignisai.Browser"
        android:parentActivityName="comi.coding.prometheus.ignisai.Main" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="comi.coding.prometheus.ignisai.Main" />
    </activity>
</application>

<Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Browser"
            android:id="@+id/startBrowser"
            android:onClick="StartBrowser"
            android:layout_above="@+id/btnSay"
            android:layout_alignRight="@+id/lblOutput"
            android:layout_alignEnd="@+id/lblOutput" />

public void StartBrowser(View view) {
            Intent intent = new Intent(this, Browser.class);
            startActivity(intent);
        }

Code for Browser.java(Second activity)
package comi.coding.prometheus.ignisai;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class Browser extends Activity {
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();

        webView = (WebView) findViewById(R.id.webBrowser);
        webView.setWebViewClient(new MyWebViewClient());

        String url = "http://google.com";
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
}

Errors:
   11-11 20:38:34.831 24169-24169/? E/AndroidRuntime: FATAL EXCEPTION: main
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime: Process: comi.coding.prometheus.ignisai, PID: 24169
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime: java.lang.IllegalStateException: Could not execute method for android:onClick
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:278)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.view.View.performClick(View.java:4497)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.view.View$PerformClick.run(View.java:18590)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:733)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:136)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5021)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:  Caused by: java.lang.reflect.InvocationTargetException
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:273)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.view.View.performClick(View.java:4497)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.view.View$PerformClick.run(View.java:18590)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:733)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:136)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5021)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:  Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {comi.coding.prometheus.ignisai/android.provider.Browser}; have you declared this activity in your AndroidManifest.xml?
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1723)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1511)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.app.Activity.startActivityForResult(Activity.java:3424)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.app.Activity.startActivityForResult(Activity.java:3385)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:784)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.app.Activity.startActivity(Activity.java:3627)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.app.Activity.startActivity(Activity.java:3595)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at comi.coding.prometheus.ignisai.Main.StartBrowser(Main.java:251)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:273)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.view.View.performClick(View.java:4497)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.view.View$PerformClick.run(View.java:18590)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:733)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:136)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5021)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
11-11 20:38:34.831 24169-24169/? E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)

A: Add this inside your button click :
  mWebView=(WebView)findViewById(R.id.yourID);
  mWebView.setWebViewClient(new MyBrowser());

Add this as a class inside your class:
private class MyBrowser extends WebViewClient {
      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
         view.loadUrl(url);
         return true;
      }
   }

This is a simple example class for using WebView:
 public class WebViewActivity extends Activity {
        private WebView webView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_webview);

            webView = (WebView) findViewById(R.id.webView);
            webView.setWebViewClient(new MyWebViewClient());

            String url = "http://google.com";
            webView.getSettings().setJavaScriptEnabled(true);
            webView.loadUrl(url);
        }

        private class MyWebViewClient extends WebViewClient {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        }
    }

This is all you need for doing this. Compare your code with this

A: The issue was something to do with the way the intent or manifest was being used. I found an in depth tutorial I replicated, and now it's calling on the second activity. The code you provided isn't quite working (The web view itself isn't loading, yet a button and text edit in the same layout are) and while some layout is being called,  Log.d("Tag Name", "Browser class running"); shows it isn't being called. Anyway, I totally redid the manifest and how it called on the second activity and it's working. I believe the exact change that fixed it was adding this to the manifest:

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>


text:
Q: Query string lost from a submit button I am new to both web application and the play framework, and the problem I am asking might be very naive. However, I googled around for a little while and couldn't find a good answer to it, so please bear with me.
First, my platform is play-2.1.1 + java 1.6 + OS X 10.8.3.
A short version of the problem: I have a form of submit button with action="hello?id=100". However, when I click the button, the request being sent seems to be hello? rather than hello?id=100. The action for this request expects the parameter id, so I get an error for hello?.
Here is the full setup.
conf/routes:
GET     /                           controllers.Application.index()
GET     /hello                      controllers.Application.hello(id: Long)

app/controllers/Application.java:
package controllers;

import play.*;
import play.mvc.*;

import views.html.*;

public class Application extends Controller {

    public static Result index() {
        return ok(index.render());
    }

    public static Result hello(Long id) {
        return ok("Hello, No. " + id);
    }

}

app/views/index.scala.html
This is an index page.

<form name="helloButton" action="hello?id=100" method="get">
    <input type="submit" value="Hello">
</form>

According to the play documentation, the id is supposed to be extracted from the query string ?id=100. However, when I click the submit button, the request becomes hello? rather than hello?id=100, and thus I get an error like this:

For request 'GET /hello?' [Missing parameter: id]

Can someone tell me why this is happening, please? Thank you in advance.

A: The problem is with the form:
<form name="helloButton" action="hello?id=100" method="get">
    <input type="submit" value="Hello">
</form>

As the form method is set to get, it's changing the query string. method="get" tells the browser to add the contents of the form to the query string which means the current query string gets removed.
You can add the ID as a hidden field in the form like this:
<form name="helloButton" action="hello" method="get">
    <input type="hidden" name="id" value="100">
    <input type="submit" value="Hello">
</form>

That will tell the browser to add the hidden field to the query string resulting in hello?id=100. Alternatively you could change the form method to POST.


text:
Q: Cassandra Time Window Compaction Strategy There is Cassandra table:
CREATE TABLE data.data (
dataid bigint,
sequencenumber bigint,
createdat timestamp,
datetime timestamp,
PRIMARY KEY (dataid, sequencenumber)) WITH CLUSTERING ORDER BY (sequencenumber ASC)
AND bloom_filter_fp_chance = 0.01
AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
AND comment = ''
AND compaction = {'class': 'org.apache.cassandra.db.compaction.TimeWindowCompactionStrategy', 'compaction_window_size': '7', 'compaction_window_unit': 'DAYS', 'max_threshold': '32', 'min_threshold': '4'}
AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
AND crc_check_chance = 1.0
AND dclocal_read_repair_chance = 0.1
AND default_time_to_live = 0
AND gc_grace_seconds = 3600
AND max_index_interval = 2048
AND memtable_flush_period_in_ms = 0
AND min_index_interval = 128
AND read_repair_chance = 0.0
AND speculative_retry = '99PERCENTILE';
CREATE INDEX data_datetime_idx ON data.data(datetime);

Writing data with write options ttl for 7 days.
What I noticed, every same day of week we hit big Cassandra node load, especially big wa (I/O). I think this is related with compaction strategy. Should I use this strategy with lesser compaction_window_strategy e.g. 3 days? How to tune compaction strategy with ttl? How these params correlates? O maybe I have wrong primary key?
Cassandra ring 3x nodes, 8CPU, 16GB ram. Every node load ~90GiB.

A: Your TWCS configuration seems sub-optimal. What you've told Cassandra to do is have a window/bucket (consolidation) occur every 7 days, which is also your TTL. Typically what you want, from what I have read, is 15-30 "buckets" for your TTL period. That being said, what you'd want to do in your case is take 7 days and divide that into, say, 30 buckets. If you changed it to 12 HOUR buckets, you'd have 14 buckets, which seems OK.
For 12 hours, STCS would occur for the current bucket/window. At the 12 hour mark, all of the sstables that existed in that window would be consolidated into a single sstable. After 7 days, you'd have 14 sstables in which the oldest could simply be deleted (v.s. a compaction comparison).
As long as you're not updating or deleting rows that cross windows, TWCS can save a lot of resources and is very efficient. We use it whenever we can. If you're updating rows that exist in a prior bucket, TWCS is not a good choice.
Also remember to turn off repair on the table that has TWCS. I have seen that mess things up quite badly.
As for your big wait I/O issues, it could be compaction, could be flushing, could be many things. With your current TWCS configuration, it could be compaction (depending on how many and how large the sstables are). I think you could try to use other tools to see where the busy threads are (e.g. ttop). Either way, I'd fix your TWCS configuration to be in line with best practices.
-Jim


text:
Q: primefaces dialog slide effect I am using below primefaces dialog.
<p:commandButton value="Effects" type="button" onclick="PF('dlg3').show();" />

<p:dialog header="Effects" widgetVar="dlg3" showEffect="slide" hideEffect="slide" height="100">
    <h:outputText value="This dialog has nice effects." />
</p:dialog>

slide working perfectly.
but i need slide right to left.
normally above effect work left to right.
how to i change slide direction?
Thanks in advance.


text:
Q: Angular Compilation Error: Deprecation warning I have started getting this deprecation warning ever since upgraded to Angular 13.

TypeError: message.trim is not a function
at Function.Rule.FAILURE_STRING (/home/app/node_modules/tslint/lib/rules/deprecationRule.js:30:81)
at cb (/home/app/node_modules/tslint/lib/rules/deprecationRule.js:57:53)

App works fine but it spits this error every time building the app.
This warning is present even with Angular 14.

A: Try updating to the latest version of tslint
npm install tslint@latest


text:
Q: Function handle to a method in a constant property In R2018b, I have the following setup:
classdef SomeClass < handle
    methods
        function SomeMethod(obj)
            disp in!
        end
    end
end

classdef SomeOtherClass < handle

    properties (Constant)
        instance = SomeClass()
    end

    methods
        function Test(obj)
            hdl = @obj.instance.SomeMethod;
            hdl();
        end
    end

end

However, running the Test() method gives an error:
>> SomeOtherClass().Test()
Undefined function or variable 'obj.instance.SomeMethod'.

Changing the Test() method to:
function Test(obj)
    A   = obj.instance;
    hdl = @A.SomeMethod;
    hdl();
end

gives the desired result:
>> SomeOtherClass().Test
in!

I'm puzzled...why do I need the middle man A?

A: Following @gnovice's finding:
>> obj = struct('instance', SomeClass());
>> hdl = @obj.instance.SomeMethod
hdl =
  function_handle with value:
    @obj.instance.SomeMethod

>> hdl(obj.instance)
Undefined function or variable 'obj.instance.SomeMethod'.

>> hdl()
Undefined function or variable 'obj.instance.SomeMethod'.

But:
>> instance=SomeClass();
>> hdl = @instance.SomeMethod
hdl =
  function_handle with value:
    @(varargin)instance.SomeMethod(varargin{:})

>> hdl(instance)
Error using SomeClass/SomeMethod
Too many input arguments.

Error in @(varargin)instance.SomeMethod(varargin{:})

>> hdl()
in!

Note how the function handle created in this second case is actually an anonymous function, which includes the object in it. This is a special case of the @ operator, not the normal usage, which would be:
>> hdl=@SomeMethod
hdl =
  function_handle with value:
    @SomeMethod

>> hdl(instance)
in!

What this case actually does is create an anonymous function that embeds the object you intend to call this method on. You can create such a function this way:
>> hdl=@()obj.instance.SomeMethod()
hdl =
  function_handle with value:
    @()obj.instance.SomeMethod()

>> hdl()
in!

A: I don't have a complete answer yet, but here's some more food for thought: you can recreate the same result using a structure in place of SomeOtherClass:
>> obj = struct('instance', SomeClass());
>> hdl = @obj.instance.SomeMethod;
>> hdl()
Undefined function or variable 'obj.instance.SomeMethod'.

I'm leaning towards this being a limitation of how the function handle operator works as opposed to the MATLAB class system.


text:
Q: Create a dropdown animation in react How can I create dropdown animation when I click to 3 dots and if I click one more time it will toggle the dropdown.

Here is my following code:
  const [modalStatus, setModalStatus] = useState(false);

  const openModal = () => {
    setModalStatus(true);
  };

  <Symlink />

{modalStatus && <TeamStatusModal />}
<div
  className="member-avatar"
  style={{
    backgroundImage: `url(${member.User.picture})`,
  }}
/>

{member.User.fullname}

    Joined on {moment(member.date_joined).format("MMMM Do, YYYY")}

Updated add TeamStatusModal.js:
const TeamStatusModal = () => {
  return (

        <ProfileIcon /> View Profile

        <MessageIcon /> Message Me

        <ReviewIcon /> Leave Review

  );
};

A: You should reorganize the logic a bit. Intead of: {modalStatus && <TeamStatusModal />} you can pass the state as a prop like this:
<TeamStatusModal active={modalStatus} />

and then you will use it in the TeamStatusModal component:
const TeamStatusModal = ({ active }) => {
  return (
    <div className={`team-status-modal-container ${active ? 'ACTIVE_CLASS' : ''}`}>

        <ProfileIcon /> View Profile

        <MessageIcon /> Message Me

        <ReviewIcon /> Leave Review

  );
};

Another approach is using e.g. Framer Motion library, which allows animate removing elements from DOM.
https://www.framer.com/api/motion/animate-shared-layout/#syncing-layout-animations


text:
Q: Pass Product Code to MSI: This installation is forbidden by system policy I'm trying to apply an update to an installed application (which is installed multiple times on the machine). As I know the ProductCode of the instance I pass it to the .msi on update.
From code this amounts to:
// Leaving out my set of global parameters (for brevity), instance is first (:I1)
Installer.InstallProduct("FullNameOfMsiFile", @"MSIINSTANCEGUID={GUISDF-F5FD-4333-9D02-F0B72E048AB6} TRANSFORMS="":I1""");

When I try this, I get a InstallerException telling me that "This installation is forbidden by system policy. Contact your system administrator". The program calling the .msi has elevated privileges and can install/update programs fine if no product code is passed.
This also happens when I try to pass the ProductCode on the command line (passing the Product Code with /n).
The installation/update works nicely without the ProductCode, so I assume this to be the problem.
I've tried several proposed solutations from the internet, like turning of UCA or looking for some sort of registry key and changing it, without success.
So, why does windows (Win 7 32 bit) explicitly forbid me to pass the Product Code and is there an easy way to fix this?
In any case, if this would only work after a user changing some settings by hand then my nice installer has a serious problem, as it is meant to install/update without any fuss.
Edit to answer question from taffit:
The update is a major upgrade, for each instance a new ProductCode is generated, through the WIX code, so every instance has a own Upgrade Code (which is unique for the instance):
<Property Id="InstanceId" Value="Default"/>
<InstanceTransforms Property="InstanceId">
  <Instance Id="I1" ProductCode="*" UpgradeCode="{GUID-2B92-407D-A609-C8DD9A0CF09C}" />
  <Instance Id="I2" ProductCode="*" UpgradeCode="{GUID-85B4-4C68-B687-EBE02F282C2D}" />
<!-- further possible instances here, removed for brevity -->

</InstanceTransforms>

The product code is stored for each instance, so when trying the upgrade I know which product code to pass for the instance.
Edit Nr. 2:
The EventLog was not very enlightning, it just has three events which belong to the not working upgrade (one that the msi started, one that a recovery point was created and then one that the installer transaction was stopped, but without saying why)
The log of the .msi just stops with an error code 1625, which means that the system policies reject the installation. I just really don't know what for policies these are and what to do about them.
MSI (c) (78:84) [08:51:46:479]: Machine policy value 'DisableUserInstalls' is 0
MSI (c) (78:84) [08:51:46:530]: Client-side and UI is none or basic: Running entire     install on the server.
MSI (c) (78:84) [08:51:46:570]: Grabbed execution mutex.
MSI (c) (78:84) [08:51:47:083]: Cloaking enabled.
MSI (c) (78:84) [08:51:47:120]: Attempting to enable all disabled privileges before     calling Install on Server
MSI (c) (78:84) [08:51:47:170]: Incrementing counter to disable shutdown. Counter after increment: 0
MSI (s) (B4:4C) [08:51:47:248]: Running installation inside multi-package transaction    C:\Program Files\MyProgram\installer.msi
MSI (s) (B4:4C) [08:51:47:295]: Grabbed execution mutex.
MSI (s) (B4:A8) [08:51:47:340]: Resetting cached policy values
MSI (s) (B4:A8) [08:51:47:368]: Machine policy value 'Debug' is 0
MSI (s) (B4:A8) [08:51:47:403]: ******* RunEngine:
       ******* Product: C:\Program Files\MyProgram\installer.msi
       ******* Action:
       ******* CommandLine: **********
MSI (s) (B4:A8) [08:51:47:453]: Machine policy value 'DisableUserInstalls' is 0
MSI (s) (B4:A8) [08:51:47:498]: Machine policy value 'LimitSystemRestoreCheckpointing' is 0
MSI (s) (B4:A8) [08:51:47:561]: Note: 1: 1715 2: MyProgram
MSI (s) (B4:A8) [08:51:47:620]: Calling SRSetRestorePoint API. dwRestorePtType: 0,  dwEventType: 102, llSequenceNumber: 0, szDescription: "MyProgram wird installiert".
MSI (s) (B4:A8) [08:52:07:257]: The call to SRSetRestorePoint API succeeded. Returned status: 0, llSequenceNumber: 14.
MSI (s) (B4:A8) [08:52:07:497]: MainEngineThread is returning 1625
MSI (s) (B4:4C) [08:52:07:587]: Calling SRSetRestorePoint API. dwRestorePtType: 13, dwEventType: 103, llSequenceNumber: 14, szDescription: "".
MSI (s) (B4:4C) [08:52:07:763]: The call to SRSetRestorePoint API succeeded. Returned status: 0.
MSI (s) (B4:4C) [08:52:07:863]: User policy value 'DisableRollback' is 0
MSI (s) (B4:4C) [08:52:07:944]: Machine policy value 'DisableRollback' is 0
MSI (s) (B4:4C) [08:52:08:045]: Incrementing counter to disable shutdown. Counter after increment: 0
MSI (s) (B4:4C) [08:52:08:195]: Note: 1: 1402 2:    HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer\Rollback\Scripts 3:   2
MSI (s) (B4:4C) [08:52:08:262]: Note: 1: 1402 2: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer\Rollback\Scripts 3: 2
MSI (s) (B4:4C) [08:52:08:330]: Note: 1: 1402 2:  HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer\InProgress 3: 2
MSI (s) (B4:4C) [08:52:08:443]: Note: 1: 1402 2: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer\InProgress 3: 2
MSI (s) (B4:4C) [08:52:08:627]: Decrementing counter to disable shutdown. If counter >= 0, shutdown will be denied.  Counter after decrement: -1
MSI (s) (B4:4C) [08:52:08:720]: Restoring environment variables
MSI (c) (78:84) [08:52:08:871]: Decrementing counter to disable shutdown. If counter >= 0, shutdown will be denied.  Counter after decrement: -1
MSI (c) (78:84) [08:52:08:936]: MainEngineThread is returning 1625
=== Verbose logging stopped: 28.05.2014  08:52:09 ===

A: Try to peruse this old thread from the Installshield User Community: http://community.flexerasoftware.com/archive/index.php?t-169856.html or this discussion: Instance Transform incorrect on update


text:
Q: Doubts about the address of the tensor on GPU I used C++ and libtorch to debug tensor calculation.
I put a tensor on the GPU and define its pointer and output its address. And next, I defined another pointer to point a numcpp array and output their address. The code as follows:
torch::Tensor tensor = std::get<1>(max_out).to(at::kCUDA);
nc::NdArray<long> np = nc::zeros<long>(10, 20);
...
cout << "tensor address in function: " << &tensor << endl;
cout << "np address in function: " << &np << endl;

I found their addresses are close to each other as follows. In fact, tensor is on CUDA, np is on CPU. Is the address of CUDA on GPU have been mapped to the memory?


text:
Q: Coq: unfold all Definitions Is there a tactic for unfolding all Definitions (in the goal, optionally also in hypotheses)? Something shorter than unfold def, def0, ... in *.

A: You can use cbv delta in * for example.
See https://coq.inria.fr/distrib/current/refman/proof-engine/tactics.html?highlight=cbv#coq:tacn.cbv


text:
Q: Issue with the function "digitise" from "survHE" I am trying to replicate the steps from a blog on survival modelling: https://healthdatacounts.com/2019/12/03/reconstructing-data-from-kaplan-meier-curves/
I work in R with the package "survHE" with the function "digitise"
When I run the code attached ("Code_Guyot") I get an error message when I try to run the "digitise" function: "Error in [.data.frame(pub.risk, , 5) : undefined columns selected".

#Read survival data
Guyot_data <- read.csv("Guyot_data_2.csv", header = TRUE)
head(Guyot_data)

#Determine which rows the upper and lower values of each interval are
find_interval_limits <- function(start_time,
                                 surv_time){

if (max(surv_time) > max(start_time))
stop("Intervals must span all survival times. Later interval missing.")

interval <- 1
end_time <- start_time[2]
upper <- NULL

for (i in seq_along(surv_time)){
    if (surv_time[i] >= end_time) {

      upper[interval] <- i - 1
      interval <- interval + 1
      end_time <- start_time[interval + 1]
    }
}

cbind(lower = c(1, upper + 1),
     upper = c(upper, length(surv_time)))
}

interval_limits <-
 find_interval_limits(start_time = c(0, 10, 20, 30, 40, 50, 60),
                      surv_time = Guyot_data$Time)

#We can then add this extraction date-specific values to the numbers at risk data take `enter code here from a table in the paper

Guyot_atrisk <- read.csv("Guyot_atrisk.csv", header = TRUE)
Guyot_atrisk[, c("lower", "upper")] <- interval_limits
head(Guyot_atrisk)

# required row number
Guyot_data <- cbind("k" = rownames(Guyot_data), Guyot_data)

# The arguments of digitise are file names of text file so we need to save these data `enter code here`first
write.table(Guyot_atrisk, file = "Guyot_atrisk.txt", row.names = FALSE)
write.table(Guyot_data, file = "Guyot_data.txt", row.names = FALSE)

#my code
surv.inp <- "Guyot_data.txt"
nrisk.inp <- "Guyot_atrisk.txt"
km_out <- "KMdata.txt"
ipd_out <- "IPDdata.txt"
digitise(surv.inp, nrisk.inp)

It looks like I have some issues with the lower and upper bound values for the file containing the number of patients at risk.
Did I do anything wrong? Where is the mistake?
At the link below you can fin the input files.
The *.csv files are the files where I have extracted survival data from the Kaplan Meier plot (I have used the radiotherapy arm data from the publication from "Guyot et al. BMC Medical Research Methodology 2012, 12:9").
The *.txt files are the input of the "digitise" function at the final stage of the calculation.
Blockquote

A: Can you open an issue on the survHE GitHub repo - possibly including a link to the actual data so I can replicate the problem? (I am kind of swamped with a million things and, believe you me, I would much rather do this, than everything else!, so may not be immediate, but I can try and look at it!).


text:
Q: Have an icon next to page title using html / ejs I am trying to put an icon next to my page title. I have read quite a few articles and similar questions on the internet but i still can't see my little icon up there next to the page title. I literally don't know what is wrong with my code.
I have the following directories among other: data/public, data/files, public (which includes all my css files), views (which includes all my ejs files). Inside the /views folder i have a few folders and a few files that are responsible for my viewing experience while using the web app i am building. Now in the /views/includes directory i have a file named head.ejs which contains all my head code i will use in pretty much every other ejs file. so i just have the head.ejs file and i can include it in every ejs file i want. The head.ejs file looks like that:
<!DOCTYPE html>
<html lang="en">

<head>
    <!-- <link rel="shortcut icon" href="/data/public/boxTitle.jpg" type="image/jpg" /> -->
    <link rel="icon" href="favicon.ico" type="image/x-icon" />
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><%= pageTitle %></title>
    <link rel="stylesheet" href="/css/main.css">

I expected to see the icon up there but still haven't seen it. I have tried to move my favicon.ico image around in different directories and play a bit around with the paths. the best for me is for the image to be in the /data/public/ directory. while the head.ejs is in the /views/includes/ directory. The image is 16x16, black and white. Tried with a jpg image, too. I am probably failing really hard cause it's seems pretty easy and straight forward but... Any help is appreciated! I will delete the post if the answer is totally obvious and the post is worthless.

A: Assuming your icon is in your public folder inside an images folder.
If you have defined your public folder as you mentioned, with something like this:
app.use(express.static(path.join(__dirname, 'public')));

then you can easily display your icon this way:
<link rel="icon" href="/images/your-icon" type="image/x-icon" />


text:
Q: rxjs angular 2: search filter with multiple terms I am trying to implement search with multiple terms. N chart flow of want i tried to implement
i read this blog: https://netbasal.com/manage-your-filters-like-a-pro-in-angular-with-combinelatest-e7b0204be2df it similar case. but i didn't understand how i can implement it with dynamic observables(search terms input).
let say i have filter with 30 search terms. the easy solution will be to use combineLatest to all search terms components but its not efficient.
My goal is to subscribe to observables on their first change.
i tried to use the combineLatest operator with dynamic array but it didnt work:(.
my code:

import {Component, OnInit, Input, ViewChildren, QueryList, AfterViewInit} from '@angular/core';
import {Table} from "../../models/table";
import {InputFilterComponent} from "../types/input-filter/input-filter.component";
import {Observable} from "rxjs/Observable";

@Component({
  selector: '[phantom-thead-filter]',
  template: 'Actions

    <input-filter [col]="col" [table]="table"></input-filter>

  ',
  styleUrls: ['./phantom-thead-filter.component.css']
})
export class PhantomTheadFilterComponent implements OnInit, AfterViewInit {
  @Input() cols;
  @Input() table: Table;
  @ViewChildren(InputFilterComponent) filters : QueryList<InputFilterComponent>;

  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit() {
    const filters = this.filters.map(f => f.getFilterWatcher());
    Observable.combineLatest(filters)
      .map(( filters : any[] ) => {
        filters.map((filter) => {
          return filter;
        });
      });
  }

}

import {Component, Input, OnInit} from '@angular/core';
import {FormControl} from "@angular/forms";
import {Table} from "../../../models/table";

@Component({
  selector: 'input-filter',
  template: '<input [formControl]="inputControl"
                    class="form-control"
                    type="text"
                    placeholder="input" />',
  styleUrls: ['./input-filter.component.css']
})
export class InputFilterComponent implements OnInit {
  inputControl = new FormControl();
  @Input() col;
  @Input() table: Table;
  changeFilter: any;
  constructor() { }

  ngOnInit() {
    this.changeFilter =this.inputControl.valueChanges
      .skip(1)
      .distinctUntilChanged()
      .debounceTime(400)
      .map((value: string) => {
        return value;
      }).startWith(null);
  }

  getFilterWatcher() {
    return this.changeFilter;
  }

  ngOnDestroy() {
    this.changeFilter.unsubscribe();
  }

}

A: CombineLatest waits for all observables to emit their first value.
If you want to query even if you don't set all filters, you can use startWith to provide a virtual first null value.
const filters = this.filters.map(f => f.changeFilter.startWith(null));

Observable.combineLatest(...filters)
          .map(( filters : ActiveFilter[] ) => {
                // All filters are defined, but not all have values [null, 'search', null, null]
          });

A: You can try with this approach:
let listObs = [];
const searchTermA = Observable.fromEvent(this.searchInputARef.nativeElement, 'keyup').debounceTime(300).distinctUntilChanged();
listObs = [...listObs, searchTermA];

const searchTermB = Observable.fromEvent(this.searchInputBRef.nativeElement, 'keyup').debounceTime(300).distinctUntilChanged();
listObs = [...listObs, searchTermB];

Observable.combineLatest(list).subscribe(latestValues => {
    const [searchTermAValue, searchTermBValue] = latestValues;
});


text:
Q: Running Websocket on remote server I Have a problem with laravel websockets .
I'm trying to run websocket server using Artisan call like this :
Artisan::call('websockets:serve');

but it didn't work (returned request timeout) knowing that it works correctly when i run :
php artisan websockets:serve

Here are some illustrations :

still like that then give me request timeout .

A: websocket:serve is trying to start a long running process. I'm not sure I understand the context in which you are trying to call Artisan::call('websockets:serve');, but if that is behind an http session, the http session is likely timing out and the websocket process is ending.


text:
Q: Why "npm link" install all packed dependencies of the target module I try to testing "some-hook" localy: my working progress npm package .
For that i'm does npm link on the working module.
Then npm link some-hook on the target project.
Before I do the second command I deleted all npm_module folders from the target project as it was also make other problem that good for another question. but in the process npm reinstall again whole dependencies of target project ,including pear and dev and make a mess
What is the reason for that and how I can prevent it from do it


text:
Q: Is it correct way to import the image into react component and uploading it into mdx story? I have created simple react component with  styled for styles and folder structure as attached. However, my image is not importing correctly. Can you please advise and check why? I am also using storybook for displaying the components, so could this be an issue?
This is the code for the component:
import { string, urlPropType } from "prop-types"
import * as Styled from "./Image.styled"

import image from "./components/image/dog.jpg"

const Image = ({ src, alt }) => (
  <Styled.Image>
    <img src={image} alt={dog} />
  </Styled.Image>
)
Image.propTypes = {
  src: urlPropType.isRequired,
  alt: string.isRequired,
}
export default Image

This is the code for the image.styled :
import styled from "@emotion/styled"

export const Image = styled.div`
  display: inline block;
  float: left;
  width: 100%;
  border radius: 5rem;
`

and here my story for displaying in storybook:
import { Meta, Canvas, Story, ArgsTable } from "@storybook/addon-docs"

import Image from "../image"

<Meta title="Components/Image" />

# Image

<Canvas>
  <Story>
    <__Image__ />
  </Story>
</Canvas>

<ArgsTable />

export const Template = (args) => <Image {...args} />

Attached, you can find folder structure.
Thank you for all the help :)
regards,
Emilia


text:
Q: How does terraria have so big worlds and still has silky smooth fps? I was working on my own procedural generator and finished making it.
Here is how I did it,
generate the entire world at the beginning,
store info about spawn positions and tiles positions into arrays and data structures
Now obviously, I have to loop through all the arrays, to render/update stuff,
this is creating problems,
I tried dealing with this problem by applying a condition that if any object is visible, only then render update else don't, but it does not make much of a difference.
my TILE_SIZE is 1 world units
so when my world size was
a)500 by 500,fps was 60
b)2000 by 2000, fps was 50
c)5000 by 5000 fps decreased further and so on
If only I could know how Terraria does it, or any way it done, would really help thanks.

A:
I have to loop through all the arrays, to render/update stuff

You don't have to do that.
For rendering stuff you really only need to consider the blocks that are close to the player. Here is some code(x, y are the player coordinates, width, height are the dimensions of your world, render(x, y) is a placeholder for your rendering functionality, and for simplicity I assumed the player can see 100 blocks in each direction):
for (int i = Math.max(x-100, 0); i ≤ Math.min(x+100, width); i++) {
    for (int j = Math.max(y-100, 0); j ≤ Math.min(y+100, height); j++) {
        render(i, j);
    }
}

The process of updating can also be simplified:
For npcs you only need to check a few blocks around it.
For block updates(liquid flowing, sand falling, corruption spread, …) there are actually two possibilities:

*

*Iterate through a different part of the array each update:
Block updates don't have to be that frequent. For fluid flow it might be good enough to update only every 50th block in each update.

*You can store the blocks that might need to be updated in an ArrayList(I suggest storing only the coordinates, not the blocks itself).
Then when the update function is called you go through that list and check wether the block really needs an update. If that's the case, you add the blocks neighbors to the list, which will then get updated in the next iteration.
Make sure to remove the blocks you just updated from the list and avoid adding duplicates!

While the second approach is normally faster(ususally the list is only determined by player actions and even if the player decides to drain the entire ocean the whole list would probably take less than ¹⁄₂₀ of the entire world).
But the first approach is certainly easier to implement and will be faster if for whatever reason you have lots of block updates.

A: *

*Anything you do not see on screen is stored as values. This means that all tiles that are not visible in your viewbox do not get rendered. They are stored as objects (e.g. {x, y, type}); Make sure you count how many tiles are on screen VS how many you are rendering each loop in your code. Never render something that is not visible to the user as this will eat up your memory.

*Any tile groups that cannot be rendered soon (i.e. by moving left/right) are not looped through. So say you are using tile sectors to group your tiles, and you're in sector D. Moving left will put you in C, and moving right will put you in E. So these sectors should be loaded in to arrays (but not rendered) There is no need for you to loop through any other sectors (e.g. A or B). So these can be stored externally (e.g. as text files). So they are available, but not taking up space in your games memory.
Good luck. :)


text:
Q: What method can I use to call a web service from VBA? What is the easiest way to call a web service from Excel (I am using version 2002)?  Please, no third party tools or libraries.  This has to be easy with some VBA that I can paste there, use it, and ever touch.

A: I don't think there is any especially easy way to talk to SOAP directly from VBA, but a web service with a RESTful interface (i.e. the whole thing can be done via a URL) is easier: I was looking at this article just today. Another article I just found is here.
If you're stuck with SOAP, however, you could start by reading this and this. Frankly, it all looks a bit nasty.


text:
Q: Extend the CUDA.@atomic enum to a custom struct i was wondering weather it is possible to extend the CUDA.@atomic operation to a custom type.
Here is an example of what i am trying to do:
using CUDA

struct Dual
    x
    y
end

cu0 = CuArray([Dual(1, 2), Dual(2,3)])
cu1 = CuArray([Dual(1, 2), Dual(2,3)])

indexes = CuArray([1, 1])

function my_kernel(dst, src, idx)
   index = threadIdx().x + (blockIdx().x - 1) * blockDim().x

    @inbounds if index <= length(idx)
       CUDA.@atomic dst[idx[index]] = dst[idx[index]] + src[index]
    end
    return nothing
end

@cuda threads = 100 my_kernel(cu0, cu1, indexes)

The Problem of this code is that the CUDA.@atomic call only supports basic types like
Int, Float or Real.
I need it to work with my own struct.
Would be nice if someone has an idea how this could be possible.

A: The underlying PTX instruction set for CUDA provides a subset of atomic store, exchange, add/subtract,increment/decrement, min/max, and compare-and-set operations for global and shared memory locations (not all architectures support all operations with all POD types, and there is evidence that not all operations are implemented in hardware on all architectures).
What all these instructions have in common is that they execute only one operation atomically. I am completely unfamiliar with Julia, but if
CUDA.@atomic dst[idx[index]] = dst[idx[index]] + src[index]

means "atomically add src[].x and src[].y to dst[].x and dst[].y" then that isn't possible because that implies two additions on separate memory locations in one atomic operation. If the members of your structure could be packed into a compatible type (a 32 bit or 64 bit unsigned integer, for example), you could perform atomic store, exchange or compare-and-set in CUDA. But not arithmetic.
If you consult this section of the programming guide, you can see an example of a brute force double precision add implementation using compare-and-set in a tight loop. If your structure can be packed into something which can be manipulated with compare-and-set, then it might be possible to roll your own atomic add for a custom type (limited to a maximum of 64 bits).
How you might approach that in Julia is definitely an exercise left to the reader.


text:
Q: Selecting First and Last Test in a group of Labtests I have a table PatientLab i has a group of tests as below
patientid  labtest       dateordered    result
100          cd4         1/1/14          500
100          cd4         1/4/14          200
100          cd4         1/5/15          800
100          vl          1/4/14          564
200          cd4         1/5/16          455
200          cd4         1/6/16          678
200          cd4         1/7/16          234
200          cd4         1/8/16          356
200          vl          1/7/16          1000

my desired result;
patientid    FirstCD4     FirstCD4Date     LastCD4     LastCD4Date
100          500          1/1/14           800         1/5/15
200          455          1/5/16           356         1/8/16

am using postgresql 9

A: with CTE as
(
select p1.*,
       row_number() over(partition by patientid order by dateordered asc) as r1,
       row_number() over(partition by patientid order by dateordered desc) as r2
from PatientLab p1
where labtest = 'cd4' -- Case sensitive, thanks etsa
)
select C1.PatientID,
       C1.result as FirstCD4,
       C1.dateordered as FirstCD4Date,
       C2.result as LastCD4,
       C2.dateordered as LastCD4Date
from CTE C1
inner join CTE C2
on C1.PatientID = C2.PatientID
where C1.r1 = 1
and C2.r2 = 1

A: You can use min and max
select a.patientid, min(a.result) as FirstCD4, min(dateordered) as FirstCD4Date
    , max(a.result) as LastCD4, max(dateordered) as LastCD4Date
    from (
select * from yourpatient where labtest = 'cd4' ) a
group by a.patientid;

Your table and details Code


text:
Q: Excel VBA - Copy + Paste Based on Whether a Number is in Another Cell In short, what I'm trying to do is have a button at the top of an excel spreadsheet with an assigned VBA macro that will copy an already set up hyperlink in, lets say Cell B2 and paste down from B3:B200 based on whether there is a number (could be any number from 1 to 10000) in a Cell in column A of the same row.
Edit:
Code will need to look something like below but I'm not very knowledgeable about VBA terms
    Dim ws As Worksheet
    Dim Rng As Range
    Dim cell As Range

   Set ws = ActiveSheet
   Set Rng = ws.Range("A3:A200")

   For Each cell In Rng
        If IsNumeric(cell) = True Then
        Range ("B2").Copy
   "And now paste in adjacent cell in Row B if number in Row A is found"

    Else "Do Nothing"

   "Repeat for all cells in range"

Hope that explains it a bit better

A: I might try using something like this:
Sub Test()
Dim ws As Worksheet
Dim Row As Integer
Dim cell As Range

Set ws = ActiveSheet

For Row = 3 To 200
  If IsNumeric(Cells(Row, "A")) Then
'And now paste in adjacent cell in Row B if number in Row A is found
    Range("B2").Copy Range("B" & Row)
  Else 'Do Nothing"
  End If
'Repeat for all cells in range"
Next Row

End Sub

I used row 200 because that was your example, adjust as needed.


text:
Q: N number of coins tossed before first head appears on all of them This was a question that was asked in my distributed network algorithms assignment
Say I have n nodes in a distributed network and at every node I'm tossing a coin. Let $X_i$ be the independent random variables following geometric distribution, where $1 \leq i \leq n$, that denotes the number of coin tosses before a heads appear. let the parameter $ p =  1/2$. Then show with high probability that $Max\{X_i | 1 \leq i \leq n\} = O(logn)$.
Added the picture of question for more clarity:

This is the partial answer that I submitted.
E[x] = 1/P = 2
P($x_i = k_i$) = $(1-p)^{k_i-1}p$ where $k_i$ denotes the number of trails before heads appear in $i^{th}$ node
substituting p= 1/2, we get
P($x_i = k_i$) = $(1/2)^{k_i}$ for $ 1 \leq i \leq n$
How to procced after this ?

A: Here $X_i\sim\text{Geom}\left(p=\frac{1}{2}\right)$ $\forall i=1(1)n$.
Now let us turn our attention towards $\mathcal{O}$:
$$\begin{align}
&\max\{X_i|1\leq i\leq n\}=\mathcal{O}\left(\log n\right)\\
\implies &\max\{X_i|1\leq i\leq n\}\leq \text{c}\cdot\log n \hspace{1em}\text{as }n\rightarrow\infty\hspace{1em}\text{where c is a positive constant}\\
\implies &X_i\leq\text{c}\cdot\log n \hspace{1em}\forall i=1(1)n \hspace{1em}\text{as }n\rightarrow\infty
\end{align}$$
Now we can find the probability as
$$\begin{align}
P\left(X_i\leq\text{c}\cdot\log n|1\leq i\leq n\right)&=\{P\left(X_1\leq\text{c}\cdot\log n\right)\}^n\hspace{5em}\text{as all are i.i.d}\\
&=\left\{\sum_{k=1}^{\lfloor\text{c}\cdot\log n\rfloor}\left(\frac{1}{2}\right)^k\right\}^n\\
&=\left\{1-\left(\frac{1}{2}\right)^{\lfloor\text{c}\cdot\log n\rfloor}\right\}^n
\end{align}$$
Now, do you understand why with high probability?

 Take $\lim_{n\rightarrow\infty}$ on the above probability. Then $\left(\frac{1}{2}\right)^{\lfloor\text{c}\cdot\log n\rfloor}\rightarrow0$ [Why?].

 So $1-\left(\frac{1}{2}\right)^{\lfloor\text{c}\cdot\log n\rfloor}\rightarrow1$.

 The rest is trivial...

A: To add to the previous answer. Why and when does $(1-(\frac12)^{\lfloor c \log n\rfloor})^n$ converge to $1$? We can calculate
$$\Big(1-\Big(\frac12\Big)^{\lfloor c \log n\rfloor}\Big)^n = \Big(1-\frac{n0.5^{\lfloor c \log n\rfloor}}{n}\Big)^n = \Big(1+\frac{-e^{\log n}0.5^{\lfloor c \log n\rfloor}}{n}\Big)^n$$
which converges to $e$ to the power of something depending on the numerator. If numerator converges to $0$ then the expression converges to $1$ and we are done. Thus, when just ignoring the floor function we need
$$e 0.5^c < 1 \Leftrightarrow c\log 0.5 < \log (1/e) \Leftrightarrow c > 1/\log 2$$
and it follows that for $c>1/\log 2$ with high probability $\max_{i=1,\dots,n} X_i \leq c\log n$.
But we also get that the above probability converges to $0$ if $c< 1/\log 2$. This means that in this case with high probability $\max_{i=1,\dots,n} X_i \geq c\log n$.
To summarize: With high probability
$$c_1\log n \leq \max_{i=1,\dots,n} X_i \leq c_2\log n$$
for $c_1<1/\log 2$ and $c_2>1/\log 2$.


text:
Q: How to plot in python where x-axis values appears more than once, like 0 1 2 3 2 1 0 I'm new to python, and was playing around with it's plotting capability. I wanted to plot Y1 and Y2 where X values go from 10 to 100 with steps of 10, and 100 to 10 with steps of -10.
I was able to plot this using Excel.
Here are the X and Y values
X  = [10 20 30 40 50 60 70 80 90 100 100 90 80 70 60 50 40 30 20 10]
Y1 = [0 100 200 300 400 500 600 700 800 900 900 800 700 600 500 400 300 200 100 0]
Y2 = [100 200 300 400 500 600 700 800 900 1000 1000 900 800 700 600 500 400 300 200 100]

How do we plot something like this in python using matplotlib and numpy?

A: Its unclear exactly what you are asking. Do you want the repeated X values to plot on top of each other? In which case, you can use ax.plot as shown in the first example (ax1) below.
If you want the X axis to show all the X values in the order they appear in your list, you could use scatter, then just set the xticklabels to the values in X, as shown in the second example below (ax2)
As stated above in comments, neither of these are particularly difficult: there are lots of examples in the matplotlib gallery.
import matplotlib.pyplot as plt

X  = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
Y1 = [0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 900, 800, 700, 600, 500, 400, 300, 200, 100, 0]
Y2 = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100]

fig = plt.figure()
ax1=plt.subplot(211)
ax2=plt.subplot(212)

# First example: overlap repeated X values
ax1.plot(X,Y1,'ro')
ax1.plot(X,Y2,'bo')
ax1.set_title('ax.plot')

# Second example: keep all X values in sequential order
ax2.scatter(range(len(Y1)),Y1,color='r')
ax2.scatter(range(len(Y2)),Y2,c='b')
ax2.set_title('ax.scatter')
ax2.set_xlim(0,len(Y1)-1)
ax2.set_xticks(range(len(Y1)))
ax2.set_xticklabels(X)

plt.show()

A: Actually you don't HAVE to use numpy to plot with matplotlib. You can use normal python lists for plotting with matplotlib. NumPy is the package for scientific computation with Python. Its used for its great capabilities for handling matrices. Doing the matrix operation with standard lists is slower. That's why numpy is great.
You can read about numpy here!
You can take help from this link for plotting data with pyplot. Tweak around the parameters to see what you find.
Also I am providing this simple code for plotting. I assume you know how to use import in python.
import matplotlib.pyplot as plt

X = [range(0,100,10)]
Y = [range(0,1000,100)]

plt.scatter(X,Y)
plt.show()

If you insist on using numpy you can change the code of these two portions
import numpy as np

X = np.array([range(0,100,10)])
Y = np.array([range(0,1000,100)])


text:
Q: Dynamic sized int list I would like to create a int list in C++, but it just doesn't make sense at all.
Also I don't want it to have static size.
I tried this, but "array size must be specified in new expressions without an initializer", what should I do?
int* list = {};
int* list = new int[];
int list[];

Full code
#include <iostream>

using namespace std;

int* list = new int[];

int main() {
    int num;
    cout << "Select number > ";
    cin >> num;

    rozloz(num, list);

    for (int j = 0; j < sizeof(list)/sizeof(list[0]); j++) {
        cout << list[j] << endl;
    }
}

int avaible[] = { 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1 };

void rozloz(int num, int* list) {
    int i = 0;
    int i2 = 0;

    while (num > 0) {
        int current = avaible[i];

        if (current > num) {
            i++;
            continue;
        }

        list[i2] = current;
        num -= current;
        i2++;
    };
}

A:
"array size must be specified in new expressions without an initializer", what should I do?

As per the error message, you should specify a size when you create an array. That size determines how many elements the array has. That said, you normally shouldn't use allocating new expressions at all. See end of the answer for a recommendable solution.

sizeof(list)/sizeof(list[0])

This is wrong. This works only with arrays. I recommend using std::size with arrays, so that you won't encounter this problem because the program would safely fail to compile instead of give you the wrong size.
The type of list is not an array type. Its type is "pointer to int". It points to first element of a dynamic array.
The most convenient way to create a dynamic array is to use std::vector from the standard library. Example:
std::vector<int> rozloz(int num) {
    std::vector<int> list;
    //...
    list.push_back(current); // add elements like this
    //...
    return list;
}


text:
Q: How to change the background color of current day in the calendar? I use Ubuntu 12.04 LTS and I think the default color for the current day is not right. It lacks of contrast. For usability and accessibility purposes, it's better to highlight a little bit more the current day. How can I do that? Should I send a change / improvement request to Canonical?

A: What you are going to want to do is submit a bug report against the calendar on Launchpad, a website pertaining to the development, maintenance, and contributions to Ubuntu software.  This what you have to do:

*

*Make a launchpad account here.

*Find out exactly which package you have the issue with (when in doubt, submit the report against a more general package, such as unity, then someone can help you change it to the right one) .

*Make sure that the bug has not already been reported here.

*Submit the bug report, being sure to be clear and concise.  A general layout to follow is to use 3 headings: "general issue", "what was expected", "what happened instead", "fix/solution/suggestion".

This list applies to any bug you wish to report.
Your contributions are always welcome and appreciated by the Ubuntu community.


text:
Q: Test data generation for neural network handwriting recognition Can someone share some Octave/Matlab code or algorithm to pre-process a photo taken from mobile camera of a handwritten digit.
After pre-processing, the data should have similar characteristics to the MNIST data set digit images.
I have a neural network trained using the MNIST data set. Now I want to test my implementation by taking handwritten digit images using a phone camera and saving it on my computer.
I want to give this image as input to test my neural net implementation.
Thanks in advance !!

A: When people train a model using a dataset, they split the data into several parts and do cross-validation: http://en.wikipedia.org/wiki/Cross-validation_(statistics)
If you scientifically want to find out the exact test performance of the model, you see on which portion of the data it is trained on, and test on the remaining.

A: There might be something in the Octave forge image package that you could use or adapt to your purposes.

A: Actually, this is an old topic to answer, but somebody else may need similar code. Here is a MATLAB code that I wrote for my application. It is a bit messy, so I will explain it in general.
subject_list = {'X','Y'};

output = cell(1,size(subject_list,2)*30);
for subject = 1:size(subject_list,2)
    uncropped = rgb2gray(imread([subject_list{subject},'.jpg']));
    bw = imcomplement(im2bw(uncropped));
    se = strel('disk',10);
    bw_closed = imclose(bw,se);
    [L,n]= bwlabel(bw_closed);
    stats = regionprops(L);
    mean_array(subject) = mean([stats.Area]);
    mr = 22; mc = 22;
    numbers = cell(1,n);
    for i = 1:n
        if((stats(i).Area > 300) && (stats(i).Area < 3000))
            bs = stats(i).BoundingBox;
            numbers{i}(:,:) = imcomplement(uncropped(round(bs(2)-mr):round(bs(2)+bs(4)+mr),...
                round(bs(1)-mc):round(bs(1)+bs(3)+mc)));
        end
    end

    numbers(cellfun(@isempty,numbers))= [];

    for i = 1:size(numbers,2)
        output{1,30*(subject-1)+i} = numbers{i} ;
    end
end

MNIST_centmean = [14.9475,15.0064];

for num = 1:size(output,2)
    sample = imresize(im2double(output{num}),[28 28]);
    rp = regionprops(logical(im2bw(sample,0.1)));
    sample_tr = imtranslate(sample,[MNIST_centmean(1) - rp(1).Centroid(1),...
        MNIST_centmean(2)- rp(1).Centroid(2)]);
    sample_tr(sample_tr<=0.05) = 0;
    imwrite(sample_tr,['n_',int2str(num),'.png'],'PNG');
    resized_numbers(num,:) = reshape(sample_tr,[784,1]);
end

There are two subjects in subject_list each has 30 digits.

*

*read the subject.jpg with imread convert it to grayscale apply
some morphological operation with imclose (this is because some
digits may not be continous body like 5 or 9 for some subjects)

*label    each digit with bwlabel and find their properties with
regionprops (this step is necassary to locate where the digits are)

*take structures which has area between 300 & 3000 that correspond to
digit size in my case. It depends on resolution of the input image.

*discard empthy cells by usign cellfun
at the second part

*Resize each pacth to 28 x 28 with imresize with default bicubic interpolation.

*Translate the center of each pacthes to resemble it into MNIST dataset by using imtranslate. Assign the values to 0 which smaller then 0.05 . (bicubic interpolation added an offset to background which is not the case in MNIST)

*Reshaped the patches to 784x1 and stored them into a matrix (this is
default size for NN trained with MNIST)